player_core_v2.cpp 59 KB

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