playercontroller.cpp 23 KB

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