| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557 |
- #include "player_core_v2.h"
- #include "../base/media_common.h"
- #include "../base/logger.h"
- #include "../base/types.h"
- #include "../codec/codec_video_decoder.h"
- #include "../codec/codec_audio_decoder.h"
- #include "../utils/utils_synchronizer_v2.h"
- #include <chrono>
- #include <thread>
- #include <algorithm>
- #ifdef _WIN32
- #include <windows.h>
- #include <psapi.h>
- #else
- #include <sys/times.h>
- #include <unistd.h>
- #endif
- namespace av {
- namespace player {
- PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
- : m_eventCallback(nullptr)
- , m_formatContext(nullptr)
- , m_openGLVideoRenderer(nullptr)
- , m_volume(1.0)
- , m_playbackSpeed(1.0)
- , m_seekTarget(-1)
- , m_seeking(false)
- , m_baseTime(0)
- , m_lastUpdateTime(0)
- , m_threadsShouldStop(false)
- , m_threadsRunning(false)
- , m_initialized(false)
- , m_frameCount(0)
- , m_lastFrameCount(0)
- , m_errorCount(0)
- , m_buffering(false)
- , m_bufferHealth(1.0)
- , m_state(PlayerState::Idle) {
-
- Logger::instance().info("PlayerCoreV2 created");
-
- try {
- // 初始化FFmpeg
- if (!initializeFFmpeg()) {
- Logger::instance().error("Failed to initialize FFmpeg");
- setState(PlayerState::Error);
- return;
- }
-
- // 创建队列
- m_packetQueue = av::utils::PacketQueueFactory::createStandardQueue(2000); // 增加队列大小
- if (!m_packetQueue) {
- Logger::instance().error("Failed to create packet queue");
- setState(PlayerState::Error);
- return;
- }
-
- m_videoFrameQueue = av::utils::FrameQueueFactory::createStandardQueue(50); // 增加视频帧队列
- if (!m_videoFrameQueue) {
- Logger::instance().error("Failed to create video frame queue");
- setState(PlayerState::Error);
- return;
- }
-
- m_audioFrameQueue = av::utils::FrameQueueFactory::createStandardQueue(200); // 增加音频帧队列
- if (!m_audioFrameQueue) {
- Logger::instance().error("Failed to create audio frame queue");
- setState(PlayerState::Error);
- return;
- }
-
- // 创建改进的同步器
- m_synchronizer = std::make_unique<SynchronizerV2>(syncConfig);
- if (!m_synchronizer) {
- Logger::instance().error("Failed to create synchronizer");
- setState(PlayerState::Error);
- return;
- }
-
- // 设置同步器回调
- m_synchronizer->setSyncErrorCallback([this](double error, const std::string& reason) {
- handleSyncError(error, reason);
- });
-
- m_synchronizer->setFrameDropCallback([this](av::utils::ClockType type, double pts) {
- std::lock_guard<std::mutex> lock(m_mutex);
- m_stats.droppedFrames++;
- if (m_eventCallback) {
- m_eventCallback->onFrameDropped(m_stats.droppedFrames);
- }
- });
- // 创建解码器
- m_videoDecoder = std::make_unique<VideoDecoder>();
- if (!m_videoDecoder) {
- Logger::instance().error("Failed to create video decoder");
- setState(PlayerState::Error);
- return;
- }
-
- m_audioDecoder = std::make_unique<AudioDecoder>();
- if (!m_audioDecoder) {
- Logger::instance().error("Failed to create audio decoder");
- setState(PlayerState::Error);
- return;
- }
-
- // 创建音频输出设备
- m_audioOutput = std::make_unique<AudioOutput>();
- if (!m_audioOutput) {
- Logger::instance().error("Failed to create audio output");
- setState(PlayerState::Error);
- return;
- }
-
- // 初始化性能监控
- m_lastStatsUpdate = std::chrono::steady_clock::now();
- m_lastCpuMeasure = m_lastStatsUpdate;
- #ifdef _WIN32
- m_lastCpuTime = GetTickCount64();
- #else
- struct tms tm;
- m_lastCpuTime = times(&tm);
- #endif
-
- m_initialized = true;
- Logger::instance().info("PlayerCoreV2 initialized successfully");
-
- } catch (const std::exception& e) {
- Logger::instance().error("Exception during PlayerCoreV2 initialization: " + std::string(e.what()));
- setState(PlayerState::Error);
- m_initialized = false;
- } catch (...) {
- Logger::instance().error("Unknown exception during PlayerCoreV2 initialization");
- setState(PlayerState::Error);
- m_initialized = false;
- }
- }
- PlayerCoreV2::~PlayerCoreV2() {
- Logger::instance().info("PlayerCoreV2 destroying...");
- stop();
- cleanup();
- Logger::instance().info("PlayerCoreV2 destroyed");
- }
- void PlayerCoreV2::setEventCallback(PlayerEventCallback* callback) {
- std::lock_guard<std::mutex> lock(m_mutex);
- m_eventCallback = callback;
- }
- ErrorCode PlayerCoreV2::openFile(const std::string& filename) {
- Logger::instance().info("Opening file: " + filename);
-
- if (!m_initialized) {
- Logger::instance().error("PlayerCoreV2 not initialized");
- return ErrorCode::NOT_INITIALIZED;
- }
-
- // 如果正在播放,先停止
- if (m_state != PlayerState::Idle) {
- stop();
- }
-
- setState(PlayerState::Opening);
-
- // 打开媒体文件
- if (!openMediaFile(filename)) {
- setState(PlayerState::Error);
- notifyError("Failed to open media file: " + filename);
- return ErrorCode::FILE_OPEN_FAILED;
- }
-
- // 设置媒体信息
- m_mediaInfo.filename = filename;
-
- // 设置解码器
- if (m_mediaInfo.hasVideo && !setupVideoDecoder()) {
- Logger::instance().error("Failed to setup video decoder");
- setState(PlayerState::Error);
- return ErrorCode::CODEC_OPEN_FAILED;
- }
-
- if (m_mediaInfo.hasAudio && !setupAudioDecoder()) {
- Logger::instance().error("Failed to setup audio decoder");
- setState(PlayerState::Error);
- return ErrorCode::CODEC_OPEN_FAILED;
- }
-
- // 初始化同步器
- if (m_synchronizer->initialize() != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to initialize synchronizer");
- setState(PlayerState::Error);
- return ErrorCode::SYNC_ERROR;
- }
-
- setState(PlayerState::Stopped);
-
- // 如果已设置视频渲染器且有视频流,重新初始化渲染器
- if (m_mediaInfo.hasVideo && m_openGLVideoRenderer) {
- AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
-
- bool rendererInitResult = m_openGLVideoRenderer->Open(
- videoStream->codecpar->width,
- videoStream->codecpar->height
- );
-
- if (!rendererInitResult) {
- Logger::instance().warning("Failed to initialize OpenGL video renderer");
- } else {
- Logger::instance().info("OpenGL video renderer initialized successfully");
- }
- }
-
- // 通知媒体信息变化
- if (m_eventCallback) {
- m_eventCallback->onMediaInfoChanged(m_mediaInfo);
- }
-
- Logger::instance().info("File opened successfully: " + filename);
- return ErrorCode::SUCCESS;
- }
- ErrorCode PlayerCoreV2::play() {
- Logger::instance().info("Starting playback");
-
- if (m_state == PlayerState::Playing) {
- Logger::instance().debug("Already playing");
- return ErrorCode::SUCCESS;
- }
-
- if (m_state != PlayerState::Stopped && m_state != PlayerState::Paused) {
- Logger::instance().error("Invalid state for play: " + std::to_string(static_cast<int>(m_state.load())));
- return ErrorCode::INVALID_STATE;
- }
-
- // 启动同步器
- if (m_synchronizer->start() != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to start synchronizer");
- return ErrorCode::SYNC_ERROR;
- }
-
- // 记录播放开始时间
- m_playStartTime = std::chrono::steady_clock::now();
-
- // 如果是从停止状态开始播放,重置基准时间
- if (m_state == PlayerState::Stopped) {
- m_baseTime = 0;
- m_frameCount = 0;
- m_lastFrameCount = 0;
-
- // 重置统计信息
- std::lock_guard<std::mutex> lock(m_mutex);
- m_stats = PlaybackStats();
- m_stats.playbackSpeed = m_playbackSpeed;
- }
-
- // 启动音频输出设备
- if (m_audioOutput && m_mediaInfo.hasAudio) {
- if (m_state == PlayerState::Paused) {
- m_audioOutput->resume();
- } else {
- Logger::instance().info("Starting audio output device...");
- m_audioOutput->start();
-
- // 检查音频设备是否成功启动
- if (!m_audioOutput->isPlaying()) {
- Logger::instance().error("Audio output device failed to start");
- // 不要因为音频失败而停止整个播放,继续播放视频
- Logger::instance().warning("Continuing playback without audio");
- } else {
- Logger::instance().info("Audio output device started successfully");
- }
- }
-
- // 设置音频参数
- m_audioOutput->setVolume(m_volume);
- m_audioOutput->setPlaybackSpeed(m_playbackSpeed);
-
- // 给音频输出设备更多时间初始化
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- }
-
- // 启动线程
- m_threadsShouldStop = false;
-
- if (!startReadThread()) {
- Logger::instance().error("Failed to start read thread");
- return ErrorCode::THREAD_ERROR;
- }
-
- if (!startDecodeThreads()) {
- Logger::instance().error("Failed to start decode threads");
- return ErrorCode::THREAD_ERROR;
- }
-
- if (m_mediaInfo.hasVideo && !startVideoPlayThread()) {
- Logger::instance().error("Failed to start video play thread");
- return ErrorCode::THREAD_ERROR;
- }
-
- if (m_mediaInfo.hasAudio && !startAudioPlayThread()) {
- Logger::instance().error("Failed to start audio play thread");
- return ErrorCode::THREAD_ERROR;
- }
-
- m_threadsRunning = true;
- setState(PlayerState::Playing);
-
- Logger::instance().info("Playback started");
- return ErrorCode::SUCCESS;
- }
- ErrorCode PlayerCoreV2::pause() {
- Logger::instance().info("Pausing playback");
-
- if (m_state != PlayerState::Playing) {
- Logger::instance().debug("Not playing, cannot pause");
- return ErrorCode::INVALID_STATE;
- }
-
- // 暂停同步器
- if (m_synchronizer->pause() != ErrorCode::SUCCESS) {
- Logger::instance().warning("Failed to pause synchronizer");
- }
-
- // 记录暂停时的播放时间
- if (m_playStartTime.time_since_epoch().count() != 0) {
- auto currentTime = std::chrono::steady_clock::now();
- auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
- currentTime - m_playStartTime).count();
- m_baseTime += static_cast<int64_t>(elapsed * m_playbackSpeed);
- m_playStartTime = std::chrono::steady_clock::time_point{};
- }
-
- // 暂停音频输出
- if (m_audioOutput) {
- m_audioOutput->pause();
- }
-
- setState(PlayerState::Paused);
- Logger::instance().info("Playback paused");
- return ErrorCode::SUCCESS;
- }
- ErrorCode PlayerCoreV2::stop() {
- Logger::instance().info("Stopping playback");
-
- if (m_state == PlayerState::Idle || m_state == PlayerState::Stopped) {
- Logger::instance().debug("Already stopped");
- return ErrorCode::SUCCESS;
- }
-
- // 停止同步器
- if (m_synchronizer) {
- m_synchronizer->stop();
- }
-
- // 停止音频输出
- if (m_audioOutput) {
- m_audioOutput->stop();
- }
-
- // 清空OpenGL视频渲染器
- if (m_openGLVideoRenderer) {
- m_openGLVideoRenderer->Close();
- }
-
- // 停止所有线程
- stopAllThreads();
-
- // 重置解码器
- resetDecoders();
-
- // 清空队列
- if (m_packetQueue) m_packetQueue->clear();
- if (m_videoFrameQueue) m_videoFrameQueue->clear();
- if (m_audioFrameQueue) m_audioFrameQueue->clear();
-
- // 重置时间
- m_baseTime = 0;
- m_playStartTime = std::chrono::steady_clock::time_point{};
-
- setState(PlayerState::Stopped);
- Logger::instance().info("Playback stopped");
- return ErrorCode::SUCCESS;
- }
- ErrorCode PlayerCoreV2::seek(int64_t timestamp) {
- Logger::instance().info("Seeking to: " + std::to_string(timestamp));
-
- if (m_state == PlayerState::Idle || m_state == PlayerState::Opening) {
- Logger::instance().error("Invalid state for seek");
- return ErrorCode::INVALID_STATE;
- }
-
- std::unique_lock<std::mutex> lock(m_seekMutex);
-
- // 设置seek目标
- m_seekTarget = timestamp;
- m_seeking = true;
-
- // 更新基准时间为跳转目标时间
- m_baseTime = timestamp;
- m_playStartTime = std::chrono::steady_clock::now();
-
- // 重置同步器
- if (m_synchronizer) {
- m_synchronizer->reset();
- }
-
- // 清空队列
- flushBuffers();
-
- setState(PlayerState::Seeking);
-
- // 通知seek条件
- m_seekCondition.notify_all();
-
- Logger::instance().info("Seek initiated");
- return ErrorCode::SUCCESS;
- }
- ErrorCode PlayerCoreV2::setPlaybackSpeed(double speed) {
- if (speed <= 0.0 || speed > 4.0) {
- Logger::instance().error("Invalid playback speed: " + std::to_string(speed));
- return ErrorCode::INVALID_PARAMS;
- }
-
- std::lock_guard<std::mutex> lock(m_mutex);
- m_playbackSpeed = speed;
-
- // 设置同步器的播放速度
- if (m_synchronizer) {
- m_synchronizer->setPlaybackSpeed(speed);
- }
-
- // 设置音频输出的播放速度
- if (m_audioOutput) {
- m_audioOutput->setPlaybackSpeed(speed);
- }
-
- // 更新统计信息
- m_stats.playbackSpeed = speed;
-
- Logger::instance().info("Playback speed set to: " + std::to_string(speed));
- return ErrorCode::SUCCESS;
- }
- MediaInfo PlayerCoreV2::getMediaInfo() const {
- std::lock_guard<std::mutex> lock(m_mutex);
- return m_mediaInfo;
- }
- PlaybackStats PlayerCoreV2::getStats() const {
- std::lock_guard<std::mutex> lock(m_mutex);
- PlaybackStats stats = m_stats;
-
- // 更新当前时间
- stats.currentTime = getCurrentTime();
-
- // 更新队列大小
- if (m_packetQueue) stats.queuedPackets = m_packetQueue->size();
- if (m_videoFrameQueue) stats.queuedVideoFrames = m_videoFrameQueue->size();
- if (m_audioFrameQueue) stats.queuedAudioFrames = m_audioFrameQueue->size();
-
- // 更新同步统计
- if (m_synchronizer) {
- auto syncStats = m_synchronizer->getStats();
- stats.syncError = syncStats.syncError;
- stats.avgSyncError = syncStats.avgSyncError;
- stats.maxSyncError = syncStats.maxSyncError;
- stats.droppedFrames = syncStats.droppedFrames;
- stats.duplicatedFrames = syncStats.duplicatedFrames;
- }
-
- return stats;
- }
- int64_t PlayerCoreV2::getCurrentTime() const {
- if (m_state == PlayerState::Idle || m_state == PlayerState::Stopped) {
- return 0;
- }
-
- if (m_state == PlayerState::Paused) {
- return m_baseTime;
- }
-
- if (m_playStartTime.time_since_epoch().count() == 0) {
- return m_baseTime;
- }
-
- auto currentTime = std::chrono::steady_clock::now();
- auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
- currentTime - m_playStartTime).count();
-
- return m_baseTime + static_cast<int64_t>(elapsed * m_playbackSpeed);
- }
- double PlayerCoreV2::getPlaybackSpeed() const {
- return m_playbackSpeed;
- }
- void PlayerCoreV2::setVolume(double volume) {
- volume = std::max(0.0, std::min(1.0, volume));
- m_volume = volume;
-
- // 同时设置音频输出设备的音量
- if (m_audioOutput) {
- m_audioOutput->setVolume(volume);
- }
-
- Logger::instance().debug("Volume set to: " + std::to_string(volume));
- }
- void PlayerCoreV2::setSyncConfig(const SyncConfigV2& config) {
- if (m_synchronizer) {
- m_synchronizer->setConfig(config);
- }
- }
- SyncConfigV2 PlayerCoreV2::getSyncConfig() const {
- if (m_synchronizer) {
- return m_synchronizer->getConfig();
- }
- return SyncConfigV2();
- }
- void PlayerCoreV2::setOpenGLVideoRenderer(OpenGLVideoWidget* renderer) {
- m_openGLVideoRenderer = renderer;
- }
- AVFrame* PlayerCoreV2::getNextVideoFrame() {
- if (!m_videoFrameQueue || m_state != PlayerState::Playing) {
- return nullptr;
- }
-
- return m_videoFrameQueue->pop();
- }
- AVFrame* PlayerCoreV2::getNextAudioFrame() {
- if (!m_audioFrameQueue || m_state != PlayerState::Playing) {
- return nullptr;
- }
-
- return m_audioFrameQueue->pop();
- }
- void PlayerCoreV2::releaseVideoFrame(AVFrame* frame) {
- if (frame) {
- av_frame_free(&frame);
- }
- }
- void PlayerCoreV2::releaseAudioFrame(AVFrame* frame) {
- if (frame) {
- av_frame_free(&frame);
- }
- }
- void PlayerCoreV2::update() {
- if (!m_initialized) {
- return;
- }
-
- // 更新同步状态
- updateSynchronization();
-
- // 更新统计信息
- auto now = std::chrono::steady_clock::now();
- if (std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastStatsUpdate).count() > 500) {
- updateStats();
- updatePerformanceStats();
- m_lastStatsUpdate = now;
-
- // 通知位置变化
- notifyPositionChanged();
- }
-
- // 检查错误恢复
- if (m_errorCount > 0) {
- auto timeSinceError = std::chrono::duration_cast<std::chrono::seconds>(now - m_lastErrorTime).count();
- if (timeSinceError > 5) { // 5秒后重置错误计数
- m_errorCount = 0;
- }
- }
- }
- std::string PlayerCoreV2::getDebugInfo() const {
- std::ostringstream oss;
-
- oss << "PlayerCoreV2 Debug Info:\n";
- oss << " State: " << static_cast<int>(m_state.load()) << "\n";
- oss << " Initialized: " << (m_initialized ? "Yes" : "No") << "\n";
- oss << " Threads Running: " << (m_threadsRunning ? "Yes" : "No") << "\n";
- oss << " Current Time: " << getCurrentTime() << " us\n";
- oss << " Playback Speed: " << m_playbackSpeed << "x\n";
- oss << " Volume: " << m_volume << "\n";
- oss << " Error Count: " << m_errorCount << "\n";
-
- if (m_synchronizer) {
- oss << "\n" << m_synchronizer->getDebugInfo();
- }
-
- return oss.str();
- }
- void PlayerCoreV2::dumpStats() const {
- PlaybackStats stats = getStats();
-
- Logger::instance().info("=== PlayerCoreV2 Statistics ===");
- Logger::instance().info("Current Time: " + std::to_string(stats.currentTime) + " us");
- Logger::instance().info("Total Frames: " + std::to_string(stats.totalFrames));
- Logger::instance().info("Dropped Frames: " + std::to_string(stats.droppedFrames));
- Logger::instance().info("Duplicated Frames: " + std::to_string(stats.duplicatedFrames));
- Logger::instance().info("Sync Error: " + std::to_string(stats.syncError * 1000) + " ms");
- Logger::instance().info("Avg Sync Error: " + std::to_string(stats.avgSyncError * 1000) + " ms");
- Logger::instance().info("Max Sync Error: " + std::to_string(stats.maxSyncError * 1000) + " ms");
- Logger::instance().info("CPU Usage: " + std::to_string(stats.cpuUsage) + "%");
- Logger::instance().info("Memory Usage: " + std::to_string(stats.memoryUsage) + " MB");
- Logger::instance().info("Queued Packets: " + std::to_string(stats.queuedPackets));
- Logger::instance().info("Queued Video Frames: " + std::to_string(stats.queuedVideoFrames));
- Logger::instance().info("Queued Audio Frames: " + std::to_string(stats.queuedAudioFrames));
- Logger::instance().info("===============================");
- }
- bool PlayerCoreV2::openMediaFile(const std::string& filename) {
- // 关闭之前的文件
- if (m_formatContext) {
- avformat_close_input(&m_formatContext);
- m_formatContext = nullptr;
- }
-
- // 分配格式上下文
- m_formatContext = avformat_alloc_context();
- if (!m_formatContext) {
- Logger::instance().error("Failed to allocate format context");
- return false;
- }
-
- // 打开输入文件
- if (avformat_open_input(&m_formatContext, filename.c_str(), nullptr, nullptr) < 0) {
- Logger::instance().error("Failed to open input file: " + filename);
- avformat_free_context(m_formatContext);
- m_formatContext = nullptr;
- return false;
- }
-
- // 查找流信息
- if (avformat_find_stream_info(m_formatContext, nullptr) < 0) {
- Logger::instance().error("Failed to find stream info");
- avformat_close_input(&m_formatContext);
- return false;
- }
-
- // 查找视频和音频流
- m_mediaInfo.videoStreamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
- m_mediaInfo.audioStreamIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
-
- m_mediaInfo.hasVideo = (m_mediaInfo.videoStreamIndex >= 0);
- m_mediaInfo.hasAudio = (m_mediaInfo.audioStreamIndex >= 0);
-
- if (!m_mediaInfo.hasVideo && !m_mediaInfo.hasAudio) {
- Logger::instance().error("No video or audio streams found");
- avformat_close_input(&m_formatContext);
- return false;
- }
-
- // 获取媒体信息
- m_mediaInfo.duration = m_formatContext->duration;
- m_mediaInfo.bitrate = m_formatContext->bit_rate;
-
- if (m_mediaInfo.hasVideo) {
- AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
- m_mediaInfo.width = videoStream->codecpar->width;
- m_mediaInfo.height = videoStream->codecpar->height;
-
- // 计算帧率
- if (videoStream->avg_frame_rate.den != 0) {
- m_mediaInfo.fps = av_q2d(videoStream->avg_frame_rate);
- } else if (videoStream->r_frame_rate.den != 0) {
- m_mediaInfo.fps = av_q2d(videoStream->r_frame_rate);
- } else {
- m_mediaInfo.fps = 25.0; // 默认帧率
- }
-
- Logger::instance().info("Video stream found: " + std::to_string(m_mediaInfo.width) + "x" +
- std::to_string(m_mediaInfo.height) + " @ " + std::to_string(m_mediaInfo.fps) + " fps");
- }
-
- if (m_mediaInfo.hasAudio) {
- AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
- m_mediaInfo.sampleRate = audioStream->codecpar->sample_rate;
- m_mediaInfo.channels = audioStream->codecpar->ch_layout.nb_channels;
-
- Logger::instance().info("Audio stream found: " + std::to_string(m_mediaInfo.sampleRate) + " Hz, " +
- std::to_string(m_mediaInfo.channels) + " channels");
- }
-
- // 设置同步器的流信息
- if (m_synchronizer) {
- m_synchronizer->setStreamInfo(m_mediaInfo.hasAudio, m_mediaInfo.hasVideo);
- Logger::instance().info("Synchronizer stream info set: hasAudio=" + std::to_string(m_mediaInfo.hasAudio) +
- ", hasVideo=" + std::to_string(m_mediaInfo.hasVideo));
- }
-
- Logger::instance().info("Media file opened successfully: " + filename);
- return true;
- }
- bool PlayerCoreV2::setupVideoDecoder() {
- if (!m_mediaInfo.hasVideo || !m_videoDecoder) {
- return false;
- }
-
- AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
-
- // 查找解码器
- const AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
- if (!codec) {
- Logger::instance().error("Video codec not found");
- return false;
- }
-
- Logger::instance().info("Found video codec: " + std::string(codec->name));
- Logger::instance().info("Video stream info: width=" + std::to_string(videoStream->codecpar->width) +
- ", height=" + std::to_string(videoStream->codecpar->height) +
- ", format=" + std::to_string(videoStream->codecpar->format));
-
- // 创建视频解码器参数
- VideoDecoderParams videoParams;
- videoParams.codecName = codec->name;
- videoParams.width = videoStream->codecpar->width;
- videoParams.height = videoStream->codecpar->height;
- videoParams.pixelFormat = static_cast<AVPixelFormat>(videoStream->codecpar->format);
- videoParams.hardwareAccel = false; // 先禁用硬件加速来排除问题
- videoParams.lowLatency = false;
-
- Logger::instance().info("Video decoder params: codec=" + videoParams.codecName +
- ", size=" + std::to_string(videoParams.width) + "x" + std::to_string(videoParams.height) +
- ", format=" + std::to_string(static_cast<int>(videoParams.pixelFormat)));
-
- // 初始化视频解码器
- if (m_videoDecoder->initialize(videoParams) != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to initialize video decoder");
- return false;
- }
-
- // 设置流参数
- if (m_videoDecoder->setStreamParameters(videoStream->codecpar) != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to set video decoder stream parameters");
- return false;
- }
-
- // 打开视频解码器
- if (m_videoDecoder->open(videoParams) != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to open video decoder");
- return false;
- }
-
- Logger::instance().info("Video decoder setup successfully");
- return true;
- }
- bool PlayerCoreV2::setupAudioDecoder() {
- if (!m_mediaInfo.hasAudio || !m_audioDecoder) {
- return false;
- }
-
- AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
-
- // 查找解码器
- const AVCodec* codec = avcodec_find_decoder(audioStream->codecpar->codec_id);
- if (!codec) {
- Logger::instance().error("Audio codec not found");
- return false;
- }
-
- // 分配解码器上下文
- AVCodecContext* codecContext = avcodec_alloc_context3(codec);
- if (!codecContext) {
- Logger::instance().error("Failed to allocate audio codec context");
- return false;
- }
-
- // 复制流参数到解码器上下文
- if (avcodec_parameters_to_context(codecContext, audioStream->codecpar) < 0) {
- Logger::instance().error("Failed to copy audio codec parameters");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 打开解码器
- if (avcodec_open2(codecContext, codec, nullptr) < 0) {
- Logger::instance().error("Failed to open audio codec");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 创建音频解码器参数
- AudioDecoderParams audioParams;
- audioParams.codecName = codec->name;
- audioParams.sampleRate = codecContext->sample_rate;
- audioParams.channels = codecContext->ch_layout.nb_channels;
- audioParams.sampleFormat = codecContext->sample_fmt;
- audioParams.lowLatency = false;
- audioParams.enableResampling = true;
-
- // 初始化音频解码器
- if (m_audioDecoder->initialize(audioParams) != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to initialize audio decoder");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 打开音频解码器
- if (m_audioDecoder->open(audioParams) != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to open audio decoder");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 初始化音频输出设备
- if (m_audioOutput && !m_audioOutput->initialize(codecContext->sample_rate,
- codecContext->ch_layout.nb_channels,
- codecContext->sample_fmt)) {
- Logger::instance().error("Failed to initialize audio output");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 释放解码器上下文
- avcodec_free_context(&codecContext);
-
- Logger::instance().info("Audio decoder setup successfully");
- return true;
- }
- void PlayerCoreV2::resetDecoders() {
- if (m_videoDecoder) {
- m_videoDecoder->reset();
- }
- if (m_audioDecoder) {
- m_audioDecoder->reset();
- }
- }
- bool PlayerCoreV2::startReadThread() {
- try {
- m_readThread = std::thread(&PlayerCoreV2::readThreadFunc, this);
- Logger::instance().info("Read thread started");
- return true;
- } catch (const std::exception& e) {
- Logger::instance().error("Failed to start read thread: " + std::string(e.what()));
- return false;
- }
- }
- bool PlayerCoreV2::startDecodeThreads() {
- try {
- if (m_mediaInfo.hasVideo) {
- m_videoDecodeThread = std::thread(&PlayerCoreV2::videoDecodeThreadFunc, this);
- Logger::instance().info("Video decode thread started");
- }
-
- if (m_mediaInfo.hasAudio) {
- m_audioDecodeThread = std::thread(&PlayerCoreV2::audioDecodeThreadFunc, this);
- Logger::instance().info("Audio decode thread started");
- }
-
- return true;
- } catch (const std::exception& e) {
- Logger::instance().error("Failed to start decode threads: " + std::string(e.what()));
- return false;
- }
- }
- bool PlayerCoreV2::startVideoPlayThread() {
- try {
- m_videoPlayThread = std::thread(&PlayerCoreV2::videoPlayThreadFunc, this);
- Logger::instance().info("Video play thread started");
- return true;
- } catch (const std::exception& e) {
- Logger::instance().error("Failed to start video play thread: " + std::string(e.what()));
- return false;
- }
- }
- bool PlayerCoreV2::startAudioPlayThread() {
- try {
- m_audioPlayThread = std::thread(&PlayerCoreV2::audioPlayThreadFunc, this);
- Logger::instance().info("Audio play thread started");
- return true;
- } catch (const std::exception& e) {
- Logger::instance().error("Failed to start audio play thread: " + std::string(e.what()));
- return false;
- }
- }
- bool PlayerCoreV2::initializeFFmpeg() {
- // FFmpeg初始化逻辑
- av_log_set_level(AV_LOG_WARNING);
- return true;
- }
- void PlayerCoreV2::cleanup() {
- stopAllThreads();
-
- if (m_formatContext) {
- avformat_close_input(&m_formatContext);
- m_formatContext = nullptr;
- }
-
- if (m_synchronizer) {
- m_synchronizer->close();
- }
- }
- void PlayerCoreV2::setState(PlayerState newState) {
- PlayerState oldState = m_state.exchange(newState);
- if (oldState != newState) {
- notifyStateChanged(newState);
- }
- }
- void PlayerCoreV2::notifyStateChanged(PlayerState newState) {
- if (m_eventCallback) {
- m_eventCallback->onStateChanged(newState);
- }
- }
- void PlayerCoreV2::notifyError(const std::string& error) {
- Logger::instance().error(error);
- if (m_eventCallback) {
- m_eventCallback->onErrorOccurred(error);
- }
- }
- void PlayerCoreV2::notifyPositionChanged() {
- if (m_eventCallback) {
- m_eventCallback->onPositionChanged(getCurrentTime());
- }
- }
- void PlayerCoreV2::handleSyncError(double error, const std::string& reason) {
- Logger::instance().warning("Sync error: " + std::to_string(error * 1000) + "ms, reason: " + reason);
-
- if (m_eventCallback) {
- m_eventCallback->onSyncError(error, reason);
- }
-
- // 如果同步误差太大,尝试恢复
- if (error > 0.2) { // 200ms
- attemptRecovery();
- }
- }
- void PlayerCoreV2::attemptRecovery() {
- m_errorCount++;
- m_lastErrorTime = std::chrono::steady_clock::now();
-
- Logger::instance().warning("Attempting recovery, error count: " + std::to_string(m_errorCount.load()));
-
- if (m_errorCount > 5) {
- Logger::instance().error("Too many errors, stopping playback");
- handleError("Too many sync errors");
- return;
- }
-
- // 重置同步器
- if (m_synchronizer) {
- m_synchronizer->reset();
- }
-
- // 清空部分缓冲区
- if (m_videoFrameQueue) {
- m_videoFrameQueue->clear();
- }
- if (m_audioFrameQueue) {
- m_audioFrameQueue->clear();
- }
- }
- void PlayerCoreV2::handleError(const std::string& error) {
- setState(PlayerState::Error);
- notifyError(error);
- }
- void PlayerCoreV2::updateSynchronization() {
- if (!m_synchronizer || !m_threadsRunning) {
- return;
- }
-
- // 同步器会在内部自动更新
- // 这里可以添加额外的同步逻辑
- }
- void PlayerCoreV2::updateStats() {
- std::lock_guard<std::mutex> lock(m_mutex);
-
- // 更新帧率统计
- int64_t currentFrameCount = m_frameCount;
- int64_t frameDiff = currentFrameCount - m_lastFrameCount;
- m_lastFrameCount = currentFrameCount;
-
- // 计算比特率等其他统计信息
- if (m_formatContext) {
- m_stats.bitrate = m_formatContext->bit_rate / 1000.0; // kbps
- }
- }
- void PlayerCoreV2::updatePerformanceStats() {
- std::lock_guard<std::mutex> lock(m_mutex);
-
- m_stats.cpuUsage = calculateCpuUsage();
- m_stats.memoryUsage = calculateMemoryUsage();
- }
- double PlayerCoreV2::calculateCpuUsage() {
- #ifdef _WIN32
- FILETIME idleTime, kernelTime, userTime;
- if (GetSystemTimes(&idleTime, &kernelTime, &userTime)) {
- // 简化的CPU使用率计算
- return 0.0; // 实际实现需要更复杂的逻辑
- }
- #endif
- return 0.0;
- }
- double PlayerCoreV2::calculateMemoryUsage() {
- #ifdef _WIN32
- PROCESS_MEMORY_COUNTERS pmc;
- if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) {
- return pmc.WorkingSetSize / (1024.0 * 1024.0); // MB
- }
- #endif
- return 0.0;
- }
- void PlayerCoreV2::stopAllThreads() {
- Logger::instance().info("Stopping all threads...");
-
- m_threadsShouldStop = true;
-
- // 等待线程结束
- if (m_readThread.joinable()) {
- m_readThread.join();
- }
- if (m_videoDecodeThread.joinable()) {
- m_videoDecodeThread.join();
- }
- if (m_audioDecodeThread.joinable()) {
- m_audioDecodeThread.join();
- }
- if (m_videoPlayThread.joinable()) {
- m_videoPlayThread.join();
- }
- if (m_audioPlayThread.joinable()) {
- m_audioPlayThread.join();
- }
-
- m_threadsRunning = false;
- Logger::instance().info("All threads stopped");
- }
- void PlayerCoreV2::flushBuffers() {
- if (m_packetQueue) m_packetQueue->clear();
- if (m_videoFrameQueue) m_videoFrameQueue->clear();
- if (m_audioFrameQueue) m_audioFrameQueue->clear();
- }
- void PlayerCoreV2::readThreadFunc() {
- Logger::instance().info("Read thread started");
-
- AVPacket* packet = av_packet_alloc();
- if (!packet) {
- Logger::instance().error("Failed to allocate packet");
- return;
- }
-
- while (!m_threadsShouldStop) {
- // 检查是否需要seek
- if (m_seeking) {
- std::unique_lock<std::mutex> lock(m_seekMutex);
-
- // 执行seek操作
- int64_t seekTarget = m_seekTarget;
- int flags = AVSEEK_FLAG_BACKWARD;
-
- if (av_seek_frame(m_formatContext, -1, seekTarget, flags) < 0) {
- Logger::instance().error("Seek failed");
- } else {
- Logger::instance().info("Seek completed to: " + std::to_string(seekTarget));
-
- // 清空缓冲区
- flushBuffers();
-
- // 重置解码器
- resetDecoders();
- }
-
- m_seeking = false;
- setState(m_state == PlayerState::Seeking ? PlayerState::Playing : m_state.load());
- lock.unlock();
- m_seekCondition.notify_all();
- }
-
- // 检查队列是否已满
- if (m_packetQueue && m_packetQueue->size() > 1000) {
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- continue;
- }
-
- // 读取数据包
- int ret = av_read_frame(m_formatContext, packet);
- if (ret < 0) {
- if (ret == AVERROR_EOF) {
- Logger::instance().info("End of file reached, sending EOF packets to queues");
-
- // 向队列发送EOF标记,让解码线程知道文件结束
- if (m_packetQueue) {
- // 创建EOF标记包
- AVPacket* eofPacket = av_packet_alloc();
- if (eofPacket) {
- eofPacket->data = nullptr;
- eofPacket->size = 0;
- eofPacket->stream_index = -1; // 特殊标记表示EOF
- m_packetQueue->push(eofPacket);
- Logger::instance().info("EOF packet sent to queue");
- }
- }
- break;
- } else {
- Logger::instance().error("Error reading frame: " + std::to_string(ret));
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- continue;
- }
- }
-
- // 将数据包放入队列
- if (packet->stream_index == m_mediaInfo.videoStreamIndex ||
- packet->stream_index == m_mediaInfo.audioStreamIndex) {
-
- if (m_packetQueue) {
- AVPacket* packetCopy = av_packet_alloc();
- if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
- m_packetQueue->push(packetCopy);
- } else {
- av_packet_free(&packetCopy);
- }
- }
- }
-
- av_packet_unref(packet);
- }
-
- av_packet_free(&packet);
- Logger::instance().info("Read thread finished");
- }
- void PlayerCoreV2::videoDecodeThreadFunc() {
- Logger::instance().info("Video decode thread started");
-
- int packetCount = 0;
- int frameCount = 0;
- while (!m_threadsShouldStop) {
- if (!m_packetQueue || !m_videoFrameQueue || !m_videoDecoder) {
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- continue;
- }
-
- // 从包队列获取视频包
- AVPacket* packet = nullptr;
- while (!m_threadsShouldStop && !packet) {
- packet = m_packetQueue->pop();
- if (packet) {
- // 检查是否是EOF标记
- if (packet->stream_index == -1 && packet->data == nullptr) {
- Logger::instance().info("Video decode thread received EOF packet");
- av_packet_free(&packet);
-
- // 向视频帧队列发送EOF标记
- if (m_videoFrameQueue) {
- AVFrame* eofFrame = av_frame_alloc();
- if (eofFrame) {
- eofFrame->data[0] = nullptr;
- eofFrame->width = 0;
- eofFrame->height = 0;
- eofFrame->pts = AV_NOPTS_VALUE;
- m_videoFrameQueue->push(eofFrame);
- Logger::instance().info("EOF frame sent to video frame queue");
- }
- }
-
- // 视频解码线程结束
- Logger::instance().info("Video decode thread finishing due to EOF");
- return;
- }
-
- if (packet->stream_index != m_mediaInfo.videoStreamIndex) {
- Logger::instance().debug("Skipping non-video packet, stream_index=" + std::to_string(packet->stream_index) +
- ", expected=" + std::to_string(m_mediaInfo.videoStreamIndex));
- av_packet_free(&packet);
- packet = nullptr;
- }
- }
- if (!packet) {
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- }
- }
-
- if (!packet) {
- Logger::instance().debug("Video decode thread: no more packets available");
- continue;
- }
-
- packetCount++;
- Logger::instance().debug("Video decode thread got packet #" + std::to_string(packetCount) +
- ", size=" + std::to_string(packet->size) +
- ", pts=" + std::to_string(packet->pts));
-
- // 解码视频帧
- AVPacketPtr packetPtr(packet);
- std::vector<AVFramePtr> frames;
- ErrorCode decodeResult = m_videoDecoder->decode(packetPtr, frames);
-
- Logger::instance().debug("Video decode result: " + std::to_string(static_cast<int>(decodeResult)) +
- ", frames count: " + std::to_string(frames.size()));
-
- if (decodeResult == ErrorCode::SUCCESS) {
- for (auto& framePtr : frames) {
- if (framePtr && !m_threadsShouldStop) {
- frameCount++;
- Logger::instance().debug("Processing video frame #" + std::to_string(frameCount) +
- ", width=" + std::to_string(framePtr->width) +
- ", height=" + std::to_string(framePtr->height) +
- ", pts=" + std::to_string(framePtr->pts));
-
- // 设置帧的时间戳
- if (framePtr->pts != AV_NOPTS_VALUE) {
- AVStream* stream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
- double pts = framePtr->pts * av_q2d(stream->time_base) * 1000000; // 转换为微秒
- framePtr->pts = static_cast<int64_t>(pts);
- Logger::instance().debug("Frame PTS converted to: " + std::to_string(framePtr->pts) + " microseconds");
- }
-
- // 将帧放入队列
- if (m_videoFrameQueue->size() < 30) { // 限制队列大小
- // 释放智能指针的所有权,让队列管理帧的生命周期
- m_videoFrameQueue->push(framePtr.release());
- m_frameCount++;
- Logger::instance().debug("Video frame pushed to queue, queue size: " + std::to_string(m_videoFrameQueue->size()));
- } else {
- Logger::instance().warning("Video frame queue full, dropping frame");
- }
- }
- }
- } else {
- Logger::instance().warning("Video decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
- }
-
- // packet已经被packetPtr管理,不需要手动释放
- }
-
- Logger::instance().info("Video decode thread finished, packets processed: " + std::to_string(packetCount) +
- ", frames decoded: " + std::to_string(frameCount));
- }
- void PlayerCoreV2::audioDecodeThreadFunc() {
- Logger::instance().info("Audio decode thread started");
-
- int packetCount = 0;
- int frameCount = 0;
- while (!m_threadsShouldStop) {
- if (!m_packetQueue || !m_audioFrameQueue || !m_audioDecoder) {
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- continue;
- }
-
- // 从包队列获取音频包
- AVPacket* packet = nullptr;
- while (!m_threadsShouldStop && !packet) {
- packet = m_packetQueue->pop();
- if (packet) {
- // 检查是否是EOF标记
- if (packet->stream_index == -1 && packet->data == nullptr) {
- Logger::instance().info("Audio decode thread received EOF packet");
- av_packet_free(&packet);
-
- // 向音频帧队列发送EOF标记
- if (m_audioFrameQueue) {
- AVFrame* eofFrame = av_frame_alloc();
- if (eofFrame) {
- eofFrame->data[0] = nullptr;
- eofFrame->nb_samples = 0;
- eofFrame->pts = AV_NOPTS_VALUE;
- m_audioFrameQueue->push(eofFrame);
- Logger::instance().info("EOF frame sent to audio frame queue");
- }
- }
-
- // 音频解码线程结束
- Logger::instance().info("Audio decode thread finishing due to EOF");
- return;
- }
-
- if (packet->stream_index != m_mediaInfo.audioStreamIndex) {
- Logger::instance().debug("Skipping non-audio packet, stream_index=" + std::to_string(packet->stream_index) +
- ", expected=" + std::to_string(m_mediaInfo.audioStreamIndex));
- av_packet_free(&packet);
- packet = nullptr;
- }
- }
- if (!packet) {
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- }
- }
-
- if (!packet) {
- Logger::instance().debug("Audio decode thread: no more packets available");
- continue;
- }
-
- packetCount++;
- Logger::instance().debug("Audio decode thread got packet #" + std::to_string(packetCount) +
- ", size=" + std::to_string(packet->size) +
- ", pts=" + std::to_string(packet->pts));
-
- // 解码音频帧
- AVPacketPtr packetPtr(packet);
- std::vector<AVFramePtr> frames;
- ErrorCode decodeResult = m_audioDecoder->decode(packetPtr, frames);
-
- Logger::instance().debug("Audio decode result: " + std::to_string(static_cast<int>(decodeResult)) +
- ", frames count: " + std::to_string(frames.size()));
-
- if (decodeResult == ErrorCode::SUCCESS) {
- for (auto& framePtr : frames) {
- if (framePtr && !m_threadsShouldStop) {
- frameCount++;
- Logger::instance().debug("Processing audio frame #" + std::to_string(frameCount) +
- ", nb_samples=" + std::to_string(framePtr->nb_samples) +
- ", pts=" + std::to_string(framePtr->pts));
-
- // 设置帧的时间戳
- if (framePtr->pts != AV_NOPTS_VALUE) {
- AVStream* stream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
- double pts = framePtr->pts * av_q2d(stream->time_base) * 1000000; // 转换为微秒
- framePtr->pts = static_cast<int64_t>(pts);
- Logger::instance().debug("Frame PTS converted to: " + std::to_string(framePtr->pts) + " microseconds");
- }
-
- // 将帧放入队列
- if (m_audioFrameQueue->size() < 100) { // 限制队列大小
- // 释放智能指针的所有权,让队列管理帧的生命周期
- m_audioFrameQueue->push(framePtr.release());
- Logger::instance().debug("Audio frame pushed to queue, queue size: " + std::to_string(m_audioFrameQueue->size()));
- } else {
- Logger::instance().warning("Audio frame queue full, dropping frame");
- }
- }
- }
- } else {
- Logger::instance().warning("Audio decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
- }
-
- // packet已经被packetPtr管理,不需要手动释放
- }
-
- Logger::instance().info("Audio decode thread finished, packets processed: " + std::to_string(packetCount) +
- ", frames decoded: " + std::to_string(frameCount));
- }
- void PlayerCoreV2::videoPlayThreadFunc() {
- Logger::instance().info("Video play thread started");
-
- auto lastFrameTime = std::chrono::steady_clock::now();
- double targetFrameInterval = 1000.0 / m_mediaInfo.fps; // 毫秒
-
- while (!m_threadsShouldStop) {
- if (!m_videoFrameQueue || !m_synchronizer) {
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- continue;
- }
-
- // 获取视频帧,使用超时避免无限阻塞
- AVFrame* frame = m_videoFrameQueue->pop(100); // 100ms超时
- if (!frame) {
- // 检查是否应该继续等待
- if (m_threadsShouldStop) {
- break;
- }
- continue;
- }
-
- Logger::instance().debug("Video play thread got frame, pts=" + std::to_string(frame->pts));
-
- // 更新视频时钟
- if (frame->pts != AV_NOPTS_VALUE) {
- m_synchronizer->setVideoClock(frame->pts / 1000000.0); // 转换为秒
- }
-
- // 检查是否应该显示这一帧
- auto decision = m_synchronizer->shouldDisplayVideoFrame(frame->pts / 1000000.0);
-
- // 创建智能指针管理帧内存
- AVFramePtr framePtr(frame);
-
- switch (decision.action) {
- case av::utils::FrameAction::DISPLAY:
- // 显示帧
- if (m_openGLVideoRenderer) {
- m_openGLVideoRenderer->Render(framePtr.get());
- }
-
- // 计算下一帧的延迟
- if (decision.delay > 0) {
- auto delayMs = static_cast<int>(decision.delay * 1000);
- std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));
- }
- break;
-
- case av::utils::FrameAction::DROP:
- // 丢弃帧
- Logger::instance().debug("Dropping video frame");
- break;
- case av::utils::FrameAction::Frame_DUPLICATE:
- // 重复显示上一帧(这里简化处理)
- if (m_openGLVideoRenderer) {
- m_openGLVideoRenderer->Render(framePtr.get());
- }
- break;
-
- case av::utils::FrameAction::DELAY:
- // 延迟显示
- auto delayMs = static_cast<int>(decision.delay * 1000);
- std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));
- if (m_openGLVideoRenderer) {
- m_openGLVideoRenderer->Render(framePtr.get());
- }
- break;
- }
-
- // framePtr 会自动释放内存,无需手动调用 av_frame_free
-
- // 更新帧时间
- lastFrameTime = std::chrono::steady_clock::now();
- }
-
- Logger::instance().info("Video play thread finished");
- }
- void PlayerCoreV2::audioPlayThreadFunc() {
- Logger::instance().info("Audio play thread started");
-
- int frameCount = 0;
- while (!m_threadsShouldStop) {
- if (!m_audioFrameQueue || !m_synchronizer || !m_audioOutput) {
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- continue;
- }
-
- // 获取音频帧,使用较长的超时时间以确保能接收到EOF帧
- AVFrame* frame = m_audioFrameQueue->pop(100); // 100ms超时
- if (!frame) {
- // 检查是否应该继续等待
- if (m_threadsShouldStop) {
- break;
- }
- continue;
- }
-
- // 检查是否是EOF帧
- if (frame->data[0] == nullptr && frame->nb_samples == 0) {
- Logger::instance().info("Audio play thread received EOF frame, playback completed");
- av_frame_free(&frame);
-
- // 通知播放完成
- setState(PlayerState::Stopped);
- Logger::instance().info("Audio playback finished naturally");
- return;
- }
-
- frameCount++;
- Logger::instance().debug("Audio play thread got frame #" + std::to_string(frameCount) +
- ", pts=" + std::to_string(frame->pts) +
- ", nb_samples=" + std::to_string(frame->nb_samples));
-
- // 更新音频时钟
- if (frame->pts != AV_NOPTS_VALUE) {
- m_synchronizer->setAudioClock(frame->pts / 1000000.0); // 转换为秒
- }
-
- // 检查是否应该播放这一帧
- auto decision = m_synchronizer->shouldPlayAudioFrame(frame->pts / 1000000.0);
-
- Logger::instance().debug("Audio frame decision: action=" + std::to_string(static_cast<int>(decision.action)) +
- ", delay=" + std::to_string(decision.delay));
-
- // 创建智能指针管理帧内存
- AVFramePtr framePtr(frame);
-
- switch (decision.action) {
- case av::utils::FrameAction::DISPLAY:
- // 播放音频帧
- {
- Logger::instance().debug("Writing audio frame to output device");
- bool writeResult = m_audioOutput->writeFrame(framePtr);
- Logger::instance().debug("Audio frame write result: " + std::to_string(writeResult));
- }
-
- // 如果需要延迟
- if (decision.delay > 0) {
- auto delayMs = static_cast<int>(decision.delay * 1000);
- std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));
- }
- break;
-
- case av::utils::FrameAction::DROP:
- // 丢弃音频帧
- Logger::instance().debug("Dropping audio frame");
- break;
- case av::utils::FrameAction::Frame_DUPLICATE:
- // 重复播放(音频中较少使用)
- {
- Logger::instance().debug("Duplicating audio frame");
- bool writeResult = m_audioOutput->writeFrame(framePtr);
- Logger::instance().debug("Audio frame duplicate write result: " + std::to_string(writeResult));
- }
- break;
-
- case av::utils::FrameAction::DELAY:
- // 延迟播放
- auto delayMs = static_cast<int>(decision.delay * 1000);
- std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));
- {
- Logger::instance().debug("Writing delayed audio frame to output device");
- bool writeResult = m_audioOutput->writeFrame(framePtr);
- Logger::instance().debug("Audio frame delayed write result: " + std::to_string(writeResult));
- }
- break;
- }
-
- // framePtr 会自动释放内存,无需手动调用 av_frame_free
- }
-
- Logger::instance().info("Audio play thread finished, total frames processed: " + std::to_string(frameCount));
- }
- } // namespace player
- } // namespace av
|