#ifndef AV_PLAYER_CORE_V2_H #define AV_PLAYER_CORE_V2_H #pragma once #include "../base/logger.h" #include "../base/types.h" #include "../codec/codec_audio_decoder.h" #include "../codec/codec_video_decoder.h" #include "../utils/utils_frame_queue.h" #include "../utils/utils_packet_queue.h" #include "../utils/utils_synchronizer_v2.h" #include "audio_output.h" #include #include #include #include #include #include #include #include extern "C" { #include #include #include #include } namespace av { namespace player { using VideoDecoder = av::codec::VideoDecoder; using AudioDecoder = av::codec::AudioDecoder; using VideoDecoderParams = av::codec::VideoDecoderParams; using AudioDecoderParams = av::codec::AudioDecoderParams; using SynchronizerV2 = av::utils::SynchronizerV2; using SyncConfigV2 = av::utils::SyncConfigV2; using FrameDecision = av::utils::FrameDecision; using FrameAction = av::utils::FrameAction; /** * 播放器状态枚举 */ enum class PlayerState { Idle, // 空闲 Opening, // 正在打开文件 Playing, // 播放中 Paused, // 暂停 Seeking, // 跳转中 Stopped, // 已停止 Error // 错误状态 }; /** * 媒体信息结构 */ struct MediaInfo { std::string filename; int64_t duration = 0; // 总时长(微秒) int width = 0; int height = 0; double fps = 0.0; int audioSampleRate = 0; int audioChannels = 0; bool hasVideo = false; bool hasAudio = false; bool hasSubtitle = false; // 流索引 int videoStreamIndex = -1; int audioStreamIndex = -1; int subtitleStreamIndex = -1; // 时间基 AVRational videoTimeBase; AVRational audioTimeBase; // 兼容性字段 (与编译错误中的字段名匹配) int sampleRate = 0; // 音频采样率 (与audioSampleRate相同) int channels = 0; // 音频通道数 (与audioChannels相同) double bitrate = 0.0; // 比特率 }; /** * 播放统计信息 */ struct PlaybackStats { int64_t currentTime = 0; // 当前播放时间(微秒) int64_t totalFrames = 0; // 总帧数 int64_t droppedFrames = 0; // 丢帧数 int64_t duplicatedFrames = 0; // 重复帧数 double playbackSpeed = 1.0; // 播放速度 int queuedVideoFrames = 0; // 视频帧队列大小 int queuedAudioFrames = 0; // 音频帧队列大小 int queuedPackets = 0; // 数据包队列大小 // 同步统计 double syncError = 0.0; // 当前同步误差 double avgSyncError = 0.0; // 平均同步误差 double maxSyncError = 0.0; // 最大同步误差 // 性能统计 double cpuUsage = 0.0; double memoryUsage = 0.0; int64_t bytesRead = 0; double bitrate = 0.0; }; /** * 播放器事件回调接口 */ class PlayerEventCallback { public: virtual ~PlayerEventCallback() = default; virtual void onStateChanged(PlayerState newState) = 0; virtual void onMediaInfoChanged(const MediaInfo& info) = 0; virtual void onPositionChanged(int64_t position) = 0; // 微秒 virtual void onErrorOccurred(const std::string& error) = 0; virtual void onEndOfFile() = 0; virtual void onSyncError(double error, const std::string& reason) = 0; virtual void onFrameDropped(int64_t count) = 0; // 视频渲染相关回调 virtual void onVideoFrameReady(AVFrame* frame) = 0; virtual void onVideoRendererInitRequired(int width, int height) = 0; virtual void onVideoRendererCloseRequired() = 0; }; /** * 改进的播放器核心类 - 基于AVPlayer2的经验重新设计 * * 主要改进: * 1. 使用新的SynchronizerV2进行精确时间同步 * 2. 改进的线程管理和错误处理 * 3. 更好的seek操作和状态管理 * 4. 详细的性能监控和统计 * 5. 自适应播放策略 */ class PlayerCoreV2 { public: explicit PlayerCoreV2(const SyncConfigV2& syncConfig = SyncConfigV2()); ~PlayerCoreV2(); // 事件回调设置 void setEventCallback(PlayerEventCallback* callback); // 播放控制接口 ErrorCode openFile(const std::string& filename); ErrorCode play(); ErrorCode pause(); ErrorCode stop(); ErrorCode seek(int64_t timestamp); // 微秒 ErrorCode setPlaybackSpeed(double speed); // 流控制接口 void enableVideoStream(bool enable); void enableAudioStream(bool enable); bool isVideoStreamEnabled() const; bool isAudioStreamEnabled() const; // 状态查询 PlayerState getState() const { return m_state.load(); } MediaInfo getMediaInfo() const; PlaybackStats getStats() const; int64_t getCurrentTime() const; double getPlaybackSpeed() const; // 音量控制 void setVolume(double volume); // 0.0 - 1.0 double getVolume() const { return m_volume; } // 同步控制 void setSyncConfig(const SyncConfigV2& config); SyncConfigV2 getSyncConfig() const; // 视频渲染器设置(已废弃,请使用PlayerEventCallback中的视频渲染回调) // void setOpenGLVideoRenderer(OpenGLVideoWidget* renderer); // OpenGLVideoWidget* getOpenGLVideoRenderer() const { return m_openGLVideoRenderer; } // 安全帧获取接口 AVFramePtr getNextVideoFrame(); // 获取下一个视频帧 AVFramePtr getNextAudioFrame(); // 获取下一个音频帧 // 线程安全的更新接口 void update(); // 定期调用以更新播放状态 // 调试接口 std::string getDebugInfo() const; void dumpStats() const; private: // 初始化和清理 bool initializeFFmpeg(); void cleanup(); bool openMediaFile(const std::string& filename); void closeMediaFile(); // 线程管理 bool startReadThread(); bool startDecodeThreads(); bool startVideoPlayThread(); bool startAudioPlayThread(); void stopAllThreads(); // 解码器管理 bool setupVideoDecoder(); bool setupAudioDecoder(); void resetDecoders(); // 同步控制 void updateSynchronization(); int64_t getCurrentPlayTime(); void handleSyncError(double error, const std::string& reason); // 状态管理 void setState(PlayerState newState); void updateStats(); void notifyStateChanged(PlayerState newState); void notifyError(const std::string& error); void notifyPositionChanged(); // 线程函数 void readThreadFunc(); void videoDecodeThreadFunc(); void audioDecodeThreadFunc(); void videoPlayThreadFunc(); void audioPlayThreadFunc(); // 帧处理 bool processVideoFrame(); bool processAudioFrame(); void handleVideoFrameDecision(const FrameDecision& decision, AVFrame* frame); void handleAudioFrameDecision(const FrameDecision& decision, AVFrame* frame); // Seek处理 void performSeek(); void flushBuffers(); // 错误处理 void handleError(const std::string& error); void attemptRecovery(); // 性能监控 void updatePerformanceStats(); double calculateCpuUsage(); double calculateMemoryUsage(); private: // 状态变量 std::atomic m_state{PlayerState::Idle}; mutable std::mutex m_mutex; // 事件回调 PlayerEventCallback* m_eventCallback = nullptr; // 媒体信息 MediaInfo m_mediaInfo; PlaybackStats m_stats; // FFmpeg相关 AVFormatContext* m_formatContext = nullptr; // 解码器 std::unique_ptr m_videoDecoder; std::unique_ptr m_audioDecoder; // 队列管理 - 分离视频和音频包队列以提高效率 std::unique_ptr m_videoPacketQueue; std::unique_ptr m_audioPacketQueue; std::unique_ptr m_videoFrameQueue; std::unique_ptr m_audioFrameQueue; // 同步器 std::unique_ptr m_synchronizer; // 音频输出 std::unique_ptr m_audioOutput; // 视频渲染(已移除直接依赖,改为使用回调) // OpenGLVideoWidget* m_openGLVideoRenderer = nullptr; // 播放控制 std::atomic m_volume{1.0}; std::atomic m_playbackSpeed{1.0}; // Seek控制 std::atomic m_seekTarget{-1}; std::atomic m_seekMinTime{INT64_MIN}; std::atomic m_seekMaxTime{INT64_MAX}; std::atomic m_seekFlags{AVSEEK_FLAG_BACKWARD}; std::atomic m_seeking{false}; std::mutex m_seekMutex; std::condition_variable m_seekCondition; // 流控制 std::atomic m_videoStreamEnabled{true}; std::atomic m_audioStreamEnabled{true}; // 时间管理 std::chrono::steady_clock::time_point m_playStartTime; std::atomic m_baseTime{0}; std::atomic m_lastUpdateTime{0}; // 线程 std::thread m_readThread; std::thread m_videoDecodeThread; std::thread m_audioDecodeThread; std::thread m_videoPlayThread; std::thread m_audioPlayThread; // 线程控制 std::atomic m_threadsShouldStop{false}; std::atomic m_threadsRunning{false}; std::atomic m_paused{false}; // 暂停标志,类似ffplay.c中的paused std::condition_variable m_pauseCondition; // 暂停条件变量,类似ffplay.c中的continue_read_thread std::mutex m_pauseMutex; // 暂停互斥锁 // 初始化标志 std::atomic m_initialized{false}; // 帧计数 std::atomic m_frameCount{0}; std::atomic m_lastFrameCount{0}; // 性能监控 std::chrono::steady_clock::time_point m_lastStatsUpdate; std::chrono::steady_clock::time_point m_lastCpuMeasure; clock_t m_lastCpuTime; // 错误恢复 std::atomic m_errorCount{0}; std::chrono::steady_clock::time_point m_lastErrorTime; // 缓冲控制 std::atomic m_buffering{false}; std::atomic m_bufferHealth{1.0}; }; } // namespace player } // namespace av #endif // AV_PLAYER_CORE_V2_H