player_core_v2.cpp 58 KB

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