playercontroller.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. #include "playercontroller.h"
  2. #include "common.h"
  3. #include <QApplication>
  4. #include <QElapsedTimer>
  5. #include <QStatusBar>
  6. #include <cassert>
  7. #include <memory>
  8. #include "ffmpeg_init.h"
  9. #include "start_play_thread.h"
  10. #include "video_state.h"
  11. #include "audio_decode_thread.h"
  12. #include "audio_effect_helper.h"
  13. #include "audio_play_thread.h"
  14. #include "play_control_window.h"
  15. #include "read_thread.h"
  16. #include "start_play_thread.h"
  17. #include "stopplay_waiting_thread.h"
  18. #include "subtitle_decode_thread.h"
  19. #include "video_decode_thread.h"
  20. #include "video_play_thread.h"
  21. #include "video_state.h"
  22. Q_LOGGING_CATEGORY(playerControllerLog, "player.controller")
  23. PlayerController::PlayerController(QWidget* parent)
  24. : QObject(parent)
  25. {
  26. ffmpeg_init();
  27. m_state = PlayerState::Idle;
  28. }
  29. PlayerController::~PlayerController()
  30. {
  31. if (m_initThread.joinable()) {
  32. m_initThread.join();
  33. }
  34. stopPlay();
  35. }
  36. void PlayerController::startToPlay(const QString& file)
  37. {
  38. std::lock_guard<std::mutex> lock(m_stopMutex);
  39. qCDebug(playerControllerLog) << "[PlayerController] m_state" << (int) m_state.load();
  40. // 自愈:如果状态为Playing但所有线程都已退出,强制Idle
  41. if (m_state == PlayerState::Playing && areAllThreadsStopped()) {
  42. stopAndResetThreads();
  43. m_videoState.reset();
  44. m_currentFile.clear();
  45. m_state = PlayerState::Idle;
  46. qCDebug(playerControllerLog)
  47. << "[PlayerController] All threads stopped, force reset to Idle.";
  48. }
  49. // 初始化中,忽略新请求
  50. if (m_state == PlayerState::Initializing) {
  51. qCDebug(playerControllerLog) << "Player is initializing. Ignoring request.";
  52. return;
  53. }
  54. // 正在播放中,检查是否需要切换文件
  55. if (m_state == PlayerState::Playing) {
  56. if (m_currentFile == file) {
  57. qCDebug(playerControllerLog) << "Already playing the same file. Ignoring request.";
  58. return;
  59. } else {
  60. qCDebug(playerControllerLog)
  61. << "Player is busy with another file, stopping and switching to:" << file;
  62. stopPlay();
  63. // 这里直接 fallthrough 到 Idle 状态
  64. }
  65. }
  66. // 空闲状态,开始新播放
  67. if (m_state == PlayerState::Idle) {
  68. // 确保所有线程已停止
  69. if (!areAllThreadsStopped()) {
  70. qCDebug(playerControllerLog) << "Some threads still running, stopping them first";
  71. stopAndResetThreads();
  72. }
  73. // 重置状态
  74. m_videoState.reset();
  75. m_currentFile.clear();
  76. qCDebug(playerControllerLog) << "Player is idle. Starting playback for:" << file;
  77. m_state = PlayerState::Initializing;
  78. m_currentFile = file;
  79. // 启动异步初始化线程
  80. if (m_initThread.joinable()) {
  81. m_initThread.join();
  82. }
  83. m_initThread = std::thread(&PlayerController::asyncInit, this, file);
  84. }
  85. }
  86. void PlayerController::asyncInit(const QString& file)
  87. {
  88. bool success = false;
  89. QElapsedTimer timer;
  90. timer.start();
  91. qCDebug(playerControllerLog) << "[Init] asyncInit started";
  92. // 检查文件有效性
  93. if (file.isEmpty()) {
  94. qCWarning(playerControllerLog) << "Filename is invalid. Please select a valid media file.";
  95. success = false;
  96. } else {
  97. // 检查文件是否存在和可访问
  98. QFileInfo fileInfo(file);
  99. if (!fileInfo.exists() || !fileInfo.isReadable()) {
  100. qCWarning(playerControllerLog)
  101. << "File does not exist or is not readable:" << toNativePath(file);
  102. success = false;
  103. } else {
  104. qCInfo(playerControllerLog) << "File check passed:" << toNativePath(file);
  105. success = true;
  106. }
  107. }
  108. m_initSuccess = success;
  109. onAsyncInitFinished(file, success);
  110. qCDebug(playerControllerLog) << "[Init] asyncInit finished in " << timer.elapsed() << " ms";
  111. }
  112. void PlayerController::onAsyncInitFinished(const QString& file, bool success)
  113. {
  114. std::lock_guard<std::mutex> lock(m_stopMutex);
  115. QElapsedTimer timer;
  116. timer.start();
  117. // 初始化失败处理
  118. if (!success) {
  119. playFailed(m_currentFile);
  120. m_state = PlayerState::Idle;
  121. return;
  122. }
  123. // 创建视频状态对象
  124. qCDebug(playerControllerLog) << "[Init] createVideoState...";
  125. if (!createVideoState(m_currentFile)) {
  126. qCWarning(playerControllerLog) << "Video state creation failed";
  127. readPacketStopped();
  128. playFailed(m_currentFile);
  129. m_state = PlayerState::Idle;
  130. return;
  131. }
  132. // 检查状态有效性
  133. assert(m_videoState);
  134. if (!m_videoState) {
  135. qCWarning(playerControllerLog) << "Video state initialization error";
  136. playFailed(m_currentFile);
  137. m_state = PlayerState::Idle;
  138. return;
  139. }
  140. // 创建数据包读取线程
  141. qCDebug(playerControllerLog) << "[Init] createReadThread...";
  142. if (!createReadThread()) {
  143. qCWarning(playerControllerLog) << "Packet read thread creation failed";
  144. playFailed(m_currentFile);
  145. m_state = PlayerState::Idle;
  146. return;
  147. }
  148. // 设置视频状态
  149. m_packetReadThread->set_video_state(m_videoState->get_state());
  150. // 检查媒体流类型
  151. const bool hasVideo = playingHasVideo();
  152. const bool hasAudio = playingHasAudio();
  153. const bool hasSubtitle = playingHasSubtitle();
  154. // 创建视频相关线程
  155. if (hasVideo) {
  156. if (!createDecodeVideoThread() || !createVideoPlayThread()) {
  157. qCWarning(playerControllerLog) << "Video processing setup failed";
  158. playFailed(m_currentFile);
  159. stopPlay();
  160. m_state = PlayerState::Idle;
  161. return;
  162. }
  163. }
  164. // 创建音频相关线程
  165. if (hasAudio) {
  166. if (!createDecodeAudioThread() || !createAudioPlayThread()) {
  167. qCWarning(playerControllerLog) << "Audio processing setup failed";
  168. playFailed(m_currentFile);
  169. stopPlay();
  170. m_state = PlayerState::Idle;
  171. return;
  172. }
  173. }
  174. // 创建字幕线程
  175. if (hasSubtitle && !createDecodeSubtitleThread()) {
  176. qCWarning(playerControllerLog) << "Subtitle processing setup failed";
  177. playFailed(m_currentFile);
  178. stopPlay();
  179. m_state = PlayerState::Idle;
  180. return;
  181. }
  182. // 开始播放
  183. if (hasAudio) {
  184. startPlayThread(); // 异步启动(处理音频设备初始化)
  185. } else {
  186. playStarted(); // 同步启动(无音频流)
  187. }
  188. emit startToPlaySignal();
  189. m_state = PlayerState::Playing;
  190. qCDebug(playerControllerLog) << "Playback initialized in " << timer.elapsed() << " ms";
  191. }
  192. void PlayerController::stopPlay()
  193. {
  194. std::lock_guard<std::mutex> lock(m_stopMutex);
  195. if (m_state == PlayerState::Idle)
  196. return;
  197. qCDebug(playerControllerLog) << "Stopping playback...";
  198. m_state = PlayerState::Stopping;
  199. // 停止并重置所有线程
  200. stopAndResetThreads();
  201. // 清理视频状态
  202. m_videoState.reset();
  203. m_currentFile.clear();
  204. m_state = PlayerState::Idle;
  205. qCDebug(playerControllerLog) << "Playback stopped.";
  206. }
  207. void PlayerController::pausePlay()
  208. {
  209. if (!m_videoState)
  210. return;
  211. if (auto state = m_videoState->get_state())
  212. toggle_pause(state, !state->paused);
  213. emit updatePlayControlStatus();
  214. }
  215. void PlayerController::playMute(bool mute)
  216. {
  217. if (!m_videoState)
  218. return;
  219. if (auto state = m_videoState->get_state())
  220. toggle_mute(state, mute);
  221. }
  222. void PlayerController::playStartSeek()
  223. {
  224. pausePlay();
  225. }
  226. void PlayerController::playSeekPre()
  227. {
  228. videoSeekInc(-0.5); // 将步长从2秒减小到0.5秒,提高精度
  229. }
  230. void PlayerController::playSeekNext()
  231. {
  232. videoSeekInc(0.5); // 将步长从2秒减小到0.5秒,提高精度
  233. }
  234. void PlayerController::setVolume(int volume, int maxValue)
  235. {
  236. if (!m_audioPlayThread)
  237. return;
  238. const float vol = static_cast<float>(volume) / maxValue;
  239. m_audioPlayThread->set_device_volume(vol);
  240. }
  241. void PlayerController::setPlaySpeed(double speed)
  242. {
  243. if (m_videoState) {
  244. if (auto state = m_videoState->get_state()) {
  245. #if USE_AVFILTER_AUDIO
  246. set_audio_playspeed(state, speed);
  247. #endif
  248. }
  249. }
  250. }
  251. // 状态访问接口
  252. QString PlayerController::playingFile() const
  253. {
  254. return isPlaying() ? m_currentFile : QString();
  255. }
  256. bool PlayerController::isPlaying() const
  257. {
  258. // 不仅检查状态标志,还检查线程是否实际运行
  259. if (m_state != PlayerState::Playing) {
  260. return false;
  261. }
  262. // 如果状态是Playing但所有线程都已停止,则实际上不是在播放状态
  263. if (areAllThreadsStopped()) {
  264. qCDebug(playerControllerLog) << "[isPlaying] State is Playing but all threads stopped";
  265. return false;
  266. }
  267. return true;
  268. }
  269. bool PlayerController::playingHasVideo()
  270. {
  271. return m_videoState ? m_videoState->has_video() : false;
  272. }
  273. bool PlayerController::playingHasAudio()
  274. {
  275. return m_videoState ? m_videoState->has_audio() : false;
  276. }
  277. bool PlayerController::playingHasSubtitle()
  278. {
  279. return m_videoState ? m_videoState->has_subtitle() : false;
  280. }
  281. VideoState* PlayerController::state()
  282. {
  283. return m_videoState ? m_videoState->get_state() : nullptr;
  284. }
  285. float PlayerController::deviceVolume() const
  286. {
  287. return m_audioPlayThread ? m_audioPlayThread->get_device_volume() : 0.0f;
  288. }
  289. void PlayerController::setDeviceVolume(float volume)
  290. {
  291. if (m_audioPlayThread)
  292. m_audioPlayThread->set_device_volume(volume);
  293. }
  294. // 播放状态回调槽函数
  295. void PlayerController::playStarted(bool success)
  296. {
  297. if (!success) {
  298. qCWarning(playerControllerLog) << "Audio device initialization failed!";
  299. return;
  300. }
  301. allThreadStart();
  302. setThreads();
  303. }
  304. void PlayerController::playFailed(const QString& file)
  305. {
  306. qCWarning(playerControllerLog) << "Playback failed for file:" << toNativePath(file);
  307. // 确保状态一致性
  308. if (m_state != PlayerState::Idle) {
  309. // 检查线程状态并重置
  310. if (!areAllThreadsStopped()) {
  311. qCDebug(playerControllerLog) << "Some threads still running, stopping them first";
  312. stopAndResetThreads();
  313. }
  314. }
  315. emit showMessage(QString("Playback failed: %1").arg(toNativePath(file)), "Warning", "");
  316. }
  317. // 线程 finished 槽函数只做日志和信号
  318. void PlayerController::readPacketStopped()
  319. {
  320. qCDebug(playerControllerLog) << "************* Read packets thread stopped signal received.";
  321. //m_packetReadThread.reset();
  322. if (m_videoState) {
  323. m_videoState->delete_video_state();
  324. }
  325. emit audioStopped();
  326. }
  327. void PlayerController::decodeVideoStopped()
  328. {
  329. qCDebug(playerControllerLog) << "************* Video decode thread stopped.";
  330. }
  331. void PlayerController::decodeAudioStopped()
  332. {
  333. qCDebug(playerControllerLog) << "************* Audio decode thread stopped.";
  334. }
  335. void PlayerController::decodeSubtitleStopped()
  336. {
  337. qCDebug(playerControllerLog) << "************* Subtitle decode thread stopped.";
  338. }
  339. void PlayerController::audioPlayStopped()
  340. {
  341. qCDebug(playerControllerLog) << "************* Audio play thread stopped.";
  342. emit audioStopped();
  343. }
  344. void PlayerController::videoPlayStopped()
  345. {
  346. qCDebug(playerControllerLog) << "************* Video play thread stopped.";
  347. emit videoStopped();
  348. }
  349. // 线程管理槽函数
  350. void PlayerController::setThreads()
  351. {
  352. if (!m_videoState)
  353. return;
  354. Threads threads;
  355. threads.read_tid = m_packetReadThread.get();
  356. threads.video_decode_tid = m_decodeVideoThread.get();
  357. threads.audio_decode_tid = m_decodeAudioThread.get();
  358. threads.video_play_tid = m_videoPlayThread.get();
  359. threads.audio_play_tid = m_audioPlayThread.get();
  360. threads.subtitle_decode_tid = m_decodeSubtitleThread.get();
  361. m_videoState->threads_setting(m_videoState->get_state(), threads);
  362. }
  363. void PlayerController::startSendData(bool send)
  364. {
  365. if (m_audioPlayThread)
  366. m_audioPlayThread->send_visual_open(send);
  367. }
  368. void PlayerController::videoSeek(double position, double increment)
  369. {
  370. if (!m_videoState)
  371. return;
  372. auto state = m_videoState->get_state();
  373. if (!state)
  374. return;
  375. if (state->ic->start_time != AV_NOPTS_VALUE
  376. && position < state->ic->start_time / static_cast<double>(AV_TIME_BASE)) {
  377. position = state->ic->start_time / static_cast<double>(AV_TIME_BASE);
  378. }
  379. // 添加量化操作,精确到0.01秒
  380. position = round(position * 100) / 100.0;
  381. qDebug() << "position:" << position
  382. << "position * AV_TIME_BASE:" << static_cast<int64_t>(position * AV_TIME_BASE)
  383. << "increment * AV_TIME_BASE:" << static_cast<int64_t>(increment * AV_TIME_BASE);
  384. stream_seek(state,
  385. static_cast<int64_t>(position * AV_TIME_BASE),
  386. static_cast<int64_t>(increment * AV_TIME_BASE),
  387. 0);
  388. }
  389. void PlayerController::videoSeekEx(double value, double maxValue)
  390. {
  391. if (!m_videoState)
  392. return;
  393. auto state = m_videoState->get_state();
  394. if (!state)
  395. return;
  396. auto cur_stream = state;
  397. auto x = value;
  398. double frac;
  399. if (m_videoState->seekByBytes() || cur_stream->ic->duration <= 0) {
  400. uint64_t size = avio_size(cur_stream->ic->pb);
  401. stream_seek(cur_stream, size * x / maxValue, 0, 1);
  402. } else {
  403. int64_t ts;
  404. int ns, hh, mm, ss;
  405. int tns, thh, tmm, tss;
  406. tns = cur_stream->ic->duration / 1000000LL;
  407. thh = tns / 3600;
  408. tmm = (tns % 3600) / 60;
  409. tss = (tns % 60);
  410. frac = x / maxValue;
  411. ns = frac * tns;
  412. hh = ns / 3600;
  413. mm = (ns % 3600) / 60;
  414. ss = (ns % 60);
  415. av_log(NULL,
  416. AV_LOG_INFO,
  417. "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n",
  418. frac * 100,
  419. hh,
  420. mm,
  421. ss,
  422. thh,
  423. tmm,
  424. tss);
  425. qDebug("Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)",
  426. frac * 100,
  427. hh,
  428. mm,
  429. ss,
  430. thh,
  431. tmm,
  432. tss);
  433. ts = frac * cur_stream->ic->duration;
  434. if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
  435. ts += cur_stream->ic->start_time;
  436. stream_seek(cur_stream, ts, 0, 0);
  437. }
  438. return;
  439. }
  440. // 线程管理辅助方法
  441. void PlayerController::stopAndResetThreads()
  442. {
  443. auto stopAndReset = [](auto& threadPtr, const QString& threadName) {
  444. if (threadPtr) {
  445. qCDebug(playerControllerLog)
  446. << "[stopAndReset] [" << threadName
  447. << "] try stop/join thread, isRunning=" << threadPtr->isRunning();
  448. threadPtr->stop();
  449. // 添加超时等待机制
  450. const int MAX_WAIT_MS = 500; // 最多等待500毫秒
  451. auto startTime = std::chrono::steady_clock::now();
  452. while (threadPtr->isRunning()) {
  453. auto now = std::chrono::steady_clock::now();
  454. auto elapsed
  455. = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
  456. if (elapsed > MAX_WAIT_MS) {
  457. qCWarning(playerControllerLog)
  458. << "[stopAndReset] [" << threadName << "] Thread stop timeout after"
  459. << elapsed << "ms";
  460. break;
  461. }
  462. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  463. }
  464. // 只有线程已停止才join
  465. if (!threadPtr->isRunning()) {
  466. threadPtr->join();
  467. qCDebug(playerControllerLog)
  468. << "[stopAndReset] [" << threadName << "] thread joined and will reset.";
  469. }
  470. threadPtr.reset();
  471. }
  472. };
  473. // 按依赖顺序停止线程
  474. stopAndReset(m_beforePlayThread, "BeforePlay");
  475. stopAndReset(m_videoPlayThread, "VideoPlay");
  476. stopAndReset(m_audioPlayThread, "AudioPlay");
  477. // 解码前先 关闭流 不然会卡死异常
  478. if (m_videoState) {
  479. m_videoState->delete_video_state();
  480. }
  481. stopAndReset(m_decodeVideoThread, "DecodeVideo");
  482. stopAndReset(m_decodeAudioThread, "DecodeAudio");
  483. stopAndReset(m_decodeSubtitleThread, "DecodeSubtitle");
  484. stopAndReset(m_packetReadThread, "PacketRead");
  485. }
  486. bool PlayerController::areAllThreadsStopped() const
  487. {
  488. // 检查所有线程是否已停止
  489. return (!m_packetReadThread || !m_packetReadThread->isRunning())
  490. && (!m_decodeVideoThread || !m_decodeVideoThread->isRunning())
  491. && (!m_decodeAudioThread || !m_decodeAudioThread->isRunning())
  492. && (!m_audioPlayThread || !m_audioPlayThread->isRunning())
  493. && (!m_videoPlayThread || !m_videoPlayThread->isRunning())
  494. && (!m_decodeSubtitleThread || !m_decodeSubtitleThread->isRunning());
  495. }
  496. void PlayerController::allThreadStart()
  497. {
  498. // 启动所有创建的线程
  499. if (m_packetReadThread) {
  500. if (!m_videoState || !m_videoState->get_state()) {
  501. qCWarning(playerControllerLog) << "VideoState invalid, skip starting read thread";
  502. } else {
  503. m_packetReadThread->start();
  504. }
  505. qCDebug(playerControllerLog) << "++++++++++ Read packets thread started";
  506. }
  507. if (m_decodeVideoThread) {
  508. m_decodeVideoThread->start();
  509. qCDebug(playerControllerLog) << "++++++++++ Video decode thread started";
  510. }
  511. if (m_decodeAudioThread) {
  512. m_decodeAudioThread->start();
  513. qCDebug(playerControllerLog) << "++++++++++ Audio decode thread started";
  514. }
  515. if (m_decodeSubtitleThread) {
  516. m_decodeSubtitleThread->start();
  517. qCDebug(playerControllerLog) << "++++++++++ Subtitle decode thread started";
  518. }
  519. if (m_videoPlayThread) {
  520. m_videoPlayThread->start();
  521. qCDebug(playerControllerLog) << "++++++++++ Video play thread started";
  522. }
  523. if (m_audioPlayThread) {
  524. m_audioPlayThread->start();
  525. qCDebug(playerControllerLog) << "++++++++++ Audio play thread started";
  526. }
  527. // 通知UI更新
  528. emit setPlayControlWnd(true);
  529. emit updatePlayControlVolume();
  530. emit updatePlayControlStatus();
  531. }
  532. // 辅助函数
  533. void PlayerController::videoSeekInc(double increment)
  534. {
  535. if (!m_videoState)
  536. return;
  537. auto state = m_videoState->get_state();
  538. if (!state)
  539. return;
  540. double position = get_master_clock(state);
  541. if (std::isnan(position)) {
  542. position = static_cast<double>(state->seek_pos) / AV_TIME_BASE;
  543. }
  544. position += increment;
  545. videoSeek(position, increment);
  546. }
  547. // 线程创建方法
  548. bool PlayerController::createVideoState(const QString& file)
  549. {
  550. const bool useHardware = false; // 待实现:来自UI设置
  551. const bool loop = false; // 待实现:来自UI设置
  552. if (m_videoState)
  553. return false;
  554. m_videoState = std::make_unique<VideoStateData>(useHardware, loop);
  555. const int ret = m_videoState->create_video_state(file.toUtf8().constData());
  556. if (ret < 0) {
  557. m_videoState.reset();
  558. qCWarning(playerControllerLog) << "Video state creation failed (error: " << ret << ")";
  559. return false;
  560. }
  561. return true;
  562. }
  563. void PlayerController::deleteVideoState()
  564. {
  565. m_videoState.reset();
  566. }
  567. bool PlayerController::createReadThread()
  568. {
  569. if (m_packetReadThread)
  570. return false;
  571. m_packetReadThread = std::make_unique<ReadThread>(m_videoState ? m_videoState->get_state()
  572. : nullptr);
  573. m_packetReadThread->setOnFinished([this]() { readPacketStopped(); });
  574. return true;
  575. }
  576. bool PlayerController::createDecodeVideoThread()
  577. {
  578. if (!m_videoState || m_decodeVideoThread)
  579. return false;
  580. auto state = m_videoState->get_state();
  581. if (!state)
  582. return false;
  583. m_decodeVideoThread = std::make_unique<VideoDecodeThread>(state);
  584. m_decodeVideoThread->setOnFinished([this]() { decodeVideoStopped(); });
  585. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  586. // 初始化视频解码器
  587. int ret = decoder_init(&state->viddec,
  588. codecContext,
  589. &state->videoq,
  590. state->continue_read_thread);
  591. if (ret < 0) {
  592. qCWarning(playerControllerLog)
  593. << "Video decoder initialization failed (error: " << ret << ")";
  594. return false;
  595. }
  596. ret = decoder_start(&state->viddec, m_decodeVideoThread.get(), "video_decoder");
  597. if (ret < 0) {
  598. qCWarning(playerControllerLog) << "Video decoder start failed (error: " << ret << ")";
  599. return false;
  600. }
  601. state->queue_attachments_req = 1;
  602. return true;
  603. }
  604. bool PlayerController::createDecodeAudioThread()
  605. {
  606. if (!m_videoState || m_decodeAudioThread)
  607. return false;
  608. auto state = m_videoState->get_state();
  609. if (!state)
  610. return false;
  611. m_decodeAudioThread = std::make_unique<AudioDecodeThread>(state);
  612. m_decodeAudioThread->setOnFinished([this]() { decodeAudioStopped(); });
  613. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_AUDIO);
  614. // 初始化音频解码器
  615. int ret = decoder_init(&state->auddec,
  616. codecContext,
  617. &state->audioq,
  618. state->continue_read_thread);
  619. if (ret < 0) {
  620. qCWarning(playerControllerLog)
  621. << "Audio decoder initialization failed (error: " << ret << ")";
  622. return false;
  623. }
  624. ret = decoder_start(&state->auddec, m_decodeAudioThread.get(), "audio_decoder");
  625. if (ret < 0) {
  626. qCWarning(playerControllerLog) << "Audio decoder start failed (error: " << ret << ")";
  627. return false;
  628. }
  629. return true;
  630. }
  631. bool PlayerController::createDecodeSubtitleThread()
  632. {
  633. if (!m_videoState || m_decodeSubtitleThread)
  634. return false;
  635. auto state = m_videoState->get_state();
  636. if (!state)
  637. return false;
  638. m_decodeSubtitleThread = std::make_unique<SubtitleDecodeThread>(state);
  639. m_decodeSubtitleThread->setOnFinished([this]() { decodeSubtitleStopped(); });
  640. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_SUBTITLE);
  641. // 初始化字幕解码器
  642. int ret = decoder_init(&state->subdec,
  643. codecContext,
  644. &state->subtitleq,
  645. state->continue_read_thread);
  646. if (ret < 0) {
  647. qCWarning(playerControllerLog)
  648. << "Subtitle decoder initialization failed (error: " << ret << ")";
  649. return false;
  650. }
  651. ret = decoder_start(&state->subdec, m_decodeSubtitleThread.get(), "subtitle_decoder");
  652. if (ret < 0) {
  653. qCWarning(playerControllerLog) << "Subtitle decoder start failed (error: " << ret << ")";
  654. return false;
  655. }
  656. return true;
  657. }
  658. bool PlayerController::createVideoPlayThread()
  659. {
  660. if (!m_videoState || m_videoPlayThread)
  661. return false;
  662. auto state = m_videoState->get_state();
  663. if (!state)
  664. return false;
  665. m_videoPlayThread = std::make_unique<VideoPlayThread>(state);
  666. m_videoPlayThread->setOnFinished([this]() { videoPlayStopped(); });
  667. m_videoPlayThread->setOnFrameReady([this](AVFrame* frame) { this->onFrameReady(frame); });
  668. m_videoPlayThread->setOnSubtitleReady([this](const QString& text) {
  669. // TODO: 实现 PlayerController::onSubtitleReady(const QString&) 处理字幕
  670. // onSubtitleReady(text);
  671. });
  672. // 初始化参数
  673. auto videoContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  674. const bool useHardware = m_videoState->is_hardware_decode();
  675. if (!m_videoPlayThread->init_resample_param(videoContext, useHardware)) {
  676. qCWarning(playerControllerLog) << "Video resample parameters initialization failed";
  677. return false;
  678. }
  679. return true;
  680. }
  681. bool PlayerController::createAudioPlayThread()
  682. {
  683. if (!m_videoState || m_audioPlayThread)
  684. return false;
  685. auto state = m_videoState->get_state();
  686. if (!state)
  687. return false;
  688. m_audioPlayThread = std::make_unique<AudioPlayThread>(state);
  689. m_audioPlayThread->setOnFinished([this]() { audioPlayStopped(); });
  690. m_audioPlayThread->setOnUpdatePlayTime([this]() {
  691. // TODO: 实现 PlayerController::onUpdatePlayTime() 处理播放时间更新
  692. //emit updatePlayTime();
  693. });
  694. m_audioPlayThread->setOnDataVisualReady([this](const AudioData& data) {
  695. // 异步 ?
  696. emit audioData(data);
  697. });
  698. // 音频设备初始化在独立线程中完成
  699. return true;
  700. }
  701. bool PlayerController::startPlayThread()
  702. {
  703. if (m_beforePlayThread)
  704. return false;
  705. m_beforePlayThread = std::make_unique<StartPlayThread>(m_audioPlayThread.get(),
  706. m_videoState.get());
  707. m_beforePlayThread->setOnFinished([this]() {
  708. qCDebug(playerControllerLog) << "[StartPlayThread] finished, call playStarted()";
  709. playStarted();
  710. });
  711. m_beforePlayThread->start();
  712. qCDebug(playerControllerLog) << "++++++++++ StartPlay thread (audio init) started";
  713. return true;
  714. }
  715. // 调试辅助函数
  716. void PlayerController::printDecodeContext(const AVCodecContext* codecCtx, bool isVideo) const
  717. {
  718. if (!codecCtx)
  719. return;
  720. qCInfo(playerControllerLog) << (isVideo ? "Video" : "Audio")
  721. << " codec: " << codecCtx->codec->name;
  722. qCInfo(playerControllerLog) << " Type:" << codecCtx->codec_type << "ID:" << codecCtx->codec_id
  723. << "Tag:" << codecCtx->codec_tag;
  724. if (isVideo) {
  725. qCInfo(playerControllerLog)
  726. << " Dimensions: " << codecCtx->width << "x" << codecCtx->height;
  727. } else {
  728. qCInfo(playerControllerLog) << " Sample rate: " << codecCtx->sample_rate
  729. << " Hz, Channels: " << codecCtx->ch_layout.nb_channels
  730. << ", Format: " << codecCtx->sample_fmt;
  731. qCInfo(playerControllerLog) << " Frame size: " << codecCtx->frame_size
  732. << ", Block align: " << codecCtx->block_align;
  733. }
  734. }
  735. // 在合适位置实现 onFrameReady
  736. void PlayerController::onFrameReady(AVFrame* frame)
  737. {
  738. // 这里可以做帧处理、缓存、同步等操作
  739. emit frameReady(frame); // 直接转发给 UI 层
  740. }