playercontroller.cpp 33 KB

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