playercontroller.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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. if (m_videoState) {
  200. m_videoState->delete_video_state();
  201. }
  202. // 清理视频状态
  203. m_videoState.reset();
  204. // 停止并重置所有线程
  205. stopAndResetThreads();
  206. m_currentFile.clear();
  207. m_state = PlayerState::Idle;
  208. qCDebug(playerControllerLog) << "Playback stopped.";
  209. }
  210. void PlayerController::pausePlay()
  211. {
  212. if (!m_videoState)
  213. return;
  214. if (auto state = m_videoState->get_state())
  215. toggle_pause(state, !state->paused);
  216. emit updatePlayControlStatus();
  217. }
  218. void PlayerController::playMute(bool mute)
  219. {
  220. if (!m_videoState)
  221. return;
  222. if (auto state = m_videoState->get_state())
  223. toggle_mute(state, mute);
  224. }
  225. void PlayerController::playStartSeek()
  226. {
  227. emit playSeek();
  228. pausePlay();
  229. }
  230. void PlayerController::playSeekPre()
  231. {
  232. videoSeekInc(-2);
  233. }
  234. void PlayerController::playSeekNext()
  235. {
  236. videoSeekInc(2);
  237. }
  238. void PlayerController::setVolume(int volume, int maxValue)
  239. {
  240. if (!m_audioPlayThread)
  241. return;
  242. const float vol = static_cast<float>(volume) / maxValue;
  243. m_audioPlayThread->set_device_volume(vol);
  244. }
  245. void PlayerController::setPlaySpeed(double speed)
  246. {
  247. if (m_videoState) {
  248. if (auto state = m_videoState->get_state()) {
  249. #if USE_AVFILTER_AUDIO
  250. set_audio_playspeed(state, speed);
  251. #endif
  252. }
  253. }
  254. }
  255. // 状态访问接口
  256. QString PlayerController::playingFile() const
  257. {
  258. return isPlaying() ? m_currentFile : QString();
  259. }
  260. bool PlayerController::isPlaying() const
  261. {
  262. // 不仅检查状态标志,还检查线程是否实际运行
  263. if (m_state != PlayerState::Playing) {
  264. return false;
  265. }
  266. // 如果状态是Playing但所有线程都已停止,则实际上不是在播放状态
  267. if (areAllThreadsStopped()) {
  268. qCDebug(playerControllerLog) << "[isPlaying] State is Playing but all threads stopped";
  269. return false;
  270. }
  271. return true;
  272. }
  273. bool PlayerController::playingHasVideo()
  274. {
  275. return m_videoState ? m_videoState->has_video() : false;
  276. }
  277. bool PlayerController::playingHasAudio()
  278. {
  279. return m_videoState ? m_videoState->has_audio() : false;
  280. }
  281. bool PlayerController::playingHasSubtitle()
  282. {
  283. return m_videoState ? m_videoState->has_subtitle() : false;
  284. }
  285. VideoState* PlayerController::state()
  286. {
  287. return m_videoState ? m_videoState->get_state() : nullptr;
  288. }
  289. float PlayerController::deviceVolume() const
  290. {
  291. return m_audioPlayThread ? m_audioPlayThread->get_device_volume() : 0.0f;
  292. }
  293. void PlayerController::setDeviceVolume(float volume)
  294. {
  295. if (m_audioPlayThread)
  296. m_audioPlayThread->set_device_volume(volume);
  297. }
  298. // 播放状态回调槽函数
  299. void PlayerController::playStarted(bool success)
  300. {
  301. if (!success) {
  302. qCWarning(playerControllerLog) << "Audio device initialization failed!";
  303. return;
  304. }
  305. allThreadStart();
  306. setThreads();
  307. }
  308. void PlayerController::playFailed(const QString& file)
  309. {
  310. qCWarning(playerControllerLog) << "Playback failed for file:" << toNativePath(file);
  311. // 确保状态一致性
  312. if (m_state != PlayerState::Idle) {
  313. // 检查线程状态并重置
  314. if (!areAllThreadsStopped()) {
  315. qCDebug(playerControllerLog) << "Some threads still running, stopping them first";
  316. stopAndResetThreads();
  317. }
  318. }
  319. emit showMessage(QString("Playback failed: %1").arg(toNativePath(file)), "Warning", "");
  320. }
  321. // 线程 finished 槽函数只做日志和信号
  322. void PlayerController::readPacketStopped()
  323. {
  324. qCDebug(playerControllerLog) << "************* Read packets thread stopped signal received.";
  325. //m_packetReadThread.reset();
  326. if (m_videoState) {
  327. m_videoState->delete_video_state();
  328. }
  329. emit audioStopped();
  330. }
  331. void PlayerController::decodeVideoStopped()
  332. {
  333. qCDebug(playerControllerLog) << "************* Video decode thread stopped.";
  334. }
  335. void PlayerController::decodeAudioStopped()
  336. {
  337. qCDebug(playerControllerLog) << "************* Audio decode thread stopped.";
  338. }
  339. void PlayerController::decodeSubtitleStopped()
  340. {
  341. qCDebug(playerControllerLog) << "************* Subtitle decode thread stopped.";
  342. }
  343. void PlayerController::audioPlayStopped()
  344. {
  345. qCDebug(playerControllerLog) << "************* Audio play thread stopped.";
  346. emit audioStopped();
  347. }
  348. void PlayerController::videoPlayStopped()
  349. {
  350. qCDebug(playerControllerLog) << "************* Video play thread stopped.";
  351. emit videoStopped();
  352. }
  353. // 线程管理槽函数
  354. void PlayerController::setThreads()
  355. {
  356. if (!m_videoState)
  357. return;
  358. Threads threads;
  359. threads.read_tid = m_packetReadThread.get();
  360. threads.video_decode_tid = m_decodeVideoThread.get();
  361. threads.audio_decode_tid = m_decodeAudioThread.get();
  362. threads.video_play_tid = m_videoPlayThread.get();
  363. threads.audio_play_tid = m_audioPlayThread.get();
  364. threads.subtitle_decode_tid = m_decodeSubtitleThread.get();
  365. m_videoState->threads_setting(m_videoState->get_state(), threads);
  366. }
  367. void PlayerController::startSendData(bool send)
  368. {
  369. if (m_audioPlayThread)
  370. m_audioPlayThread->send_visual_open(send);
  371. }
  372. void PlayerController::videoSeek(double position, double increment)
  373. {
  374. if (!m_videoState)
  375. return;
  376. auto state = m_videoState->get_state();
  377. if (!state)
  378. return;
  379. if (state->ic->start_time != AV_NOPTS_VALUE
  380. && position < state->ic->start_time / static_cast<double>(AV_TIME_BASE)) {
  381. position = state->ic->start_time / static_cast<double>(AV_TIME_BASE);
  382. }
  383. stream_seek(state,
  384. static_cast<int64_t>(position * AV_TIME_BASE),
  385. static_cast<int64_t>(increment * AV_TIME_BASE),
  386. 0);
  387. }
  388. // 线程管理辅助方法
  389. void PlayerController::stopAndResetThreads()
  390. {
  391. auto stopAndReset = [](auto& threadPtr, const QString& threadName) {
  392. if (threadPtr) {
  393. qCDebug(playerControllerLog)
  394. << "[stopAndReset] [" << threadName << "] try stop/join thread, isRunning=" << threadPtr->isRunning();
  395. threadPtr->stop();
  396. // 添加超时等待机制
  397. const int MAX_WAIT_MS = 500; // 最多等待500毫秒
  398. auto startTime = std::chrono::steady_clock::now();
  399. while (threadPtr->isRunning()) {
  400. auto now = std::chrono::steady_clock::now();
  401. auto elapsed
  402. = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
  403. if (elapsed > MAX_WAIT_MS) {
  404. qCWarning(playerControllerLog)
  405. << "[stopAndReset] [" << threadName << "] Thread stop timeout after" << elapsed << "ms";
  406. break;
  407. }
  408. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  409. }
  410. threadPtr->join();
  411. qCDebug(playerControllerLog) << "[stopAndReset] [" << threadName << "] thread joined and will reset.";
  412. threadPtr.reset();
  413. }
  414. };
  415. // 按依赖顺序停止线程
  416. stopAndReset(m_beforePlayThread, "BeforePlay");
  417. stopAndReset(m_packetReadThread, "PacketRead");
  418. stopAndReset(m_decodeVideoThread, "DecodeVideo");
  419. stopAndReset(m_decodeAudioThread, "DecodeAudio");
  420. stopAndReset(m_decodeSubtitleThread, "DecodeSubtitle");
  421. stopAndReset(m_videoPlayThread, "VideoPlay");
  422. stopAndReset(m_audioPlayThread, "AudioPlay");
  423. }
  424. bool PlayerController::areAllThreadsStopped() const
  425. {
  426. // 检查所有线程是否已停止
  427. return (!m_packetReadThread || !m_packetReadThread->isRunning())
  428. && (!m_decodeVideoThread || !m_decodeVideoThread->isRunning())
  429. && (!m_decodeAudioThread || !m_decodeAudioThread->isRunning())
  430. && (!m_audioPlayThread || !m_audioPlayThread->isRunning())
  431. && (!m_videoPlayThread || !m_videoPlayThread->isRunning())
  432. && (!m_decodeSubtitleThread || !m_decodeSubtitleThread->isRunning());
  433. }
  434. void PlayerController::allThreadStart()
  435. {
  436. // 启动所有创建的线程
  437. if (m_packetReadThread) {
  438. if (!m_videoState || !m_videoState->get_state()) {
  439. qCWarning(playerControllerLog) << "VideoState invalid, skip starting read thread";
  440. } else {
  441. m_packetReadThread->start();
  442. }
  443. qCDebug(playerControllerLog) << "++++++++++ Read packets thread started";
  444. }
  445. if (m_decodeVideoThread) {
  446. m_decodeVideoThread->start();
  447. qCDebug(playerControllerLog) << "++++++++++ Video decode thread started";
  448. }
  449. if (m_decodeAudioThread) {
  450. m_decodeAudioThread->start();
  451. qCDebug(playerControllerLog) << "++++++++++ Audio decode thread started";
  452. }
  453. if (m_decodeSubtitleThread) {
  454. m_decodeSubtitleThread->start();
  455. qCDebug(playerControllerLog) << "++++++++++ Subtitle decode thread started";
  456. }
  457. if (m_videoPlayThread) {
  458. m_videoPlayThread->start();
  459. qCDebug(playerControllerLog) << "++++++++++ Video play thread started";
  460. }
  461. if (m_audioPlayThread) {
  462. m_audioPlayThread->start();
  463. qCDebug(playerControllerLog) << "++++++++++ Audio play thread started";
  464. }
  465. // 通知UI更新
  466. emit setPlayControlWnd(true);
  467. emit updatePlayControlVolume();
  468. emit updatePlayControlStatus();
  469. }
  470. // 辅助函数
  471. void PlayerController::videoSeekInc(double increment)
  472. {
  473. if (!m_videoState)
  474. return;
  475. auto state = m_videoState->get_state();
  476. if (!state)
  477. return;
  478. double position = get_master_clock(state);
  479. if (std::isnan(position)) {
  480. position = static_cast<double>(state->seek_pos) / AV_TIME_BASE;
  481. }
  482. position += increment;
  483. videoSeek(position, increment);
  484. }
  485. // 线程创建方法
  486. bool PlayerController::createVideoState(const QString& file)
  487. {
  488. const bool useHardware = false; // 待实现:来自UI设置
  489. const bool loop = false; // 待实现:来自UI设置
  490. if (m_videoState)
  491. return false;
  492. m_videoState = std::make_unique<VideoStateData>(useHardware, loop);
  493. const int ret = m_videoState->create_video_state(file.toUtf8().constData());
  494. if (ret < 0) {
  495. m_videoState.reset();
  496. qCWarning(playerControllerLog) << "Video state creation failed (error: " << ret << ")";
  497. return false;
  498. }
  499. return true;
  500. }
  501. void PlayerController::deleteVideoState()
  502. {
  503. m_videoState.reset();
  504. }
  505. bool PlayerController::createReadThread()
  506. {
  507. if (m_packetReadThread)
  508. return false;
  509. m_packetReadThread = std::make_unique<ReadThread>(m_videoState ? m_videoState->get_state()
  510. : nullptr);
  511. m_packetReadThread->setOnFinished([this]() { readPacketStopped(); });
  512. return true;
  513. }
  514. bool PlayerController::createDecodeVideoThread()
  515. {
  516. if (!m_videoState || m_decodeVideoThread)
  517. return false;
  518. auto state = m_videoState->get_state();
  519. if (!state)
  520. return false;
  521. m_decodeVideoThread = std::make_unique<VideoDecodeThread>(state);
  522. m_decodeVideoThread->setOnFinished([this]() { decodeVideoStopped(); });
  523. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  524. // 初始化视频解码器
  525. int ret = decoder_init(&state->viddec,
  526. codecContext,
  527. &state->videoq,
  528. state->continue_read_thread);
  529. if (ret < 0) {
  530. qCWarning(playerControllerLog)
  531. << "Video decoder initialization failed (error: " << ret << ")";
  532. return false;
  533. }
  534. ret = decoder_start(&state->viddec, m_decodeVideoThread.get(), "video_decoder");
  535. if (ret < 0) {
  536. qCWarning(playerControllerLog) << "Video decoder start failed (error: " << ret << ")";
  537. return false;
  538. }
  539. state->queue_attachments_req = 1;
  540. return true;
  541. }
  542. bool PlayerController::createDecodeAudioThread()
  543. {
  544. if (!m_videoState || m_decodeAudioThread)
  545. return false;
  546. auto state = m_videoState->get_state();
  547. if (!state)
  548. return false;
  549. m_decodeAudioThread = std::make_unique<AudioDecodeThread>(state);
  550. m_decodeAudioThread->setOnFinished([this]() { decodeAudioStopped(); });
  551. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_AUDIO);
  552. // 初始化音频解码器
  553. int ret = decoder_init(&state->auddec,
  554. codecContext,
  555. &state->audioq,
  556. state->continue_read_thread);
  557. if (ret < 0) {
  558. qCWarning(playerControllerLog)
  559. << "Audio decoder initialization failed (error: " << ret << ")";
  560. return false;
  561. }
  562. ret = decoder_start(&state->auddec, m_decodeAudioThread.get(), "audio_decoder");
  563. if (ret < 0) {
  564. qCWarning(playerControllerLog) << "Audio decoder start failed (error: " << ret << ")";
  565. return false;
  566. }
  567. return true;
  568. }
  569. bool PlayerController::createDecodeSubtitleThread()
  570. {
  571. if (!m_videoState || m_decodeSubtitleThread)
  572. return false;
  573. auto state = m_videoState->get_state();
  574. if (!state)
  575. return false;
  576. m_decodeSubtitleThread = std::make_unique<SubtitleDecodeThread>(state);
  577. m_decodeSubtitleThread->setOnFinished([this]() { decodeSubtitleStopped(); });
  578. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_SUBTITLE);
  579. // 初始化字幕解码器
  580. int ret = decoder_init(&state->subdec,
  581. codecContext,
  582. &state->subtitleq,
  583. state->continue_read_thread);
  584. if (ret < 0) {
  585. qCWarning(playerControllerLog)
  586. << "Subtitle decoder initialization failed (error: " << ret << ")";
  587. return false;
  588. }
  589. ret = decoder_start(&state->subdec, m_decodeSubtitleThread.get(), "subtitle_decoder");
  590. if (ret < 0) {
  591. qCWarning(playerControllerLog) << "Subtitle decoder start failed (error: " << ret << ")";
  592. return false;
  593. }
  594. return true;
  595. }
  596. bool PlayerController::createVideoPlayThread()
  597. {
  598. if (!m_videoState || m_videoPlayThread)
  599. return false;
  600. auto state = m_videoState->get_state();
  601. if (!state)
  602. return false;
  603. m_videoPlayThread = std::make_unique<VideoPlayThread>(state);
  604. m_videoPlayThread->setOnFinished([this]() { videoPlayStopped(); });
  605. m_videoPlayThread->setOnFrameReady([this](AVFrame* frame) { this->onFrameReady(frame); });
  606. m_videoPlayThread->setOnSubtitleReady([this](const QString& text) {
  607. // TODO: 实现 PlayerController::onSubtitleReady(const QString&) 处理字幕
  608. // onSubtitleReady(text);
  609. });
  610. // 初始化参数
  611. auto videoContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  612. const bool useHardware = m_videoState->is_hardware_decode();
  613. if (!m_videoPlayThread->init_resample_param(videoContext, useHardware)) {
  614. qCWarning(playerControllerLog) << "Video resample parameters initialization failed";
  615. return false;
  616. }
  617. return true;
  618. }
  619. bool PlayerController::createAudioPlayThread()
  620. {
  621. if (!m_videoState || m_audioPlayThread)
  622. return false;
  623. auto state = m_videoState->get_state();
  624. if (!state)
  625. return false;
  626. m_audioPlayThread = std::make_unique<AudioPlayThread>(state);
  627. m_audioPlayThread->setOnFinished([this]() { audioPlayStopped(); });
  628. m_audioPlayThread->setOnUpdatePlayTime([this]() {
  629. // TODO: 实现 PlayerController::onUpdatePlayTime() 处理播放时间更新
  630. // emit updatePlayTime();
  631. });
  632. m_audioPlayThread->setOnDataVisualReady([this](const AudioData& data) {
  633. // 异步 ?
  634. // emit audioData(data);
  635. });
  636. // 音频设备初始化在独立线程中完成
  637. return true;
  638. }
  639. bool PlayerController::startPlayThread()
  640. {
  641. if (m_beforePlayThread)
  642. return false;
  643. m_beforePlayThread = std::make_unique<StartPlayThread>(m_audioPlayThread.get(),
  644. m_videoState.get());
  645. m_beforePlayThread->setOnFinished([this]() {
  646. qCDebug(playerControllerLog) << "[StartPlayThread] finished, call playStarted()";
  647. playStarted();
  648. });
  649. m_beforePlayThread->start();
  650. qCDebug(playerControllerLog) << "++++++++++ StartPlay thread (audio init) started";
  651. return true;
  652. }
  653. // 调试辅助函数
  654. void PlayerController::printDecodeContext(const AVCodecContext* codecCtx, bool isVideo) const
  655. {
  656. if (!codecCtx)
  657. return;
  658. qCInfo(playerControllerLog) << (isVideo ? "Video" : "Audio")
  659. << " codec: " << codecCtx->codec->name;
  660. qCInfo(playerControllerLog) << " Type:" << codecCtx->codec_type << "ID:" << codecCtx->codec_id
  661. << "Tag:" << codecCtx->codec_tag;
  662. if (isVideo) {
  663. qCInfo(playerControllerLog)
  664. << " Dimensions: " << codecCtx->width << "x" << codecCtx->height;
  665. } else {
  666. qCInfo(playerControllerLog) << " Sample rate: " << codecCtx->sample_rate
  667. << " Hz, Channels: " << codecCtx->ch_layout.nb_channels
  668. << ", Format: " << codecCtx->sample_fmt;
  669. qCInfo(playerControllerLog) << " Frame size: " << codecCtx->frame_size
  670. << ", Block align: " << codecCtx->block_align;
  671. }
  672. }
  673. // 在合适位置实现 onFrameReady
  674. void PlayerController::onFrameReady(AVFrame* frame)
  675. {
  676. // 这里可以做帧处理、缓存、同步等操作
  677. emit frameReady(frame); // 直接转发给 UI 层
  678. }