playercontroller.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. auto state = m_videoState->get_state();
  324. // if (state) {
  325. // state->abort_request = 1;
  326. // }
  327. if (m_videoState && m_videoState->get_state()) {
  328. m_videoState->delete_video_state(); // stream_close
  329. }
  330. emit audioStopped();
  331. }
  332. void PlayerController::decodeVideoStopped()
  333. {
  334. dump();
  335. qCDebug(playerControllerLog) << "************* Video decode thread stopped.";
  336. }
  337. void PlayerController::decodeAudioStopped()
  338. {
  339. dump();
  340. qCDebug(playerControllerLog) << "************* Audio decode thread stopped.";
  341. }
  342. void PlayerController::decodeSubtitleStopped()
  343. {
  344. dump();
  345. qCDebug(playerControllerLog) << "************* Subtitle decode thread stopped.";
  346. }
  347. void PlayerController::audioPlayStopped()
  348. {
  349. dump();
  350. qCDebug(playerControllerLog) << "************* Audio play thread stopped.";
  351. emit audioStopped();
  352. }
  353. void PlayerController::videoPlayStopped()
  354. {
  355. dump();
  356. qCDebug(playerControllerLog) << "************* Video play thread stopped.";
  357. emit videoStopped();
  358. }
  359. // 线程管理槽函数
  360. void PlayerController::setThreads()
  361. {
  362. if (!m_videoState)
  363. return;
  364. Threads threads;
  365. threads.read_tid = m_packetReadThread.get();
  366. threads.video_decode_tid = m_decodeVideoThread.get();
  367. threads.audio_decode_tid = m_decodeAudioThread.get();
  368. threads.video_play_tid = m_videoPlayThread.get();
  369. threads.audio_play_tid = m_audioPlayThread.get();
  370. threads.subtitle_decode_tid = m_decodeSubtitleThread.get();
  371. m_videoState->threads_setting(m_videoState->get_state(), threads);
  372. }
  373. void PlayerController::startSendData(bool send)
  374. {
  375. if (m_audioPlayThread)
  376. m_audioPlayThread->send_visual_open(send);
  377. }
  378. void PlayerController::videoSeek(double position, double increment)
  379. {
  380. if (!m_videoState)
  381. return;
  382. auto state = m_videoState->get_state();
  383. if (!state)
  384. return;
  385. if (state->ic->start_time != AV_NOPTS_VALUE
  386. && position < state->ic->start_time / static_cast<double>(AV_TIME_BASE)) {
  387. position = state->ic->start_time / static_cast<double>(AV_TIME_BASE);
  388. }
  389. // 边界检查:防止seek到超出视频时长的位置
  390. double max_position = state->ic->duration / static_cast<double>(AV_TIME_BASE);
  391. if (state->ic->start_time != AV_NOPTS_VALUE)
  392. max_position += state->ic->start_time / static_cast<double>(AV_TIME_BASE);
  393. qDebug() << "[videoSeek] 边界检查: position=" << position << ", max_position=" << max_position
  394. << ", duration=" << state->ic->duration << ", start_time=" << state->ic->start_time;
  395. // 更保守的边界检查:减去3秒作为安全边界
  396. double safe_boundary = 3.0;
  397. if (position > max_position - safe_boundary) {
  398. qDebug() << "[videoSeek] 调整seek位置: 原始position=" << position
  399. << ", 最大position=" << max_position;
  400. position = max_position - safe_boundary;
  401. if (position < 0)
  402. position = 0;
  403. qDebug() << "[videoSeek] 调整后position=" << position;
  404. }
  405. // 添加量化操作,精确到0.01秒
  406. qDebug() << "position:" << position
  407. << "position * AV_TIME_BASE:" << static_cast<int64_t>(position * AV_TIME_BASE)
  408. << "increment * AV_TIME_BASE:" << static_cast<int64_t>(increment * AV_TIME_BASE);
  409. // 启用精确帧定位
  410. int64_t target_pts = static_cast<int64_t>(position * AV_TIME_BASE);
  411. // if (state->video_st) {
  412. // // 将目标时间转换为视频流的时间基准
  413. // target_pts = av_rescale_q(target_pts,
  414. // AV_TIME_BASE_Q,
  415. // state->video_st->time_base);
  416. // qDebug() << "[精确帧定位] 设置目标PTS:" << target_pts
  417. // << "原始位置(秒):" << position
  418. // << "视频时间基准:" << state->video_st->time_base.num << "/" << state->video_st->time_base.den;
  419. // state->exact_seek = 1;
  420. // state->target_pts = target_pts;
  421. // }
  422. stream_seek(state,
  423. static_cast<int64_t>(position * AV_TIME_BASE),
  424. static_cast<int64_t>(increment * AV_TIME_BASE),
  425. 0);
  426. }
  427. void PlayerController::videoSeekEx(double value, double maxValue)
  428. {
  429. if (!m_videoState)
  430. return;
  431. auto state = m_videoState->get_state();
  432. if (!state)
  433. return;
  434. auto cur_stream = state;
  435. auto x = value;
  436. double frac;
  437. if (m_videoState->seekByBytes() || cur_stream->ic->duration <= 0) {
  438. uint64_t size = avio_size(cur_stream->ic->pb);
  439. stream_seek(cur_stream, size * x / maxValue, 0, 1);
  440. } else {
  441. int64_t ts;
  442. int ns, hh, mm, ss;
  443. int tns, thh, tmm, tss;
  444. tns = cur_stream->ic->duration / 1000000LL;
  445. thh = tns / 3600;
  446. tmm = (tns % 3600) / 60;
  447. tss = (tns % 60);
  448. frac = x / maxValue;
  449. ns = frac * tns;
  450. hh = ns / 3600;
  451. mm = (ns % 3600) / 60;
  452. ss = (ns % 60);
  453. av_log(NULL,
  454. AV_LOG_INFO,
  455. "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n",
  456. frac * 100,
  457. hh,
  458. mm,
  459. ss,
  460. thh,
  461. tmm,
  462. tss);
  463. qDebug("Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)",
  464. frac * 100,
  465. hh,
  466. mm,
  467. ss,
  468. thh,
  469. tmm,
  470. tss);
  471. ts = frac * cur_stream->ic->duration;
  472. if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
  473. ts += cur_stream->ic->start_time;
  474. // 边界检查:防止seek到超出视频时长的位置
  475. int64_t max_ts = cur_stream->ic->duration;
  476. if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
  477. max_ts += cur_stream->ic->start_time;
  478. qDebug() << "[videoSeekEx] 边界检查: ts=" << ts << ", max_ts=" << max_ts
  479. << ", duration=" << cur_stream->ic->duration
  480. << ", start_time=" << cur_stream->ic->start_time
  481. << ", 请求位置(秒)=" << ts / (double) AV_TIME_BASE
  482. << ", 最大位置(秒)=" << max_ts / (double) AV_TIME_BASE;
  483. // 更保守的边界检查:减去3秒作为安全边界
  484. int64_t safe_boundary = 3 * AV_TIME_BASE;
  485. if (ts > max_ts - safe_boundary) {
  486. qDebug() << "[videoSeekEx] 调整seek位置: 原始ts=" << ts << ", 最大ts=" << max_ts;
  487. ts = max_ts - safe_boundary;
  488. if (ts < 0)
  489. ts = 0;
  490. qDebug() << "[videoSeekEx] 调整后ts=" << ts
  491. << ", 调整后位置(秒)=" << ts / (double) AV_TIME_BASE;
  492. }
  493. // // 启用精确帧定位
  494. // if (cur_stream->video_st) {
  495. // int64_t target_pts = av_rescale_q(ts,
  496. // AV_TIME_BASE_Q,
  497. // cur_stream->video_st->time_base);
  498. // qDebug() << "[精确帧定位Ex] 设置目标PTS:" << target_pts
  499. // << "原始位置(秒):" << ts / (double)AV_TIME_BASE
  500. // << "视频时间基准:" << cur_stream->video_st->time_base.num << "/" << cur_stream->video_st->time_base.den;
  501. // state->exact_seek = 1;
  502. // state->target_pts = target_pts;
  503. // }
  504. stream_seek(cur_stream, ts, 0, 0);
  505. }
  506. return;
  507. }
  508. // 线程管理辅助方法
  509. void PlayerController::stopAndResetThreads()
  510. {
  511. qDebug() << "++++++++++ stopAndResetThreads";
  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 && m_videoState->get_state()) {
  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. bool PlayerController::createReadThread()
  637. {
  638. if (m_packetReadThread)
  639. return false;
  640. m_packetReadThread = std::make_unique<ReadThread>(m_videoState ? m_videoState->get_state()
  641. : nullptr);
  642. m_packetReadThread->setOnFinished([this]() { readPacketStopped(); });
  643. return true;
  644. }
  645. bool PlayerController::createDecodeVideoThread()
  646. {
  647. if (!m_videoState || m_decodeVideoThread)
  648. return false;
  649. auto state = m_videoState->get_state();
  650. if (!state)
  651. return false;
  652. m_decodeVideoThread = std::make_unique<VideoDecodeThread>(state);
  653. m_decodeVideoThread->setOnFinished([this]() { decodeVideoStopped(); });
  654. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  655. // 初始化视频解码器
  656. int ret = decoder_init(&state->viddec,
  657. codecContext,
  658. &state->videoq,
  659. state->continue_read_thread);
  660. if (ret < 0) {
  661. qCWarning(playerControllerLog)
  662. << "Video decoder initialization failed (error: " << ret << ")";
  663. return false;
  664. }
  665. ret = decoder_start(&state->viddec, m_decodeVideoThread.get(), "video_decoder");
  666. if (ret < 0) {
  667. qCWarning(playerControllerLog) << "Video decoder start failed (error: " << ret << ")";
  668. return false;
  669. }
  670. state->queue_attachments_req = 1;
  671. return true;
  672. }
  673. bool PlayerController::createDecodeAudioThread()
  674. {
  675. if (!m_videoState || m_decodeAudioThread)
  676. return false;
  677. auto state = m_videoState->get_state();
  678. if (!state)
  679. return false;
  680. m_decodeAudioThread = std::make_unique<AudioDecodeThread>(state);
  681. m_decodeAudioThread->setOnFinished([this]() { decodeAudioStopped(); });
  682. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_AUDIO);
  683. // 初始化音频解码器
  684. int ret = decoder_init(&state->auddec,
  685. codecContext,
  686. &state->audioq,
  687. state->continue_read_thread);
  688. if (ret < 0) {
  689. qCWarning(playerControllerLog)
  690. << "Audio decoder initialization failed (error: " << ret << ")";
  691. return false;
  692. }
  693. ret = decoder_start(&state->auddec, m_decodeAudioThread.get(), "audio_decoder");
  694. if (ret < 0) {
  695. qCWarning(playerControllerLog) << "Audio decoder start failed (error: " << ret << ")";
  696. return false;
  697. }
  698. return true;
  699. }
  700. bool PlayerController::createDecodeSubtitleThread()
  701. {
  702. if (!m_videoState || m_decodeSubtitleThread)
  703. return false;
  704. auto state = m_videoState->get_state();
  705. if (!state)
  706. return false;
  707. m_decodeSubtitleThread = std::make_unique<SubtitleDecodeThread>(state);
  708. m_decodeSubtitleThread->setOnFinished([this]() { decodeSubtitleStopped(); });
  709. auto codecContext = m_videoState->get_contex(AVMEDIA_TYPE_SUBTITLE);
  710. // 初始化字幕解码器
  711. int ret = decoder_init(&state->subdec,
  712. codecContext,
  713. &state->subtitleq,
  714. state->continue_read_thread);
  715. if (ret < 0) {
  716. qCWarning(playerControllerLog)
  717. << "Subtitle decoder initialization failed (error: " << ret << ")";
  718. return false;
  719. }
  720. ret = decoder_start(&state->subdec, m_decodeSubtitleThread.get(), "subtitle_decoder");
  721. if (ret < 0) {
  722. qCWarning(playerControllerLog) << "Subtitle decoder start failed (error: " << ret << ")";
  723. return false;
  724. }
  725. return true;
  726. }
  727. bool PlayerController::createVideoPlayThread()
  728. {
  729. if (!m_videoState || m_videoPlayThread)
  730. return false;
  731. auto state = m_videoState->get_state();
  732. if (!state)
  733. return false;
  734. m_videoPlayThread = std::make_unique<VideoPlayThread>(state);
  735. m_videoPlayThread->setOnFinished([this]() { videoPlayStopped(); });
  736. m_videoPlayThread->setOnFrameReady([this](AVFrame* frame) { this->onFrameReady(frame); });
  737. m_videoPlayThread->setOnSubtitleReady([this](const QString& text) {
  738. // TODO: 实现 PlayerController::onSubtitleReady(const QString&) 处理字幕
  739. // onSubtitleReady(text);
  740. });
  741. // 初始化参数
  742. auto videoContext = m_videoState->get_contex(AVMEDIA_TYPE_VIDEO);
  743. const bool useHardware = m_videoState->is_hardware_decode();
  744. if (!m_videoPlayThread->init_resample_param(videoContext, useHardware)) {
  745. qCWarning(playerControllerLog) << "Video resample parameters initialization failed";
  746. return false;
  747. }
  748. return true;
  749. }
  750. bool PlayerController::createAudioPlayThread()
  751. {
  752. if (!m_videoState || m_audioPlayThread)
  753. return false;
  754. auto state = m_videoState->get_state();
  755. if (!state)
  756. return false;
  757. m_audioPlayThread = std::make_unique<AudioPlayThread>(state);
  758. m_audioPlayThread->setOnFinished([this]() { audioPlayStopped(); });
  759. m_audioPlayThread->setOnUpdatePlayTime([this]() {
  760. // TODO: 实现 PlayerController::onUpdatePlayTime() 处理播放时间更新
  761. emit updatePlayTime();
  762. });
  763. m_audioPlayThread->setOnDataVisualReady([this](const AudioData& data) {
  764. // 异步 ?
  765. emit audioData(data);
  766. });
  767. // 音频设备初始化在独立线程中完成
  768. return true;
  769. }
  770. bool PlayerController::startPlayThread()
  771. {
  772. if (m_beforePlayThread)
  773. return false;
  774. m_beforePlayThread = std::make_unique<StartPlayThread>(m_audioPlayThread.get(),
  775. m_videoState.get());
  776. m_beforePlayThread->setOnFinished([this]() {
  777. qCDebug(playerControllerLog) << "[StartPlayThread] finished, call playStarted()";
  778. playStarted();
  779. });
  780. m_beforePlayThread->start();
  781. qCDebug(playerControllerLog) << "++++++++++ StartPlay thread (audio init) started";
  782. return true;
  783. }
  784. // 调试辅助函数
  785. void PlayerController::printDecodeContext(const AVCodecContext* codecCtx, bool isVideo) const
  786. {
  787. if (!codecCtx)
  788. return;
  789. qCInfo(playerControllerLog) << (isVideo ? "Video" : "Audio")
  790. << " codec: " << codecCtx->codec->name;
  791. qCInfo(playerControllerLog) << " Type:" << codecCtx->codec_type << "ID:" << codecCtx->codec_id
  792. << "Tag:" << codecCtx->codec_tag;
  793. if (isVideo) {
  794. qCInfo(playerControllerLog)
  795. << " Dimensions: " << codecCtx->width << "x" << codecCtx->height;
  796. } else {
  797. qCInfo(playerControllerLog) << " Sample rate: " << codecCtx->sample_rate
  798. << " Hz, Channels: " << codecCtx->ch_layout.nb_channels
  799. << ", Format: " << codecCtx->sample_fmt;
  800. qCInfo(playerControllerLog) << " Frame size: " << codecCtx->frame_size
  801. << ", Block align: " << codecCtx->block_align;
  802. }
  803. }
  804. // 在合适位置实现 onFrameReady
  805. void PlayerController::onFrameReady(AVFrame* frame)
  806. {
  807. // 这里可以做帧处理、缓存、同步等操作
  808. emit frameReady(frame); // 直接转发给 UI 层
  809. }
  810. void PlayerController::dump() const
  811. {
  812. qCInfo(playerControllerLog) << "=== PlayerController Thread Status Dump ===";
  813. qCInfo(playerControllerLog) << "Current State:" << static_cast<int>(m_state.load());
  814. qCInfo(playerControllerLog) << "Current File:" << m_currentFile;
  815. // 检查数据包读取线程
  816. if (m_packetReadThread) {
  817. qCInfo(playerControllerLog)
  818. << "ReadThread: exists, isRunning:" << m_packetReadThread->isRunning()
  819. << ", isFinished:" << m_packetReadThread->isExit();
  820. } else {
  821. qCInfo(playerControllerLog) << "ReadThread: null";
  822. }
  823. // 检查视频解码线程
  824. if (m_decodeVideoThread) {
  825. qCInfo(playerControllerLog)
  826. << "VideoDecodeThread: exists, isRunning:" << m_decodeVideoThread->isRunning()
  827. << ", isFinished:" << m_decodeVideoThread->isExit();
  828. } else {
  829. qCInfo(playerControllerLog) << "VideoDecodeThread: null";
  830. }
  831. // 检查音频解码线程
  832. if (m_decodeAudioThread) {
  833. qCInfo(playerControllerLog)
  834. << "AudioDecodeThread: exists, isRunning:" << m_decodeAudioThread->isRunning()
  835. << ", isFinished:" << m_decodeAudioThread->isExit();
  836. } else {
  837. qCInfo(playerControllerLog) << "AudioDecodeThread: null";
  838. }
  839. // 检查字幕解码线程
  840. if (m_decodeSubtitleThread) {
  841. qCInfo(playerControllerLog)
  842. << "SubtitleDecodeThread: exists, isRunning:" << m_decodeSubtitleThread->isRunning()
  843. << ", isFinished:" << m_decodeSubtitleThread->isExit();
  844. } else {
  845. qCInfo(playerControllerLog) << "SubtitleDecodeThread: null";
  846. }
  847. // 检查音频播放线程
  848. if (m_audioPlayThread) {
  849. qCInfo(playerControllerLog)
  850. << "AudioPlayThread: exists, isRunning:" << m_audioPlayThread->isRunning()
  851. << ", isFinished:" << m_audioPlayThread->isExit();
  852. } else {
  853. qCInfo(playerControllerLog) << "AudioPlayThread: null";
  854. }
  855. // 检查视频播放线程
  856. if (m_videoPlayThread) {
  857. qCInfo(playerControllerLog)
  858. << "VideoPlayThread: exists, isRunning:" << m_videoPlayThread->isRunning()
  859. << ", isFinished:" << m_videoPlayThread->isExit();
  860. } else {
  861. qCInfo(playerControllerLog) << "VideoPlayThread: null";
  862. }
  863. // 检查播放前准备线程
  864. if (m_beforePlayThread) {
  865. qCInfo(playerControllerLog)
  866. << "StartPlayThread: exists, isRunning:" << m_beforePlayThread->isRunning()
  867. << ", isFinished:" << m_beforePlayThread->isExit();
  868. } else {
  869. qCInfo(playerControllerLog) << "StartPlayThread: null";
  870. }
  871. // 检查初始化线程
  872. if (m_initThread.joinable()) {
  873. qCInfo(playerControllerLog) << "InitThread: joinable (running)";
  874. } else {
  875. qCInfo(playerControllerLog) << "InitThread: not joinable (stopped or not started)";
  876. }
  877. // 检查事件线程
  878. if (m_eventThread.joinable()) {
  879. qCInfo(playerControllerLog) << "EventThread: joinable (running)";
  880. } else {
  881. qCInfo(playerControllerLog) << "EventThread: not joinable (stopped or not started)";
  882. }
  883. qCInfo(playerControllerLog) << "=== End of Thread Status Dump ===";
  884. }