playercontroller.cpp 33 KB

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