player_core_v2.cpp 54 KB

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