player_core_v2.cpp 70 KB

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