|
|
@@ -0,0 +1,1447 @@
|
|
|
+#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
|