player_core_v2.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  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. AVFrame* PlayerCoreV2::getNextVideoFrame() {
  555. if (!m_videoFrameQueue || m_state != PlayerState::Playing) {
  556. return nullptr;
  557. }
  558. return m_videoFrameQueue->pop();
  559. }
  560. AVFrame* PlayerCoreV2::getNextAudioFrame() {
  561. if (!m_audioFrameQueue || m_state != PlayerState::Playing) {
  562. return nullptr;
  563. }
  564. return m_audioFrameQueue->pop();
  565. }
  566. void PlayerCoreV2::releaseVideoFrame(AVFrame* frame) {
  567. if (frame) {
  568. av_frame_free(&frame);
  569. }
  570. }
  571. void PlayerCoreV2::releaseAudioFrame(AVFrame* frame) {
  572. if (frame) {
  573. av_frame_free(&frame);
  574. }
  575. }
  576. void PlayerCoreV2::update() {
  577. if (!m_initialized) {
  578. return;
  579. }
  580. // 更新同步状态
  581. updateSynchronization();
  582. // 更新统计信息
  583. auto now = std::chrono::steady_clock::now();
  584. if (std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastStatsUpdate).count() > 500) {
  585. updateStats();
  586. updatePerformanceStats();
  587. m_lastStatsUpdate = now;
  588. // 通知位置变化
  589. notifyPositionChanged();
  590. }
  591. // 检查错误恢复
  592. if (m_errorCount > 0) {
  593. auto timeSinceError = std::chrono::duration_cast<std::chrono::seconds>(now - m_lastErrorTime).count();
  594. if (timeSinceError > 5) { // 5秒后重置错误计数
  595. m_errorCount = 0;
  596. }
  597. }
  598. }
  599. std::string PlayerCoreV2::getDebugInfo() const {
  600. std::ostringstream oss;
  601. oss << "PlayerCoreV2 Debug Info:\n";
  602. oss << " State: " << static_cast<int>(m_state.load()) << "\n";
  603. oss << " Initialized: " << (m_initialized ? "Yes" : "No") << "\n";
  604. oss << " Threads Running: " << (m_threadsRunning ? "Yes" : "No") << "\n";
  605. oss << " Current Time: " << getCurrentTime() << " us\n";
  606. oss << " Playback Speed: " << m_playbackSpeed << "x\n";
  607. oss << " Volume: " << m_volume << "\n";
  608. oss << " Error Count: " << m_errorCount << "\n";
  609. if (m_synchronizer) {
  610. oss << "\n" << m_synchronizer->getDebugInfo();
  611. }
  612. return oss.str();
  613. }
  614. void PlayerCoreV2::dumpStats() const {
  615. PlaybackStats stats = getStats();
  616. Logger::instance().info("=== PlayerCoreV2 Statistics ===");
  617. Logger::instance().info("Current Time: " + std::to_string(stats.currentTime) + " us");
  618. Logger::instance().info("Total Frames: " + std::to_string(stats.totalFrames));
  619. Logger::instance().info("Dropped Frames: " + std::to_string(stats.droppedFrames));
  620. Logger::instance().info("Duplicated Frames: " + std::to_string(stats.duplicatedFrames));
  621. Logger::instance().info("Sync Error: " + std::to_string(stats.syncError * 1000) + " ms");
  622. Logger::instance().info("Avg Sync Error: " + std::to_string(stats.avgSyncError * 1000) + " ms");
  623. Logger::instance().info("Max Sync Error: " + std::to_string(stats.maxSyncError * 1000) + " ms");
  624. Logger::instance().info("CPU Usage: " + std::to_string(stats.cpuUsage) + "%");
  625. Logger::instance().info("Memory Usage: " + std::to_string(stats.memoryUsage) + " MB");
  626. Logger::instance().info("Queued Packets: " + std::to_string(stats.queuedPackets));
  627. Logger::instance().info("Queued Video Frames: " + std::to_string(stats.queuedVideoFrames));
  628. Logger::instance().info("Queued Audio Frames: " + std::to_string(stats.queuedAudioFrames));
  629. Logger::instance().info("===============================");
  630. }
  631. bool PlayerCoreV2::openMediaFile(const std::string& filename) {
  632. // 关闭之前的文件
  633. if (m_formatContext) {
  634. avformat_close_input(&m_formatContext);
  635. m_formatContext = nullptr;
  636. }
  637. // 分配格式上下文
  638. m_formatContext = avformat_alloc_context();
  639. if (!m_formatContext) {
  640. Logger::instance().error("Failed to allocate format context");
  641. return false;
  642. }
  643. // 打开输入文件
  644. if (avformat_open_input(&m_formatContext, filename.c_str(), nullptr, nullptr) < 0) {
  645. Logger::instance().error("Failed to open input file: " + filename);
  646. avformat_free_context(m_formatContext);
  647. m_formatContext = nullptr;
  648. return false;
  649. }
  650. // 查找流信息
  651. if (avformat_find_stream_info(m_formatContext, nullptr) < 0) {
  652. Logger::instance().error("Failed to find stream info");
  653. avformat_close_input(&m_formatContext);
  654. return false;
  655. }
  656. // 查找视频和音频流
  657. m_mediaInfo.videoStreamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
  658. m_mediaInfo.audioStreamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
  659. m_mediaInfo.hasVideo = (m_mediaInfo.videoStreamIndex >= 0);
  660. m_mediaInfo.hasAudio = (m_mediaInfo.audioStreamIndex >= 0);
  661. if (!m_mediaInfo.hasVideo && !m_mediaInfo.hasAudio) {
  662. Logger::instance().error("No video or audio streams found");
  663. avformat_close_input(&m_formatContext);
  664. return false;
  665. }
  666. // 获取媒体信息
  667. m_mediaInfo.duration = m_formatContext->duration;
  668. m_mediaInfo.bitrate = m_formatContext->bit_rate;
  669. if (m_mediaInfo.hasVideo) {
  670. AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
  671. m_mediaInfo.width = videoStream->codecpar->width;
  672. m_mediaInfo.height = videoStream->codecpar->height;
  673. // 计算帧率
  674. if (videoStream->avg_frame_rate.den != 0) {
  675. m_mediaInfo.fps = av_q2d(videoStream->avg_frame_rate);
  676. } else if (videoStream->r_frame_rate.den != 0) {
  677. m_mediaInfo.fps = av_q2d(videoStream->r_frame_rate);
  678. } else {
  679. m_mediaInfo.fps = 25.0; // 默认帧率
  680. }
  681. Logger::instance().info("Video stream found: " + std::to_string(m_mediaInfo.width) + "x" +
  682. std::to_string(m_mediaInfo.height) + " @ " + std::to_string(m_mediaInfo.fps) + " fps");
  683. }
  684. if (m_mediaInfo.hasAudio) {
  685. AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
  686. m_mediaInfo.sampleRate = audioStream->codecpar->sample_rate;
  687. m_mediaInfo.channels = audioStream->codecpar->ch_layout.nb_channels;
  688. Logger::instance().info("Audio stream found: " + std::to_string(m_mediaInfo.sampleRate) + " Hz, " +
  689. std::to_string(m_mediaInfo.channels) + " channels");
  690. }
  691. // 设置同步器的流信息
  692. if (m_synchronizer) {
  693. bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
  694. bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
  695. m_synchronizer->setStreamInfo(useAudio, useVideo);
  696. Logger::instance().info("Synchronizer stream info set: hasAudio=" + std::to_string(useAudio) +
  697. ", hasVideo=" + std::to_string(useVideo));
  698. // 在设置流信息后初始化同步器,确保主时钟选择基于正确的流信息
  699. if (m_synchronizer->initialize() != ErrorCode::SUCCESS) {
  700. Logger::instance().error("Failed to initialize synchronizer");
  701. return false;
  702. }
  703. Logger::instance().info("Synchronizer initialized with correct stream info");
  704. }
  705. Logger::instance().info("Media file opened successfully: " + filename);
  706. return true;
  707. }
  708. bool PlayerCoreV2::setupVideoDecoder() {
  709. if (!m_mediaInfo.hasVideo || !m_videoDecoder) {
  710. return false;
  711. }
  712. AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
  713. // 查找解码器
  714. const AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
  715. if (!codec) {
  716. Logger::instance().error("Video codec not found");
  717. return false;
  718. }
  719. Logger::instance().info("Found video codec: " + std::string(codec->name));
  720. Logger::instance().info("Video stream info: width=" + std::to_string(videoStream->codecpar->width) +
  721. ", height=" + std::to_string(videoStream->codecpar->height) +
  722. ", format=" + std::to_string(videoStream->codecpar->format));
  723. // 创建视频解码器参数
  724. VideoDecoderParams videoParams;
  725. videoParams.codecName = codec->name;
  726. videoParams.width = videoStream->codecpar->width;
  727. videoParams.height = videoStream->codecpar->height;
  728. videoParams.pixelFormat = static_cast<AVPixelFormat>(videoStream->codecpar->format);
  729. videoParams.hardwareAccel = false; // 先禁用硬件加速来排除问题
  730. videoParams.lowLatency = false;
  731. Logger::instance().info("Video decoder params: codec=" + videoParams.codecName +
  732. ", size=" + std::to_string(videoParams.width) + "x" + std::to_string(videoParams.height) +
  733. ", format=" + std::to_string(static_cast<int>(videoParams.pixelFormat)));
  734. // 初始化视频解码器
  735. if (m_videoDecoder->initialize(videoParams) != ErrorCode::SUCCESS) {
  736. Logger::instance().error("Failed to initialize video decoder");
  737. return false;
  738. }
  739. // 设置流参数
  740. if (m_videoDecoder->setStreamParameters(videoStream->codecpar) != ErrorCode::SUCCESS) {
  741. Logger::instance().error("Failed to set video decoder stream parameters");
  742. return false;
  743. }
  744. // 打开视频解码器
  745. if (m_videoDecoder->open(videoParams) != ErrorCode::SUCCESS) {
  746. Logger::instance().error("Failed to open video decoder");
  747. return false;
  748. }
  749. Logger::instance().info("Video decoder setup successfully");
  750. return true;
  751. }
  752. bool PlayerCoreV2::setupAudioDecoder() {
  753. if (!m_mediaInfo.hasAudio || !m_audioDecoder) {
  754. return false;
  755. }
  756. AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
  757. // 查找解码器
  758. const AVCodec* codec = avcodec_find_decoder(audioStream->codecpar->codec_id);
  759. if (!codec) {
  760. Logger::instance().error("Audio codec not found");
  761. return false;
  762. }
  763. // 分配解码器上下文
  764. AVCodecContext* codecContext = avcodec_alloc_context3(codec);
  765. if (!codecContext) {
  766. Logger::instance().error("Failed to allocate audio codec context");
  767. return false;
  768. }
  769. // 复制流参数到解码器上下文
  770. if (avcodec_parameters_to_context(codecContext, audioStream->codecpar) < 0) {
  771. Logger::instance().error("Failed to copy audio codec parameters");
  772. avcodec_free_context(&codecContext);
  773. return false;
  774. }
  775. // 打开解码器
  776. if (avcodec_open2(codecContext, codec, nullptr) < 0) {
  777. Logger::instance().error("Failed to open audio codec");
  778. avcodec_free_context(&codecContext);
  779. return false;
  780. }
  781. // 创建音频解码器参数
  782. AudioDecoderParams audioParams;
  783. audioParams.codecName = codec->name;
  784. audioParams.sampleRate = codecContext->sample_rate;
  785. audioParams.channels = codecContext->ch_layout.nb_channels;
  786. audioParams.sampleFormat = codecContext->sample_fmt;
  787. audioParams.lowLatency = false;
  788. audioParams.enableResampling = true;
  789. // 初始化音频解码器
  790. if (m_audioDecoder->initialize(audioParams) != ErrorCode::SUCCESS) {
  791. Logger::instance().error("Failed to initialize audio decoder");
  792. avcodec_free_context(&codecContext);
  793. return false;
  794. }
  795. // 打开音频解码器
  796. if (m_audioDecoder->open(audioParams) != ErrorCode::SUCCESS) {
  797. Logger::instance().error("Failed to open audio decoder");
  798. avcodec_free_context(&codecContext);
  799. return false;
  800. }
  801. // 初始化音频输出设备
  802. if (m_audioOutput && !m_audioOutput->initialize(codecContext->sample_rate,
  803. codecContext->ch_layout.nb_channels,
  804. codecContext->sample_fmt)) {
  805. Logger::instance().error("Failed to initialize audio output");
  806. avcodec_free_context(&codecContext);
  807. return false;
  808. }
  809. // 释放解码器上下文
  810. avcodec_free_context(&codecContext);
  811. Logger::instance().info("Audio decoder setup successfully");
  812. return true;
  813. }
  814. void PlayerCoreV2::resetDecoders() {
  815. if (m_videoDecoder) {
  816. m_videoDecoder->reset();
  817. }
  818. if (m_audioDecoder) {
  819. m_audioDecoder->reset();
  820. }
  821. }
  822. bool PlayerCoreV2::startReadThread() {
  823. try {
  824. // 确保之前的线程已经完全停止
  825. if (m_readThread.joinable()) {
  826. Logger::instance().warning("Read thread still running, waiting for it to stop...");
  827. m_readThread.join();
  828. }
  829. m_readThread = std::thread(&PlayerCoreV2::readThreadFunc, this);
  830. Logger::instance().info("Read thread started");
  831. return true;
  832. } catch (const std::exception& e) {
  833. Logger::instance().error("Failed to start read thread: " + std::string(e.what()));
  834. return false;
  835. }
  836. }
  837. bool PlayerCoreV2::startDecodeThreads() {
  838. try {
  839. if (m_mediaInfo.hasVideo) {
  840. // 确保之前的视频解码线程已经完全停止
  841. if (m_videoDecodeThread.joinable()) {
  842. Logger::instance().warning("Video decode thread still running, waiting for it to stop...");
  843. m_videoDecodeThread.join();
  844. }
  845. m_videoDecodeThread = std::thread(&PlayerCoreV2::videoDecodeThreadFunc, this);
  846. Logger::instance().info("Video decode thread started");
  847. }
  848. if (m_mediaInfo.hasAudio) {
  849. // 确保之前的音频解码线程已经完全停止
  850. if (m_audioDecodeThread.joinable()) {
  851. Logger::instance().warning("Audio decode thread still running, waiting for it to stop...");
  852. m_audioDecodeThread.join();
  853. }
  854. m_audioDecodeThread = std::thread(&PlayerCoreV2::audioDecodeThreadFunc, this);
  855. Logger::instance().info("Audio decode thread started");
  856. }
  857. return true;
  858. } catch (const std::exception& e) {
  859. Logger::instance().error("Failed to start decode threads: " + std::string(e.what()));
  860. return false;
  861. }
  862. }
  863. bool PlayerCoreV2::startVideoPlayThread() {
  864. try {
  865. // 确保之前的视频播放线程已经完全停止
  866. if (m_videoPlayThread.joinable()) {
  867. Logger::instance().warning("Video play thread still running, waiting for it to stop...");
  868. m_videoPlayThread.join();
  869. }
  870. m_videoPlayThread = std::thread(&PlayerCoreV2::videoPlayThreadFunc, this);
  871. Logger::instance().info("Video play thread started");
  872. return true;
  873. } catch (const std::exception& e) {
  874. Logger::instance().error("Failed to start video play thread: " + std::string(e.what()));
  875. return false;
  876. }
  877. }
  878. bool PlayerCoreV2::startAudioPlayThread() {
  879. try {
  880. // 确保之前的音频播放线程已经完全停止
  881. if (m_audioPlayThread.joinable()) {
  882. Logger::instance().warning("Audio play thread still running, waiting for it to stop...");
  883. m_audioPlayThread.join();
  884. }
  885. m_audioPlayThread = std::thread(&PlayerCoreV2::audioPlayThreadFunc, this);
  886. Logger::instance().info("Audio play thread started");
  887. return true;
  888. } catch (const std::exception& e) {
  889. Logger::instance().error("Failed to start audio play thread: " + std::string(e.what()));
  890. return false;
  891. }
  892. }
  893. bool PlayerCoreV2::initializeFFmpeg() {
  894. // FFmpeg初始化逻辑
  895. av_log_set_level(AV_LOG_WARNING);
  896. return true;
  897. }
  898. void PlayerCoreV2::cleanup() {
  899. stopAllThreads();
  900. if (m_formatContext) {
  901. avformat_close_input(&m_formatContext);
  902. m_formatContext = nullptr;
  903. }
  904. // if (m_synchronizer) {
  905. // m_synchronizer->close();
  906. // }
  907. }
  908. void PlayerCoreV2::setState(PlayerState newState) {
  909. PlayerState oldState = m_state.exchange(newState);
  910. if (oldState != newState) {
  911. notifyStateChanged(newState);
  912. }
  913. }
  914. void PlayerCoreV2::notifyStateChanged(PlayerState newState) {
  915. if (m_eventCallback) {
  916. m_eventCallback->onStateChanged(newState);
  917. }
  918. }
  919. void PlayerCoreV2::notifyError(const std::string& error) {
  920. Logger::instance().error(error);
  921. if (m_eventCallback) {
  922. m_eventCallback->onErrorOccurred(error);
  923. }
  924. }
  925. void PlayerCoreV2::notifyPositionChanged() {
  926. if (m_eventCallback) {
  927. m_eventCallback->onPositionChanged(getCurrentTime());
  928. }
  929. }
  930. void PlayerCoreV2::handleSyncError(double error, const std::string& reason) {
  931. Logger::instance().warning("Sync error: " + std::to_string(error * 1000) + "ms, reason: " + reason);
  932. if (m_eventCallback) {
  933. m_eventCallback->onSyncError(error, reason);
  934. }
  935. // 如果同步误差太大,尝试恢复
  936. if (error > 0.2) { // 200ms
  937. attemptRecovery();
  938. }
  939. }
  940. void PlayerCoreV2::attemptRecovery() {
  941. m_errorCount++;
  942. m_lastErrorTime = std::chrono::steady_clock::now();
  943. Logger::instance().warning("Attempting recovery, error count: " + std::to_string(m_errorCount.load()));
  944. if (m_errorCount > 5) {
  945. Logger::instance().error("Too many errors, stopping playback");
  946. handleError("Too many sync errors");
  947. return;
  948. }
  949. // // 重置同步器
  950. // if (m_synchronizer) {
  951. // m_synchronizer->reset();
  952. // }
  953. // 清空部分缓冲区
  954. if (m_videoFrameQueue) {
  955. m_videoFrameQueue->clear();
  956. }
  957. if (m_audioFrameQueue) {
  958. m_audioFrameQueue->clear();
  959. }
  960. }
  961. void PlayerCoreV2::handleError(const std::string& error) {
  962. setState(PlayerState::Error);
  963. notifyError(error);
  964. }
  965. void PlayerCoreV2::updateSynchronization() {
  966. if (!m_synchronizer || !m_threadsRunning) {
  967. return;
  968. }
  969. // 同步器会在内部自动更新
  970. // 更新同步器统计信息
  971. //m_synchronizer->updateStats();
  972. // 获取同步器统计信息并更新播放器统计
  973. std::lock_guard<std::mutex> lock(m_mutex);
  974. auto syncStats = m_synchronizer->getStats();
  975. m_stats.syncError = syncStats.audioVideoSyncError;
  976. m_stats.avgSyncError = syncStats.avgSyncError;
  977. m_stats.maxSyncError = syncStats.maxSyncError;
  978. m_stats.droppedFrames = syncStats.droppedFrames;
  979. m_stats.duplicatedFrames = syncStats.duplicatedFrames;
  980. }
  981. void PlayerCoreV2::updateStats() {
  982. std::lock_guard<std::mutex> lock(m_mutex);
  983. // 更新帧率统计
  984. int64_t currentFrameCount = m_frameCount;
  985. int64_t frameDiff = currentFrameCount - m_lastFrameCount;
  986. m_lastFrameCount = currentFrameCount;
  987. // 计算比特率等其他统计信息
  988. if (m_formatContext) {
  989. m_stats.bitrate = m_formatContext->bit_rate / 1000.0; // kbps
  990. }
  991. }
  992. void PlayerCoreV2::updatePerformanceStats() {
  993. std::lock_guard<std::mutex> lock(m_mutex);
  994. m_stats.cpuUsage = calculateCpuUsage();
  995. m_stats.memoryUsage = calculateMemoryUsage();
  996. }
  997. double PlayerCoreV2::calculateCpuUsage() {
  998. return 0.0;
  999. }
  1000. double PlayerCoreV2::calculateMemoryUsage() {
  1001. return 0.0;
  1002. }
  1003. void PlayerCoreV2::stopAllThreads() {
  1004. Logger::instance().info("Stopping all threads...");
  1005. m_threadsShouldStop = true;
  1006. // 唤醒所有等待的队列,确保线程能够检查停止标志
  1007. flushBuffers();
  1008. // 等待线程结束,添加超时保护
  1009. auto joinWithTimeout = [](std::thread& t, const std::string& name) {
  1010. if (t.joinable()) {
  1011. Logger::instance().info("Waiting for " + name + " to stop...");
  1012. t.join();
  1013. Logger::instance().info(name + " stopped");
  1014. }
  1015. };
  1016. joinWithTimeout(m_readThread, "read thread");
  1017. joinWithTimeout(m_videoDecodeThread, "video decode thread");
  1018. joinWithTimeout(m_audioDecodeThread, "audio decode thread");
  1019. joinWithTimeout(m_videoPlayThread, "video play thread");
  1020. joinWithTimeout(m_audioPlayThread, "audio play thread");
  1021. m_threadsRunning = false;
  1022. Logger::instance().info("All threads stopped successfully");
  1023. }
  1024. void PlayerCoreV2::flushBuffers() {
  1025. if (m_videoPacketQueue) {
  1026. m_videoPacketQueue->clear();
  1027. m_videoPacketQueue->wakeup(); // 唤醒等待的解码线程
  1028. }
  1029. if (m_audioPacketQueue) {
  1030. m_audioPacketQueue->clear();
  1031. m_audioPacketQueue->wakeup(); // 唤醒等待的解码线程
  1032. }
  1033. if (m_videoFrameQueue) {
  1034. m_videoFrameQueue->clear();
  1035. m_videoFrameQueue->wakeup(); // 唤醒等待的播放线程
  1036. }
  1037. if (m_audioFrameQueue) {
  1038. m_audioFrameQueue->clear();
  1039. m_audioFrameQueue->wakeup(); // 唤醒等待的播放线程
  1040. }
  1041. }
  1042. void PlayerCoreV2::readThreadFunc() {
  1043. Logger::instance().info("Read thread started");
  1044. AVPacket* packet = av_packet_alloc();
  1045. if (!packet) {
  1046. Logger::instance().error("Failed to allocate packet");
  1047. return;
  1048. }
  1049. while (!m_threadsShouldStop) {
  1050. // 检查暂停状态,类似ffplay.c中的paused检查
  1051. bool pausedState = m_paused.load();
  1052. Logger::instance().debug("Read thread loop - m_paused: " + std::to_string(pausedState));
  1053. if (pausedState) {
  1054. Logger::instance().info("Read thread entering pause wait");
  1055. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1056. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1057. if (m_threadsShouldStop) {
  1058. break;
  1059. }
  1060. Logger::instance().info("Read thread exiting pause wait");
  1061. // 暂停状态结束后,继续下一次循环
  1062. continue;
  1063. }
  1064. // 检查是否需要seek
  1065. if (m_seeking) {
  1066. std::unique_lock<std::mutex> lock(m_seekMutex);
  1067. // 获取seek参数
  1068. int64_t seekMinTime = m_seekMinTime;
  1069. int64_t seekTarget = m_seekTarget;
  1070. int64_t seekMaxTime = m_seekMaxTime;
  1071. int flags = m_seekFlags;
  1072. Logger::instance().info("Performing precise seek - min: " + std::to_string(seekMinTime) +
  1073. ", target: " + std::to_string(seekTarget) +
  1074. ", max: " + std::to_string(seekMaxTime) +
  1075. ", flags: " + std::to_string(flags));
  1076. // 首先尝试定位到最近的关键帧以确保视频解码正常
  1077. int ret = av_seek_frame(m_formatContext, -1, seekTarget, AVSEEK_FLAG_BACKWARD);
  1078. if (ret < 0) {
  1079. Logger::instance().warning("Video keyframe seek failed, trying precise seek");
  1080. // 如果关键帧定位失败,回退到精确seek
  1081. ret = avformat_seek_file(m_formatContext, -1, seekMinTime, seekTarget, seekMaxTime, flags);
  1082. if (ret < 0) {
  1083. Logger::instance().error("All seek methods failed");
  1084. } else {
  1085. Logger::instance().info("Fallback precise seek completed to: " + std::to_string(seekTarget));
  1086. }
  1087. } else {
  1088. Logger::instance().info("Keyframe seek completed successfully to target: " + std::to_string(seekTarget));
  1089. }
  1090. // 清空缓冲区
  1091. flushBuffers();
  1092. // 重置解码器
  1093. resetDecoders();
  1094. // 重置时间
  1095. if (flags & AVSEEK_FLAG_BYTE) {
  1096. m_synchronizer->setClock(av::utils::ClockType::EXTERNAL, NAN, 0);
  1097. } else {
  1098. m_synchronizer->setClock(av::utils::ClockType::EXTERNAL,
  1099. seekTarget / (double) AV_TIME_BASE,
  1100. 0);
  1101. }
  1102. m_seeking = false;
  1103. setState(m_state == PlayerState::Seeking ? PlayerState::Playing : m_state.load());
  1104. lock.unlock();
  1105. m_seekCondition.notify_all();
  1106. }
  1107. // 检查队列是否接近容量上限 - 使用队列容量的90%作为警告阈值,但不丢弃包
  1108. bool videoQueueNearFull = m_videoPacketQueue && m_videoPacketQueue->size() > 800;
  1109. bool audioQueueNearFull = m_audioPacketQueue && m_audioPacketQueue->size() > 800;
  1110. if (videoQueueNearFull || audioQueueNearFull) {
  1111. // 队列接近满,暂停一段时间让解码线程处理
  1112. Logger::instance().warning("Packet queue is getting large: Video=" +
  1113. std::to_string(m_videoPacketQueue ? m_videoPacketQueue->size() : 0) +
  1114. ", Audio=" + std::to_string(m_audioPacketQueue ? m_audioPacketQueue->size() : 0) +
  1115. ". Slowing down read thread.");
  1116. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  1117. continue;
  1118. }
  1119. // 在读取数据包前检查暂停状态,避免在读取期间阻塞
  1120. if (m_paused.load()) {
  1121. Logger::instance().debug("Read thread detected pause before av_read_frame");
  1122. continue;
  1123. }
  1124. // 读取数据包
  1125. int ret = av_read_frame(m_formatContext, packet);
  1126. if (ret < 0) {
  1127. if (ret == AVERROR_EOF) {
  1128. Logger::instance().info("End of file reached, sending EOF packets to queues");
  1129. // 向视频和音频队列分别发送EOF标记,让解码线程知道文件结束
  1130. if (m_videoPacketQueue && m_mediaInfo.hasVideo) {
  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_videoPacketQueue->push(eofPacket);
  1137. Logger::instance().info("EOF packet sent to video queue");
  1138. }
  1139. }
  1140. if (m_audioPacketQueue && m_mediaInfo.hasAudio) {
  1141. AVPacket* eofPacket = av_packet_alloc();
  1142. if (eofPacket) {
  1143. eofPacket->data = nullptr;
  1144. eofPacket->size = 0;
  1145. eofPacket->stream_index = -1; // 特殊标记表示EOF
  1146. m_audioPacketQueue->push(eofPacket);
  1147. Logger::instance().info("EOF packet sent to audio queue");
  1148. }
  1149. }
  1150. break;
  1151. } else {
  1152. Logger::instance().error("Error reading frame: " + std::to_string(ret));
  1153. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1154. continue;
  1155. }
  1156. }
  1157. // 根据流索引将数据包分发到对应队列
  1158. if (packet->stream_index == m_mediaInfo.videoStreamIndex && m_videoStreamEnabled) {
  1159. // 视频包放入视频队列 - 不考虑队列是否已满,确保不丢包
  1160. if (m_videoPacketQueue) {
  1161. AVPacket* packetCopy = av_packet_alloc();
  1162. if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
  1163. m_videoPacketQueue->push(packetCopy);
  1164. // 记录队列大小,用于监控
  1165. if (m_videoPacketQueue->size() % 100 == 0) {
  1166. Logger::instance().debug("Video packet queue size: " + std::to_string(m_videoPacketQueue->size()));
  1167. }
  1168. } else {
  1169. av_packet_free(&packetCopy);
  1170. }
  1171. }
  1172. } else if (packet->stream_index == m_mediaInfo.audioStreamIndex && m_audioStreamEnabled) {
  1173. // 音频包放入音频队列 - 不考虑队列是否已满,确保不丢包
  1174. if (m_audioPacketQueue) {
  1175. AVPacket* packetCopy = av_packet_alloc();
  1176. if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
  1177. m_audioPacketQueue->push(packetCopy);
  1178. // 记录队列大小,用于监控
  1179. if (m_audioPacketQueue->size() % 100 == 0) {
  1180. Logger::instance().debug("Audio packet queue size: " + std::to_string(m_audioPacketQueue->size()));
  1181. }
  1182. } else {
  1183. av_packet_free(&packetCopy);
  1184. }
  1185. }
  1186. }
  1187. m_audioPacketQueue->wakeup();
  1188. m_videoPacketQueue->wakeup();
  1189. av_packet_unref(packet);
  1190. }
  1191. av_packet_free(&packet);
  1192. Logger::instance().info("Read thread finished");
  1193. }
  1194. void PlayerCoreV2::videoDecodeThreadFunc() {
  1195. Logger::instance().info("Video decode thread started");
  1196. int packetCount = 0;
  1197. int frameCount = 0;
  1198. while (!m_threadsShouldStop) {
  1199. // 检查暂停状态,类似ffplay.c中的paused检查
  1200. bool pausedState = m_paused.load();
  1201. Logger::instance().debug("Video decode thread loop - m_paused: "
  1202. + std::to_string(pausedState));
  1203. if (pausedState) {
  1204. Logger::instance().info("Video decode thread entering pause wait");
  1205. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1206. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1207. if (m_threadsShouldStop) {
  1208. break;
  1209. }
  1210. Logger::instance().info("Video decode thread exiting pause wait");
  1211. // 暂停状态结束后,继续下一次循环
  1212. continue;
  1213. }
  1214. if (!m_videoPacketQueue || !m_videoFrameQueue || !m_videoDecoder) {
  1215. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1216. continue;
  1217. }
  1218. if (m_seeking) {
  1219. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1220. continue;
  1221. }
  1222. Logger::instance().info("Video decode thread read Packet111");
  1223. // 从视频包队列获取包
  1224. AVPacket* packet = nullptr;
  1225. while (!m_threadsShouldStop && !packet) {
  1226. // 在 pop 操作前检查暂停状态,避免在 pop 期间阻塞
  1227. if (m_paused.load()) {
  1228. Logger::instance().debug("Video decode thread detected pause before pop");
  1229. break;
  1230. }
  1231. Logger::instance().info("Video decode thread read Packet");
  1232. packet = m_videoPacketQueue->pop(10); // 减少超时时间以提高seek响应速度
  1233. Logger::instance().infof("Video decode thread read Packet %d", packet);
  1234. if (packet) {
  1235. // 检查是否是EOF标记
  1236. if (packet->stream_index == -1 && packet->data == nullptr) {
  1237. Logger::instance().info("Video decode thread received EOF packet");
  1238. av_packet_free(&packet);
  1239. // 向视频帧队列发送EOF标记
  1240. if (m_videoFrameQueue) {
  1241. AVFrame* eofFrame = av_frame_alloc();
  1242. if (eofFrame) {
  1243. eofFrame->data[0] = nullptr;
  1244. eofFrame->width = 0;
  1245. eofFrame->height = 0;
  1246. eofFrame->pts = AV_NOPTS_VALUE;
  1247. m_videoFrameQueue->push(eofFrame);
  1248. Logger::instance().info("EOF frame sent to video frame queue");
  1249. }
  1250. }
  1251. // 视频解码线程结束
  1252. Logger::instance().info("Video decode thread finishing due to EOF");
  1253. return;
  1254. }
  1255. }
  1256. if (!packet) {
  1257. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  1258. }
  1259. }
  1260. if (!packet) {
  1261. Logger::instance().debug("Video decode thread: no more packets available");
  1262. continue;
  1263. }
  1264. packetCount++;
  1265. Logger::instance().debug("Video decode thread got packet #" + std::to_string(packetCount) +
  1266. ", size=" + std::to_string(packet->size) +
  1267. ", pts=" + std::to_string(packet->pts));
  1268. // 解码视频帧
  1269. AVPacketPtr packetPtr(packet);
  1270. std::vector<AVFramePtr> frames;
  1271. ErrorCode decodeResult = m_videoDecoder->decode(packetPtr, frames);
  1272. Logger::instance().debug("Video decode result: " + std::to_string(static_cast<int>(decodeResult)) +
  1273. ", frames count: " + std::to_string(frames.size()));
  1274. if (decodeResult == ErrorCode::SUCCESS) {
  1275. for (auto& framePtr : frames) {
  1276. if (framePtr && !m_threadsShouldStop) {
  1277. frameCount++;
  1278. Logger::instance().debug("Processing video frame #" + std::to_string(frameCount) +
  1279. ", width=" + std::to_string(framePtr->width) +
  1280. ", height=" + std::to_string(framePtr->height) +
  1281. ", pts=" + std::to_string(framePtr->pts));
  1282. // 设置帧的时间戳(保持原始PTS,在播放时再转换)
  1283. if (framePtr->pts != AV_NOPTS_VALUE) {
  1284. Logger::instance().debug("Frame PTS: " + std::to_string(framePtr->pts));
  1285. }
  1286. // 将帧放入队列 - 不丢弃任何帧
  1287. // 释放智能指针的所有权,让队列管理帧的生命周期
  1288. m_videoFrameQueue->push(framePtr.release());
  1289. m_frameCount++;
  1290. Logger::instance().debug("Video frame pushed to queue, queue size: " + std::to_string(m_videoFrameQueue->size()));
  1291. // 如果队列大小超过警告阈值,记录警告但不丢弃
  1292. if (m_videoFrameQueue->size() > 80) {
  1293. Logger::instance().warning("Video frame queue is getting large: " + std::to_string(m_videoFrameQueue->size()) +
  1294. " frames. Performance may be affected.");
  1295. }
  1296. }
  1297. }
  1298. } else {
  1299. Logger::instance().warning("Video decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
  1300. }
  1301. }
  1302. Logger::instance().info("Video decode thread finished, packets processed: "
  1303. + std::to_string(packetCount)
  1304. + ", frames decoded: " + std::to_string(frameCount));
  1305. }
  1306. void PlayerCoreV2::audioDecodeThreadFunc() {
  1307. Logger::instance().info("Audio decode thread started");
  1308. int packetCount = 0;
  1309. int frameCount = 0;
  1310. while (!m_threadsShouldStop) {
  1311. // 检查暂停状态,类似ffplay.c中的paused检查
  1312. bool pausedState = m_paused.load();
  1313. Logger::instance().debug("Audio decode thread loop - m_paused: "
  1314. + std::to_string(pausedState));
  1315. if (pausedState) {
  1316. Logger::instance().info("Audio decode thread entering pause wait");
  1317. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1318. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1319. if (m_threadsShouldStop) {
  1320. break;
  1321. }
  1322. Logger::instance().info("Audio decode thread exiting pause wait");
  1323. // 暂停状态结束后,继续下一次循环
  1324. continue;
  1325. }
  1326. if (!m_audioPacketQueue || !m_audioFrameQueue || !m_audioDecoder) {
  1327. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1328. continue;
  1329. }
  1330. if (m_seeking) {
  1331. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1332. continue;
  1333. }
  1334. // 从音频包队列获取包
  1335. AVPacket* packet = nullptr;
  1336. while (!m_threadsShouldStop && !packet) {
  1337. // 在 pop 操作前检查暂停状态,避免在 pop 期间阻塞
  1338. if (m_paused.load()) {
  1339. Logger::instance().debug("Audio decode thread detected pause before pop");
  1340. break;
  1341. }
  1342. packet = m_audioPacketQueue->pop(10); // 减少超时时间以提高seek响应速度
  1343. if (packet) {
  1344. // 检查是否是EOF标记
  1345. if (packet->stream_index == -1 && packet->data == nullptr) {
  1346. Logger::instance().info("Audio decode thread received EOF packet");
  1347. av_packet_free(&packet);
  1348. // 向音频帧队列发送EOF标记
  1349. if (m_audioFrameQueue) {
  1350. AVFrame* eofFrame = av_frame_alloc();
  1351. if (eofFrame) {
  1352. eofFrame->data[0] = nullptr;
  1353. eofFrame->nb_samples = 0;
  1354. eofFrame->pts = AV_NOPTS_VALUE;
  1355. m_audioFrameQueue->push(eofFrame);
  1356. Logger::instance().info("EOF frame sent to audio frame queue");
  1357. }
  1358. }
  1359. // 音频解码线程结束
  1360. Logger::instance().info("Audio decode thread finishing due to EOF");
  1361. return;
  1362. }
  1363. }
  1364. if (!packet) {
  1365. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  1366. }
  1367. }
  1368. if (!packet) {
  1369. Logger::instance().debug("Audio decode thread: no more packets available");
  1370. continue;
  1371. }
  1372. packetCount++;
  1373. Logger::instance().debug("Audio decode thread got packet #" + std::to_string(packetCount) +
  1374. ", size=" + std::to_string(packet->size) +
  1375. ", pts=" + std::to_string(packet->pts));
  1376. // 解码音频帧
  1377. AVPacketPtr packetPtr(packet);
  1378. std::vector<AVFramePtr> frames;
  1379. ErrorCode decodeResult = m_audioDecoder->decode(packetPtr, frames);
  1380. Logger::instance().debug("Audio decode result: " + std::to_string(static_cast<int>(decodeResult)) +
  1381. ", frames count: " + std::to_string(frames.size()));
  1382. if (decodeResult == ErrorCode::SUCCESS) {
  1383. for (auto& framePtr : frames) {
  1384. if (framePtr && !m_threadsShouldStop) {
  1385. frameCount++;
  1386. Logger::instance().debug("Processing audio frame #" + std::to_string(frameCount) +
  1387. ", nb_samples=" + std::to_string(framePtr->nb_samples) +
  1388. ", pts=" + std::to_string(framePtr->pts));
  1389. // 设置帧的时间戳(保持原始PTS,在播放时再转换)
  1390. if (framePtr->pts != AV_NOPTS_VALUE) {
  1391. Logger::instance().debug("Audio Frame PTS: " + std::to_string(framePtr->pts));
  1392. }
  1393. // 将帧放入队列 - 不丢弃任何帧
  1394. // 释放智能指针的所有权,让队列管理帧的生命周期
  1395. m_audioFrameQueue->push(framePtr.release());
  1396. Logger::instance().debug("Audio frame pushed to queue, queue size: " + std::to_string(m_audioFrameQueue->size()));
  1397. // 如果队列大小超过警告阈值,记录警告但不丢弃
  1398. if (m_audioFrameQueue->size() > 300) {
  1399. Logger::instance().warning("Audio frame queue is getting large: " + std::to_string(m_audioFrameQueue->size()) +
  1400. " frames. Performance may be affected.");
  1401. }
  1402. }
  1403. }
  1404. } else {
  1405. Logger::instance().warning("Audio decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
  1406. }
  1407. // packet已经被packetPtr管理,不需要手动释放
  1408. }
  1409. Logger::instance().info("Audio decode thread finished, packets processed: " + std::to_string(packetCount) +
  1410. ", frames decoded: " + std::to_string(frameCount));
  1411. }
  1412. void PlayerCoreV2::videoPlayThreadFunc() {
  1413. Logger::instance().info("Video play thread started");
  1414. // 用于计算帧持续时间的变量
  1415. AVFrame* lastFrame = nullptr;
  1416. while (!m_threadsShouldStop) {
  1417. // 检查暂停状态,类似ffplay.c中的paused检查
  1418. bool pausedState = m_paused.load();
  1419. Logger::instance().debug("Video play thread loop - m_paused: "
  1420. + std::to_string(pausedState));
  1421. if (pausedState) {
  1422. Logger::instance().info("Video play thread entering pause wait");
  1423. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1424. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1425. if (m_threadsShouldStop) {
  1426. break;
  1427. }
  1428. Logger::instance().info("Video play thread exiting pause wait");
  1429. // 暂停状态结束后,继续下一次循环
  1430. continue;
  1431. }
  1432. if (!m_videoFrameQueue || !m_synchronizer) {
  1433. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1434. continue;
  1435. }
  1436. // 在pop之前再次检查暂停状态,避免在pop期间阻塞
  1437. if (m_paused.load()) {
  1438. Logger::instance().debug("Video play thread detected pause before pop");
  1439. continue;
  1440. }
  1441. // 获取视频帧,使用更短的超时时间以提高暂停响应速度
  1442. AVFrame* frame = m_videoFrameQueue->pop(1); // 使用1ms超时以快速响应暂停
  1443. if (!frame) {
  1444. // 检查是否应该继续等待
  1445. if (m_threadsShouldStop) {
  1446. break;
  1447. }
  1448. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1449. continue;
  1450. }
  1451. // 获取帧后立即检查暂停状态,如果已暂停则释放帧并继续
  1452. bool pausedAfterPop = m_paused.load();
  1453. Logger::instance().debug("Video play thread after pop - m_paused: " + std::to_string(pausedAfterPop));
  1454. if (pausedAfterPop) {
  1455. Logger::instance().info("Video play thread releasing frame due to pause");
  1456. av_frame_free(&frame);
  1457. continue;
  1458. }
  1459. Logger::instance().debug("Video play thread got frame, pts=" + std::to_string(frame->pts));
  1460. // 创建智能指针管理帧内存
  1461. AVFramePtr framePtr(frame);
  1462. // 使用同步器计算视频帧显示时间
  1463. double pts = frame->pts * av_q2d(m_formatContext->streams[m_mediaInfo.videoStreamIndex]->time_base);
  1464. // 只在非暂停状态下更新时钟和处理帧
  1465. m_synchronizer->setClock(av::utils::ClockType::VIDEO, pts, 0);
  1466. // 计算帧持续时间
  1467. double last_duration = 0.0;
  1468. if (lastFrame && lastFrame->pts != AV_NOPTS_VALUE && frame->pts != AV_NOPTS_VALUE) {
  1469. // 计算两帧之间的时间差
  1470. double last_pts = lastFrame->pts * av_q2d(m_formatContext->streams[m_mediaInfo.videoStreamIndex]->time_base);
  1471. last_duration = pts - last_pts;
  1472. if (last_duration < 0 || last_duration > 10.0) {
  1473. // 如果持续时间不合理,使用帧率的倒数作为默认值
  1474. last_duration = 1.0 / m_mediaInfo.fps;
  1475. }
  1476. } else {
  1477. // 如果没有上一帧,使用帧率的倒数作为默认值
  1478. last_duration = 1.0 / m_mediaInfo.fps;
  1479. }
  1480. // 计算视频帧延迟并决定是否显示
  1481. FrameDecision decision = m_synchronizer->synchronizeVideo(pts, 0, last_duration);
  1482. if (decision.action == FrameAction::DISPLAY) {
  1483. // 如果需要延迟显示,等待指定时间
  1484. if (decision.delay > 0.0) {
  1485. std::this_thread::sleep_for(
  1486. std::chrono::microseconds(static_cast<int64_t>(decision.delay * 1000000)));
  1487. }
  1488. // 通知显示帧
  1489. if (m_eventCallback) {
  1490. m_eventCallback->onVideoFrameReady(framePtr.get());
  1491. Logger::instance().debug("Video frame ready for display, pts=" + std::to_string(pts) + ", delay=" + std::to_string(decision.delay));
  1492. }
  1493. // 更新上一帧指针
  1494. if (lastFrame) {
  1495. av_frame_free(&lastFrame);
  1496. }
  1497. lastFrame = av_frame_clone(frame);
  1498. } else if (decision.action == FrameAction::DROP) {
  1499. Logger::instance().debug("Video frame dropped due to sync, pts=" + std::to_string(pts) + ", error=" + std::to_string(decision.syncError));
  1500. }
  1501. }
  1502. // 清理最后一帧
  1503. if (lastFrame) {
  1504. av_frame_free(&lastFrame);
  1505. }
  1506. Logger::instance().info("Video play thread finished");
  1507. }
  1508. void PlayerCoreV2::audioPlayThreadFunc() {
  1509. Logger::instance().info("Audio play thread started");
  1510. int frameCount = 0;
  1511. while (!m_threadsShouldStop) {
  1512. // 检查暂停状态,类似ffplay.c中的paused检查
  1513. bool pausedState = m_paused.load();
  1514. Logger::instance().debug("Audio play thread loop - m_paused: "
  1515. + std::to_string(pausedState));
  1516. if (pausedState) {
  1517. Logger::instance().info("Audio play thread entering pause wait");
  1518. std::unique_lock<std::mutex> lock(m_pauseMutex);
  1519. m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
  1520. if (m_threadsShouldStop) {
  1521. break;
  1522. }
  1523. Logger::instance().info("Audio play thread exiting pause wait");
  1524. // 暂停状态结束后,继续下一次循环
  1525. continue;
  1526. }
  1527. if (!m_audioFrameQueue || !m_synchronizer || !m_audioOutput) {
  1528. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1529. continue;
  1530. }
  1531. // 在pop之前再次检查暂停状态,避免在pop期间阻塞
  1532. if (m_paused.load()) {
  1533. Logger::instance().debug("Audio play thread detected pause before pop");
  1534. continue;
  1535. }
  1536. // 获取音频帧,使用更短的超时时间以提高暂停响应速度
  1537. AVFrame* frame = m_audioFrameQueue->pop(1); // 使用1ms超时以快速响应暂停
  1538. if (!frame) {
  1539. // 检查是否应该继续等待
  1540. if (m_threadsShouldStop) {
  1541. break;
  1542. }
  1543. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1544. continue;
  1545. }
  1546. // 获取帧后立即检查暂停状态,如果已暂停则释放帧并继续
  1547. bool pausedAfterPop = m_paused.load();
  1548. Logger::instance().debug("Audio play thread after pop - m_paused: " + std::to_string(pausedAfterPop));
  1549. if (pausedAfterPop) {
  1550. Logger::instance().info("Audio play thread releasing frame due to pause");
  1551. av_frame_free(&frame);
  1552. continue;
  1553. }
  1554. // 检查是否是EOF帧
  1555. if (frame->data[0] == nullptr && frame->nb_samples == 0) {
  1556. Logger::instance().info("Audio play thread received EOF frame, playback completed");
  1557. av_frame_free(&frame);
  1558. // 通知播放完成
  1559. setState(PlayerState::Stopped);
  1560. Logger::instance().info("Audio playback finished naturally");
  1561. return;
  1562. }
  1563. frameCount++;
  1564. Logger::instance().debug("Audio play thread got frame #" + std::to_string(frameCount)
  1565. + ", pts=" + std::to_string(frame->pts)
  1566. + ", nb_samples=" + std::to_string(frame->nb_samples));
  1567. // 创建智能指针管理帧内存
  1568. AVFramePtr framePtr(frame);
  1569. // 计算音频PTS
  1570. double pts = frame->pts
  1571. * av_q2d(m_formatContext->streams[m_mediaInfo.audioStreamIndex]->time_base);
  1572. // 只在非暂停状态下更新音频时钟
  1573. m_synchronizer->setClock(av::utils::ClockType::AUDIO, pts, 0);
  1574. // 同步音频样本数量
  1575. int originalSamples = frame->nb_samples;
  1576. int adjustedSamples = m_synchronizer->synchronizeAudio((short*) frame->data[0],
  1577. frame->nb_samples,
  1578. pts);
  1579. if (adjustedSamples != originalSamples) {
  1580. Logger::instance().debug("Audio samples adjusted from " + std::to_string(originalSamples)
  1581. + " to " + std::to_string(adjustedSamples) + " for sync");
  1582. }
  1583. if (m_paused) {
  1584. continue;
  1585. }
  1586. {
  1587. Logger::instance().debug("Writing audio frame to output device");
  1588. bool writeResult = m_audioOutput->writeFrame(framePtr);
  1589. Logger::instance().debug("Audio frame write result: " + std::to_string(writeResult));
  1590. // 如果写入失败,等待一段时间避免快速循环
  1591. if (!writeResult) {
  1592. Logger::instance().warning("Audio frame write failed, waiting before next frame");
  1593. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1594. }
  1595. }
  1596. // framePtr 会自动释放内存,无需手动调用 av_frame_free
  1597. }
  1598. Logger::instance().info("Audio play thread finished, total frames processed: "
  1599. + std::to_string(frameCount));
  1600. }
  1601. } // namespace player
  1602. } // namespace av