playercontroller.cpp 33 KB

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