playercontroller.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. qDebug() << "++++++++++ stopAndResetThreads";
  513. auto stopAndReset = [](auto& threadPtr, const QString& threadName) {
  514. if (threadPtr) {
  515. qCDebug(playerControllerLog)
  516. << "[stopAndReset] [" << threadName
  517. << "] try stop/join thread, isRunning=" << threadPtr->isRunning();
  518. threadPtr->stop();
  519. // 添加超时等待机制
  520. const int MAX_WAIT_MS = 500; // 最多等待500毫秒
  521. auto startTime = std::chrono::steady_clock::now();
  522. while (threadPtr->isRunning()) {
  523. auto now = std::chrono::steady_clock::now();
  524. auto elapsed
  525. = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
  526. if (elapsed > MAX_WAIT_MS) {
  527. qCWarning(playerControllerLog)
  528. << "[stopAndReset] [" << threadName << "] Thread stop timeout after"
  529. << elapsed << "ms";
  530. break;
  531. }
  532. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  533. }
  534. // 只有线程已停止才join
  535. if (!threadPtr->isRunning()) {
  536. threadPtr->join();
  537. qCDebug(playerControllerLog)
  538. << "[stopAndReset] [" << threadName << "] thread joined and will reset.";
  539. }
  540. threadPtr.reset();
  541. }
  542. };
  543. // 按依赖顺序停止线程
  544. stopAndReset(m_beforePlayThread, "BeforePlay");
  545. stopAndReset(m_videoPlayThread, "VideoPlay");
  546. stopAndReset(m_audioPlayThread, "AudioPlay");
  547. // 解码前先 关闭流 不然会卡死异常
  548. if (m_videoState) {
  549. m_videoState->delete_video_state();
  550. }
  551. // auto state = m_videoState->get_state();
  552. // if (state) {
  553. // state->abort_request = 1;
  554. // }
  555. stopAndReset(m_packetReadThread, "PacketRead");
  556. stopAndReset(m_decodeVideoThread, "DecodeVideo");
  557. stopAndReset(m_decodeAudioThread, "DecodeAudio");
  558. stopAndReset(m_decodeSubtitleThread, "DecodeSubtitle");
  559. }
  560. bool PlayerController::areAllThreadsStopped() const
  561. {
  562. // 检查所有线程是否已停止
  563. return (!m_packetReadThread || !m_packetReadThread->isRunning())
  564. && (!m_decodeVideoThread || !m_decodeVideoThread->isRunning())
  565. && (!m_decodeAudioThread || !m_decodeAudioThread->isRunning())
  566. && (!m_audioPlayThread || !m_audioPlayThread->isRunning())
  567. && (!m_videoPlayThread || !m_videoPlayThread->isRunning())
  568. && (!m_decodeSubtitleThread || !m_decodeSubtitleThread->isRunning());
  569. }
  570. void PlayerController::allThreadStart()
  571. {
  572. // 启动所有创建的线程
  573. if (m_packetReadThread) {
  574. if (!m_videoState || !m_videoState->get_state()) {
  575. qCWarning(playerControllerLog) << "VideoState invalid, skip starting read thread";
  576. } else {
  577. m_packetReadThread->start();
  578. }
  579. qCDebug(playerControllerLog) << "++++++++++ Read packets thread started";
  580. }
  581. if (m_decodeVideoThread) {
  582. m_decodeVideoThread->start();
  583. qCDebug(playerControllerLog) << "++++++++++ Video decode thread started";
  584. }
  585. if (m_decodeAudioThread) {
  586. m_decodeAudioThread->start();
  587. qCDebug(playerControllerLog) << "++++++++++ Audio decode thread started";
  588. }
  589. if (m_decodeSubtitleThread) {
  590. m_decodeSubtitleThread->start();
  591. qCDebug(playerControllerLog) << "++++++++++ Subtitle decode thread started";
  592. }
  593. if (m_videoPlayThread) {
  594. m_videoPlayThread->start();
  595. qCDebug(playerControllerLog) << "++++++++++ Video play thread started";
  596. }
  597. if (m_audioPlayThread) {
  598. m_audioPlayThread->start();
  599. qCDebug(playerControllerLog) << "++++++++++ Audio play thread started";
  600. }
  601. // 通知UI更新
  602. emit setPlayControlWnd(true);
  603. emit updatePlayControlVolume();
  604. emit updatePlayControlStatus();
  605. }
  606. // 辅助函数
  607. void PlayerController::videoSeekInc(double increment)
  608. {
  609. if (!m_videoState)
  610. return;
  611. auto state = m_videoState->get_state();
  612. if (!state)
  613. return;
  614. double position = get_master_clock(state);
  615. if (std::isnan(position)) {
  616. position = static_cast<double>(state->seek_pos) / AV_TIME_BASE;
  617. }
  618. position += increment;
  619. videoSeek(position, increment);
  620. }
  621. // 线程创建方法
  622. bool PlayerController::createVideoState(const QString& file)
  623. {
  624. const bool useHardware = false; // 待实现:来自UI设置
  625. const bool loop = false; // 待实现:来自UI设置
  626. if (m_videoState)
  627. return false;
  628. m_videoState = std::make_unique<VideoStateData>(useHardware, loop);
  629. const int ret = m_videoState->create_video_state(file.toUtf8().constData());
  630. if (ret < 0) {
  631. m_videoState.reset();
  632. qCWarning(playerControllerLog) << "Video state creation failed (error: " << ret << ")";
  633. return false;
  634. }
  635. return true;
  636. }
  637. bool PlayerController::createReadThread()
  638. {
  639. if (m_packetReadThread)
  640. return false;
  641. m_packetReadThread = std::make_unique<ReadThread>(m_videoState ? m_videoState->get_state()
  642. : nullptr);
  643. m_packetReadThread->setOnFinished([this]() { readPacketStopped(); });
  644. return true;
  645. }
  646. bool PlayerController::createDecodeVideoThread()
  647. {
  648. if (!m_videoState || m_decodeVideoThread)
  649. return false;
  650. auto state = m_videoState->get_state();
  651. if (!state)
  652. return false;
  653. m_decodeVideoThread = std::make_unique<VideoDecodeThread>(state);
  654. m_decodeVideoThread->setOnFinished([this]() { decodeVideoStopped(); });
  655. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  656. // 初始化视频解码器
  657. int ret = decoder_init(&state->viddec,
  658. codecContext,
  659. &state->videoq,
  660. state->continue_read_thread);
  661. if (ret < 0) {
  662. qCWarning(playerControllerLog)
  663. << "Video decoder initialization failed (error: " << ret << ")";
  664. return false;
  665. }
  666. ret = decoder_start(&state->viddec, m_decodeVideoThread.get(), "video_decoder");
  667. if (ret < 0) {
  668. qCWarning(playerControllerLog) << "Video decoder start failed (error: " << ret << ")";
  669. return false;
  670. }
  671. state->queue_attachments_req = 1;
  672. return true;
  673. }
  674. bool PlayerController::createDecodeAudioThread()
  675. {
  676. if (!m_videoState || m_decodeAudioThread)
  677. return false;
  678. auto state = m_videoState->get_state();
  679. if (!state)
  680. return false;
  681. m_decodeAudioThread = std::make_unique<AudioDecodeThread>(state);
  682. m_decodeAudioThread->setOnFinished([this]() { decodeAudioStopped(); });
  683. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_AUDIO);
  684. // 初始化音频解码器
  685. int ret = decoder_init(&state->auddec,
  686. codecContext,
  687. &state->audioq,
  688. state->continue_read_thread);
  689. if (ret < 0) {
  690. qCWarning(playerControllerLog)
  691. << "Audio decoder initialization failed (error: " << ret << ")";
  692. return false;
  693. }
  694. ret = decoder_start(&state->auddec, m_decodeAudioThread.get(), "audio_decoder");
  695. if (ret < 0) {
  696. qCWarning(playerControllerLog) << "Audio decoder start failed (error: " << ret << ")";
  697. return false;
  698. }
  699. return true;
  700. }
  701. bool PlayerController::createDecodeSubtitleThread()
  702. {
  703. if (!m_videoState || m_decodeSubtitleThread)
  704. return false;
  705. auto state = m_videoState->get_state();
  706. if (!state)
  707. return false;
  708. m_decodeSubtitleThread = std::make_unique<SubtitleDecodeThread>(state);
  709. m_decodeSubtitleThread->setOnFinished([this]() { decodeSubtitleStopped(); });
  710. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_SUBTITLE);
  711. // 初始化字幕解码器
  712. int ret = decoder_init(&state->subdec,
  713. codecContext,
  714. &state->subtitleq,
  715. state->continue_read_thread);
  716. if (ret < 0) {
  717. qCWarning(playerControllerLog)
  718. << "Subtitle decoder initialization failed (error: " << ret << ")";
  719. return false;
  720. }
  721. ret = decoder_start(&state->subdec, m_decodeSubtitleThread.get(), "subtitle_decoder");
  722. if (ret < 0) {
  723. qCWarning(playerControllerLog) << "Subtitle decoder start failed (error: " << ret << ")";
  724. return false;
  725. }
  726. return true;
  727. }
  728. bool PlayerController::createVideoPlayThread()
  729. {
  730. if (!m_videoState || m_videoPlayThread)
  731. return false;
  732. auto state = m_videoState->get_state();
  733. if (!state)
  734. return false;
  735. m_videoPlayThread = std::make_unique<VideoPlayThread>(state);
  736. m_videoPlayThread->setOnFinished([this]() { videoPlayStopped(); });
  737. m_videoPlayThread->setOnFrameReady([this](AVFrame* frame) { this->onFrameReady(frame); });
  738. m_videoPlayThread->setOnSubtitleReady([this](const QString& text) {
  739. // TODO: 实现 PlayerController::onSubtitleReady(const QString&) 处理字幕
  740. // onSubtitleReady(text);
  741. });
  742. // 初始化参数
  743. auto videoContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  744. const bool useHardware = m_videoState->is_hardware_decode();
  745. if (!m_videoPlayThread->init_resample_param(videoContext, useHardware)) {
  746. qCWarning(playerControllerLog) << "Video resample parameters initialization failed";
  747. return false;
  748. }
  749. return true;
  750. }
  751. bool PlayerController::createAudioPlayThread()
  752. {
  753. if (!m_videoState || m_audioPlayThread)
  754. return false;
  755. auto state = m_videoState->get_state();
  756. if (!state)
  757. return false;
  758. m_audioPlayThread = std::make_unique<AudioPlayThread>(state);
  759. m_audioPlayThread->setOnFinished([this]() { audioPlayStopped(); });
  760. m_audioPlayThread->setOnUpdatePlayTime([this]() {
  761. // TODO: 实现 PlayerController::onUpdatePlayTime() 处理播放时间更新
  762. emit updatePlayTime();
  763. });
  764. m_audioPlayThread->setOnDataVisualReady([this](const AudioData& data) {
  765. // 异步 ?
  766. emit audioData(data);
  767. });
  768. // 音频设备初始化在独立线程中完成
  769. return true;
  770. }
  771. bool PlayerController::startPlayThread()
  772. {
  773. if (m_beforePlayThread)
  774. return false;
  775. m_beforePlayThread = std::make_unique<StartPlayThread>(m_audioPlayThread.get(),
  776. m_videoState.get());
  777. m_beforePlayThread->setOnFinished([this]() {
  778. qCDebug(playerControllerLog) << "[StartPlayThread] finished, call playStarted()";
  779. playStarted();
  780. });
  781. m_beforePlayThread->start();
  782. qCDebug(playerControllerLog) << "++++++++++ StartPlay thread (audio init) started";
  783. return true;
  784. }
  785. // 调试辅助函数
  786. void PlayerController::printDecodeContext(const AVCodecContext* codecCtx, bool isVideo) const
  787. {
  788. if (!codecCtx)
  789. return;
  790. qCInfo(playerControllerLog) << (isVideo ? "Video" : "Audio")
  791. << " codec: " << codecCtx->codec->name;
  792. qCInfo(playerControllerLog) << " Type:" << codecCtx->codec_type << "ID:" << codecCtx->codec_id
  793. << "Tag:" << codecCtx->codec_tag;
  794. if (isVideo) {
  795. qCInfo(playerControllerLog)
  796. << " Dimensions: " << codecCtx->width << "x" << codecCtx->height;
  797. } else {
  798. qCInfo(playerControllerLog) << " Sample rate: " << codecCtx->sample_rate
  799. << " Hz, Channels: " << codecCtx->ch_layout.nb_channels
  800. << ", Format: " << codecCtx->sample_fmt;
  801. qCInfo(playerControllerLog) << " Frame size: " << codecCtx->frame_size
  802. << ", Block align: " << codecCtx->block_align;
  803. }
  804. }
  805. // 在合适位置实现 onFrameReady
  806. void PlayerController::onFrameReady(AVFrame* frame)
  807. {
  808. // 这里可以做帧处理、缓存、同步等操作
  809. emit frameReady(frame); // 直接转发给 UI 层
  810. }
  811. void PlayerController::dump() const
  812. {
  813. qCInfo(playerControllerLog) << "=== PlayerController Thread Status Dump ===";
  814. qCInfo(playerControllerLog) << "Current State:" << static_cast<int>(m_state.load());
  815. qCInfo(playerControllerLog) << "Current File:" << m_currentFile;
  816. // 检查数据包读取线程
  817. if (m_packetReadThread) {
  818. qCInfo(playerControllerLog)
  819. << "ReadThread: exists, isRunning:" << m_packetReadThread->isRunning()
  820. << ", isFinished:" << m_packetReadThread->isExit();
  821. } else {
  822. qCInfo(playerControllerLog) << "ReadThread: null";
  823. }
  824. // 检查视频解码线程
  825. if (m_decodeVideoThread) {
  826. qCInfo(playerControllerLog)
  827. << "VideoDecodeThread: exists, isRunning:" << m_decodeVideoThread->isRunning()
  828. << ", isFinished:" << m_decodeVideoThread->isExit();
  829. } else {
  830. qCInfo(playerControllerLog) << "VideoDecodeThread: null";
  831. }
  832. // 检查音频解码线程
  833. if (m_decodeAudioThread) {
  834. qCInfo(playerControllerLog)
  835. << "AudioDecodeThread: exists, isRunning:" << m_decodeAudioThread->isRunning()
  836. << ", isFinished:" << m_decodeAudioThread->isExit();
  837. } else {
  838. qCInfo(playerControllerLog) << "AudioDecodeThread: null";
  839. }
  840. // 检查字幕解码线程
  841. if (m_decodeSubtitleThread) {
  842. qCInfo(playerControllerLog)
  843. << "SubtitleDecodeThread: exists, isRunning:" << m_decodeSubtitleThread->isRunning()
  844. << ", isFinished:" << m_decodeSubtitleThread->isExit();
  845. } else {
  846. qCInfo(playerControllerLog) << "SubtitleDecodeThread: null";
  847. }
  848. // 检查音频播放线程
  849. if (m_audioPlayThread) {
  850. qCInfo(playerControllerLog)
  851. << "AudioPlayThread: exists, isRunning:" << m_audioPlayThread->isRunning()
  852. << ", isFinished:" << m_audioPlayThread->isExit();
  853. } else {
  854. qCInfo(playerControllerLog) << "AudioPlayThread: null";
  855. }
  856. // 检查视频播放线程
  857. if (m_videoPlayThread) {
  858. qCInfo(playerControllerLog)
  859. << "VideoPlayThread: exists, isRunning:" << m_videoPlayThread->isRunning()
  860. << ", isFinished:" << m_videoPlayThread->isExit();
  861. } else {
  862. qCInfo(playerControllerLog) << "VideoPlayThread: null";
  863. }
  864. // 检查播放前准备线程
  865. if (m_beforePlayThread) {
  866. qCInfo(playerControllerLog)
  867. << "StartPlayThread: exists, isRunning:" << m_beforePlayThread->isRunning()
  868. << ", isFinished:" << m_beforePlayThread->isExit();
  869. } else {
  870. qCInfo(playerControllerLog) << "StartPlayThread: null";
  871. }
  872. // 检查初始化线程
  873. if (m_initThread.joinable()) {
  874. qCInfo(playerControllerLog) << "InitThread: joinable (running)";
  875. } else {
  876. qCInfo(playerControllerLog) << "InitThread: not joinable (stopped or not started)";
  877. }
  878. // 检查事件线程
  879. if (m_eventThread.joinable()) {
  880. qCInfo(playerControllerLog) << "EventThread: joinable (running)";
  881. } else {
  882. qCInfo(playerControllerLog) << "EventThread: not joinable (stopped or not started)";
  883. }
  884. qCInfo(playerControllerLog) << "=== End of Thread Status Dump ===";
  885. }