playercontroller.cpp 32 KB

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