player_core_v2.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  1. #include "player_core_v2.h"
  2. #include "../base/media_common.h"
  3. #include "../base/logger.h"
  4. #include "../base/types.h"
  5. #include "../codec/codec_video_decoder.h"
  6. #include "../codec/codec_audio_decoder.h"
  7. #include "../utils/utils_synchronizer_v2.h"
  8. #include <chrono>
  9. #include <thread>
  10. #include <algorithm>
  11. #include <cmath>
  12. namespace av {
  13. namespace player {
  14. PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
  15. : m_state(PlayerState::Idle)
  16. , m_eventCallback(nullptr)
  17. , m_formatContext(nullptr)
  18. // , m_openGLVideoRenderer(nullptr) // 已移除
  19. , m_volume(1.0)
  20. , m_playbackSpeed(1.0)
  21. , m_seekTarget(-1)
  22. , m_seeking(false)
  23. , m_baseTime(0)
  24. , m_lastUpdateTime(0)
  25. , m_threadsShouldStop(false)
  26. , m_threadsRunning(false)
  27. , m_paused(false)
  28. , m_initialized(false)
  29. , m_frameCount(0)
  30. , m_lastFrameCount(0)
  31. , m_errorCount(0)
  32. , m_buffering(false)
  33. , m_bufferHealth(1.0)
  34. {
  35. Logger::instance().info("PlayerCoreV2 created");
  36. try {
  37. // 初始化FFmpeg
  38. if (!initializeFFmpeg()) {
  39. Logger::instance().error("Failed to initialize FFmpeg");
  40. setState(PlayerState::Error);
  41. return;
  42. }
  43. // 创建分离的视频和音频包队列 - 使用高容量队列以避免丢帧
  44. m_videoPacketQueue = av::utils::PacketQueueFactory::createHighCapacityQueue(2000); // 视频包队列,增大容量
  45. if (!m_videoPacketQueue) {
  46. Logger::instance().error("Failed to create video packet queue");
  47. setState(PlayerState::Error);
  48. return;
  49. }
  50. // 禁用丢包策略
  51. m_videoPacketQueue->setDropPolicy(false, true);
  52. m_audioPacketQueue = av::utils::PacketQueueFactory::createHighCapacityQueue(2000); // 音频包队列,增大容量
  53. if (!m_audioPacketQueue) {
  54. Logger::instance().error("Failed to create audio packet queue");
  55. setState(PlayerState::Error);
  56. return;
  57. }
  58. // 禁用丢包策略
  59. m_audioPacketQueue->setDropPolicy(false, true);
  60. m_videoFrameQueue = av::utils::FrameQueueFactory::createHighCapacityQueue(100); // 增加视频帧队列容量并禁用丢帧
  61. if (!m_videoFrameQueue) {
  62. Logger::instance().error("Failed to create video frame queue");
  63. setState(PlayerState::Error);
  64. return;
  65. }
  66. // 禁用丢帧策略
  67. m_videoFrameQueue->setDropPolicy(false, true);
  68. m_audioFrameQueue = av::utils::FrameQueueFactory::createHighCapacityQueue(400); // 增加音频帧队列容量并禁用丢帧
  69. if (!m_audioFrameQueue) {
  70. Logger::instance().error("Failed to create audio frame queue");
  71. setState(PlayerState::Error);
  72. return;
  73. }
  74. // 禁用丢帧策略
  75. m_audioFrameQueue->setDropPolicy(false, true);
  76. // 创建改进的同步器
  77. m_synchronizer = std::make_unique<SynchronizerV2>(syncConfig);
  78. if (!m_synchronizer) {
  79. Logger::instance().error("Failed to create synchronizer");
  80. setState(PlayerState::Error);
  81. return;
  82. }
  83. // 设置同步器回调
  84. m_synchronizer->setSyncErrorCallback([this](double error, const std::string& reason) {
  85. handleSyncError(error, reason);
  86. });
  87. m_synchronizer->setFrameDropCallback([this](av::utils::ClockType type, int64_t pts) {
  88. std::lock_guard<std::mutex> lock(m_mutex);
  89. m_stats.droppedFrames++;
  90. if (m_eventCallback) {
  91. m_eventCallback->onFrameDropped(m_stats.droppedFrames);
  92. }
  93. });
  94. // 创建解码器
  95. m_videoDecoder = std::make_unique<VideoDecoder>();
  96. if (!m_videoDecoder) {
  97. Logger::instance().error("Failed to create video decoder");
  98. setState(PlayerState::Error);
  99. return;
  100. }
  101. m_audioDecoder = std::make_unique<AudioDecoder>();
  102. if (!m_audioDecoder) {
  103. Logger::instance().error("Failed to create audio decoder");
  104. setState(PlayerState::Error);
  105. return;
  106. }
  107. // 创建音频输出设备
  108. m_audioOutput = std::make_unique<AudioOutput>();
  109. if (!m_audioOutput) {
  110. Logger::instance().error("Failed to create audio output");
  111. setState(PlayerState::Error);
  112. return;
  113. }
  114. // 初始化性能监控
  115. m_lastStatsUpdate = std::chrono::steady_clock::now();
  116. m_lastCpuMeasure = m_lastStatsUpdate;
  117. m_initialized = true;
  118. Logger::instance().info("PlayerCoreV2 initialized successfully");
  119. } catch (const std::exception& e) {
  120. Logger::instance().error("Exception during PlayerCoreV2 initialization: " + std::string(e.what()));
  121. setState(PlayerState::Error);
  122. m_initialized = false;
  123. } catch (...) {
  124. Logger::instance().error("Unknown exception during PlayerCoreV2 initialization");
  125. setState(PlayerState::Error);
  126. m_initialized = false;
  127. }
  128. }
  129. PlayerCoreV2::~PlayerCoreV2() {
  130. Logger::instance().info("PlayerCoreV2 destroying...");
  131. stop();
  132. cleanup();
  133. Logger::instance().info("PlayerCoreV2 destroyed");
  134. }
  135. void PlayerCoreV2::setEventCallback(PlayerEventCallback* callback) {
  136. std::lock_guard<std::mutex> lock(m_mutex);
  137. m_eventCallback = callback;
  138. }
  139. ErrorCode PlayerCoreV2::openFile(const std::string& filename) {
  140. Logger::instance().info("Opening file: " + filename);
  141. if (!m_initialized) {
  142. Logger::instance().error("PlayerCoreV2 not initialized");
  143. return ErrorCode::NOT_INITIALIZED;
  144. }
  145. // 如果正在播放,先停止
  146. if (m_state != PlayerState::Idle) {
  147. stop();
  148. }
  149. setState(PlayerState::Opening);
  150. // 打开媒体文件
  151. if (!openMediaFile(filename)) {
  152. setState(PlayerState::Error);
  153. notifyError("Failed to open media file: " + filename);
  154. return ErrorCode::FILE_OPEN_FAILED;
  155. }
  156. // 设置媒体信息
  157. m_mediaInfo.filename = filename;
  158. // 设置解码器
  159. if (m_mediaInfo.hasVideo && !setupVideoDecoder()) {
  160. Logger::instance().error("Failed to setup video decoder");
  161. setState(PlayerState::Error);
  162. return ErrorCode::CODEC_OPEN_FAILED;
  163. }
  164. if (m_mediaInfo.hasAudio && !setupAudioDecoder()) {
  165. Logger::instance().error("Failed to setup audio decoder");
  166. setState(PlayerState::Error);
  167. return ErrorCode::CODEC_OPEN_FAILED;
  168. }
  169. // 注意:同步器的初始化已经在openMediaFile()中完成,这里不需要重复调用
  170. // 因为initialize()会重新选择主时钟,可能覆盖之前设置的流信息
  171. setState(PlayerState::Stopped);
  172. // 如果有视频流,通知需要初始化渲染器
  173. if (m_mediaInfo.hasVideo && m_eventCallback) {
  174. AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
  175. m_eventCallback->onVideoRendererInitRequired(
  176. videoStream->codecpar->width,
  177. videoStream->codecpar->height
  178. );
  179. Logger::instance().info("Video renderer initialization requested");
  180. }
  181. // 通知媒体信息变化
  182. if (m_eventCallback) {
  183. m_eventCallback->onMediaInfoChanged(m_mediaInfo);
  184. }
  185. Logger::instance().info("File opened successfully: " + filename);
  186. return ErrorCode::SUCCESS;
  187. }
  188. ErrorCode PlayerCoreV2::play() {
  189. Logger::instance().info("Starting playback");
  190. if (m_state == PlayerState::Playing) {
  191. Logger::instance().debug("Already playing");
  192. return ErrorCode::SUCCESS;
  193. }
  194. if (m_state != PlayerState::Stopped && m_state != PlayerState::Paused) {
  195. Logger::instance().error("Invalid state for play: " + std::to_string(static_cast<int>(m_state.load())));
  196. return ErrorCode::INVALID_STATE;
  197. }
  198. // 启动或恢复同步器
  199. if (m_synchronizer) {
  200. ErrorCode syncResult = ErrorCode::SUCCESS;
  201. if (m_state == PlayerState::Paused) {
  202. // 从暂停状态恢复,调用resume方法
  203. syncResult = m_synchronizer->resume();
  204. } else {
  205. // 从停止状态开始,调用start方法
  206. syncResult = m_synchronizer->start();
  207. }
  208. if (syncResult != ErrorCode::SUCCESS) {
  209. Logger::instance().error("Failed to start/resume synchronizer");
  210. return ErrorCode::SYNC_ERROR;
  211. }
  212. }
  213. // 根据当前状态设置播放开始时间
  214. if (m_state == PlayerState::Stopped) {
  215. // 从停止状态开始播放,重置所有时间相关变量
  216. m_baseTime = 0;
  217. m_frameCount = 0;
  218. m_lastFrameCount = 0;
  219. m_playStartTime = std::chrono::steady_clock::now();
  220. // 重置统计信息
  221. std::lock_guard<std::mutex> lock(m_mutex);
  222. m_stats = PlaybackStats();
  223. m_stats.playbackSpeed = m_playbackSpeed;
  224. } else if (m_state == PlayerState::Paused) {
  225. // 从暂停状态恢复播放,重新设置播放开始时间
  226. // m_baseTime已经在pause()方法中正确更新,这里只需要重新设置开始时间
  227. m_playStartTime = std::chrono::steady_clock::now();
  228. // 清除暂停标志并唤醒等待的线程,类似ffplay.c中的continue_read_thread机制
  229. {
  230. std::lock_guard<std::mutex> lock(m_pauseMutex);
  231. m_paused = false;
  232. }
  233. m_pauseCondition.notify_all();
  234. }
  235. // 启动音频输出设备
  236. if (m_audioOutput && m_mediaInfo.hasAudio) {
  237. if (m_state == PlayerState::Paused) {
  238. // 从暂停状态恢复音频
  239. try {
  240. m_audioOutput->resume();
  241. } catch (const std::exception& e) {
  242. Logger::instance().error("Failed to resume audio output: " + std::string(e.what()));
  243. // 尝试重新初始化音频设备
  244. try {
  245. m_audioOutput->stop();
  246. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  247. m_audioOutput->start();
  248. } catch (const std::exception& e2) {
  249. Logger::instance().error("Failed to restart audio output: " + std::string(e2.what()));
  250. Logger::instance().warning("Continuing playback without audio");
  251. }
  252. }
  253. } else {
  254. Logger::instance().info("Starting audio output device...");
  255. try {
  256. m_audioOutput->start();
  257. // 检查音频设备是否成功启动
  258. if (!m_audioOutput->isPlaying()) {
  259. Logger::instance().error("Audio output device failed to start");
  260. // 不要因为音频失败而停止整个播放,继续播放视频
  261. Logger::instance().warning("Continuing playback without audio");
  262. }
  263. } catch (const std::exception& e) {
  264. Logger::instance().error("Exception starting audio output: " + std::string(e.what()));
  265. Logger::instance().warning("Continuing playback without audio");
  266. }
  267. }
  268. }
  269. // 根据状态启动或恢复线程
  270. if (m_state == PlayerState::Stopped) {
  271. // 从停止状态开始,需要启动所有线程
  272. // 启动播放线程
  273. if (m_mediaInfo.hasVideo && !startVideoPlayThread()) {
  274. Logger::instance().error("Failed to start video play thread");
  275. return ErrorCode::THREAD_ERROR;
  276. }
  277. if (m_mediaInfo.hasAudio && !startAudioPlayThread()) {
  278. Logger::instance().error("Failed to start audio play thread");
  279. return ErrorCode::THREAD_ERROR;
  280. }
  281. // 启动解码线程
  282. if (!startDecodeThreads()) {
  283. Logger::instance().error("Failed to start decode threads");
  284. return ErrorCode::THREAD_ERROR;
  285. }
  286. // 启动读取线程
  287. if (!startReadThread()) {
  288. Logger::instance().error("Failed to start read thread");
  289. return ErrorCode::THREAD_ERROR;
  290. }
  291. m_threadsRunning = true;
  292. }
  293. // 从暂停状态恢复时,线程已经在运行,只需要唤醒它们(已在上面完成)
  294. setState(PlayerState::Playing);
  295. Logger::instance().info("Playback started");
  296. return ErrorCode::SUCCESS;
  297. }
  298. ErrorCode PlayerCoreV2::pause() {
  299. Logger::instance().info("Pausing playback");
  300. if (m_state != PlayerState::Playing) {
  301. Logger::instance().debug("Not playing, cannot pause");
  302. return ErrorCode::INVALID_STATE;
  303. }
  304. // 设置暂停标志,让线程在内部循环中等待,而不是停止线程
  305. // 类似ffplay.c中的paused标志机制
  306. {
  307. std::lock_guard<std::mutex> lock(m_pauseMutex);
  308. Logger::instance().info("Setting m_paused to true");
  309. m_paused = true;
  310. m_videoPacketQueue->wakeup(); // 唤醒等待的解码线程
  311. m_audioPacketQueue->wakeup(); // 唤醒等待的解码线程
  312. m_videoFrameQueue->wakeup(); // 唤醒等待的播放线程
  313. m_audioFrameQueue->wakeup(); // 唤醒等待的播放线程
  314. Logger::instance().info("m_paused set to: " + std::to_string(m_paused.load()));
  315. }
  316. // 立即通知所有等待的线程检查暂停状态
  317. Logger::instance().info("Notifying all threads about pause state change");
  318. m_pauseCondition.notify_all();
  319. // 暂停同步器
  320. if (m_synchronizer && m_synchronizer->pause() != ErrorCode::SUCCESS) {
  321. Logger::instance().warning("Failed to pause synchronizer");
  322. }
  323. // 记录暂停时的播放时间
  324. if (m_playStartTime.time_since_epoch().count() != 0) {
  325. auto currentTime = std::chrono::steady_clock::now();
  326. auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
  327. currentTime - m_playStartTime).count();
  328. m_baseTime += static_cast<int64_t>(elapsed * m_playbackSpeed);
  329. m_playStartTime = std::chrono::steady_clock::time_point{};
  330. }
  331. // 暂停音频输出
  332. if (m_audioOutput) {
  333. m_audioOutput->pause();
  334. }
  335. setState(PlayerState::Paused);
  336. Logger::instance().info("Playback paused (threads continue running)");
  337. return ErrorCode::SUCCESS;
  338. }
  339. ErrorCode PlayerCoreV2::stop() {
  340. Logger::instance().info("Stopping playback");
  341. if (m_state == PlayerState::Idle || m_state == PlayerState::Stopped) {
  342. Logger::instance().debug("Already stopped");
  343. return ErrorCode::SUCCESS;
  344. }
  345. // 停止同步器
  346. if (m_synchronizer) {
  347. m_synchronizer->stop();
  348. }
  349. // 停止音频输出
  350. if (m_audioOutput) {
  351. m_audioOutput->stop();
  352. }
  353. // 通知关闭视频渲染器
  354. if (m_eventCallback) {
  355. m_eventCallback->onVideoRendererCloseRequired();
  356. }
  357. // 清除暂停标志并唤醒所有等待的线程
  358. {
  359. std::lock_guard<std::mutex> lock(m_pauseMutex);
  360. m_paused = false;
  361. }
  362. m_pauseCondition.notify_all();
  363. // 停止所有线程
  364. stopAllThreads();
  365. // 重置解码器
  366. resetDecoders();
  367. // 清空队列
  368. if (m_videoPacketQueue) m_videoPacketQueue->clear();
  369. if (m_audioPacketQueue) m_audioPacketQueue->clear();
  370. if (m_videoFrameQueue) m_videoFrameQueue->clear();
  371. if (m_audioFrameQueue) m_audioFrameQueue->clear();
  372. // 重置时间
  373. m_baseTime = 0;
  374. m_playStartTime = std::chrono::steady_clock::time_point{};
  375. setState(PlayerState::Stopped);
  376. Logger::instance().info("Playback stopped");
  377. return ErrorCode::SUCCESS;
  378. }
  379. ErrorCode PlayerCoreV2::seek(int64_t timestamp) {
  380. Logger::instance().info("Seeking to: " + std::to_string(timestamp));
  381. if (m_state == PlayerState::Idle || m_state == PlayerState::Opening) {
  382. Logger::instance().error("Invalid state for seek");
  383. return ErrorCode::INVALID_STATE;
  384. }
  385. std::unique_lock<std::mutex> lock(m_seekMutex);
  386. // 设置seek目标和精确范围参数
  387. m_seekTarget = timestamp;
  388. m_seekMinTime = INT64_MIN; // 允许向前跳转的最小时间
  389. m_seekMaxTime = INT64_MAX; // 允许向后跳转的最大时间
  390. m_seekFlags = AVSEEK_FLAG_BACKWARD; // 默认向后跳转到关键帧
  391. m_seeking = true;
  392. // 更新基准时间为跳转目标时间
  393. m_baseTime = timestamp;
  394. m_playStartTime = std::chrono::steady_clock::now();
  395. // 重置同步器
  396. if (m_synchronizer) {
  397. m_synchronizer->reset();
  398. }
  399. // 清空队列
  400. flushBuffers();
  401. setState(PlayerState::Seeking);
  402. // 通知seek条件
  403. m_seekCondition.notify_all();
  404. Logger::instance().info("Precise seek initiated with avformat_seek_file support");
  405. return ErrorCode::SUCCESS;
  406. }
  407. ErrorCode PlayerCoreV2::setPlaybackSpeed(double speed) {
  408. if (speed <= 0.0 || speed > 4.0) {
  409. Logger::instance().error("Invalid playback speed: " + std::to_string(speed));
  410. return ErrorCode::INVALID_PARAMS;
  411. }
  412. std::lock_guard<std::mutex> lock(m_mutex);
  413. m_playbackSpeed = speed;
  414. // 设置同步器的播放速度
  415. if (m_synchronizer) {
  416. m_synchronizer->setPlaybackSpeed(speed);
  417. }
  418. // 设置音频输出的播放速度
  419. if (m_audioOutput) {
  420. m_audioOutput->setPlaybackSpeed(speed);
  421. }
  422. // 更新统计信息
  423. m_stats.playbackSpeed = speed;
  424. Logger::instance().info("Playback speed set to: " + std::to_string(speed));
  425. return ErrorCode::SUCCESS;
  426. }
  427. MediaInfo PlayerCoreV2::getMediaInfo() const {
  428. std::lock_guard<std::mutex> lock(m_mutex);
  429. return m_mediaInfo;
  430. }
  431. PlaybackStats PlayerCoreV2::getStats() const {
  432. std::lock_guard<std::mutex> lock(m_mutex);
  433. PlaybackStats stats = m_stats;
  434. // 更新当前时间
  435. stats.currentTime = getCurrentTime();
  436. // 更新队列大小
  437. if (m_videoPacketQueue) stats.queuedPackets += m_videoPacketQueue->size();
  438. if (m_audioPacketQueue) stats.queuedPackets += m_audioPacketQueue->size();
  439. if (m_videoFrameQueue) stats.queuedVideoFrames = m_videoFrameQueue->size();
  440. if (m_audioFrameQueue) stats.queuedAudioFrames = m_audioFrameQueue->size();
  441. // 更新同步统计
  442. if (m_synchronizer) {
  443. auto syncStats = m_synchronizer->getStats();
  444. stats.syncError = syncStats.audioVideoSyncError;
  445. stats.avgSyncError = syncStats.avgSyncError;
  446. stats.maxSyncError = syncStats.maxSyncError;
  447. stats.droppedFrames = syncStats.droppedFrames;
  448. stats.duplicatedFrames = syncStats.duplicatedFrames;
  449. }
  450. return stats;
  451. }
  452. int64_t PlayerCoreV2::getCurrentTime() const {
  453. if (m_state == PlayerState::Idle || m_state == PlayerState::Stopped) {
  454. return 0;
  455. }
  456. // 如果同步器可用,尝试使用主时钟的播放时间
  457. if (m_synchronizer) {
  458. // 获取主时钟时间(秒),转换为微秒
  459. double masterClockTime = m_synchronizer->getMasterClock();
  460. // 确保时间值合理(非负且不是NaN)
  461. if (masterClockTime >= 0.0 && !std::isnan(masterClockTime)) {
  462. return static_cast<int64_t>(masterClockTime * 1000000);
  463. }
  464. }
  465. // 回退到原来的计算方式(兼容性保证)
  466. if (m_state == PlayerState::Paused) {
  467. return m_baseTime;
  468. }
  469. if (m_playStartTime.time_since_epoch().count() == 0) {
  470. return m_baseTime;
  471. }
  472. auto currentTime = std::chrono::steady_clock::now();
  473. auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
  474. currentTime - m_playStartTime).count();
  475. return m_baseTime + static_cast<int64_t>(elapsed * m_playbackSpeed);
  476. }
  477. double PlayerCoreV2::getPlaybackSpeed() const {
  478. return m_playbackSpeed;
  479. }
  480. void PlayerCoreV2::setVolume(double volume) {
  481. volume = std::max(0.0, std::min(1.0, volume));
  482. m_volume = volume;
  483. // 同时设置音频输出设备的音量
  484. if (m_audioOutput) {
  485. m_audioOutput->setVolume(volume);
  486. }
  487. Logger::instance().debug("Volume set to: " + std::to_string(volume));
  488. }
  489. // 流控制接口实现
  490. void PlayerCoreV2::enableVideoStream(bool enable) {
  491. if (m_videoStreamEnabled == enable) {
  492. return; // 状态未变,不需要处理
  493. }
  494. m_videoStreamEnabled = enable;
  495. Logger::instance().info("Video stream " + std::string(enable ? "enabled" : "disabled"));
  496. // 如果播放器已经打开文件,需要更新同步器的流信息
  497. if (m_formatContext && m_synchronizer) {
  498. bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
  499. bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
  500. m_synchronizer->setStreamInfo(useAudio, useVideo);
  501. // 如果正在播放,需要重新启动播放
  502. if (m_state == PlayerState::Playing || m_state == PlayerState::Paused) {
  503. // 停止当前播放
  504. PlayerState oldState = m_state;
  505. stop();
  506. // 重新开始播放
  507. openFile(m_mediaInfo.filename);
  508. if (oldState == PlayerState::Playing) {
  509. play();
  510. }
  511. }
  512. }
  513. }
  514. void PlayerCoreV2::enableAudioStream(bool enable) {
  515. if (m_audioStreamEnabled == enable) {
  516. return; // 状态未变,不需要处理
  517. }
  518. m_audioStreamEnabled = enable;
  519. Logger::instance().info("Audio stream " + std::string(enable ? "enabled" : "disabled"));
  520. // 如果播放器已经打开文件,需要更新同步器的流信息
  521. if (m_formatContext && m_synchronizer) {
  522. bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
  523. bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
  524. m_synchronizer->setStreamInfo(useAudio, useVideo);
  525. // 如果正在播放,需要重新启动播放
  526. if (m_state == PlayerState::Playing) {
  527. // 暂停当前播放
  528. pause();
  529. // 重新开始播放
  530. play();
  531. }
  532. }
  533. }
  534. bool PlayerCoreV2::isVideoStreamEnabled() const {
  535. return m_videoStreamEnabled;
  536. }
  537. bool PlayerCoreV2::isAudioStreamEnabled() const {
  538. return m_audioStreamEnabled;
  539. }
  540. void PlayerCoreV2::setSyncConfig(const SyncConfigV2& config) {
  541. if (m_synchronizer) {
  542. m_synchronizer->setConfig(config);
  543. }
  544. }
  545. SyncConfigV2 PlayerCoreV2::getSyncConfig() const {
  546. if (m_synchronizer) {
  547. return m_synchronizer->getConfig();
  548. }
  549. return SyncConfigV2();
  550. }
  551. // void PlayerCoreV2::setOpenGLVideoRenderer(OpenGLVideoWidget* renderer) {
  552. // m_openGLVideoRenderer = renderer;
  553. // }
  554. AVFramePtr PlayerCoreV2::getNextVideoFrame() {
  555. if (!m_videoFrameQueue || m_state != PlayerState::Playing) {
  556. return nullptr;
  557. }
  558. return m_videoFrameQueue->pop();
  559. }
  560. AVFramePtr PlayerCoreV2::getNextAudioFrame() {
  561. if (!m_audioFrameQueue || m_state != PlayerState::Playing) {
  562. return nullptr;
  563. }
  564. return m_audioFrameQueue->pop();
  565. }
  566. void PlayerCoreV2::update() {
  567. if (!m_initialized) {
  568. return;
  569. }
  570. // 更新同步状态
  571. updateSynchronization();
  572. // 更新统计信息
  573. auto now = std::chrono::steady_clock::now();
  574. if (std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastStatsUpdate).count() > 500) {
  575. updateStats();
  576. updatePerformanceStats();
  577. m_lastStatsUpdate = now;
  578. // 通知位置变化
  579. notifyPositionChanged();
  580. }
  581. // 检查错误恢复
  582. if (m_errorCount > 0) {
  583. auto timeSinceError = std::chrono::duration_cast<std::chrono::seconds>(now - m_lastErrorTime).count();
  584. if (timeSinceError > 5) { // 5秒后重置错误计数
  585. m_errorCount = 0;
  586. }
  587. }
  588. }
  589. std::string PlayerCoreV2::getDebugInfo() const {
  590. std::ostringstream oss;
  591. oss << "PlayerCoreV2 Debug Info:\n";
  592. oss << " State: " << static_cast<int>(m_state.load()) << "\n";
  593. oss << " Initialized: " << (m_initialized ? "Yes" : "No") << "\n";
  594. oss << " Threads Running: " << (m_threadsRunning ? "Yes" : "No") << "\n";
  595. oss << " Current Time: " << getCurrentTime() << " us\n";
  596. oss << " Playback Speed: " << m_playbackSpeed << "x\n";
  597. oss << " Volume: " << m_volume << "\n";
  598. oss << " Error Count: " << m_errorCount << "\n";
  599. if (m_synchronizer) {
  600. oss << "\n" << m_synchronizer->getDebugInfo();
  601. }
  602. return oss.str();
  603. }
  604. void PlayerCoreV2::dumpStats() const {
  605. PlaybackStats stats = getStats();
  606. Logger::instance().info("=== PlayerCoreV2 Statistics ===");
  607. Logger::instance().info("Current Time: " + std::to_string(stats.currentTime) + " us");
  608. Logger::instance().info("Total Frames: " + std::to_string(stats.totalFrames));
  609. Logger::instance().info("Dropped Frames: " + std::to_string(stats.droppedFrames));
  610. Logger::instance().info("Duplicated Frames: " + std::to_string(stats.duplicatedFrames));
  611. Logger::instance().info("Sync Error: " + std::to_string(stats.syncError * 1000) + " ms");
  612. Logger::instance().info("Avg Sync Error: " + std::to_string(stats.avgSyncError * 1000) + " ms");
  613. Logger::instance().info("Max Sync Error: " + std::to_string(stats.maxSyncError * 1000) + " ms");
  614. Logger::instance().info("CPU Usage: " + std::to_string(stats.cpuUsage) + "%");
  615. Logger::instance().info("Memory Usage: " + std::to_string(stats.memoryUsage) + " MB");
  616. Logger::instance().info("Queued Packets: " + std::to_string(stats.queuedPackets));
  617. Logger::instance().info("Queued Video Frames: " + std::to_string(stats.queuedVideoFrames));
  618. Logger::instance().info("Queued Audio Frames: " + std::to_string(stats.queuedAudioFrames));
  619. Logger::instance().info("===============================");
  620. }
  621. bool PlayerCoreV2::openMediaFile(const std::string& filename) {
  622. // 关闭之前的文件
  623. if (m_formatContext) {
  624. avformat_close_input(&m_formatContext);
  625. m_formatContext = nullptr;
  626. }
  627. // 分配格式上下文
  628. m_formatContext = avformat_alloc_context();
  629. if (!m_formatContext) {
  630. Logger::instance().error("Failed to allocate format context");
  631. return false;
  632. }
  633. // 打开输入文件
  634. if (avformat_open_input(&m_formatContext, filename.c_str(), nullptr, nullptr) < 0) {
  635. Logger::instance().error("Failed to open input file: " + filename);
  636. avformat_free_context(m_formatContext);
  637. m_formatContext = nullptr;
  638. return false;
  639. }
  640. // 查找流信息
  641. if (avformat_find_stream_info(m_formatContext, nullptr) < 0) {
  642. Logger::instance().error("Failed to find stream info");
  643. avformat_close_input(&m_formatContext);
  644. return false;
  645. }
  646. // 查找视频和音频流
  647. m_mediaInfo.videoStreamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
  648. m_mediaInfo.audioStreamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
  649. m_mediaInfo.hasVideo = (m_mediaInfo.videoStreamIndex >= 0);
  650. m_mediaInfo.hasAudio = (m_mediaInfo.audioStreamIndex >= 0);
  651. if (!m_mediaInfo.hasVideo && !m_mediaInfo.hasAudio) {
  652. Logger::instance().error("No video or audio streams found");
  653. avformat_close_input(&m_formatContext);
  654. return false;
  655. }
  656. // 获取媒体信息
  657. m_mediaInfo.duration = m_formatContext->duration;
  658. m_mediaInfo.bitrate = m_formatContext->bit_rate;
  659. if (m_mediaInfo.hasVideo) {
  660. AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
  661. m_mediaInfo.width = videoStream->codecpar->width;
  662. m_mediaInfo.height = videoStream->codecpar->height;
  663. // 计算帧率
  664. if (videoStream->avg_frame_rate.den != 0) {
  665. m_mediaInfo.fps = av_q2d(videoStream->avg_frame_rate);
  666. } else if (videoStream->r_frame_rate.den != 0) {
  667. m_mediaInfo.fps = av_q2d(videoStream->r_frame_rate);
  668. } else {
  669. m_mediaInfo.fps = 25.0; // 默认帧率
  670. }
  671. Logger::instance().info("Video stream found: " + std::to_string(m_mediaInfo.width) + "x" +
  672. std::to_string(m_mediaInfo.height) + " @ " + std::to_string(m_mediaInfo.fps) + " fps");
  673. }
  674. if (m_mediaInfo.hasAudio) {
  675. AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
  676. m_mediaInfo.sampleRate = audioStream->codecpar->sample_rate;
  677. m_mediaInfo.channels = audioStream->codecpar->ch_layout.nb_channels;
  678. Logger::instance().info("Audio stream found: " + std::to_string(m_mediaInfo.sampleRate) + " Hz, " +
  679. std::to_string(m_mediaInfo.channels) + " channels");
  680. }
  681. // 设置同步器的流信息
  682. if (m_synchronizer) {
  683. bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
  684. bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
  685. m_synchronizer->setStreamInfo(useAudio, useVideo);
  686. Logger::instance().info("Synchronizer stream info set: hasAudio=" + std::to_string(useAudio) +
  687. ", hasVideo=" + std::to_string(useVideo));
  688. // 在设置流信息后初始化同步器,确保主时钟选择基于正确的流信息
  689. if (m_synchronizer->initialize() != ErrorCode::SUCCESS) {
  690. Logger::instance().error("Failed to initialize synchronizer");
  691. return false;
  692. }
  693. Logger::instance().info("Synchronizer initialized with correct stream info");
  694. }
  695. Logger::instance().info("Media file opened successfully: " + filename);
  696. return true;
  697. }
  698. bool PlayerCoreV2::setupVideoDecoder() {
  699. if (!m_mediaInfo.hasVideo || !m_videoDecoder) {
  700. return false;
  701. }
  702. AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
  703. // 查找解码器
  704. const AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
  705. if (!codec) {
  706. Logger::instance().error("Video codec not found");
  707. return false;
  708. }
  709. Logger::instance().info("Found video codec: " + std::string(codec->name));
  710. Logger::instance().info("Video stream info: width=" + std::to_string(videoStream->codecpar->width) +
  711. ", height=" + std::to_string(videoStream->codecpar->height) +
  712. ", format=" + std::to_string(videoStream->codecpar->format));
  713. // 创建视频解码器参数
  714. VideoDecoderParams videoParams;
  715. videoParams.codecName = codec->name;
  716. videoParams.width = videoStream->codecpar->width;
  717. videoParams.height = videoStream->codecpar->height;
  718. videoParams.pixelFormat = static_cast<AVPixelFormat>(videoStream->codecpar->format);
  719. videoParams.hardwareAccel = false; // 先禁用硬件加速来排除问题
  720. videoParams.lowLatency = false;
  721. Logger::instance().info("Video decoder params: codec=" + videoParams.codecName +
  722. ", size=" + std::to_string(videoParams.width) + "x" + std::to_string(videoParams.height) +
  723. ", format=" + std::to_string(static_cast<int>(videoParams.pixelFormat)));
  724. // 初始化视频解码器
  725. if (m_videoDecoder->initialize(videoParams) != ErrorCode::SUCCESS) {
  726. Logger::instance().error("Failed to initialize video decoder");
  727. return false;
  728. }
  729. // 设置流参数
  730. if (m_videoDecoder->setStreamParameters(videoStream->codecpar) != ErrorCode::SUCCESS) {
  731. Logger::instance().error("Failed to set video decoder stream parameters");
  732. return false;
  733. }
  734. // 打开视频解码器
  735. if (m_videoDecoder->open(videoParams) != ErrorCode::SUCCESS) {
  736. Logger::instance().error("Failed to open video decoder");
  737. return false;
  738. }
  739. Logger::instance().info("Video decoder setup successfully");
  740. return true;
  741. }
  742. bool PlayerCoreV2::setupAudioDecoder() {
  743. if (!m_mediaInfo.hasAudio || !m_audioDecoder) {
  744. return false;
  745. }
  746. AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
  747. // 查找解码器
  748. const AVCodec* codec = avcodec_find_decoder(audioStream->codecpar->codec_id);
  749. if (!codec) {
  750. Logger::instance().error("Audio codec not found");
  751. return false;
  752. }
  753. // 分配解码器上下文
  754. AVCodecContext* codecContext = avcodec_alloc_context3(codec);
  755. if (!codecContext) {
  756. Logger::instance().error("Failed to allocate audio codec context");
  757. return false;
  758. }
  759. // 复制流参数到解码器上下文
  760. if (avcodec_parameters_to_context(codecContext, audioStream->codecpar) < 0) {
  761. Logger::instance().error("Failed to copy audio codec parameters");
  762. avcodec_free_context(&codecContext);
  763. return false;
  764. }
  765. // 打开解码器
  766. if (avcodec_open2(codecContext, codec, nullptr) < 0) {
  767. Logger::instance().error("Failed to open audio codec");
  768. avcodec_free_context(&codecContext);
  769. return false;
  770. }
  771. // 创建音频解码器参数
  772. AudioDecoderParams audioParams;
  773. audioParams.codecName = codec->name;
  774. audioParams.sampleRate = codecContext->sample_rate;
  775. audioParams.channels = codecContext->ch_layout.nb_channels;
  776. audioParams.sampleFormat = codecContext->sample_fmt;
  777. audioParams.lowLatency = false;
  778. audioParams.enableResampling = true;
  779. // 初始化音频解码器
  780. if (m_audioDecoder->initialize(audioParams) != ErrorCode::SUCCESS) {
  781. Logger::instance().error("Failed to initialize audio decoder");
  782. avcodec_free_context(&codecContext);
  783. return false;
  784. }
  785. // 打开音频解码器
  786. if (m_audioDecoder->open(audioParams) != ErrorCode::SUCCESS) {
  787. Logger::instance().error("Failed to open audio decoder");
  788. avcodec_free_context(&codecContext);
  789. return false;
  790. }
  791. // 初始化音频输出设备
  792. if (m_audioOutput && !m_audioOutput->initialize(codecContext->sample_rate,
  793. codecContext->ch_layout.nb_channels,
  794. codecContext->sample_fmt)) {
  795. Logger::instance().error("Failed to initialize audio output");
  796. avcodec_free_context(&codecContext);
  797. return false;
  798. }
  799. // 释放解码器上下文
  800. avcodec_free_context(&codecContext);
  801. Logger::instance().info("Audio decoder setup successfully");
  802. return true;
  803. }
  804. void PlayerCoreV2::resetDecoders() {
  805. if (m_videoDecoder) {
  806. m_videoDecoder->reset();
  807. }
  808. if (m_audioDecoder) {
  809. m_audioDecoder->reset();
  810. }
  811. }
  812. bool PlayerCoreV2::startReadThread() {
  813. try {
  814. // 确保之前的线程已经完全停止
  815. if (m_readThread.joinable()) {
  816. Logger::instance().warning("Read thread still running, waiting for it to stop...");
  817. m_readThread.join();
  818. }
  819. m_readThread = std::thread(&PlayerCoreV2::readThreadFunc, this);
  820. Logger::instance().info("Read thread started");
  821. return true;
  822. } catch (const std::exception& e) {
  823. Logger::instance().error("Failed to start read thread: " + std::string(e.what()));
  824. return false;
  825. }
  826. }
  827. bool PlayerCoreV2::startDecodeThreads() {
  828. try {
  829. if (m_mediaInfo.hasVideo) {
  830. // 确保之前的视频解码线程已经完全停止
  831. if (m_videoDecodeThread.joinable()) {
  832. Logger::instance().warning("Video decode thread still running, waiting for it to stop...");
  833. m_videoDecodeThread.join();
  834. }
  835. m_videoDecodeThread = std::thread(&PlayerCoreV2::videoDecodeThreadFunc, this);
  836. Logger::instance().info("Video decode thread started");
  837. }
  838. if (m_mediaInfo.hasAudio) {
  839. // 确保之前的音频解码线程已经完全停止
  840. if (m_audioDecodeThread.joinable()) {
  841. Logger::instance().warning("Audio decode thread still running, waiting for it to stop...");
  842. m_audioDecodeThread.join();
  843. }
  844. m_audioDecodeThread = std::thread(&PlayerCoreV2::audioDecodeThreadFunc, this);
  845. Logger::instance().info("Audio decode thread started");
  846. }
  847. return true;
  848. } catch (const std::exception& e) {
  849. Logger::instance().error("Failed to start decode threads: " + std::string(e.what()));
  850. return false;
  851. }
  852. }
  853. bool PlayerCoreV2::startVideoPlayThread() {
  854. try {
  855. // 确保之前的视频播放线程已经完全停止
  856. if (m_videoPlayThread.joinable()) {
  857. Logger::instance().warning("Video play thread still running, waiting for it to stop...");
  858. m_videoPlayThread.join();
  859. }
  860. m_videoPlayThread = std::thread(&PlayerCoreV2::videoPlayThreadFunc, this);
  861. Logger::instance().info("Video play thread started");
  862. return true;
  863. } catch (const std::exception& e) {
  864. Logger::instance().error("Failed to start video play thread: " + std::string(e.what()));
  865. return false;
  866. }
  867. }
  868. bool PlayerCoreV2::startAudioPlayThread() {
  869. try {
  870. // 确保之前的音频播放线程已经完全停止
  871. if (m_audioPlayThread.joinable()) {
  872. Logger::instance().warning("Audio play thread still running, waiting for it to stop...");
  873. m_audioPlayThread.join();
  874. }
  875. m_audioPlayThread = std::thread(&PlayerCoreV2::audioPlayThreadFunc, this);
  876. Logger::instance().info("Audio play thread started");
  877. return true;
  878. } catch (const std::exception& e) {
  879. Logger::instance().error("Failed to start audio play thread: " + std::string(e.what()));
  880. return false;
  881. }
  882. }
  883. bool PlayerCoreV2::initializeFFmpeg() {
  884. // FFmpeg初始化逻辑
  885. av_log_set_level(AV_LOG_WARNING);
  886. return true;
  887. }
  888. void PlayerCoreV2::cleanup() {
  889. stopAllThreads();
  890. if (m_formatContext) {
  891. avformat_close_input(&m_formatContext);
  892. m_formatContext = nullptr;
  893. }
  894. // if (m_synchronizer) {
  895. // m_synchronizer->close();
  896. // }
  897. }
  898. void PlayerCoreV2::setState(PlayerState newState) {
  899. PlayerState oldState = m_state.exchange(newState);
  900. if (oldState != newState) {
  901. notifyStateChanged(newState);
  902. }
  903. }
  904. void PlayerCoreV2::notifyStateChanged(PlayerState newState) {
  905. if (m_eventCallback) {
  906. m_eventCallback->onStateChanged(newState);
  907. }
  908. }
  909. void PlayerCoreV2::notifyError(const std::string& error) {
  910. Logger::instance().error(error);
  911. if (m_eventCallback) {
  912. m_eventCallback->onErrorOccurred(error);
  913. }
  914. }
  915. void PlayerCoreV2::notifyPositionChanged() {
  916. if (m_eventCallback) {
  917. m_eventCallback->onPositionChanged(getCurrentTime());
  918. }
  919. }
  920. void PlayerCoreV2::handleSyncError(double error, const std::string& reason) {
  921. Logger::instance().warning("Sync error: " + std::to_string(error * 1000) + "ms, reason: " + reason);
  922. if (m_eventCallback) {
  923. m_eventCallback->onSyncError(error, reason);
  924. }
  925. // 如果同步误差太大,尝试恢复
  926. if (error > 0.2) { // 200ms
  927. attemptRecovery();
  928. }
  929. }
  930. void PlayerCoreV2::attemptRecovery() {
  931. m_errorCount++;
  932. m_lastErrorTime = std::chrono::steady_clock::now();
  933. Logger::instance().warning("Attempting recovery, error count: " + std::to_string(m_errorCount.load()));
  934. if (m_errorCount > 5) {
  935. Logger::instance().error("Too many errors, stopping playback");
  936. handleError("Too many sync errors");
  937. return;
  938. }
  939. // // 重置同步器
  940. // if (m_synchronizer) {
  941. // m_synchronizer->reset();
  942. // }
  943. // 清空部分缓冲区
  944. if (m_videoFrameQueue) {
  945. m_videoFrameQueue->clear();
  946. }
  947. if (m_audioFrameQueue) {
  948. m_audioFrameQueue->clear();
  949. }
  950. }
  951. void PlayerCoreV2::handleError(const std::string& error) {
  952. setState(PlayerState::Error);
  953. notifyError(error);
  954. }
  955. void PlayerCoreV2::updateSynchronization() {
  956. if (!m_synchronizer || !m_threadsRunning) {
  957. return;
  958. }
  959. // 同步器会在内部自动更新
  960. // 更新同步器统计信息
  961. //m_synchronizer->updateStats();
  962. // 获取同步器统计信息并更新播放器统计
  963. std::lock_guard<std::mutex> lock(m_mutex);
  964. auto syncStats = m_synchronizer->getStats();
  965. m_stats.syncError = syncStats.audioVideoSyncError;
  966. m_stats.avgSyncError = syncStats.avgSyncError;
  967. m_stats.maxSyncError = syncStats.maxSyncError;
  968. m_stats.droppedFrames = syncStats.droppedFrames;
  969. m_stats.duplicatedFrames = syncStats.duplicatedFrames;
  970. }
  971. void PlayerCoreV2::updateStats() {
  972. std::lock_guard<std::mutex> lock(m_mutex);
  973. // 更新帧率统计
  974. int64_t currentFrameCount = m_frameCount;
  975. int64_t frameDiff = currentFrameCount - m_lastFrameCount;
  976. m_lastFrameCount = currentFrameCount;
  977. // 计算比特率等其他统计信息
  978. if (m_formatContext) {
  979. m_stats.bitrate = m_formatContext->bit_rate / 1000.0; // kbps
  980. }
  981. }
  982. void PlayerCoreV2::updatePerformanceStats() {
  983. std::lock_guard<std::mutex> lock(m_mutex);
  984. m_stats.cpuUsage = calculateCpuUsage();
  985. m_stats.memoryUsage = calculateMemoryUsage();
  986. }
  987. double PlayerCoreV2::calculateCpuUsage() {
  988. return 0.0;
  989. }
  990. double PlayerCoreV2::calculateMemoryUsage() {
  991. return 0.0;
  992. }
  993. void PlayerCoreV2::stopAllThreads() {
  994. Logger::instance().info("Stopping all threads...");
  995. m_threadsShouldStop = true;
  996. // 唤醒所有等待的队列,确保线程能够检查停止标志
  997. flushBuffers();
  998. // 等待线程结束,添加超时保护
  999. auto joinWithTimeout = [](std::thread& t, const std::string& name) {
  1000. if (t.joinable()) {
  1001. Logger::instance().info("Waiting for " + name + " to stop...");
  1002. t.join();
  1003. Logger::instance().info(name + " stopped");
  1004. }
  1005. };
  1006. joinWithTimeout(m_readThread, "read thread");
  1007. joinWithTimeout(m_videoDecodeThread, "video decode thread");
  1008. joinWithTimeout(m_audioDecodeThread, "audio decode thread");
  1009. joinWithTimeout(m_videoPlayThread, "video play thread");
  1010. joinWithTimeout(m_audioPlayThread, "audio play thread");
  1011. m_threadsRunning = false;
  1012. Logger::instance().info("All threads stopped successfully");
  1013. }
  1014. void PlayerCoreV2::flushBuffers() {
  1015. if (m_videoPacketQueue) {
  1016. m_videoPacketQueue->clear();
  1017. m_videoPacketQueue->wakeup(); // 唤醒等待的解码线程
  1018. }
  1019. if (m_audioPacketQueue) {
  1020. m_audioPacketQueue->clear();
  1021. m_audioPacketQueue->wakeup(); // 唤醒等待的解码线程
  1022. }
  1023. if (m_videoFrameQueue) {
  1024. m_videoFrameQueue->clear();
  1025. m_videoFrameQueue->wakeup(); // 唤醒等待的播放线程
  1026. }
  1027. if (m_audioFrameQueue) {
  1028. m_audioFrameQueue->clear();
  1029. m_audioFrameQueue->wakeup(); // 唤醒等待的播放线程
  1030. }
  1031. }
  1032. void PlayerCoreV2::readThreadFunc() {
  1033. Logger::instance().info("Read thread started");
  1034. AVPacket* packet = av_packet_alloc();
  1035. if (!packet) {
  1036. Logger::instance().error("Failed to allocate packet");
  1037. return;
  1038. }
  1039. while (!m_threadsShouldStop) {
  1040. // 检查暂停状态,类似ffplay.c中的paused检查
  1041. bool pausedState = m_paused.load();
  1042. Logger::instance().debug("Read thread loop - m_paused: " + std::to_string(pausedState));
  1043. if (pausedState) {
  1044. Logger::instance().info("Read thread entering pause wait");
  1045. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1046. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1047. if (m_threadsShouldStop) {
  1048. break;
  1049. }
  1050. Logger::instance().info("Read thread exiting pause wait");
  1051. // 暂停状态结束后,继续下一次循环
  1052. continue;
  1053. }
  1054. // 检查是否需要seek
  1055. if (m_seeking) {
  1056. std::unique_lock<std::mutex> lock(m_seekMutex);
  1057. // 获取seek参数
  1058. int64_t seekMinTime = m_seekMinTime;
  1059. int64_t seekTarget = m_seekTarget;
  1060. int64_t seekMaxTime = m_seekMaxTime;
  1061. int flags = m_seekFlags;
  1062. Logger::instance().info("Performing precise seek - min: " + std::to_string(seekMinTime) +
  1063. ", target: " + std::to_string(seekTarget) +
  1064. ", max: " + std::to_string(seekMaxTime) +
  1065. ", flags: " + std::to_string(flags));
  1066. // 首先尝试定位到最近的关键帧以确保视频解码正常
  1067. int ret = av_seek_frame(m_formatContext, -1, seekTarget, AVSEEK_FLAG_BACKWARD);
  1068. if (ret < 0) {
  1069. Logger::instance().warning("Video keyframe seek failed, trying precise seek");
  1070. // 如果关键帧定位失败,回退到精确seek
  1071. ret = avformat_seek_file(m_formatContext, -1, seekMinTime, seekTarget, seekMaxTime, flags);
  1072. if (ret < 0) {
  1073. Logger::instance().error("All seek methods failed");
  1074. } else {
  1075. Logger::instance().info("Fallback precise seek completed to: " + std::to_string(seekTarget));
  1076. }
  1077. } else {
  1078. Logger::instance().info("Keyframe seek completed successfully to target: " + std::to_string(seekTarget));
  1079. }
  1080. // 清空缓冲区
  1081. flushBuffers();
  1082. // 重置解码器
  1083. resetDecoders();
  1084. // 重置时间
  1085. if (flags & AVSEEK_FLAG_BYTE) {
  1086. m_synchronizer->setClock(av::utils::ClockType::EXTERNAL, NAN, 0);
  1087. } else {
  1088. m_synchronizer->setClock(av::utils::ClockType::EXTERNAL,
  1089. seekTarget / (double) AV_TIME_BASE,
  1090. 0);
  1091. }
  1092. m_seeking = false;
  1093. setState(m_state == PlayerState::Seeking ? PlayerState::Playing : m_state.load());
  1094. lock.unlock();
  1095. m_seekCondition.notify_all();
  1096. }
  1097. // 检查队列是否接近容量上限 - 使用队列容量的90%作为警告阈值,但不丢弃包
  1098. bool videoQueueNearFull = m_videoPacketQueue && m_videoPacketQueue->size() > 800;
  1099. bool audioQueueNearFull = m_audioPacketQueue && m_audioPacketQueue->size() > 800;
  1100. if (videoQueueNearFull || audioQueueNearFull) {
  1101. // 队列接近满,暂停一段时间让解码线程处理
  1102. Logger::instance().warning("Packet queue is getting large: Video=" +
  1103. std::to_string(m_videoPacketQueue ? m_videoPacketQueue->size() : 0) +
  1104. ", Audio=" + std::to_string(m_audioPacketQueue ? m_audioPacketQueue->size() : 0) +
  1105. ". Slowing down read thread.");
  1106. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  1107. continue;
  1108. }
  1109. // 在读取数据包前检查暂停状态,避免在读取期间阻塞
  1110. if (m_paused.load()) {
  1111. Logger::instance().debug("Read thread detected pause before av_read_frame");
  1112. continue;
  1113. }
  1114. // 读取数据包
  1115. int ret = av_read_frame(m_formatContext, packet);
  1116. if (ret < 0) {
  1117. if (ret == AVERROR_EOF) {
  1118. Logger::instance().info("End of file reached, sending EOF packets to queues");
  1119. // 向视频和音频队列分别发送EOF标记,让解码线程知道文件结束
  1120. if (m_videoPacketQueue && m_mediaInfo.hasVideo) {
  1121. AVPacket* eofPacket = av_packet_alloc();
  1122. if (eofPacket) {
  1123. eofPacket->data = nullptr;
  1124. eofPacket->size = 0;
  1125. eofPacket->stream_index = -1; // 特殊标记表示EOF
  1126. m_videoPacketQueue->push(eofPacket);
  1127. Logger::instance().info("EOF packet sent to video queue");
  1128. }
  1129. }
  1130. if (m_audioPacketQueue && m_mediaInfo.hasAudio) {
  1131. AVPacket* eofPacket = av_packet_alloc();
  1132. if (eofPacket) {
  1133. eofPacket->data = nullptr;
  1134. eofPacket->size = 0;
  1135. eofPacket->stream_index = -1; // 特殊标记表示EOF
  1136. m_audioPacketQueue->push(eofPacket);
  1137. Logger::instance().info("EOF packet sent to audio queue");
  1138. }
  1139. }
  1140. break;
  1141. } else {
  1142. Logger::instance().error("Error reading frame: " + std::to_string(ret));
  1143. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1144. continue;
  1145. }
  1146. }
  1147. // 根据流索引将数据包分发到对应队列
  1148. if (packet->stream_index == m_mediaInfo.videoStreamIndex && m_videoStreamEnabled) {
  1149. // 视频包放入视频队列 - 不考虑队列是否已满,确保不丢包
  1150. if (m_videoPacketQueue) {
  1151. AVPacket* packetCopy = av_packet_alloc();
  1152. if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
  1153. m_videoPacketQueue->push(packetCopy);
  1154. // 记录队列大小,用于监控
  1155. if (m_videoPacketQueue->size() % 100 == 0) {
  1156. Logger::instance().debug("Video packet queue size: " + std::to_string(m_videoPacketQueue->size()));
  1157. }
  1158. } else {
  1159. av_packet_free(&packetCopy);
  1160. }
  1161. }
  1162. } else if (packet->stream_index == m_mediaInfo.audioStreamIndex && m_audioStreamEnabled) {
  1163. // 音频包放入音频队列 - 不考虑队列是否已满,确保不丢包
  1164. if (m_audioPacketQueue) {
  1165. AVPacket* packetCopy = av_packet_alloc();
  1166. if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
  1167. m_audioPacketQueue->push(packetCopy);
  1168. // 记录队列大小,用于监控
  1169. if (m_audioPacketQueue->size() % 100 == 0) {
  1170. Logger::instance().debug("Audio packet queue size: " + std::to_string(m_audioPacketQueue->size()));
  1171. }
  1172. } else {
  1173. av_packet_free(&packetCopy);
  1174. }
  1175. }
  1176. }
  1177. m_audioPacketQueue->wakeup();
  1178. m_videoPacketQueue->wakeup();
  1179. av_packet_unref(packet);
  1180. }
  1181. av_packet_free(&packet);
  1182. Logger::instance().info("Read thread finished");
  1183. }
  1184. void PlayerCoreV2::videoDecodeThreadFunc() {
  1185. Logger::instance().info("Video decode thread started");
  1186. int packetCount = 0;
  1187. int frameCount = 0;
  1188. while (!m_threadsShouldStop) {
  1189. // 检查暂停状态,类似ffplay.c中的paused检查
  1190. bool pausedState = m_paused.load();
  1191. Logger::instance().debug("Video decode thread loop - m_paused: "
  1192. + std::to_string(pausedState));
  1193. if (pausedState) {
  1194. Logger::instance().info("Video decode thread entering pause wait");
  1195. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1196. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1197. if (m_threadsShouldStop) {
  1198. break;
  1199. }
  1200. Logger::instance().info("Video decode thread exiting pause wait");
  1201. // 暂停状态结束后,继续下一次循环
  1202. continue;
  1203. }
  1204. if (!m_videoPacketQueue || !m_videoFrameQueue || !m_videoDecoder) {
  1205. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1206. continue;
  1207. }
  1208. if (m_seeking) {
  1209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1210. continue;
  1211. }
  1212. Logger::instance().info("Video decode thread read Packet111");
  1213. // 从视频包队列获取包
  1214. AVPacket* packet = nullptr;
  1215. while (!m_threadsShouldStop && !packet) {
  1216. // 在 pop 操作前检查暂停状态,避免在 pop 期间阻塞
  1217. if (m_paused.load()) {
  1218. Logger::instance().debug("Video decode thread detected pause before pop");
  1219. break;
  1220. }
  1221. Logger::instance().info("Video decode thread read Packet");
  1222. packet = m_videoPacketQueue->pop(10); // 减少超时时间以提高seek响应速度
  1223. Logger::instance().infof("Video decode thread read Packet %d", packet);
  1224. if (packet) {
  1225. // 检查是否是EOF标记
  1226. if (packet->stream_index == -1 && packet->data == nullptr) {
  1227. Logger::instance().info("Video decode thread received EOF packet");
  1228. av_packet_free(&packet);
  1229. // 向视频帧队列发送EOF标记
  1230. if (m_videoFrameQueue) {
  1231. AVFramePtr eofFrame = makeAVFrame();
  1232. if (eofFrame) {
  1233. eofFrame->data[0] = nullptr;
  1234. eofFrame->width = 0;
  1235. eofFrame->height = 0;
  1236. eofFrame->pts = AV_NOPTS_VALUE;
  1237. m_videoFrameQueue->push(std::move(eofFrame));
  1238. Logger::instance().info("EOF frame sent to video frame queue");
  1239. }
  1240. }
  1241. // 视频解码线程结束
  1242. Logger::instance().info("Video decode thread finishing due to EOF");
  1243. return;
  1244. }
  1245. }
  1246. if (!packet) {
  1247. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  1248. }
  1249. }
  1250. if (!packet) {
  1251. Logger::instance().debug("Video decode thread: no more packets available");
  1252. continue;
  1253. }
  1254. packetCount++;
  1255. Logger::instance().debug("Video decode thread got packet #" + std::to_string(packetCount) +
  1256. ", size=" + std::to_string(packet->size) +
  1257. ", pts=" + std::to_string(packet->pts));
  1258. // 解码视频帧
  1259. AVPacketPtr packetPtr(packet);
  1260. std::vector<AVFramePtr> frames;
  1261. ErrorCode decodeResult = m_videoDecoder->decode(packetPtr, frames);
  1262. Logger::instance().debug("Video decode result: " + std::to_string(static_cast<int>(decodeResult)) +
  1263. ", frames count: " + std::to_string(frames.size()));
  1264. if (decodeResult == ErrorCode::SUCCESS) {
  1265. for (auto& framePtr : frames) {
  1266. if (framePtr && !m_threadsShouldStop) {
  1267. frameCount++;
  1268. Logger::instance().debug("Processing video frame #" + std::to_string(frameCount) +
  1269. ", width=" + std::to_string(framePtr->width) +
  1270. ", height=" + std::to_string(framePtr->height) +
  1271. ", pts=" + std::to_string(framePtr->pts));
  1272. // 设置帧的时间戳(保持原始PTS,在播放时再转换)
  1273. if (framePtr->pts != AV_NOPTS_VALUE) {
  1274. Logger::instance().debug("Frame PTS: " + std::to_string(framePtr->pts));
  1275. }
  1276. // 将帧放入队列 - 不丢弃任何帧
  1277. // 使用移动语义转移智能指针所有权
  1278. m_videoFrameQueue->push(std::move(framePtr));
  1279. m_frameCount++;
  1280. Logger::instance().debug("Video frame pushed to queue, queue size: " + std::to_string(m_videoFrameQueue->size()));
  1281. // 如果队列大小超过警告阈值,记录警告但不丢弃
  1282. if (m_videoFrameQueue->size() > 80) {
  1283. Logger::instance().warning("Video frame queue is getting large: " + std::to_string(m_videoFrameQueue->size()) +
  1284. " frames. Performance may be affected.");
  1285. }
  1286. }
  1287. }
  1288. } else {
  1289. Logger::instance().warning("Video decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
  1290. }
  1291. }
  1292. Logger::instance().info("Video decode thread finished, packets processed: "
  1293. + std::to_string(packetCount)
  1294. + ", frames decoded: " + std::to_string(frameCount));
  1295. }
  1296. void PlayerCoreV2::audioDecodeThreadFunc() {
  1297. Logger::instance().info("Audio decode thread started");
  1298. int packetCount = 0;
  1299. int frameCount = 0;
  1300. while (!m_threadsShouldStop) {
  1301. // 检查暂停状态,类似ffplay.c中的paused检查
  1302. bool pausedState = m_paused.load();
  1303. Logger::instance().debug("Audio decode thread loop - m_paused: "
  1304. + std::to_string(pausedState));
  1305. if (pausedState) {
  1306. Logger::instance().info("Audio decode thread entering pause wait");
  1307. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1308. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1309. if (m_threadsShouldStop) {
  1310. break;
  1311. }
  1312. Logger::instance().info("Audio decode thread exiting pause wait");
  1313. // 暂停状态结束后,继续下一次循环
  1314. continue;
  1315. }
  1316. if (!m_audioPacketQueue || !m_audioFrameQueue || !m_audioDecoder) {
  1317. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1318. continue;
  1319. }
  1320. if (m_seeking) {
  1321. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1322. continue;
  1323. }
  1324. // 从音频包队列获取包
  1325. AVPacket* packet = nullptr;
  1326. while (!m_threadsShouldStop && !packet) {
  1327. // 在 pop 操作前检查暂停状态,避免在 pop 期间阻塞
  1328. if (m_paused.load()) {
  1329. Logger::instance().debug("Audio decode thread detected pause before pop");
  1330. break;
  1331. }
  1332. packet = m_audioPacketQueue->pop(10); // 减少超时时间以提高seek响应速度
  1333. if (packet) {
  1334. // 检查是否是EOF标记
  1335. if (packet->stream_index == -1 && packet->data == nullptr) {
  1336. Logger::instance().info("Audio decode thread received EOF packet");
  1337. av_packet_free(&packet);
  1338. // 向音频帧队列发送EOF标记
  1339. if (m_audioFrameQueue) {
  1340. AVFramePtr eofFrame = makeAVFrame();
  1341. if (eofFrame) {
  1342. eofFrame->data[0] = nullptr;
  1343. eofFrame->nb_samples = 0;
  1344. eofFrame->pts = AV_NOPTS_VALUE;
  1345. m_audioFrameQueue->push(std::move(eofFrame));
  1346. Logger::instance().info("EOF frame sent to audio frame queue");
  1347. }
  1348. }
  1349. // 音频解码线程结束
  1350. Logger::instance().info("Audio decode thread finishing due to EOF");
  1351. return;
  1352. }
  1353. }
  1354. if (!packet) {
  1355. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  1356. }
  1357. }
  1358. if (!packet) {
  1359. Logger::instance().debug("Audio decode thread: no more packets available");
  1360. continue;
  1361. }
  1362. packetCount++;
  1363. Logger::instance().debug("Audio decode thread got packet #" + std::to_string(packetCount) +
  1364. ", size=" + std::to_string(packet->size) +
  1365. ", pts=" + std::to_string(packet->pts));
  1366. // 解码音频帧
  1367. AVPacketPtr packetPtr(packet);
  1368. std::vector<AVFramePtr> frames;
  1369. ErrorCode decodeResult = m_audioDecoder->decode(packetPtr, frames);
  1370. Logger::instance().debug("Audio decode result: " + std::to_string(static_cast<int>(decodeResult)) +
  1371. ", frames count: " + std::to_string(frames.size()));
  1372. if (decodeResult == ErrorCode::SUCCESS) {
  1373. for (auto& framePtr : frames) {
  1374. if (framePtr && !m_threadsShouldStop) {
  1375. frameCount++;
  1376. Logger::instance().debug("Processing audio frame #" + std::to_string(frameCount) +
  1377. ", nb_samples=" + std::to_string(framePtr->nb_samples) +
  1378. ", pts=" + std::to_string(framePtr->pts));
  1379. // 设置帧的时间戳(保持原始PTS,在播放时再转换)
  1380. if (framePtr->pts != AV_NOPTS_VALUE) {
  1381. Logger::instance().debug("Audio Frame PTS: " + std::to_string(framePtr->pts));
  1382. }
  1383. // 将帧放入队列 - 不丢弃任何帧
  1384. // 使用移动语义转移智能指针所有权
  1385. m_audioFrameQueue->push(std::move(framePtr));
  1386. Logger::instance().debug("Audio frame pushed to queue, queue size: " + std::to_string(m_audioFrameQueue->size()));
  1387. // 如果队列大小超过警告阈值,记录警告但不丢弃
  1388. if (m_audioFrameQueue->size() > 300) {
  1389. Logger::instance().warning("Audio frame queue is getting large: " + std::to_string(m_audioFrameQueue->size()) +
  1390. " frames. Performance may be affected.");
  1391. }
  1392. }
  1393. }
  1394. } else {
  1395. Logger::instance().warning("Audio decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
  1396. }
  1397. // packet已经被packetPtr管理,不需要手动释放
  1398. }
  1399. Logger::instance().info("Audio decode thread finished, packets processed: " + std::to_string(packetCount) +
  1400. ", frames decoded: " + std::to_string(frameCount));
  1401. }
  1402. void PlayerCoreV2::videoPlayThreadFunc() {
  1403. Logger::instance().info("Video play thread started");
  1404. // 用于计算帧持续时间的变量
  1405. AVFramePtr lastFrame = nullptr;
  1406. while (!m_threadsShouldStop) {
  1407. // 检查暂停状态,类似ffplay.c中的paused检查
  1408. bool pausedState = m_paused.load();
  1409. Logger::instance().debug("Video play thread loop - m_paused: "
  1410. + std::to_string(pausedState));
  1411. if (pausedState) {
  1412. Logger::instance().info("Video play thread entering pause wait");
  1413. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1414. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1415. if (m_threadsShouldStop) {
  1416. break;
  1417. }
  1418. Logger::instance().info("Video play thread exiting pause wait");
  1419. // 暂停状态结束后,继续下一次循环
  1420. continue;
  1421. }
  1422. if (!m_videoFrameQueue || !m_synchronizer) {
  1423. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1424. continue;
  1425. }
  1426. // 在pop之前再次检查暂停状态,避免在pop期间阻塞
  1427. if (m_paused.load()) {
  1428. Logger::instance().debug("Video play thread detected pause before pop");
  1429. continue;
  1430. }
  1431. // 获取视频帧,使用更短的超时时间以提高暂停响应速度
  1432. AVFramePtr frame = m_videoFrameQueue->pop(1); // 使用1ms超时以快速响应暂停
  1433. if (!frame) {
  1434. // 检查是否应该继续等待
  1435. if (m_threadsShouldStop) {
  1436. break;
  1437. }
  1438. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1439. continue;
  1440. }
  1441. // 获取帧后立即检查暂停状态,如果已暂停则释放帧并继续
  1442. bool pausedAfterPop = m_paused.load();
  1443. Logger::instance().debug("Video play thread after pop - m_paused: " + std::to_string(pausedAfterPop));
  1444. if (pausedAfterPop) {
  1445. Logger::instance().info("Video play thread releasing frame due to pause");
  1446. frame.reset(); // 智能指针自动释放
  1447. continue;
  1448. }
  1449. Logger::instance().debug("Video play thread got frame, pts=" + std::to_string(frame->pts));
  1450. // frame 本身就是智能指针,直接使用
  1451. AVFramePtr& framePtr = frame;
  1452. // 使用同步器计算视频帧显示时间
  1453. double pts = frame->pts * av_q2d(m_formatContext->streams[m_mediaInfo.videoStreamIndex]->time_base);
  1454. // 只在非暂停状态下更新时钟和处理帧
  1455. m_synchronizer->setClock(av::utils::ClockType::VIDEO, pts, 0);
  1456. // 计算帧持续时间
  1457. double last_duration = 0.0;
  1458. if (lastFrame && lastFrame->pts != AV_NOPTS_VALUE && frame->pts != AV_NOPTS_VALUE) {
  1459. // 计算两帧之间的时间差
  1460. double last_pts = lastFrame->pts * av_q2d(m_formatContext->streams[m_mediaInfo.videoStreamIndex]->time_base);
  1461. last_duration = pts - last_pts;
  1462. if (last_duration < 0 || last_duration > 10.0) {
  1463. // 如果持续时间不合理,使用帧率的倒数作为默认值
  1464. last_duration = 1.0 / m_mediaInfo.fps;
  1465. }
  1466. } else {
  1467. // 如果没有上一帧,使用帧率的倒数作为默认值
  1468. last_duration = 1.0 / m_mediaInfo.fps;
  1469. }
  1470. // 计算视频帧延迟并决定是否显示
  1471. FrameDecision decision = m_synchronizer->synchronizeVideo(pts, 0, last_duration);
  1472. if (decision.action == FrameAction::DISPLAY) {
  1473. // 如果需要延迟显示,等待指定时间
  1474. if (decision.delay > 0.0) {
  1475. std::this_thread::sleep_for(
  1476. std::chrono::microseconds(static_cast<int64_t>(decision.delay * 1000000)));
  1477. }
  1478. // 通知显示帧
  1479. if (m_eventCallback) {
  1480. m_eventCallback->onVideoFrameReady(framePtr.get());
  1481. Logger::instance().debug("Video frame ready for display, pts=" + std::to_string(pts) + ", delay=" + std::to_string(decision.delay));
  1482. }
  1483. // 更新上一帧指针
  1484. lastFrame.reset(); // 智能指针自动释放旧帧
  1485. // 创建当前帧的副本
  1486. AVFramePtr clonedFrame = makeAVFrame();
  1487. if (clonedFrame && av_frame_ref(clonedFrame.get(), frame.get()) == 0) {
  1488. lastFrame = std::move(clonedFrame);
  1489. }
  1490. } else if (decision.action == FrameAction::DROP) {
  1491. Logger::instance().debug("Video frame dropped due to sync, pts=" + std::to_string(pts) + ", error=" + std::to_string(decision.syncError));
  1492. }
  1493. }
  1494. // 清理最后一帧 - 智能指针自动清理
  1495. lastFrame.reset();
  1496. Logger::instance().info("Video play thread finished");
  1497. }
  1498. void PlayerCoreV2::audioPlayThreadFunc() {
  1499. Logger::instance().info("Audio play thread started");
  1500. int frameCount = 0;
  1501. while (!m_threadsShouldStop) {
  1502. // 检查暂停状态,类似ffplay.c中的paused检查
  1503. bool pausedState = m_paused.load();
  1504. Logger::instance().debug("Audio play thread loop - m_paused: "
  1505. + std::to_string(pausedState));
  1506. if (pausedState) {
  1507. Logger::instance().info("Audio play thread entering pause wait");
  1508. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1509. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1510. if (m_threadsShouldStop) {
  1511. break;
  1512. }
  1513. Logger::instance().info("Audio play thread exiting pause wait");
  1514. // 暂停状态结束后,继续下一次循环
  1515. continue;
  1516. }
  1517. if (!m_audioFrameQueue || !m_synchronizer || !m_audioOutput) {
  1518. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1519. continue;
  1520. }
  1521. // 在pop之前再次检查暂停状态,避免在pop期间阻塞
  1522. if (m_paused.load()) {
  1523. Logger::instance().debug("Audio play thread detected pause before pop");
  1524. continue;
  1525. }
  1526. // 获取音频帧,使用更短的超时时间以提高暂停响应速度
  1527. AVFramePtr frame = m_audioFrameQueue->pop(1); // 使用1ms超时以快速响应暂停
  1528. if (!frame) {
  1529. // 检查是否应该继续等待
  1530. if (m_threadsShouldStop) {
  1531. break;
  1532. }
  1533. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1534. continue;
  1535. }
  1536. // 获取帧后立即检查暂停状态,如果已暂停则释放帧并继续
  1537. bool pausedAfterPop = m_paused.load();
  1538. Logger::instance().debug("Audio play thread after pop - m_paused: " + std::to_string(pausedAfterPop));
  1539. if (pausedAfterPop) {
  1540. Logger::instance().info("Audio play thread releasing frame due to pause");
  1541. frame.reset(); // 智能指针自动释放
  1542. continue;
  1543. }
  1544. // 检查是否是EOF帧
  1545. if (frame->data[0] == nullptr && frame->nb_samples == 0) {
  1546. Logger::instance().info("Audio play thread received EOF frame, playback completed");
  1547. frame.reset(); // 智能指针自动释放
  1548. // 通知播放完成
  1549. setState(PlayerState::Stopped);
  1550. Logger::instance().info("Audio playback finished naturally");
  1551. return;
  1552. }
  1553. frameCount++;
  1554. Logger::instance().debug("Audio play thread got frame #" + std::to_string(frameCount)
  1555. + ", pts=" + std::to_string(frame->pts)
  1556. + ", nb_samples=" + std::to_string(frame->nb_samples));
  1557. // frame 本身就是智能指针,直接使用
  1558. AVFramePtr& framePtr = frame;
  1559. // 计算音频PTS
  1560. double pts = frame->pts
  1561. * av_q2d(m_formatContext->streams[m_mediaInfo.audioStreamIndex]->time_base);
  1562. // 只在非暂停状态下更新音频时钟
  1563. m_synchronizer->setClock(av::utils::ClockType::AUDIO, pts, 0);
  1564. // 同步音频样本数量
  1565. int originalSamples = frame->nb_samples;
  1566. int adjustedSamples = m_synchronizer->synchronizeAudio((short*) frame->data[0],
  1567. frame->nb_samples,
  1568. pts);
  1569. if (adjustedSamples != originalSamples) {
  1570. Logger::instance().debug("Audio samples adjusted from " + std::to_string(originalSamples)
  1571. + " to " + std::to_string(adjustedSamples) + " for sync");
  1572. }
  1573. if (m_paused) {
  1574. continue;
  1575. }
  1576. {
  1577. Logger::instance().debug("Writing audio frame to output device");
  1578. bool writeResult = m_audioOutput->writeFrame(framePtr);
  1579. Logger::instance().debug("Audio frame write result: " + std::to_string(writeResult));
  1580. // 如果写入失败,等待一段时间避免快速循环
  1581. if (!writeResult) {
  1582. Logger::instance().warning("Audio frame write failed, waiting before next frame");
  1583. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1584. }
  1585. }
  1586. // framePtr 会自动释放内存,无需手动调用 av_frame_free
  1587. }
  1588. Logger::instance().info("Audio play thread finished, total frames processed: "
  1589. + std::to_string(frameCount));
  1590. }
  1591. } // namespace player
  1592. } // namespace av