| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447 |
- #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_threadManager = std::make_unique<ThreadManager>();
- if (!m_threadManager) {
- Logger::instance().error("Failed to create thread manager");
- setState(PlayerState::Error);
- return;
- }
-
- // 创建解码器
- 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];
- double fps = m_mediaInfo.fps > 0 ? m_mediaInfo.fps : 25.0;
-
- bool rendererInitResult = m_openGLVideoRenderer->initialize(
- videoStream->codecpar->width,
- videoStream->codecpar->height,
- static_cast<AVPixelFormat>(videoStream->codecpar->format),
- fps
- );
-
- if (!rendererInitResult) {
- Logger::instance().warning("Failed to initialize OpenGL video renderer");
- } else {
- Logger::instance().info("OpenGL video renderer initialized successfully with fps: " + std::to_string(fps));
- }
- }
-
- // 通知媒体信息变化
- 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 {
- m_audioOutput->start();
- }
-
- // 设置音频参数
- m_audioOutput->setVolume(m_volume);
- m_audioOutput->setPlaybackSpeed(m_playbackSpeed);
-
- // 给音频输出设备时间初始化
- std::this_thread::sleep_for(std::chrono::milliseconds(50));
- }
-
- // 启动线程
- 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->clear();
- }
-
- // 停止所有线程
- 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(OpenGLVideoRenderer* 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;
- }
-
- // 分配解码器上下文
- AVCodecContext* codecContext = avcodec_alloc_context3(codec);
- if (!codecContext) {
- Logger::instance().error("Failed to allocate video codec context");
- return false;
- }
-
- // 复制流参数到解码器上下文
- if (avcodec_parameters_to_context(codecContext, videoStream->codecpar) < 0) {
- Logger::instance().error("Failed to copy video codec parameters");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 打开解码器
- if (avcodec_open2(codecContext, codec, nullptr) < 0) {
- Logger::instance().error("Failed to open video codec");
- avcodec_free_context(&codecContext);
- return false;
- }
-
- // 创建视频解码器参数
- VideoDecoderParams videoParams;
- videoParams.codecName = codec->name;
- videoParams.width = codecContext->width;
- videoParams.height = codecContext->height;
- videoParams.pixelFormat = codecContext->pix_fmt;
- videoParams.hardwareAccel = true;
- videoParams.lowLatency = false;
-
- // 初始化视频解码器
- if (m_videoDecoder->initialize(videoParams) != ErrorCode::SUCCESS) {
- Logger::instance().error("Failed to initialize video decoder");
- avcodec_free_context(&codecContext);
- 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);
-
- 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");
- // 文件结束,可以选择循环播放或停止
- 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");
-
- 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 && packet->stream_index != m_mediaInfo.videoStreamIndex) {
- // packet已经被packetPtr管理,不需要手动释放
- packet = nullptr;
- }
- if (!packet) {
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- }
- }
-
- if (!packet) continue;
-
- // 解码视频帧
- AVPacketPtr packetPtr(packet);
- std::vector<AVFramePtr> frames;
- if (m_videoDecoder->decode(packetPtr, frames) == ErrorCode::SUCCESS) {
- for (const auto& framePtr : frames) {
- if (framePtr && !m_threadsShouldStop) {
- // 设置帧的时间戳
- 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);
- }
-
- // 将帧放入队列
- if (m_videoFrameQueue->size() < 30) { // 限制队列大小
- m_videoFrameQueue->push(framePtr.get());
- m_frameCount++;
- }
- }
- }
- }
-
- // packet已经被packetPtr管理,不需要手动释放
- }
-
- Logger::instance().info("Video decode thread finished");
- }
- 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 && 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 (const 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.get());
- 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();
- if (!frame) {
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- continue;
- }
-
- // 更新视频时钟
- if (frame->pts != AV_NOPTS_VALUE) {
- m_synchronizer->setVideoClock(frame->pts / 1000000.0); // 转换为秒
- }
-
- // 检查是否应该显示这一帧
- auto decision = m_synchronizer->shouldDisplayVideoFrame(frame->pts / 1000000.0);
-
- switch (decision.action) {
- case av::utils::FrameAction::DISPLAY:
- // 显示帧
- if (m_openGLVideoRenderer) {
- AVFramePtr framePtr(frame);
- m_openGLVideoRenderer->renderFrame(framePtr);
- }
-
- // 计算下一帧的延迟
- 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) {
- AVFramePtr framePtr(frame);
- m_openGLVideoRenderer->renderFrame(framePtr);
- }
- 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) {
- AVFramePtr framePtr(frame);
- m_openGLVideoRenderer->renderFrame(framePtr);
- }
- break;
- }
-
- av_frame_free(&frame);
-
- // 更新帧时间
- 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;
- }
-
- // 获取音频帧
- AVFrame* frame = m_audioFrameQueue->pop();
- if (!frame) {
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- continue;
- }
-
- 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));
-
- switch (decision.action) {
- case av::utils::FrameAction::DISPLAY:
- // 播放音频帧
- {
- Logger::instance().debug("Writing audio frame to output device");
- AVFramePtr framePtr(frame);
- 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");
- AVFramePtr framePtr(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");
- AVFramePtr framePtr(frame);
- bool writeResult = m_audioOutput->writeFrame(framePtr);
- Logger::instance().debug("Audio frame delayed write result: " + std::to_string(writeResult));
- }
- break;
- }
-
- av_frame_free(&frame);
- }
-
- Logger::instance().info("Audio play thread finished, total frames processed: " + std::to_string(frameCount));
- }
- } // namespace player
- } // namespace av
|