playercontroller.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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.load();
  35. QString currentFile;
  36. // 快速状态检查,避免不必要的锁竞争
  37. if (currentState == PlayerState::Initializing) {
  38. qCDebug(playerControllerLog) << "Player is initializing. Ignoring request.";
  39. return;
  40. }
  41. // 获取当前文件名(需要锁保护)
  42. {
  43. std::lock_guard<std::mutex> lock(m_stopMutex);
  44. currentFile = m_currentFile;
  45. currentState = m_state.load();
  46. // 自愈:如果状态为Playing但所有线程都已退出,标记需要重置
  47. if (currentState == PlayerState::Playing && areAllThreadsStopped()) {
  48. qCDebug(playerControllerLog)
  49. << "[PlayerController] All threads stopped, will force reset to Idle.";
  50. // 不在锁内调用stopAndResetThreads,避免死锁
  51. currentState = PlayerState::Idle; // 标记需要重置
  52. }
  53. }
  54. // 正在播放中,需要先停止
  55. if (currentState == PlayerState::Playing) {
  56. qCDebug(playerControllerLog)
  57. << "Player is busy, stopping and switching to:" << file;
  58. // 在锁外调用stopPlay,避免死锁
  59. stopPlay();
  60. currentState = PlayerState::Idle;
  61. }
  62. // 空闲状态,开始新播放
  63. if (currentState == PlayerState::Idle) {
  64. // 使用原子操作尝试设置状态
  65. PlayerState expected = PlayerState::Idle;
  66. if (!m_state.compare_exchange_strong(expected, PlayerState::Initializing)) {
  67. qCDebug(playerControllerLog) << "State changed during initialization attempt. Current state:" << (int)expected;
  68. return;
  69. }
  70. // 状态已成功设置为Initializing,现在可以安全地进行初始化
  71. {
  72. std::lock_guard<std::mutex> lock(m_stopMutex);
  73. // 确保所有线程已停止
  74. if (!areAllThreadsStopped()) {
  75. qCDebug(playerControllerLog) << "Some threads still running, stopping them first";
  76. stopAndResetThreads();
  77. }
  78. // 重置状态
  79. m_videoState.reset();
  80. m_currentFile = file;
  81. }
  82. qCDebug(playerControllerLog) << "Player is idle. Starting playback for:" << file;
  83. // 直接进行初始化,无需异步
  84. bool success = !file.isEmpty();
  85. onAsyncInitFinished(file, success);
  86. }
  87. }
  88. void PlayerController::onAsyncInitFinished(const QString& file, bool success)
  89. {
  90. // 移除互斥锁,避免与stopPlay产生死锁
  91. QElapsedTimer timer;
  92. timer.start();
  93. // 初始化失败处理
  94. if (!success) {
  95. playFailed(m_currentFile);
  96. m_state = PlayerState::Idle;
  97. return;
  98. }
  99. // 创建视频状态对象
  100. qCDebug(playerControllerLog) << "[Init] createVideoState...";
  101. if (!createVideoState(m_currentFile)) {
  102. qCWarning(playerControllerLog) << "Video state creation failed";
  103. readPacketStopped();
  104. playFailed(m_currentFile);
  105. m_state = PlayerState::Idle;
  106. return;
  107. }
  108. // 检查状态有效性
  109. assert(m_videoState);
  110. if (!m_videoState) {
  111. qCWarning(playerControllerLog) << "Video state initialization error";
  112. playFailed(m_currentFile);
  113. m_state = PlayerState::Idle;
  114. return;
  115. }
  116. // 创建数据包读取线程
  117. qCDebug(playerControllerLog) << "[Init] createReadThread...";
  118. if (!createReadThread()) {
  119. qCWarning(playerControllerLog) << "Packet read thread creation failed";
  120. playFailed(m_currentFile);
  121. m_state = PlayerState::Idle;
  122. return;
  123. }
  124. // 设置视频状态
  125. m_packetReadThread->set_video_state(m_videoState->get_state());
  126. // 检查媒体流类型
  127. const bool hasVideo = playingHasVideo();
  128. const bool hasAudio = playingHasAudio();
  129. const bool hasSubtitle = playingHasSubtitle();
  130. // 创建视频相关线程
  131. if (hasVideo) {
  132. if (!createDecodeVideoThread() || !createVideoPlayThread()) {
  133. qCWarning(playerControllerLog) << "Video processing setup failed";
  134. playFailed(m_currentFile);
  135. stopPlay();
  136. m_state = PlayerState::Idle;
  137. return;
  138. }
  139. }
  140. // 创建音频相关线程
  141. if (hasAudio) {
  142. if (!createDecodeAudioThread() || !createAudioPlayThread()) {
  143. qCWarning(playerControllerLog) << "Audio processing setup failed";
  144. playFailed(m_currentFile);
  145. stopPlay();
  146. m_state = PlayerState::Idle;
  147. return;
  148. }
  149. }
  150. // 创建字幕线程
  151. if (hasSubtitle && !createDecodeSubtitleThread()) {
  152. qCWarning(playerControllerLog) << "Subtitle processing setup failed";
  153. playFailed(m_currentFile);
  154. stopPlay();
  155. m_state = PlayerState::Idle;
  156. return;
  157. }
  158. // 开始播放
  159. if (hasAudio) {
  160. startPlayThread(); // 异步启动(处理音频设备初始化)
  161. } else {
  162. playStarted(); // 同步启动(无音频流)
  163. }
  164. emit startToPlaySignal();
  165. m_state = PlayerState::Playing;
  166. qCDebug(playerControllerLog) << "Playback initialized in " << timer.elapsed() << " ms";
  167. }
  168. void PlayerController::stopPlay()
  169. {
  170. // 使用原子操作检查状态,避免不必要的操作
  171. if (m_state.load() == PlayerState::Idle)
  172. return;
  173. qCDebug(playerControllerLog) << "Stopping playback...";
  174. m_state = PlayerState::Stopping;
  175. // 停止并重置所有线程
  176. stopAndResetThreads();
  177. // 清理视频状态
  178. {
  179. std::lock_guard<std::mutex> lock(m_stopMutex);
  180. m_videoState.reset();
  181. m_currentFile.clear();
  182. }
  183. m_state = PlayerState::Idle;
  184. qCDebug(playerControllerLog) << "Playback stopped.";
  185. }
  186. void PlayerController::pausePlay()
  187. {
  188. if (!m_videoState)
  189. return;
  190. if (auto state = m_videoState->get_state())
  191. toggle_pause(state, !state->paused);
  192. emit updatePlayControlStatus();
  193. }
  194. void PlayerController::playMute(bool mute)
  195. {
  196. if (!m_videoState)
  197. return;
  198. if (auto state = m_videoState->get_state())
  199. toggle_mute(state, mute);
  200. }
  201. void PlayerController::playStartSeek()
  202. {
  203. pausePlay();
  204. }
  205. void PlayerController::playSeekPre()
  206. {
  207. videoSeekInc(-0.5); // 将步长从2秒减小到0.5秒,提高精度
  208. }
  209. void PlayerController::playSeekNext()
  210. {
  211. videoSeekInc(0.5); // 将步长从2秒减小到0.5秒,提高精度
  212. }
  213. void PlayerController::setVolume(int volume, int maxValue)
  214. {
  215. if (!m_audioPlayThread)
  216. return;
  217. const float vol = static_cast<float>(volume) / maxValue;
  218. m_audioPlayThread->set_device_volume(vol);
  219. }
  220. void PlayerController::setPlaySpeed(double speed)
  221. {
  222. if (m_videoState) {
  223. if (auto state = m_videoState->get_state()) {
  224. #if USE_AVFILTER_AUDIO
  225. set_audio_playspeed(state, speed);
  226. #endif
  227. }
  228. }
  229. }
  230. // 状态访问接口
  231. QString PlayerController::playingFile() const
  232. {
  233. return isPlaying() ? m_currentFile : QString();
  234. }
  235. bool PlayerController::isPlaying() const
  236. {
  237. // 使用原子操作获取状态,避免竞态条件
  238. PlayerState currentState = m_state.load();
  239. // 不仅检查状态标志,还检查线程是否实际运行
  240. if (currentState != PlayerState::Playing) {
  241. return false;
  242. }
  243. // 如果状态是Playing但所有线程都已停止,则实际上不是在播放状态
  244. // 使用锁保护线程状态检查,确保一致性
  245. std::lock_guard<std::mutex> lock(m_stopMutex);
  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 = 0.0;
  369. double min_position = 0.0;
  370. // 安全地计算最大位置
  371. if (state->ic->duration > 0) {
  372. max_position = state->ic->duration / static_cast<double>(AV_TIME_BASE);
  373. if (state->ic->start_time != AV_NOPTS_VALUE && state->ic->start_time > 0) {
  374. min_position = state->ic->start_time / static_cast<double>(AV_TIME_BASE);
  375. max_position += min_position;
  376. }
  377. } else {
  378. qCWarning(playerControllerLog) << "[videoSeek] Invalid duration, seek operation cancelled";
  379. return;
  380. }
  381. qCDebug(playerControllerLog) << "[videoSeek] 边界检查: position=" << position
  382. << ", min_position=" << min_position
  383. << ", max_position=" << max_position
  384. << ", duration=" << state->ic->duration
  385. << ", start_time=" << state->ic->start_time;
  386. // 更严格的边界检查:减去5秒作为安全边界,并确保不小于最小位置
  387. double safe_boundary = 5.0;
  388. if (position < min_position) {
  389. qCDebug(playerControllerLog) << "[videoSeek] 调整seek位置到最小值: 原始position=" << position;
  390. position = min_position;
  391. } else if (position > max_position - safe_boundary) {
  392. qCDebug(playerControllerLog) << "[videoSeek] 调整seek位置到安全范围: 原始position=" << position
  393. << ", 最大position=" << max_position;
  394. position = std::max(min_position, max_position - safe_boundary);
  395. }
  396. qCDebug(playerControllerLog) << "[videoSeek] 最终position=" << position;
  397. // 添加量化操作,精确到0.01秒
  398. qCDebug(playerControllerLog) << "[videoSeek] position:" << position
  399. << "position * AV_TIME_BASE:" << static_cast<int64_t>(position * AV_TIME_BASE)
  400. << "increment * AV_TIME_BASE:" << static_cast<int64_t>(increment * AV_TIME_BASE);
  401. // 启用精确帧定位
  402. int64_t target_pts = static_cast<int64_t>(position * AV_TIME_BASE);
  403. // if (state->video_st) {
  404. // // 将目标时间转换为视频流的时间基准
  405. // target_pts = av_rescale_q(target_pts,
  406. // AV_TIME_BASE_Q,
  407. // state->video_st->time_base);
  408. // qDebug() << "[精确帧定位] 设置目标PTS:" << target_pts
  409. // << "原始位置(秒):" << position
  410. // << "视频时间基准:" << state->video_st->time_base.num << "/" << state->video_st->time_base.den;
  411. // state->exact_seek = 1;
  412. // state->target_pts = target_pts;
  413. // }
  414. stream_seek(state,
  415. static_cast<int64_t>(position * AV_TIME_BASE),
  416. static_cast<int64_t>(increment * AV_TIME_BASE),
  417. 0);
  418. }
  419. void PlayerController::videoSeekEx(double value, double maxValue)
  420. {
  421. if (!m_videoState)
  422. return;
  423. auto state = m_videoState->get_state();
  424. if (!state)
  425. return;
  426. auto cur_stream = state;
  427. auto x = value;
  428. double frac;
  429. if (m_videoState->seekByBytes() || cur_stream->ic->duration <= 0) {
  430. uint64_t size = avio_size(cur_stream->ic->pb);
  431. stream_seek(cur_stream, size * x / maxValue, 0, 1);
  432. } else {
  433. int64_t ts;
  434. int ns, hh, mm, ss;
  435. int tns, thh, tmm, tss;
  436. tns = cur_stream->ic->duration / 1000000LL;
  437. thh = tns / 3600;
  438. tmm = (tns % 3600) / 60;
  439. tss = (tns % 60);
  440. frac = x / maxValue;
  441. ns = frac * tns;
  442. hh = ns / 3600;
  443. mm = (ns % 3600) / 60;
  444. ss = (ns % 60);
  445. av_log(NULL,
  446. AV_LOG_INFO,
  447. "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n",
  448. frac * 100,
  449. hh,
  450. mm,
  451. ss,
  452. thh,
  453. tmm,
  454. tss);
  455. qDebug("Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)",
  456. frac * 100,
  457. hh,
  458. mm,
  459. ss,
  460. thh,
  461. tmm,
  462. tss);
  463. ts = frac * cur_stream->ic->duration;
  464. if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
  465. ts += cur_stream->ic->start_time;
  466. // 增强的边界检查:防止seek到超出视频时长的位置
  467. int64_t max_ts = 0;
  468. int64_t min_ts = 0;
  469. // 安全地计算时间戳边界
  470. if (cur_stream->ic->duration > 0) {
  471. max_ts = cur_stream->ic->duration;
  472. if (cur_stream->ic->start_time != AV_NOPTS_VALUE && cur_stream->ic->start_time > 0) {
  473. min_ts = cur_stream->ic->start_time;
  474. max_ts += min_ts;
  475. }
  476. } else {
  477. qCWarning(playerControllerLog) << "[videoSeekEx] Invalid duration, seek operation cancelled";
  478. return;
  479. }
  480. qCDebug(playerControllerLog) << "[videoSeekEx] 边界检查: ts=" << ts
  481. << ", min_ts=" << min_ts << ", max_ts=" << max_ts
  482. << ", duration=" << cur_stream->ic->duration
  483. << ", start_time=" << cur_stream->ic->start_time
  484. << ", 请求位置(秒)=" << ts / (double) AV_TIME_BASE
  485. << ", 最大位置(秒)=" << max_ts / (double) AV_TIME_BASE;
  486. // 更严格的边界检查:减去5秒作为安全边界
  487. int64_t safe_boundary = 5 * AV_TIME_BASE;
  488. if (ts < min_ts) {
  489. qCDebug(playerControllerLog) << "[videoSeekEx] 调整seek位置到最小值: 原始ts=" << ts;
  490. ts = min_ts;
  491. } else if (ts > max_ts - safe_boundary) {
  492. qCDebug(playerControllerLog) << "[videoSeekEx] 调整seek位置到安全范围: 原始ts=" << ts << ", 最大ts=" << max_ts;
  493. ts = std::max(min_ts, max_ts - safe_boundary);
  494. }
  495. qCDebug(playerControllerLog) << "[videoSeekEx] 最终ts=" << ts
  496. << ", 最终位置(秒)=" << ts / (double) AV_TIME_BASE;
  497. // // 启用精确帧定位
  498. // if (cur_stream->video_st) {
  499. // int64_t target_pts = av_rescale_q(ts,
  500. // AV_TIME_BASE_Q,
  501. // cur_stream->video_st->time_base);
  502. // qDebug() << "[精确帧定位Ex] 设置目标PTS:" << target_pts
  503. // << "原始位置(秒):" << ts / (double)AV_TIME_BASE
  504. // << "视频时间基准:" << cur_stream->video_st->time_base.num << "/" << cur_stream->video_st->time_base.den;
  505. // state->exact_seek = 1;
  506. // state->target_pts = target_pts;
  507. // }
  508. stream_seek(cur_stream, ts, 0, 0);
  509. }
  510. return;
  511. }
  512. // 线程管理辅助方法
  513. void PlayerController::stopAndResetThreads()
  514. {
  515. qDebug() << "++++++++++ stopAndResetThreads";
  516. auto stopAndReset = [](auto& threadPtr, const QString& threadName) {
  517. if (threadPtr) {
  518. qCDebug(playerControllerLog)
  519. << "[stopAndReset] [" << threadName
  520. << "] try stop/join thread, isRunning=" << threadPtr->isRunning();
  521. threadPtr->stop();
  522. // 增加超时等待时间,以便更好地处理FFmpeg清理
  523. const int MAX_WAIT_MS = 3000; // 增加到3秒,给FFmpeg足够的清理时间
  524. auto startTime = std::chrono::steady_clock::now();
  525. while (threadPtr->isRunning()) {
  526. auto now = std::chrono::steady_clock::now();
  527. auto elapsed
  528. = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
  529. if (elapsed > MAX_WAIT_MS) {
  530. qCWarning(playerControllerLog)
  531. << "[stopAndReset] [" << threadName << "] Thread stop timeout after"
  532. << elapsed << "ms - forcing termination";
  533. break;
  534. }
  535. // 减少轮询频率,降低CPU占用
  536. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  537. }
  538. // 只有线程已停止才join
  539. if (!threadPtr->isRunning()) {
  540. threadPtr->join();
  541. qCDebug(playerControllerLog)
  542. << "[stopAndReset] [" << threadName << "] thread joined and will reset.";
  543. }
  544. threadPtr.reset();
  545. }
  546. };
  547. // 优化线程停止顺序:先停止播放线程,然后清理FFmpeg状态,再停止解码线程,最后停止读取线程
  548. // 这样确保解码线程在FFmpeg资源清理后能正常退出
  549. // 第一阶段:停止播放线程
  550. stopAndReset(m_beforePlayThread, "BeforePlay");
  551. stopAndReset(m_videoPlayThread, "VideoPlay");
  552. stopAndReset(m_audioPlayThread, "AudioPlay");
  553. // 第二阶段:清理FFmpeg状态(关键修复:在解码线程停止前清理)
  554. // 这样解码线程就能检测到状态变化并正常退出
  555. if (m_videoState && m_videoState->get_state()) {
  556. qCDebug(playerControllerLog) << "[stopAndResetThreads] Cleaning up FFmpeg video state before stopping decode threads";
  557. m_videoState->delete_video_state();
  558. // 给解码线程一点时间检测到FFmpeg状态变化
  559. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  560. qCDebug(playerControllerLog) << "[stopAndResetThreads] FFmpeg state cleaned, proceeding to stop decode threads";
  561. }
  562. // 第三阶段:停止解码线程(现在FFmpeg状态已清理,线程应该能正常退出)
  563. stopAndReset(m_decodeVideoThread, "DecodeVideo");
  564. stopAndReset(m_decodeAudioThread, "DecodeAudio");
  565. stopAndReset(m_decodeSubtitleThread, "DecodeSubtitle");
  566. // 第四阶段:停止读取线程
  567. stopAndReset(m_packetReadThread, "PacketRead");
  568. }
  569. bool PlayerController::areAllThreadsStopped() const
  570. {
  571. // 检查所有线程是否已停止
  572. // 注意:此方法应在持有m_stopMutex锁的情况下调用,以确保线程状态的一致性
  573. bool allStopped = (!m_packetReadThread || !m_packetReadThread->isRunning())
  574. && (!m_decodeVideoThread || !m_decodeVideoThread->isRunning())
  575. && (!m_decodeAudioThread || !m_decodeAudioThread->isRunning())
  576. && (!m_audioPlayThread || !m_audioPlayThread->isRunning())
  577. && (!m_videoPlayThread || !m_videoPlayThread->isRunning())
  578. && (!m_decodeSubtitleThread || !m_decodeSubtitleThread->isRunning())
  579. && (!m_beforePlayThread || !m_beforePlayThread->isRunning());
  580. return allStopped;
  581. }
  582. void PlayerController::allThreadStart()
  583. {
  584. // 启动所有创建的线程
  585. if (m_packetReadThread) {
  586. if (!m_videoState || !m_videoState->get_state()) {
  587. qCWarning(playerControllerLog) << "VideoState invalid, skip starting read thread";
  588. } else {
  589. m_packetReadThread->start();
  590. }
  591. qCDebug(playerControllerLog) << "++++++++++ Read packets thread started";
  592. }
  593. if (m_decodeVideoThread) {
  594. m_decodeVideoThread->start();
  595. qCDebug(playerControllerLog) << "++++++++++ Video decode thread started";
  596. }
  597. if (m_decodeAudioThread) {
  598. m_decodeAudioThread->start();
  599. qCDebug(playerControllerLog) << "++++++++++ Audio decode thread started";
  600. }
  601. if (m_decodeSubtitleThread) {
  602. m_decodeSubtitleThread->start();
  603. qCDebug(playerControllerLog) << "++++++++++ Subtitle decode thread started";
  604. }
  605. if (m_videoPlayThread) {
  606. m_videoPlayThread->start();
  607. qCDebug(playerControllerLog) << "++++++++++ Video play thread started";
  608. }
  609. if (m_audioPlayThread) {
  610. m_audioPlayThread->start();
  611. qCDebug(playerControllerLog) << "++++++++++ Audio play thread started";
  612. }
  613. // 通知UI更新
  614. emit setPlayControlWnd(true);
  615. emit updatePlayControlVolume();
  616. emit updatePlayControlStatus();
  617. }
  618. // 辅助函数
  619. void PlayerController::videoSeekInc(double increment)
  620. {
  621. if (!m_videoState)
  622. return;
  623. auto state = m_videoState->get_state();
  624. if (!state)
  625. return;
  626. double position = get_master_clock(state);
  627. if (std::isnan(position)) {
  628. position = static_cast<double>(state->seek_pos) / AV_TIME_BASE;
  629. }
  630. position += increment;
  631. videoSeek(position, increment);
  632. }
  633. // 线程创建方法
  634. bool PlayerController::createVideoState(const QString& file)
  635. {
  636. const bool useHardware = false; // 待实现:来自UI设置
  637. const bool loop = false; // 待实现:来自UI设置
  638. if (m_videoState)
  639. return false;
  640. m_videoState = std::make_unique<VideoStateData>(useHardware, loop);
  641. const int ret = m_videoState->create_video_state(file.toUtf8().constData());
  642. if (ret < 0) {
  643. m_videoState.reset();
  644. qCWarning(playerControllerLog) << "Video state creation failed (error: " << ret << ")";
  645. return false;
  646. }
  647. return true;
  648. }
  649. bool PlayerController::createReadThread()
  650. {
  651. if (m_packetReadThread)
  652. return false;
  653. m_packetReadThread = std::make_unique<ReadThread>(m_videoState ? m_videoState->get_state()
  654. : nullptr);
  655. m_packetReadThread->setOnFinished([this]() { readPacketStopped(); });
  656. return true;
  657. }
  658. bool PlayerController::createDecodeVideoThread()
  659. {
  660. if (!m_videoState || m_decodeVideoThread)
  661. return false;
  662. auto state = m_videoState->get_state();
  663. if (!state)
  664. return false;
  665. m_decodeVideoThread = std::make_unique<VideoDecodeThread>(state);
  666. m_decodeVideoThread->setOnFinished([this]() { decodeVideoStopped(); });
  667. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  668. // 初始化视频解码器
  669. int ret = decoder_init(&state->viddec,
  670. codecContext,
  671. &state->videoq,
  672. state->continue_read_thread);
  673. if (ret < 0) {
  674. qCWarning(playerControllerLog)
  675. << "Video decoder initialization failed (error: " << ret << ")";
  676. return false;
  677. }
  678. ret = decoder_start(&state->viddec, m_decodeVideoThread.get(), "video_decoder");
  679. if (ret < 0) {
  680. qCWarning(playerControllerLog) << "Video decoder start failed (error: " << ret << ")";
  681. return false;
  682. }
  683. state->queue_attachments_req = 1;
  684. return true;
  685. }
  686. bool PlayerController::createDecodeAudioThread()
  687. {
  688. if (!m_videoState || m_decodeAudioThread)
  689. return false;
  690. auto state = m_videoState->get_state();
  691. if (!state)
  692. return false;
  693. m_decodeAudioThread = std::make_unique<AudioDecodeThread>(state);
  694. m_decodeAudioThread->setOnFinished([this]() { decodeAudioStopped(); });
  695. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_AUDIO);
  696. // 初始化音频解码器
  697. int ret = decoder_init(&state->auddec,
  698. codecContext,
  699. &state->audioq,
  700. state->continue_read_thread);
  701. if (ret < 0) {
  702. qCWarning(playerControllerLog)
  703. << "Audio decoder initialization failed (error: " << ret << ")";
  704. return false;
  705. }
  706. ret = decoder_start(&state->auddec, m_decodeAudioThread.get(), "audio_decoder");
  707. if (ret < 0) {
  708. qCWarning(playerControllerLog) << "Audio decoder start failed (error: " << ret << ")";
  709. return false;
  710. }
  711. return true;
  712. }
  713. bool PlayerController::createDecodeSubtitleThread()
  714. {
  715. if (!m_videoState || m_decodeSubtitleThread)
  716. return false;
  717. auto state = m_videoState->get_state();
  718. if (!state)
  719. return false;
  720. m_decodeSubtitleThread = std::make_unique<SubtitleDecodeThread>(state);
  721. m_decodeSubtitleThread->setOnFinished([this]() { decodeSubtitleStopped(); });
  722. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_SUBTITLE);
  723. // 初始化字幕解码器
  724. int ret = decoder_init(&state->subdec,
  725. codecContext,
  726. &state->subtitleq,
  727. state->continue_read_thread);
  728. if (ret < 0) {
  729. qCWarning(playerControllerLog)
  730. << "Subtitle decoder initialization failed (error: " << ret << ")";
  731. return false;
  732. }
  733. ret = decoder_start(&state->subdec, m_decodeSubtitleThread.get(), "subtitle_decoder");
  734. if (ret < 0) {
  735. qCWarning(playerControllerLog) << "Subtitle decoder start failed (error: " << ret << ")";
  736. return false;
  737. }
  738. return true;
  739. }
  740. bool PlayerController::createVideoPlayThread()
  741. {
  742. if (!m_videoState || m_videoPlayThread)
  743. return false;
  744. auto state = m_videoState->get_state();
  745. if (!state)
  746. return false;
  747. m_videoPlayThread = std::make_unique<VideoPlayThread>(state);
  748. m_videoPlayThread->setOnFinished([this]() { videoPlayStopped(); });
  749. m_videoPlayThread->setOnFrameReady([this](AVFrame* frame) { this->onFrameReady(frame); });
  750. m_videoPlayThread->setOnSubtitleReady([](const QString& text) {
  751. // onSubtitleReady(text);
  752. });
  753. // 初始化参数
  754. auto videoContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  755. const bool useHardware = m_videoState->is_hardware_decode();
  756. if (!m_videoPlayThread->init_resample_param(videoContext, useHardware)) {
  757. qCWarning(playerControllerLog) << "Video resample parameters initialization failed";
  758. return false;
  759. }
  760. return true;
  761. }
  762. bool PlayerController::createAudioPlayThread()
  763. {
  764. if (!m_videoState || m_audioPlayThread)
  765. return false;
  766. auto state = m_videoState->get_state();
  767. if (!state)
  768. return false;
  769. m_audioPlayThread = std::make_unique<AudioPlayThread>(state);
  770. m_audioPlayThread->setOnFinished([this]() { audioPlayStopped(); });
  771. m_audioPlayThread->setOnUpdatePlayTime([this]() {
  772. // TODO: 实现 PlayerController::onUpdatePlayTime() 处理播放时间更新
  773. emit updatePlayTime();
  774. });
  775. m_audioPlayThread->setOnDataVisualReady([this](const AudioData& data) {
  776. // 异步 ?
  777. emit audioData(data);
  778. });
  779. // 音频设备初始化在独立线程中完成
  780. return true;
  781. }
  782. bool PlayerController::startPlayThread()
  783. {
  784. if (m_beforePlayThread)
  785. return false;
  786. m_beforePlayThread = std::make_unique<StartPlayThread>(m_audioPlayThread.get(),
  787. m_videoState.get());
  788. m_beforePlayThread->setOnFinished([this]() {
  789. qCDebug(playerControllerLog) << "[StartPlayThread] finished, call playStarted()";
  790. playStarted();
  791. });
  792. m_beforePlayThread->start();
  793. qCDebug(playerControllerLog) << "++++++++++ StartPlay thread (audio init) started";
  794. return true;
  795. }
  796. // 调试辅助函数
  797. void PlayerController::printDecodeContext(const AVCodecContext* codecCtx, bool isVideo) const
  798. {
  799. if (!codecCtx)
  800. return;
  801. qCInfo(playerControllerLog) << (isVideo ? "Video" : "Audio")
  802. << " codec: " << codecCtx->codec->name;
  803. qCInfo(playerControllerLog) << " Type:" << codecCtx->codec_type << "ID:" << codecCtx->codec_id
  804. << "Tag:" << codecCtx->codec_tag;
  805. if (isVideo) {
  806. qCInfo(playerControllerLog)
  807. << " Dimensions: " << codecCtx->width << "x" << codecCtx->height;
  808. } else {
  809. qCInfo(playerControllerLog) << " Sample rate: " << codecCtx->sample_rate
  810. << " Hz, Channels: " << codecCtx->ch_layout.nb_channels
  811. << ", Format: " << codecCtx->sample_fmt;
  812. qCInfo(playerControllerLog) << " Frame size: " << codecCtx->frame_size
  813. << ", Block align: " << codecCtx->block_align;
  814. }
  815. }
  816. // 在合适位置实现 onFrameReady
  817. void PlayerController::onFrameReady(AVFrame* frame)
  818. {
  819. // 这里可以做帧处理、缓存、同步等操作
  820. emit frameReady(frame); // 直接转发给 UI 层
  821. }
  822. void PlayerController::dump() const
  823. {
  824. qCInfo(playerControllerLog) << "=== PlayerController Thread Status Dump ===";
  825. qCInfo(playerControllerLog) << "Current State:" << static_cast<int>(m_state.load());
  826. qCInfo(playerControllerLog) << "Current File:" << m_currentFile;
  827. // 检查数据包读取线程
  828. if (m_packetReadThread) {
  829. qCInfo(playerControllerLog)
  830. << "ReadThread: exists, isRunning:" << m_packetReadThread->isRunning()
  831. << ", isFinished:" << m_packetReadThread->isExit();
  832. } else {
  833. qCInfo(playerControllerLog) << "ReadThread: null";
  834. }
  835. // 检查视频解码线程
  836. if (m_decodeVideoThread) {
  837. qCInfo(playerControllerLog)
  838. << "VideoDecodeThread: exists, isRunning:" << m_decodeVideoThread->isRunning()
  839. << ", isFinished:" << m_decodeVideoThread->isExit();
  840. } else {
  841. qCInfo(playerControllerLog) << "VideoDecodeThread: null";
  842. }
  843. // 检查音频解码线程
  844. if (m_decodeAudioThread) {
  845. qCInfo(playerControllerLog)
  846. << "AudioDecodeThread: exists, isRunning:" << m_decodeAudioThread->isRunning()
  847. << ", isFinished:" << m_decodeAudioThread->isExit();
  848. } else {
  849. qCInfo(playerControllerLog) << "AudioDecodeThread: null";
  850. }
  851. // 检查字幕解码线程
  852. if (m_decodeSubtitleThread) {
  853. qCInfo(playerControllerLog)
  854. << "SubtitleDecodeThread: exists, isRunning:" << m_decodeSubtitleThread->isRunning()
  855. << ", isFinished:" << m_decodeSubtitleThread->isExit();
  856. } else {
  857. qCInfo(playerControllerLog) << "SubtitleDecodeThread: null";
  858. }
  859. // 检查音频播放线程
  860. if (m_audioPlayThread) {
  861. qCInfo(playerControllerLog)
  862. << "AudioPlayThread: exists, isRunning:" << m_audioPlayThread->isRunning()
  863. << ", isFinished:" << m_audioPlayThread->isExit();
  864. } else {
  865. qCInfo(playerControllerLog) << "AudioPlayThread: null";
  866. }
  867. // 检查视频播放线程
  868. if (m_videoPlayThread) {
  869. qCInfo(playerControllerLog)
  870. << "VideoPlayThread: exists, isRunning:" << m_videoPlayThread->isRunning()
  871. << ", isFinished:" << m_videoPlayThread->isExit();
  872. } else {
  873. qCInfo(playerControllerLog) << "VideoPlayThread: null";
  874. }
  875. // 检查播放前准备线程
  876. if (m_beforePlayThread) {
  877. qCInfo(playerControllerLog)
  878. << "StartPlayThread: exists, isRunning:" << m_beforePlayThread->isRunning()
  879. << ", isFinished:" << m_beforePlayThread->isExit();
  880. } else {
  881. qCInfo(playerControllerLog) << "StartPlayThread: null";
  882. }
  883. // 检查事件线程
  884. if (m_eventThread.joinable()) {
  885. qCInfo(playerControllerLog) << "EventThread: joinable (running)";
  886. } else {
  887. qCInfo(playerControllerLog) << "EventThread: not joinable (stopped or not started)";
  888. }
  889. qCInfo(playerControllerLog) << "=== End of Thread Status Dump ===";
  890. }