zhuizhu пре 7 месеци
родитељ
комит
fe96571da9
100 измењених фајлова са 416 додато и 38759 уклоњено
  1. 0 67
      AV/AV.pri
  2. 0 0
      AV/code/base/config_manager.h
  3. 0 1
      AV/code/base/error_handler.cpp
  4. 0 190
      AV/code/base/frame_wrapper.h
  5. 0 200
      AV/code/base/logger.cpp
  6. 0 190
      AV/code/base/logger.h
  7. 0 491
      AV/code/base/media_common.cpp
  8. 0 280
      AV/code/base/media_common.h
  9. 0 290
      AV/code/base/media_thread_base.cpp
  10. 0 153
      AV/code/base/media_thread_base.h
  11. 0 243
      AV/code/base/types.h
  12. 0 172
      AV/code/capture/capture_abstract_capturer.cpp
  13. 0 238
      AV/code/capture/capture_abstract_capturer.h
  14. 0 975
      AV/code/capture/capture_audio_capturer.cpp
  15. 0 257
      AV/code/capture/capture_audio_capturer.h
  16. 0 849
      AV/code/capture/capture_video_capturer.cpp
  17. 0 232
      AV/code/capture/capture_video_capturer.h
  18. 0 456
      AV/code/codec/codec_abstract_codec.cpp
  19. 0 344
      AV/code/codec/codec_abstract_codec.h
  20. 0 597
      AV/code/codec/codec_audio_decoder.cpp
  21. 0 208
      AV/code/codec/codec_audio_decoder.h
  22. 0 1223
      AV/code/codec/codec_audio_encoder.cpp
  23. 0 213
      AV/code/codec/codec_audio_encoder.h
  24. 0 687
      AV/code/codec/codec_video_decoder.cpp
  25. 0 161
      AV/code/codec/codec_video_decoder.h
  26. 0 911
      AV/code/codec/codec_video_encoder.cpp
  27. 0 178
      AV/code/codec/codec_video_encoder.h
  28. 0 529
      AV/code/muxer/muxer_abstract_muxer.cpp
  29. 0 247
      AV/code/muxer/muxer_abstract_muxer.h
  30. 0 891
      AV/code/muxer/muxer_file_muxer.cpp
  31. 0 197
      AV/code/muxer/muxer_file_muxer.h
  32. 0 862
      AV/code/muxer/muxer_stream_muxer.cpp
  33. 0 257
      AV/code/muxer/muxer_stream_muxer.h
  34. 0 668
      AV/code/player/audio_output.cpp
  35. 0 169
      AV/code/player/audio_output.h
  36. 0 8
      AV/code/player/player.pri
  37. 0 1892
      AV/code/player/player_core_v2.cpp
  38. 0 346
      AV/code/player/player_core_v2.h
  39. 0 200
      AV/code/recorder/recorder.cpp
  40. 0 175
      AV/code/recorder/recorder.h
  41. 0 41
      AV/code/recorder/recorder.pri
  42. 0 133
      AV/code/recorder/recorder_abstract_recorder.cpp
  43. 0 193
      AV/code/recorder/recorder_abstract_recorder.h
  44. 0 592
      AV/code/recorder/recorder_audio_recorder.cpp
  45. 0 203
      AV/code/recorder/recorder_audio_recorder.h
  46. 0 710
      AV/code/recorder/recorder_av_recorder.cpp
  47. 0 268
      AV/code/recorder/recorder_av_recorder.h
  48. 0 817
      AV/code/recorder/recorder_video_recorder.cpp
  49. 0 245
      AV/code/recorder/recorder_video_recorder.h
  50. 0 669
      AV/code/recorder/ui/recorder_audio_widget.cpp
  51. 0 320
      AV/code/recorder/ui/recorder_audio_widget.h
  52. 0 866
      AV/code/recorder/ui/recorder_example_app.cpp
  53. 0 195
      AV/code/recorder/ui/recorder_example_app.h
  54. 0 136
      AV/code/recorder/ui/recorder_main.cpp
  55. 0 1297
      AV/code/recorder/ui/recorder_main_widget.cpp
  56. 0 349
      AV/code/recorder/ui/recorder_main_widget.h
  57. 0 1461
      AV/code/recorder/ui/recorder_settings_dialog.cpp
  58. 0 413
      AV/code/recorder/ui/recorder_settings_dialog.h
  59. 0 36
      AV/code/recorder/ui/recorder_ui.pri
  60. 0 5
      AV/code/recorder/ui/recorder_ui.qrc
  61. 0 806
      AV/code/recorder/ui/recorder_video_widget.cpp
  62. 0 290
      AV/code/recorder/ui/recorder_video_widget.h
  63. 0 611
      AV/code/recorder/ui/styles/recorder_ui.qss
  64. 0 726
      AV/code/utils/utils_frame_queue.cpp
  65. 0 299
      AV/code/utils/utils_frame_queue.h
  66. 0 1101
      AV/code/utils/utils_packet_queue.cpp
  67. 0 370
      AV/code/utils/utils_packet_queue.h
  68. 0 836
      AV/code/utils/utils_performance_monitor.cpp
  69. 0 289
      AV/code/utils/utils_performance_monitor.h
  70. 0 762
      AV/code/utils/utils_synchronizer_v2.cpp
  71. 0 239
      AV/code/utils/utils_synchronizer_v2.h
  72. 0 849
      AV/code/utils/utils_thread_pool.cpp
  73. 0 390
      AV/code/utils/utils_thread_pool.h
  74. 0 1
      AV/examples/debug_player.cpp
  75. 0 59
      AV/examples/integration_example.cpp
  76. 0 321
      AV/examples/player_v2_example.cpp
  77. 0 189
      AV/test/test_audio.cpp
  78. 0 330
      AV/test/test_audio_debug.cpp
  79. 0 419
      AV/test/test_audio_encoder.cpp
  80. 0 41
      AV/test/test_audio_fix.cpp
  81. 0 70
      AV/test/test_audio_recorder_complete.cpp
  82. 0 72
      AV/test/test_audio_recorder_fix.cpp
  83. 0 156
      AV/test/test_basic.cpp
  84. 0 207
      AV/test/test_codec.cpp
  85. 0 353
      AV/test/test_decoder.cpp
  86. 0 433
      AV/test/test_muxer.cpp
  87. 0 86
      AV/test/test_muxer_fix.cpp
  88. 0 330
      AV/test/test_player.cpp
  89. 0 311
      AV/test/test_player_adapter.cpp
  90. 0 793
      AV/test/test_player_with_ui.cpp
  91. 0 22
      AV/test/test_playerv2.pri
  92. 0 315
      AV/test/test_recorder.cpp
  93. 0 202
      AV/test/test_seek_pause_fixed.cpp
  94. 0 36
      AV/test/test_simple_player.cpp
  95. 0 574
      AV/test/test_utils.cpp
  96. 0 379
      AV/test/test_window_capture.cpp
  97. 0 276
      AV/xmake.lua
  98. 372 17
      MainPanel.cpp
  99. 44 2
      MainPanel.h
  100. 0 1
      libs/libs.pri

+ 0 - 67
AV/AV.pri

@@ -1,67 +0,0 @@
-HEADERS += \
-    $$PWD/code/base/media_common.h \
-    $$PWD/code/base/logger.h \
-    $$PWD/code/base/media_thread_base.h \
-    $$PWD/code/base/types.h \
-    $$PWD/code/capture/capture_abstract_capturer.h \
-    $$PWD/code/capture/capture_audio_capturer.h \
-    $$PWD/code/capture/capture_video_capturer.h \
-    $$PWD/code/codec/codec_abstract_codec.h \
-    $$PWD/code/codec/codec_audio_decoder.h \
-    $$PWD/code/codec/codec_audio_encoder.h \
-    $$PWD/code/codec/codec_video_decoder.h \
-    $$PWD/code/codec/codec_video_encoder.h \
-    $$PWD/code/muxer/muxer_abstract_muxer.h \
-    $$PWD/code/muxer/muxer_file_muxer.h \
-    $$PWD/code/muxer/muxer_stream_muxer.h \
-    $$PWD/code/utils/utils_frame_queue.h \
-    $$PWD/code/utils/utils_packet_queue.h \
-    $$PWD/code/utils/utils_performance_monitor.h \
-    $$PWD/code/utils/utils_synchronizer_v2.h \
-    $$PWD/code/utils/utils_thread_pool.h
-
-SOURCES += \
-    $$PWD/code/base/media_common.cpp \
-    $$PWD/code/base/logger.cpp \
-    $$PWD/code/base/media_thread_base.cpp \
-    $$PWD/code/capture/capture_abstract_capturer.cpp \
-    $$PWD/code/capture/capture_audio_capturer.cpp \
-    $$PWD/code/capture/capture_video_capturer.cpp \
-    $$PWD/code/codec/codec_abstract_codec.cpp \
-    $$PWD/code/codec/codec_audio_decoder.cpp \
-    $$PWD/code/codec/codec_audio_encoder.cpp \
-    $$PWD/code/codec/codec_video_decoder.cpp \
-    $$PWD/code/codec/codec_video_encoder.cpp \
-    $$PWD/code/muxer/muxer_abstract_muxer.cpp \
-    $$PWD/code/muxer/muxer_file_muxer.cpp \
-    $$PWD/code/muxer/muxer_stream_muxer.cpp \
-    $$PWD/code/utils/utils_frame_queue.cpp \
-    $$PWD/code/utils/utils_packet_queue.cpp \
-    $$PWD/code/utils/utils_performance_monitor.cpp \
-    $$PWD/code/utils/utils_synchronizer_v2.cpp \
-    $$PWD/code/utils/utils_thread_pool.cpp
-
-include($$PWD/code/player/player.pri)
- include($$PWD/code/recorder/recorder.pri)
-
-# Test files (uncomment to enable)
-# SOURCES += $$PWD/test_basic.cpp
-# SOURCES += $$PWD/test_codec.cpp
-# SOURCES += $$PWD/test_decoder.cpp
-# SOURCES += $$PWD/test_audio_encoder.cpp
-# SOURCES += $$PWD/test_window_capture.cpp
-# SOURCES += $$PWD/test_utils.cpp
-# SOURCES += $$PWD/test_audio_debug.cpp
-# SOURCES += $$PWD/test_player_with_ui.cpp
-# SOURCES += $$PWD/test_seek_pause_fixed.cpp
-# Example files for PlayerV2 (uncomment to enable)
-# SOURCES += $$PWD/code/examples/player_v2_example.cpp
-
-# PlayerV2 Test Configuration (uncomment to enable full test suite)
-# include($$PWD/test_playerv2.pri)
-
-# Legacy integration example
-# SOURCES += $$PWD/integration_example.cpp
-
-
-

+ 0 - 0
AV/code/base/config_manager.h


+ 0 - 1
AV/code/base/error_handler.cpp

@@ -1 +0,0 @@
- 

+ 0 - 190
AV/code/base/frame_wrapper.h

@@ -1,190 +0,0 @@
-#ifndef AV_BASE_FRAME_WRAPPER_H
-#define AV_BASE_FRAME_WRAPPER_H
-
-#include "types.h"
-#include <memory>
-#include <functional>
-
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/avutil.h>
-}
-
-namespace av {
-
-/**
- * 安全的AVFrame包装器类
- * 提供比AVFramePtr更安全和易用的接口
- * 解决了智能指针在某些场景下的复杂性问题
- */
-class FrameWrapper {
-public:
-    // 默认构造函数
-    FrameWrapper() = default;
-    
-    // 从原生指针构造(接管所有权)
-    explicit FrameWrapper(AVFrame* frame) : frame_(frame) {}
-    
-    // 从智能指针构造
-    explicit FrameWrapper(AVFramePtr frame) : frame_(frame.release()) {}
-    
-    // 移动构造函数
-    FrameWrapper(FrameWrapper&& other) noexcept 
-        : frame_(other.frame_) {
-        other.frame_ = nullptr;
-    }
-    
-    // 移动赋值操作符
-    FrameWrapper& operator=(FrameWrapper&& other) noexcept {
-        if (this != &other) {
-            reset();
-            frame_ = other.frame_;
-            other.frame_ = nullptr;
-        }
-        return *this;
-    }
-    
-    // 禁用拷贝构造和拷贝赋值
-    FrameWrapper(const FrameWrapper&) = delete;
-    FrameWrapper& operator=(const FrameWrapper&) = delete;
-    
-    // 析构函数
-    ~FrameWrapper() {
-        reset();
-    }
-    
-    // 创建新帧
-    static FrameWrapper create() {
-        return FrameWrapper(av_frame_alloc());
-    }
-    
-    // 创建视频帧
-    static FrameWrapper createVideo(int width, int height, AVPixelFormat format) {
-        AVFrame* frame = av_frame_alloc();
-        if (!frame) return FrameWrapper();
-        
-        frame->width = width;
-        frame->height = height;
-        frame->format = format;
-        
-        if (av_frame_get_buffer(frame, 32) < 0) {
-            av_frame_free(&frame);
-            return FrameWrapper();
-        }
-        
-        return FrameWrapper(frame);
-    }
-    
-    // 创建音频帧
-    static FrameWrapper createAudio(int sampleRate, int channels, 
-                                   AVSampleFormat format, int nbSamples) {
-        AVFrame* frame = av_frame_alloc();
-        if (!frame) return FrameWrapper();
-        
-        frame->sample_rate = sampleRate;
-        frame->ch_layout.nb_channels = channels;
-        frame->format = format;
-        frame->nb_samples = nbSamples;
-        
-        if (av_frame_get_buffer(frame, 0) < 0) {
-            av_frame_free(&frame);
-            return FrameWrapper();
-        }
-        
-        return FrameWrapper(frame);
-    }
-    
-    // 获取原生指针(不转移所有权)
-    AVFrame* get() const { return frame_; }
-    
-    // 获取原生指针并转移所有权
-    AVFrame* release() {
-        AVFrame* temp = frame_;
-        frame_ = nullptr;
-        return temp;
-    }
-    
-    // 重置,释放当前帧
-    void reset(AVFrame* newFrame = nullptr) {
-        if (frame_) {
-            av_frame_free(&frame_);
-        }
-        frame_ = newFrame;
-    }
-    
-    // 检查是否有效
-    bool isValid() const { return frame_ != nullptr; }
-    
-    // 操作符重载
-    operator bool() const { return isValid(); }
-    AVFrame* operator->() const { return frame_; }
-    AVFrame& operator*() const { return *frame_; }
-    
-    // 克隆帧(深拷贝)
-    FrameWrapper clone() const {
-        if (!frame_) return FrameWrapper();
-        
-        AVFrame* newFrame = av_frame_alloc();
-        if (!newFrame) return FrameWrapper();
-        
-        if (av_frame_ref(newFrame, frame_) < 0) {
-            av_frame_free(&newFrame);
-            return FrameWrapper();
-        }
-        
-        return FrameWrapper(newFrame);
-    }
-    
-    // 创建引用(浅拷贝)
-    FrameWrapper ref() const {
-        if (!frame_) return FrameWrapper();
-        
-        AVFrame* newFrame = av_frame_alloc();
-        if (!newFrame) return FrameWrapper();
-        
-        if (av_frame_ref(newFrame, frame_) < 0) {
-            av_frame_free(&newFrame);
-            return FrameWrapper();
-        }
-        
-        return FrameWrapper(newFrame);
-    }
-    
-    // 便捷的属性访问
-    int64_t pts() const { return frame_ ? frame_->pts : AV_NOPTS_VALUE; }
-    void setPts(int64_t pts) { if (frame_) frame_->pts = pts; }
-    
-    int width() const { return frame_ ? frame_->width : 0; }
-    int height() const { return frame_ ? frame_->height : 0; }
-    int sampleRate() const { return frame_ ? frame_->sample_rate : 0; }
-    int channels() const { return frame_ ? frame_->ch_layout.nb_channels : 0; }
-    int nbSamples() const { return frame_ ? frame_->nb_samples : 0; }
-    
-    AVPixelFormat pixelFormat() const { 
-        return frame_ ? static_cast<AVPixelFormat>(frame_->format) : AV_PIX_FMT_NONE; 
-    }
-    
-    AVSampleFormat sampleFormat() const { 
-        return frame_ ? static_cast<AVSampleFormat>(frame_->format) : AV_SAMPLE_FMT_NONE; 
-    }
-    
-    bool isKeyFrame() const { return frame_ && frame_->key_frame; }
-    
-    // 转换为智能指针(转移所有权)
-    AVFramePtr toSmartPtr() {
-        return AVFramePtr(release());
-    }
-
-private:
-    AVFrame* frame_ = nullptr;
-};
-
-// 便捷的类型定义
-using Frame = FrameWrapper;
-
-// 回调函数类型定义(使用 FrameWrapper)
-using FrameWrapperCallback = std::function<void(const FrameWrapper&)>;
-
-} // namespace av
-
-#endif // AV_BASE_FRAME_WRAPPER_H

+ 0 - 200
AV/code/base/logger.cpp

@@ -1,200 +0,0 @@
-#include "logger.h"
-#include <iostream>
-#include <iomanip>
-
-// Qt头文件只在需要时包含
-#ifdef QT_CORE_LIB
-#include <QString>
-#include <QDebug>
-#include <QLoggingCategory>
-#endif
-
-namespace av {
-
-// ConsoleOutput实现
-void ConsoleOutput::write(LogLevel level, const std::string& message) {
-    std::ostream& stream = (level >= LogLevel::WARNING) ? std::cerr : std::cout;
-    stream << message << std::endl;
-    stream.flush();
-}
-
-// FileOutput实现
-FileOutput::FileOutput(const std::string& filename) {
-    m_file.open(filename, std::ios::app);
-    if (!m_file.is_open()) {
-        std::cerr << "Failed to open log file: " << filename << std::endl;
-    }
-}
-
-FileOutput::~FileOutput() {
-    if (m_file.is_open()) {
-        m_file.close();
-    }
-}
-
-void FileOutput::write(LogLevel level, const std::string& message) {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    if (m_file.is_open()) {
-        m_file << message << std::endl;
-        m_file.flush();
-    }
-}
-
-// QtOutput实现
-void QtOutput::write(LogLevel level, const std::string& message) {
-#ifdef QT_CORE_LIB
-    QString qmsg = QString::fromUtf8(message.c_str());
-    switch (level) {
-    case LogLevel::DEBUG:
-        qDebug() << qmsg;
-        break;
-    case LogLevel::INFO:
-        qInfo() << qmsg;
-        break;
-    case LogLevel::WARNING:
-        qWarning() << qmsg;
-        break;
-    case LogLevel::ERROR:
-        qCritical() << qmsg;
-        break;
-    }
-#else
-    // 如果没有Qt,回退到控制台输出
-    ConsoleOutput console;
-    console.write(level, message);
-#endif
-}
-
-// Logger实现
-Logger& Logger::instance() {
-    static Logger instance;
-    return instance;
-}
-
-void Logger::setLevel(LogLevel level) {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    m_level = level;
-}
-
-LogLevel Logger::getLevel() const {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    return m_level;
-}
-
-void Logger::addOutput(std::unique_ptr<LogOutput> output) {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    m_outputs.push_back(std::move(output));
-}
-
-void Logger::clearOutputs() {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    m_outputs.clear();
-}
-
-void Logger::debug(const std::string& message) {
-    if (shouldLog(LogLevel::DEBUG)) {
-        log(LogLevel::DEBUG, message);
-    }
-}
-
-void Logger::info(const std::string& message) {
-    if (shouldLog(LogLevel::INFO)) {
-        log(LogLevel::INFO, message);
-    }
-}
-
-void Logger::warning(const std::string& message) {
-    if (shouldLog(LogLevel::WARNING)) {
-        log(LogLevel::WARNING, message);
-    }
-}
-
-void Logger::error(const std::string& message) {
-    if (shouldLog(LogLevel::ERROR)) {
-        log(LogLevel::ERROR, message);
-    }
-}
-
-#ifdef QT_CORE_LIB
-void Logger::qtDebug(const QString& message) {
-    debug(message.toUtf8().toStdString());
-}
-
-void Logger::qtInfo(const QString& message) {
-    info(message.toUtf8().toStdString());
-}
-
-void Logger::qtWarning(const QString& message) {
-    warning(message.toUtf8().toStdString());
-}
-
-void Logger::qtError(const QString& message) {
-    error(message.toUtf8().toStdString());
-}
-#endif
-
-void Logger::initialize(const std::string& logFile, 
-                       LogLevel level,
-                       bool enableConsole,
-                       bool enableQt) {
-    Logger& logger = instance();
-    logger.clearOutputs();
-    logger.setLevel(level);
-    
-    // 添加文件输出
-    if (!logFile.empty()) {
-        logger.addOutput(std::make_unique<FileOutput>(logFile));
-    }
-    
-    // 添加控制台输出
-    if (enableConsole) {
-        logger.addOutput(std::make_unique<ConsoleOutput>());
-    }
-    
-    // 添加Qt输出
-    if (enableQt) {
-        logger.addOutput(std::make_unique<QtOutput>());
-    }
-    
-    logger.info("AV Logger initialized");
-}
-
-void Logger::log(LogLevel level, const std::string& message) {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    
-    std::string formattedMessage = getCurrentTime() + " [" + levelToString(level) + "] " + message;
-    
-    for (auto& output : m_outputs) {
-        if (output) {
-            output->write(level, formattedMessage);
-        }
-    }
-}
-
-bool Logger::shouldLog(LogLevel level) const {
-    return level >= m_level;
-}
-
-std::string Logger::getCurrentTime() const {
-    auto now = std::chrono::system_clock::now();
-    auto time_t = std::chrono::system_clock::to_time_t(now);
-    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
-        now.time_since_epoch()) % 1000;
-    
-    std::ostringstream oss;
-    oss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
-    oss << '.' << std::setfill('0') << std::setw(3) << ms.count();
-    return oss.str();
-}
-
-std::string Logger::levelToString(LogLevel level) const {
-    switch (level) {
-    case LogLevel::DEBUG:   return "DEBUG";
-    case LogLevel::INFO:    return "INFO";
-    case LogLevel::WARNING: return "WARN";
-    case LogLevel::ERROR:   return "ERROR";
-    default:                return "UNKNOWN";
-    }
-}
-
-} // namespace av

+ 0 - 190
AV/code/base/logger.h

@@ -1,190 +0,0 @@
-#ifndef AV_BASE_LOGGER_H
-#define AV_BASE_LOGGER_H
-
-#include <chrono>
-#include <fstream>
-#include <iomanip>
-#include <memory>
-#include <mutex>
-#include <sstream>
-#include <string>
-#include <vector>
-
-// 前向声明Qt类型,避免在头文件中包含Qt
-class QString;
-
-namespace av {
-// 日志级别枚举
-enum class LogLevel { DEBUG = 0, INFO = 1, WARNING = 2, ERROR = 3 };
-
-// 日志输出接口
-class LogOutput
-{
-public:
-    virtual ~LogOutput() = default;
-    virtual void write(LogLevel level, const std::string& message) = 0;
-};
-
-// 控制台输出
-class ConsoleOutput : public LogOutput
-{
-public:
-    void write(LogLevel level, const std::string& message) override;
-};
-
-// 文件输出
-class FileOutput : public LogOutput
-{
-public:
-    explicit FileOutput(const std::string& filename);
-    ~FileOutput();
-    void write(LogLevel level, const std::string& message) override;
-
-private:
-    std::ofstream m_file;
-    std::mutex m_mutex;
-};
-
-// Qt输出(用于兼容现有Qt日志系统)
-class QtOutput : public LogOutput
-{
-public:
-    void write(LogLevel level, const std::string& message) override;
-};
-
-// 主日志类
-class Logger
-{
-public:
-    static Logger& instance();
-
-    // 设置日志级别
-    void setLevel(LogLevel level);
-    LogLevel getLevel() const;
-
-    // 添加输出目标
-    void addOutput(std::unique_ptr<LogOutput> output);
-    void clearOutputs();
-
-    // 日志记录方法
-    void debug(const std::string& message);
-    void info(const std::string& message);
-    void warning(const std::string& message);
-    void error(const std::string& message);
-
-    // 格式化日志记录
-    template<typename... Args>
-    void debugf(const std::string& format, Args&&... args)
-    {
-        if (shouldLog(LogLevel::DEBUG)) {
-            log(LogLevel::DEBUG, formatString(format, std::forward<Args>(args)...));
-        }
-    }
-
-    template<typename... Args>
-    void infof(const std::string& format, Args&&... args)
-    {
-        if (shouldLog(LogLevel::INFO)) {
-            log(LogLevel::INFO, formatString(format, std::forward<Args>(args)...));
-        }
-    }
-
-    template<typename... Args>
-    void warningf(const std::string& format, Args&&... args)
-    {
-        if (shouldLog(LogLevel::WARNING)) {
-            log(LogLevel::WARNING, formatString(format, std::forward<Args>(args)...));
-        }
-    }
-
-    template<typename... Args>
-    void errorf(const std::string& format, Args&&... args)
-    {
-        if (shouldLog(LogLevel::ERROR)) {
-            log(LogLevel::ERROR, formatString(format, std::forward<Args>(args)...));
-        }
-    }
-
-#ifdef QT_CORE_LIB
-    // Qt兼容接口
-    void qtDebug(const QString& message);
-    void qtInfo(const QString& message);
-    void qtWarning(const QString& message);
-    void qtError(const QString& message);
-#endif
-
-    // 初始化方法(全局初始化时调用)
-    static void initialize(const std::string& logFile = "av_log.txt",
-                           LogLevel level = LogLevel::INFO,
-                           bool enableConsole = true,
-                           bool enableQt = true);
-
-private:
-    Logger() = default;
-    ~Logger() = default;
-    Logger(const Logger&) = delete;
-    Logger& operator=(const Logger&) = delete;
-
-    void log(LogLevel level, const std::string& message);
-    bool shouldLog(LogLevel level) const;
-    std::string getCurrentTime() const;
-    std::string levelToString(LogLevel level) const;
-
-    template<typename... Args>
-    std::string formatString(const std::string& format, Args&&... args)
-    {
-        std::ostringstream oss;
-        formatImpl(oss, format, std::forward<Args>(args)...);
-        return oss.str();
-    }
-
-    // 处理无参数情况的formatImpl重载
-    void formatImpl(std::ostringstream& oss, const std::string& format) { oss << format; }
-
-    template<typename T>
-    void formatImpl(std::ostringstream& oss, const std::string& format, T&& value)
-    {
-        size_t pos = format.find("{}");
-        if (pos != std::string::npos) {
-            oss << format.substr(0, pos) << std::forward<T>(value) << format.substr(pos + 2);
-        } else {
-            oss << format;
-        }
-    }
-
-    template<typename T, typename... Args>
-    void formatImpl(std::ostringstream& oss, const std::string& format, T&& value, Args&&... args)
-    {
-        size_t pos = format.find("{}");
-        if (pos != std::string::npos) {
-            oss << format.substr(0, pos) << std::forward<T>(value);
-            formatImpl(oss, format.substr(pos + 2), std::forward<Args>(args)...);
-        } else {
-            oss << format;
-        }
-    }
-
-    LogLevel m_level = LogLevel::INFO;
-    std::vector<std::unique_ptr<LogOutput>> m_outputs;
-    mutable std::mutex m_mutex;
-};
-} // namespace av
-
-// 便捷宏定义(重命名以避免与FFmpeg宏冲突)
-#define AV_LOGGER_DEBUG(msg) av::Logger::instance().debug(msg)
-#define AV_LOGGER_INFO(msg) av::Logger::instance().info(msg)
-#define AV_LOGGER_WARNING(msg) av::Logger::instance().warning(msg)
-#define AV_LOGGER_ERROR(msg) av::Logger::instance().error(msg)
-
-#define AV_LOGGER_DEBUGF(fmt, ...) av::Logger::instance().debugf(fmt, __VA_ARGS__)
-#define AV_LOGGER_INFOF(fmt, ...) av::Logger::instance().infof(fmt, __VA_ARGS__)
-#define AV_LOGGER_WARNINGF(fmt, ...) av::Logger::instance().warningf(fmt, __VA_ARGS__)
-#define AV_LOGGER_ERRORF(fmt, ...) av::Logger::instance().errorf(fmt, __VA_ARGS__)
-
-// Qt兼容宏(用于逐步替换现有代码)
-#define AV_QDEBUG(msg) av::Logger::instance().qtDebug(msg)
-#define AV_QINFO(msg) av::Logger::instance().qtInfo(msg)
-#define AV_QWARNING(msg) av::Logger::instance().qtWarning(msg)
-#define AV_QERROR(msg) av::Logger::instance().qtError(msg)
-
-#endif // AV_BASE_LOGGER_H

+ 0 - 491
AV/code/base/media_common.cpp

@@ -1,491 +0,0 @@
-#include "media_common.h"
-#include "logger.h"
-#include <algorithm>
-#include <sstream>
-#include <fstream>
-#include <filesystem>
-#include <cctype>
-#include <iomanip>
-#include <cstring>
-#include <limits>
-
-// FFmpeg头文件
-extern "C" {
-#include <libavutil/avutil.h>
-#include <libavcodec/avcodec.h>
-#include <libavformat/avformat.h>
-#include <libswscale/swscale.h>
-#include <libswresample/swresample.h>
-#include <libavutil/log.h>
-#include <libavutil/error.h>
-#include <libavutil/pixfmt.h>
-#include <libavutil/pixdesc.h>
-#include <libavutil/samplefmt.h>
-#include <libavutil/frame.h>
-#include <libavcodec/packet.h>
-}
-
-namespace av {
-
-// 字符串工具实现
-namespace string_utils {
-
-std::vector<std::string> split(const std::string& str, char delimiter) {
-    std::vector<std::string> result;
-    std::stringstream ss(str);
-    std::string item;
-    
-    while (std::getline(ss, item, delimiter)) {
-        result.push_back(item);
-    }
-    
-    return result;
-}
-
-std::vector<std::string> split(const std::string& str, const std::string& delimiter) {
-    std::vector<std::string> result;
-    size_t start = 0;
-    size_t end = str.find(delimiter);
-    
-    while (end != std::string::npos) {
-        result.push_back(str.substr(start, end - start));
-        start = end + delimiter.length();
-        end = str.find(delimiter, start);
-    }
-    
-    result.push_back(str.substr(start));
-    return result;
-}
-
-std::string trim(const std::string& str) {
-    return trimLeft(trimRight(str));
-}
-
-std::string trimLeft(const std::string& str) {
-    auto start = str.begin();
-    while (start != str.end() && std::isspace(*start)) {
-        start++;
-    }
-    return std::string(start, str.end());
-}
-
-std::string trimRight(const std::string& str) {
-    auto end = str.end();
-    while (end != str.begin() && std::isspace(*(end - 1))) {
-        end--;
-    }
-    return std::string(str.begin(), end);
-}
-
-std::string replace(const std::string& str, const std::string& from, const std::string& to) {
-    std::string result = str;
-    size_t pos = 0;
-    
-    while ((pos = result.find(from, pos)) != std::string::npos) {
-        result.replace(pos, from.length(), to);
-        pos += to.length();
-    }
-    
-    return result;
-}
-
-std::string toLower(const std::string& str) {
-    std::string result = str;
-    std::transform(result.begin(), result.end(), result.begin(), ::tolower);
-    return result;
-}
-
-std::string toUpper(const std::string& str) {
-    std::string result = str;
-    std::transform(result.begin(), result.end(), result.begin(), ::toupper);
-    return result;
-}
-
-bool startsWith(const std::string& str, const std::string& prefix) {
-    return str.length() >= prefix.length() && 
-           str.compare(0, prefix.length(), prefix) == 0;
-}
-
-bool endsWith(const std::string& str, const std::string& suffix) {
-    return str.length() >= suffix.length() && 
-           str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
-}
-
-bool contains(const std::string& str, const std::string& substr) {
-    return str.find(substr) != std::string::npos;
-}
-
-} // namespace string_utils
-
-// 文件路径工具实现
-namespace path_utils {
-
-std::string join(const std::string& path1, const std::string& path2) {
-    if (path1.empty()) return path2;
-    if (path2.empty()) return path1;
-    
-    std::filesystem::path p1(path1);
-    std::filesystem::path p2(path2);
-    return (p1 / p2).string();
-}
-
-std::string getDirectory(const std::string& path) {
-    std::filesystem::path p(path);
-    return p.parent_path().string();
-}
-
-std::string getFilename(const std::string& path) {
-    std::filesystem::path p(path);
-    return p.filename().string();
-}
-
-std::string getExtension(const std::string& path) {
-    std::filesystem::path p(path);
-    return p.extension().string();
-}
-
-std::string removeExtension(const std::string& path) {
-    std::filesystem::path p(path);
-    return p.replace_extension().string();
-}
-
-std::string normalize(const std::string& path) {
-    std::filesystem::path p(path);
-    return std::filesystem::weakly_canonical(p).string();
-}
-
-std::string toNative(const std::string& path) {
-    std::filesystem::path p(path);
-    return p.make_preferred().string();
-}
-
-bool exists(const std::string& path) {
-    return std::filesystem::exists(path);
-}
-
-bool isFile(const std::string& path) {
-    return std::filesystem::is_regular_file(path);
-}
-
-bool isDirectory(const std::string& path) {
-    return std::filesystem::is_directory(path);
-}
-
-bool isAbsolute(const std::string& path) {
-    std::filesystem::path p(path);
-    return p.is_absolute();
-}
-
-bool createDirectory(const std::string& path) {
-    try {
-        return std::filesystem::create_directories(path);
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Failed to create directory '{}': {}", path, e.what());
-        return false;
-    }
-}
-
-bool removeFile(const std::string& path) {
-    try {
-        return std::filesystem::remove(path);
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Failed to remove file '{}': {}", path, e.what());
-        return false;
-    }
-}
-
-} // namespace path_utils
-
-// 时间工具实现
-namespace time_utils {
-
-int64_t getCurrentTimeMs() {
-    return std::chrono::duration_cast<std::chrono::milliseconds>(
-        std::chrono::steady_clock::now().time_since_epoch()).count();
-}
-
-int64_t getCurrentTimeUs() {
-    return std::chrono::duration_cast<std::chrono::microseconds>(
-        std::chrono::steady_clock::now().time_since_epoch()).count();
-}
-
-std::string formatTime(int64_t timeMs, const std::string& format) {
-    auto time_t = std::chrono::system_clock::to_time_t(
-        std::chrono::system_clock::time_point(
-            std::chrono::milliseconds(timeMs)));
-    
-    std::ostringstream oss;
-    oss << std::put_time(std::localtime(&time_t), format.c_str());
-    return oss.str();
-}
-
-std::string formatDuration(int64_t durationMs) {
-    int64_t hours = durationMs / (1000 * 60 * 60);
-    int64_t minutes = (durationMs % (1000 * 60 * 60)) / (1000 * 60);
-    int64_t seconds = (durationMs % (1000 * 60)) / 1000;
-    int64_t ms = durationMs % 1000;
-    
-    std::ostringstream oss;
-    if (hours > 0) {
-        oss << hours << ":" << std::setfill('0') << std::setw(2) << minutes 
-            << ":" << std::setw(2) << seconds;
-    } else {
-        oss << minutes << ":" << std::setfill('0') << std::setw(2) << seconds;
-    }
-    
-    if (ms > 0) {
-        oss << "." << std::setw(3) << ms;
-    }
-    
-    return oss.str();
-}
-
-// Timer实现
-Timer::Timer() {
-    reset();
-}
-
-void Timer::start() {
-    m_startTime = std::chrono::high_resolution_clock::now();
-    m_running = true;
-}
-
-void Timer::stop() {
-    if (m_running) {
-        m_endTime = std::chrono::high_resolution_clock::now();
-        m_running = false;
-    }
-}
-
-void Timer::reset() {
-    m_startTime = std::chrono::high_resolution_clock::now();
-    m_endTime = m_startTime;
-    m_running = false;
-}
-
-int64_t Timer::elapsedMs() const {
-    auto endTime = m_running ? std::chrono::high_resolution_clock::now() : m_endTime;
-    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - m_startTime).count();
-}
-
-int64_t Timer::elapsedUs() const {
-    auto endTime = m_running ? std::chrono::high_resolution_clock::now() : m_endTime;
-    return std::chrono::duration_cast<std::chrono::microseconds>(endTime - m_startTime).count();
-}
-
-bool Timer::isRunning() const {
-    return m_running;
-}
-
-// ScopedTimer实现
-ScopedTimer::ScopedTimer(const std::string& name) : m_name(name) {
-    m_timer.start();
-}
-
-ScopedTimer::~ScopedTimer() {
-    m_timer.stop();
-    AV_LOGGER_INFOF("[Timer] {} took {} ms", m_name, m_timer.elapsedMs());
-}
-
-} // namespace time_utils
-
-// 内存工具实现
-namespace memory_utils {
-
-size_t alignSize(size_t size, size_t alignment) {
-    return (size + alignment - 1) & ~(alignment - 1);
-}
-
-void* alignedAlloc(size_t size, size_t alignment) {
-#ifdef _WIN32
-    return _aligned_malloc(size, alignment);
-#else
-    void* ptr = nullptr;
-    if (posix_memalign(&ptr, alignment, size) != 0) {
-        return nullptr;
-    }
-    return ptr;
-#endif
-}
-
-void alignedFree(void* ptr) {
-#ifdef _WIN32
-    _aligned_free(ptr);
-#else
-    free(ptr);
-#endif
-}
-
-// MemoryPool实现
-MemoryPool::MemoryPool(size_t blockSize, size_t blockCount) 
-    : m_blockSize(blockSize) {
-    size_t totalSize = blockSize * blockCount;
-    m_memory.resize(totalSize);
-    
-    // 初始化空闲块列表
-    for (size_t i = 0; i < blockCount; ++i) {
-        m_freeBlocks.push_back(m_memory.data() + i * blockSize);
-    }
-}
-
-MemoryPool::~MemoryPool() {
-    // 析构函数自动清理
-}
-
-void* MemoryPool::allocate() {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    
-    if (m_freeBlocks.empty()) {
-        return nullptr;
-    }
-    
-    void* ptr = m_freeBlocks.back();
-    m_freeBlocks.pop_back();
-    return ptr;
-}
-
-void MemoryPool::deallocate(void* ptr) {
-    if (!ptr) return;
-    
-    std::lock_guard<std::mutex> lock(m_mutex);
-    
-    // 验证指针是否属于这个内存池
-    uint8_t* bytePtr = static_cast<uint8_t*>(ptr);
-    if (bytePtr >= m_memory.data() && 
-        bytePtr < m_memory.data() + m_memory.size()) {
-        m_freeBlocks.push_back(ptr);
-    }
-}
-
-size_t MemoryPool::getAvailableBlocks() const {
-    std::lock_guard<std::mutex> lock(m_mutex);
-    return m_freeBlocks.size();
-}
-
-} // namespace memory_utils
-
-// FFmpeg工具实现
-namespace ffmpeg_utils {
-
-std::string errorToString(int errorCode) {
-    char buffer[AV_ERROR_MAX_STRING_SIZE];
-    av_strerror(errorCode, buffer, sizeof(buffer));
-    return std::string(buffer);
-}
-
-bool checkError(int ret, const std::string& operation) {
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("{} failed: {}", operation, errorToString(ret));
-        return false;
-    }
-    return true;
-}
-
-std::string pixelFormatToString(AVPixelFormat format) {
-    const char* name = av_get_pix_fmt_name(format);
-    return name ? std::string(name) : "unknown";
-}
-
-std::string sampleFormatToString(AVSampleFormat format) {
-    const char* name = av_get_sample_fmt_name(format);
-    return name ? std::string(name) : "unknown";
-}
-
-std::string codecTypeToString(AVMediaType type) {
-    const char* name = av_get_media_type_string(type);
-    return name ? std::string(name) : "unknown";
-}
-
-bool isValidPixelFormat(AVPixelFormat format) {
-    return format != AV_PIX_FMT_NONE && av_get_pix_fmt_name(format) != nullptr;
-}
-
-bool isValidSampleFormat(AVSampleFormat format) {
-    return format != AV_SAMPLE_FMT_NONE && av_get_sample_fmt_name(format) != nullptr;
-}
-
-bool isValidSampleRate(int sampleRate) {
-    return sampleRate > 0 && sampleRate <= 192000;
-}
-
-bool isValidChannels(int channels) {
-    return channels > 0 && channels <= 32;
-}
-
-// 统一使用智能指针的帧分配函数
-AVFramePtr allocateFrame(AVPixelFormat format, int width, int height) {
-    AVFramePtr frame = makeAVFrame();
-    if (!frame) {
-        return nullptr;
-    }
-    
-    frame->format = format;
-    frame->width = width;
-    frame->height = height;
-    
-    if (av_frame_get_buffer(frame.get(), 32) < 0) {
-        return nullptr; // 智能指针自动释放
-    }
-    
-    return frame;
-}
-
-AVFramePtr allocateAudioFrame(AVSampleFormat format, int sampleRate, int channels, int nbSamples) {
-    AVFramePtr frame = makeAVFrame();
-    if (!frame) {
-        return nullptr;
-    }
-    
-    frame->format = format;
-    frame->sample_rate = sampleRate;
-    frame->ch_layout.nb_channels = channels;
-    frame->nb_samples = nbSamples;
-    
-    if (av_frame_get_buffer(frame.get(), 0) < 0) {
-        return nullptr; // 智能指针自动释放
-    }
-    
-    return frame;
-}
-
-void freeFrame(AVFrame** frame) {
-    if (frame && *frame) {
-        av_frame_free(frame);
-    }
-}
-
-AVPacket* allocatePacket() {
-    return av_packet_alloc();
-}
-
-void freePacket(AVPacket** packet) {
-    if (packet && *packet) {
-        av_packet_free(packet);
-    }
-}
-
-bool initializeFFmpeg() {
-    static bool initialized = false;
-    if (initialized) {
-        return true;
-    }
-    
-    try {
-        // FFmpeg 4.0+ 不需要显式注册
-        av_log_set_level(AV_LOG_QUIET);
-        initialized = true;
-        AV_LOGGER_INFO("FFmpeg initialized successfully");
-        return true;
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Failed to initialize FFmpeg: {}", e.what());
-        return false;
-    }
-}
-
-void cleanupFFmpeg() {
-    // FFmpeg 4.0+ 不需要显式清理
-    AV_LOGGER_INFO("FFmpeg cleanup completed");
-}
-
-} // namespace ffmpeg_utils
-} // namespace av

+ 0 - 280
AV/code/base/media_common.h

@@ -1,280 +0,0 @@
-#ifndef AV_BASE_MEDIA_COMMON_H
-#define AV_BASE_MEDIA_COMMON_H
-
-#include "types.h"
-#include <string>
-#include <vector>
-#include <memory>
-#include <functional>
-#include <chrono>
-#include <limits>
-
-namespace av {
-
-// 字符串工具
-namespace string_utils {
-    // 字符串分割
-    std::vector<std::string> split(const std::string& str, char delimiter);
-    std::vector<std::string> split(const std::string& str, const std::string& delimiter);
-    
-    // 字符串修剪
-    std::string trim(const std::string& str);
-    std::string trimLeft(const std::string& str);
-    std::string trimRight(const std::string& str);
-    
-    // 字符串替换
-    std::string replace(const std::string& str, const std::string& from, const std::string& to);
-    
-    // 大小写转换
-    std::string toLower(const std::string& str);
-    std::string toUpper(const std::string& str);
-    
-    // 字符串判断
-    bool startsWith(const std::string& str, const std::string& prefix);
-    bool endsWith(const std::string& str, const std::string& suffix);
-    bool contains(const std::string& str, const std::string& substr);
-    
-    // 格式化
-    template<typename... Args>
-    std::string format(const std::string& format, Args&&... args);
-}
-
-// 文件路径工具
-namespace path_utils {
-    // 路径操作
-    std::string join(const std::string& path1, const std::string& path2);
-    std::string getDirectory(const std::string& path);
-    std::string getFilename(const std::string& path);
-    std::string getExtension(const std::string& path);
-    std::string removeExtension(const std::string& path);
-    
-    // 路径规范化
-    std::string normalize(const std::string& path);
-    std::string toNative(const std::string& path);
-    
-    // 路径判断
-    bool exists(const std::string& path);
-    bool isFile(const std::string& path);
-    bool isDirectory(const std::string& path);
-    bool isAbsolute(const std::string& path);
-    
-    // 目录操作
-    bool createDirectory(const std::string& path);
-    bool removeFile(const std::string& path);
-}
-
-// 时间工具
-namespace time_utils {
-    // 获取当前时间戳
-    int64_t getCurrentTimeMs();
-    int64_t getCurrentTimeUs();
-    
-    // 时间格式化
-    std::string formatTime(int64_t timeMs, const std::string& format = "%Y-%m-%d %H:%M:%S");
-    std::string formatDuration(int64_t durationMs);
-    
-    // 性能计时器
-    class Timer {
-    public:
-        Timer();
-        void start();
-        void stop();
-        void reset();
-        int64_t elapsedMs() const;
-        int64_t elapsedUs() const;
-        bool isRunning() const;
-        
-    private:
-        std::chrono::high_resolution_clock::time_point m_startTime;
-        std::chrono::high_resolution_clock::time_point m_endTime;
-        bool m_running = false;
-    };
-    
-    // RAII计时器
-    class ScopedTimer {
-    public:
-        explicit ScopedTimer(const std::string& name);
-        ~ScopedTimer();
-        
-    private:
-        std::string m_name;
-        Timer m_timer;
-    };
-}
-
-// 内存工具
-namespace memory_utils {
-    // 内存对齐
-    size_t alignSize(size_t size, size_t alignment);
-    void* alignedAlloc(size_t size, size_t alignment);
-    void alignedFree(void* ptr);
-    
-    // 内存池(简单实现)
-    class MemoryPool {
-    public:
-        explicit MemoryPool(size_t blockSize, size_t blockCount = 100);
-        ~MemoryPool();
-        
-        void* allocate();
-        void deallocate(void* ptr);
-        
-        size_t getBlockSize() const { return m_blockSize; }
-        size_t getAvailableBlocks() const;
-        
-    private:
-        size_t m_blockSize;
-        std::vector<uint8_t> m_memory;
-        std::vector<void*> m_freeBlocks;
-        mutable std::mutex m_mutex;
-    };
-}
-
-// FFmpeg工具
-namespace ffmpeg_utils {
-    // 错误处理
-    std::string errorToString(int errorCode);
-    bool checkError(int ret, const std::string& operation);
-    
-    // 格式转换
-    std::string pixelFormatToString(AVPixelFormat format);
-    std::string sampleFormatToString(AVSampleFormat format);
-    std::string codecTypeToString(AVMediaType type);
-    
-    // 参数验证
-    bool isValidPixelFormat(AVPixelFormat format);
-    bool isValidSampleFormat(AVSampleFormat format);
-    bool isValidSampleRate(int sampleRate);
-    bool isValidChannels(int channels);
-    
-    // 帧工具
-    // 统一使用智能指针的帧分配函数
-AVFramePtr allocateFrame(AVPixelFormat format, int width, int height);
-AVFramePtr allocateAudioFrame(AVSampleFormat format, int sampleRate, int channels, int nbSamples);
-    void freeFrame(AVFrame** frame);
-    
-    // 包工具
-    AVPacket* allocatePacket();
-    void freePacket(AVPacket** packet);
-    
-    // 初始化
-    bool initializeFFmpeg();
-    void cleanupFFmpeg();
-}
-
-// 数学工具
-namespace math_utils {
-    // 数值限制
-    template<typename T>
-    T clamp(T value, T min, T max) {
-        return (value < min) ? min : (value > max) ? max : value;
-    }
-    
-    // 数值转换
-    template<typename T, typename U>
-    T safeCast(U value) {
-        return static_cast<T>(clamp<U>(value, 
-            static_cast<U>(std::numeric_limits<T>::min()),
-            static_cast<U>(std::numeric_limits<T>::max())));
-    }
-    
-    // 对齐
-    template<typename T>
-    T alignUp(T value, T alignment) {
-        return (value + alignment - 1) / alignment * alignment;
-    }
-    
-    template<typename T>
-    T alignDown(T value, T alignment) {
-        return value / alignment * alignment;
-    }
-}
-
-// 线程安全的单例模板
-template<typename T>
-class Singleton {
-public:
-    static T& instance() {
-        static T instance;
-        return instance;
-    }
-    
-protected:
-    Singleton() = default;
-    virtual ~Singleton() = default;
-    
-private:
-    Singleton(const Singleton&) = delete;
-    Singleton& operator=(const Singleton&) = delete;
-};
-
-// RAII资源管理器
-template<typename Resource, typename Deleter>
-class ResourceGuard {
-public:
-    explicit ResourceGuard(Resource resource, Deleter deleter)
-        : m_resource(resource), m_deleter(deleter), m_valid(true) {}
-    
-    ~ResourceGuard() {
-        if (m_valid && m_resource) {
-            m_deleter(m_resource);
-        }
-    }
-    
-    // 移动构造
-    ResourceGuard(ResourceGuard&& other) noexcept
-        : m_resource(other.m_resource), m_deleter(std::move(other.m_deleter)), m_valid(other.m_valid) {
-        other.m_valid = false;
-    }
-    
-    // 移动赋值
-    ResourceGuard& operator=(ResourceGuard&& other) noexcept {
-        if (this != &other) {
-            if (m_valid && m_resource) {
-                m_deleter(m_resource);
-            }
-            m_resource = other.m_resource;
-            m_deleter = std::move(other.m_deleter);
-            m_valid = other.m_valid;
-            other.m_valid = false;
-        }
-        return *this;
-    }
-    
-    // 禁止拷贝
-    ResourceGuard(const ResourceGuard&) = delete;
-    ResourceGuard& operator=(const ResourceGuard&) = delete;
-    
-    Resource get() const { return m_resource; }
-    Resource release() {
-        m_valid = false;
-        return m_resource;
-    }
-    
-    bool isValid() const { return m_valid; }
-    
-private:
-    Resource m_resource;
-    Deleter m_deleter;
-    bool m_valid;
-};
-
-// 便捷的资源管理器创建函数
-template<typename Resource, typename Deleter>
-ResourceGuard<Resource, Deleter> makeResourceGuard(Resource resource, Deleter deleter) {
-    return ResourceGuard<Resource, Deleter>(resource, deleter);
-}
-
-} // namespace av
-
-// 便捷宏定义
-#define AV_SCOPED_TIMER(name) av::time_utils::ScopedTimer _timer(name)
-#define AV_MEASURE_TIME(name, code) \
-    do { \
-        av::time_utils::Timer _timer; \
-        _timer.start(); \
-        code; \
-        _timer.stop(); \
-        AV_LOGGER_INFOF("{} took {} ms", name, _timer.elapsedMs()); \
-    } while(0)
-
-#endif // AV_BASE_MEDIA_COMMON_H

+ 0 - 290
AV/code/base/media_thread_base.cpp

@@ -1,290 +0,0 @@
-#include "media_thread_base.h"
-
-#include "../base/logger.h"
-
-#include <stdexcept>
-#include <sstream>
-
-namespace av {
-
-ThreadBase::ThreadBase() {
-    AV_LOGGER_DEBUG("ThreadBase created");
-}
-
-ThreadBase::~ThreadBase() {
-    if (isRunning()) {
-        AV_LOGGER_WARNING("ThreadBase destroyed while still running, forcing stop");
-        stop();
-        join();
-    }
-    AV_LOGGER_DEBUG("ThreadBase destroyed");
-}
-
-bool ThreadBase::start() {
-    std::unique_lock<std::mutex> lock(m_stateMutex);
-    
-    if (m_state != ThreadState::STOPPED) {
-        AV_LOGGER_WARNING("Thread already started or starting");
-        return false;
-    }
-    
-    try {
-        setState(ThreadState::STARTING);
-        m_exitRequested = false;
-        
-        m_thread = std::make_unique<std::thread>(&ThreadBase::threadEntry, this);
-        m_threadId = m_thread->get_id();
-        
-        // 等待线程真正开始运行
-        m_stateCondition.wait(lock, [this] {
-            return m_state == ThreadState::RUNNING || m_state == ThreadState::STOPPED;
-        });
-        
-        bool success = (m_state == ThreadState::RUNNING);
-        if (success) {
-            AV_LOGGER_INFOF("Thread '{}' started successfully", m_threadName.empty() ? "unnamed" : m_threadName);
-        } else {
-            AV_LOGGER_ERRORF("Thread '{}' failed to start", m_threadName.empty() ? "unnamed" : m_threadName);
-        }
-        
-        return success;
-    } catch (const std::exception& e) {
-        setState(ThreadState::STOPPED);
-        AV_LOGGER_ERRORF("Failed to start thread: {}", e.what());
-        return false;
-    }
-}
-
-void ThreadBase::stop() {
-    {
-        std::lock_guard<std::mutex> lock(m_stateMutex);
-        if (m_state == ThreadState::STOPPED || m_state == ThreadState::STOPPING) {
-            return;
-        }
-        setState(ThreadState::STOPPING);
-    }
-    
-    m_exitRequested = true;
-    m_condition.notify_all();
-    
-    AV_LOGGER_INFOF("Thread '{}' stop requested", m_threadName.empty() ? "unnamed" : m_threadName);
-}
-
-void ThreadBase::join() {
-    std::unique_ptr<std::thread> thread;
-    {
-        std::lock_guard<std::mutex> lock(m_stateMutex);
-        thread = std::move(m_thread);
-    }
-    
-    if (thread && thread->joinable()) {
-        // 检查是否在同一线程中调用join
-        if (std::this_thread::get_id() == thread->get_id()) {
-            AV_LOGGER_WARNING("Cannot join thread from itself, detaching instead");
-            thread->detach();
-            return;
-        }
-        
-        try {
-            // 使用超时等待
-            std::unique_lock<std::mutex> lock(m_stateMutex);
-            bool finished = m_stateCondition.wait_for(lock, 
-                std::chrono::milliseconds(DEFAULT_JOIN_TIMEOUT_MS),
-                [this] { return m_state == ThreadState::STOPPED; });
-            
-            if (finished) {
-                lock.unlock();
-                thread->join();
-                AV_LOGGER_INFOF("Thread '{}' joined successfully", m_threadName.empty() ? "unnamed" : m_threadName);
-            } else {
-                AV_LOGGER_WARNINGF("Thread '{}' join timeout, detaching", m_threadName.empty() ? "unnamed" : m_threadName);
-                thread->detach();
-            }
-        } catch (const std::exception& e) {
-            AV_LOGGER_ERRORF("Exception during thread join: {}", e.what());
-            if (thread->joinable()) {
-                thread->detach();
-            }
-        }
-    }
-}
-
-bool ThreadBase::isRunning() const {
-    return m_state == ThreadState::RUNNING;
-}
-
-bool ThreadBase::isStopping() const {
-    return m_state == ThreadState::STOPPING;
-}
-
-ThreadState ThreadBase::getState() const {
-    return m_state.load();
-}
-
-std::thread::id ThreadBase::getThreadId() const {
-    std::lock_guard<std::mutex> lock(m_stateMutex);
-    return m_threadId;
-}
-
-void ThreadBase::setThreadName(const std::string& name) {
-    std::lock_guard<std::mutex> lock(m_stateMutex);
-    m_threadName = name;
-}
-
-std::string ThreadBase::getThreadName() const {
-    std::lock_guard<std::mutex> lock(m_stateMutex);
-    return m_threadName;
-}
-
-void ThreadBase::setOnStarted(std::function<void()> callback) {
-    std::lock_guard<std::mutex> lock(m_stateMutex);
-    m_onStarted = std::move(callback);
-}
-
-void ThreadBase::setOnFinished(std::function<void()> callback) {
-    std::lock_guard<std::mutex> lock(m_stateMutex);
-    m_onFinished = std::move(callback);
-}
-
-void ThreadBase::setOnError(std::function<void(const std::string&)> callback) {
-    std::lock_guard<std::mutex> lock(m_stateMutex);
-    m_onError = std::move(callback);
-}
-
-void ThreadBase::waitForCondition(std::function<bool()> condition, int timeoutMs) {
-    std::unique_lock<std::mutex> lock(m_mutex);
-    
-    if (timeoutMs < 0) {
-        m_condition.wait(lock, [this, &condition] {
-            return shouldExit() || condition();
-        });
-    } else {
-        m_condition.wait_for(lock, std::chrono::milliseconds(timeoutMs), [this, &condition] {
-            return shouldExit() || condition();
-        });
-    }
-}
-
-void ThreadBase::notifyCondition() {
-    m_condition.notify_all();
-}
-
-bool ThreadBase::shouldExit() const {
-    return m_exitRequested.load();
-}
-
-void ThreadBase::sleepMs(int ms) {
-    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
-}
-
-bool ThreadBase::waitForMs(int ms) {
-    std::unique_lock<std::mutex> lock(m_mutex);
-    return !m_condition.wait_for(lock, std::chrono::milliseconds(ms), [this] {
-        return shouldExit();
-    });
-}
-
-void ThreadBase::reportError(const std::string& error) {
-    AV_LOGGER_ERRORF("Thread '{}' error: {}", m_threadName.empty() ? "unnamed" : m_threadName, error);
-    
-    std::function<void(const std::string&)> errorCallback;
-    {
-        std::lock_guard<std::mutex> lock(m_stateMutex);
-        errorCallback = m_onError;
-    }
-    
-    if (errorCallback) {
-        try {
-            errorCallback(error);
-        } catch (const std::exception& e) {
-            AV_LOGGER_ERRORF("Exception in error callback: {}", e.what());
-        } catch (...) {
-            AV_LOGGER_ERROR("Unknown exception in error callback");
-        }
-    }
-}
-
-void ThreadBase::threadEntry() {
-    try {
-        // 设置线程状态为运行中
-        {
-            std::lock_guard<std::mutex> lock(m_stateMutex);
-            setState(ThreadState::RUNNING);
-            m_stateCondition.notify_all();
-        }
-        
-        // 调用启动回调
-        std::function<void()> startedCallback;
-        {
-            std::lock_guard<std::mutex> lock(m_stateMutex);
-            startedCallback = m_onStarted;
-        }
-        
-        if (startedCallback) {
-            try {
-                startedCallback();
-            } catch (const std::exception& e) {
-                AV_LOGGER_ERRORF("Exception in started callback: {}", e.what());
-            } catch (...) {
-                AV_LOGGER_ERROR("Unknown exception in started callback");
-            }
-        }
-        
-        AV_LOGGER_DEBUGF("Thread '{}' entering run loop", m_threadName.empty() ? "unnamed" : m_threadName);
-        
-        // 执行用户逻辑
-        run();
-        
-        AV_LOGGER_DEBUGF("Thread '{}' exiting run loop", m_threadName.empty() ? "unnamed" : m_threadName);
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Unhandled exception in thread '{}': {}", m_threadName.empty()
-                             ? "unnamed"
-                             : m_threadName,
-                         e.what());
-        reportError("Unhandled exception: " + std::string(e.what()));
-    } catch (...) {
-        AV_LOGGER_ERRORF("Unknown unhandled exception in thread '{}'", 
-                     m_threadName.empty() ? "unnamed" : m_threadName);
-        reportError("Unknown unhandled exception");
-    }
-    
-    cleanup();
-}
-
-void ThreadBase::setState(ThreadState state) {
-    m_state = state;
-    AV_LOGGER_DEBUGF("Thread '{}' state changed to {}", 
-                 m_threadName.empty() ? "unnamed" : m_threadName, 
-                 static_cast<int>(state));
-}
-
-void ThreadBase::cleanup() {
-    // 调用完成回调
-    std::function<void()> finishedCallback;
-    {
-        std::lock_guard<std::mutex> lock(m_stateMutex);
-        finishedCallback = m_onFinished;
-    }
-    
-    if (finishedCallback) {
-        try {
-            finishedCallback();
-        } catch (const std::exception& e) {
-            AV_LOGGER_ERRORF("Exception in finished callback: {}", e.what());
-        } catch (...) {
-            AV_LOGGER_ERROR("Unknown exception in finished callback");
-        }
-    }
-    
-    // 设置最终状态
-    {
-        std::lock_guard<std::mutex> lock(m_stateMutex);
-        setState(ThreadState::STOPPED);
-        m_stateCondition.notify_all();
-    }
-    
-    AV_LOGGER_INFOF("Thread '{}' finished", m_threadName.empty() ? "unnamed" : m_threadName);
-}
-
-} // namespace av

+ 0 - 153
AV/code/base/media_thread_base.h

@@ -1,153 +0,0 @@
-#ifndef AV_BASE_MEDIA_THREAD_BASE_H
-#define AV_BASE_MEDIA_THREAD_BASE_H
-
-#include "types.h"
-#include <atomic>
-#include <thread>
-#include <mutex>
-#include <condition_variable>
-#include <functional>
-#include <memory>
-#include <chrono>
-
-namespace av {
-
-// 线程状态枚举
-enum class ThreadState {
-    STOPPED,
-    STARTING,
-    RUNNING,
-    STOPPING
-};
-
-// 线程基类
-class ThreadBase {
-public:
-    ThreadBase();
-    virtual ~ThreadBase();
-    
-    // 禁止拷贝和移动
-    ThreadBase(const ThreadBase&) = delete;
-    ThreadBase& operator=(const ThreadBase&) = delete;
-    ThreadBase(ThreadBase&&) = delete;
-    ThreadBase& operator=(ThreadBase&&) = delete;
-    
-    // 线程控制
-    bool start();
-    void stop();
-    void join();
-    
-    // 状态查询
-    bool isRunning() const;
-    bool isStopping() const;
-    ThreadState getState() const;
-    
-    // 线程ID
-    std::thread::id getThreadId() const;
-    
-    // 设置线程名称(用于调试)
-    void setThreadName(const std::string& name);
-    std::string getThreadName() const;
-    
-    // 回调设置
-    void setOnStarted(std::function<void()> callback);
-    void setOnFinished(std::function<void()> callback);
-    void setOnError(std::function<void(const std::string&)> callback);
-    
-    // 等待条件
-    void waitForCondition(std::function<bool()> condition, int timeoutMs = -1);
-    void notifyCondition();
-    
-protected:
-    // 子类需要实现的运行逻辑
-    virtual void run() = 0;
-    
-    // 辅助方法
-    bool shouldExit() const;
-    void sleepMs(int ms);
-    bool waitForMs(int ms); // 可中断的等待
-    
-    // 错误处理
-    void reportError(const std::string& error);
-    
-    // 线程同步
-    std::mutex m_mutex;
-    std::condition_variable m_condition;
-    
-private:
-    void threadEntry();
-    void setState(ThreadState state);
-    void cleanup();
-    
-    // 线程控制
-    std::atomic<bool> m_exitRequested{false};
-    std::atomic<ThreadState> m_state{ThreadState::STOPPED};
-    std::unique_ptr<std::thread> m_thread;
-    
-    // 线程信息
-    std::string m_threadName;
-    std::thread::id m_threadId;
-    
-    // 回调函数
-    std::function<void()> m_onStarted;
-    std::function<void()> m_onFinished;
-    std::function<void(const std::string&)> m_onError;
-    
-    // 同步控制
-    mutable std::mutex m_stateMutex;
-    std::condition_variable m_stateCondition;
-    
-    // 超时控制
-    static constexpr int DEFAULT_JOIN_TIMEOUT_MS = 5000;
-};
-
-// 工作线程模板类(用于简单的循环工作)
-template<typename WorkFunc>
-class WorkerThread : public ThreadBase {
-public:
-    explicit WorkerThread(WorkFunc workFunc, int intervalMs = 10)
-        : m_workFunc(std::move(workFunc))
-        , m_intervalMs(intervalMs) {
-    }
-    
-    void setInterval(int intervalMs) {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        m_intervalMs = intervalMs;
-    }
-    
-    int getInterval() const {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        return m_intervalMs;
-    }
-    
-protected:
-    void run() override {
-        while (!shouldExit()) {
-            try {
-                m_workFunc();
-            } catch (const std::exception& e) {
-                reportError("Work function exception: " + std::string(e.what()));
-            } catch (...) {
-                reportError("Unknown work function exception");
-            }
-            
-            if (!shouldExit()) {
-                waitForMs(m_intervalMs);
-            }
-        }
-    }
-    
-private:
-    WorkFunc m_workFunc;
-    int m_intervalMs;
-};
-
-// 便捷的工作线程创建函数
-template<typename WorkFunc>
-std::unique_ptr<WorkerThread<WorkFunc>> makeWorkerThread(WorkFunc workFunc, int intervalMs = 10) {
-    return std::make_unique<WorkerThread<WorkFunc>>(std::move(workFunc), intervalMs);
-}
-
-} // namespace av
-
-#endif // AV_BASE_THREAD_BASE_H

+ 0 - 243
AV/code/base/types.h

@@ -1,243 +0,0 @@
-#ifndef AV_BASE_TYPES_H
-#define AV_BASE_TYPES_H
-
-#include <memory>
-#include <string>
-#include <functional>
-#include <atomic>
-#include <mutex>
-#include <condition_variable>
-#include <thread>
-#include <chrono>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavformat/avformat.h>
-#include <libavutil/avutil.h>
-#include <libswscale/swscale.h>
-#include <libswresample/swresample.h>
-}
-
-namespace av {
-
-// 媒体类型枚举
-enum class MediaType {
-    UNKNOWN,
-    AUDIO,
-    VIDEO
-};
-
-// 编解码参数结构
-struct CodecParams {
-    // 通用参数
-    MediaType type;
-    std::string codecName;
-    int bitRate = 0;
-    
-    // 视频参数
-    int width = 0;
-    int height = 0;
-    int fps = 0;
-    AVPixelFormat pixelFormat = AV_PIX_FMT_NONE;
-    
-    // 音频参数
-    int sampleRate = 0;
-    int channels = 0;
-    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_NONE;
-};
-
-// 音频数据结构
-struct AudioData {
-    uint8_t* data = nullptr;
-    int size = 0;
-    int sampleRate = 0;
-    int channels = 0;
-    AVSampleFormat format = AV_SAMPLE_FMT_NONE;
-    int64_t pts = 0;
-};
-
-// 视频帧数据结构
-struct VideoFrame {
-    uint8_t* data[4] = {nullptr};
-    int linesize[4] = {0};
-    int width = 0;
-    int height = 0;
-    AVPixelFormat format = AV_PIX_FMT_NONE;
-    int64_t pts = 0;
-};
-
-// 错误码定义
-enum class ErrorCode {
-    // 成功状态
-    SUCCESS = 0,
-    
-    // 参数错误
-    INVALID_PARAMS,
-    INVALID_PATH,
-    
-    // 编解码错误
-    CODEC_NOT_FOUND,
-    CODEC_OPEN_FAILED,
-    ENCODE_FAILED,
-    DECODE_FAILED,
-    
-    // 内存错误
-    MEMORY_ALLOC_FAILED,
-    
-    // 文件操作错误
-    FILE_OPEN_FAILED,
-    FILE_EXISTS,
-    FILE_OPERATION_FAILED,
-    
-    // 状态错误
-    INVALID_STATE,
-    NOT_STARTED,
-    NOT_PAUSED,
-    ALREADY_INITIALIZED,
-    NOT_INITIALIZED,
-    ALREADY_STARTED,
-    ALREADY_PAUSED,
-    
-    // 格式和转换错误
-    CONVERSION_FAILED,
-    FORMAT_NOT_SUPPORTED,
-    NOT_SUPPORTED,
-    
-    // 硬件和设备错误
-    HARDWARE_ERROR,
-    DEVICE_NOT_FOUND,
-    
-    // 流操作错误
-    STREAM_NOT_FOUND,
-    STREAM_EXISTS,
-    STREAM_CREATE_FAILED,
-    END_OF_STREAM,
-    
-    // 线程和队列错误
-    THREAD_ERROR,
-    QUEUE_FULL,
-    
-    // 同步错误
-    SYNC_ERROR,
-    
-    // 通用错误
-    ALREADY_EXISTS,
-    NOT_FOUND,
-    TIMEOUT,
-    COPY_FAILED,
-    PROCESSING_ERROR,
-    INITIALIZATION_FAILED,
-    OPERATION_FAILED,
-    UNKNOWN_ERROR
-};
-
-// AVResult 类型别名(用于兼容)
-using AVResult = ErrorCode;
-
-// 常用结果常量
-const AVResult AV_OK = AVResult::SUCCESS;
-
-// 智能指针类型定义
-// 自定义删除器用于AVFrame
-struct AVFrameDeleter
-{
-    void operator()(AVFrame* frame)
-    {
-        if (frame) {
-            // 添加调试信息,帮助追踪重复释放问题
-#ifdef DEBUG
-            // 检查帧指针的有效性
-            if (frame->data && frame->data[0]) {
-                // 帧看起来正常
-            } else {
-                // 帧可能已经被释放或损坏
-                fprintf(stderr, "Warning: AVFrameDeleter called on potentially corrupted frame\n");
-            }
-#endif
-            av_frame_free(&frame);
-        }
-    }
-};
-
-using AVFramePtr = std::unique_ptr<AVFrame, AVFrameDeleter>;
-
-// 自定义删除器用于AVPacket
-struct AVPacketDeleter
-{
-    void operator()(AVPacket* pkt) { av_packet_free(&pkt); }
-};
-using AVPacketPtr = std::unique_ptr<AVPacket, AVPacketDeleter>;
-
-// 回调函数类型定义 - 统一使用智能指针
-using FrameCallback = std::function<void(const AVFramePtr&)>;
-using PacketCallback = std::function<void(const AVPacketPtr&)>;
-using ErrorCallback = std::function<void(ErrorCode, const std::string&)>;
-
-
-// 自定义删除器用于AVCodecContext
-struct AVCodecContextDeleter {
-    void operator()(AVCodecContext* ctx) {
-        avcodec_free_context(&ctx);
-    }
-};
-using AVCodecContextPtr = std::unique_ptr<AVCodecContext, AVCodecContextDeleter>;
-
-// 自定义删除器用于AVFormatContext
-struct AVFormatContextDeleter {
-    void operator()(AVFormatContext* ctx) {
-        avformat_free_context(ctx);
-    }
-};
-using AVFormatContextPtr = std::unique_ptr<AVFormatContext, AVFormatContextDeleter>;
-
-// 智能指针创建函数
-inline AVFramePtr makeAVFrame() {
-    return AVFramePtr(av_frame_alloc());
-}
-
-inline AVPacketPtr makeAVPacket() {
-    return AVPacketPtr(av_packet_alloc());
-}
-
-inline AVCodecContextPtr makeAVCodecContext(const AVCodec* codec) {
-    return AVCodecContextPtr(avcodec_alloc_context3(codec));
-}
-
-// 内存管理辅助函数
-template<typename T, typename Func>
-void safeFree(T*& ptr, Func&& func) {
-    if (ptr != nullptr) {
-        func();
-        ptr = nullptr;
-    }
-}
-
-// 时间工具函数
-inline void sleepMs(int timeMs) {
-    std::this_thread::sleep_for(std::chrono::milliseconds(timeMs));
-}
-
-inline int64_t getCurrentTimeMs() {
-    return std::chrono::duration_cast<std::chrono::milliseconds>(
-        std::chrono::steady_clock::now().time_since_epoch()).count();
-}
-
-// 音频全局配置常量
-namespace audio {
-    constexpr int SAMPLE_RATE = 48000;
-    constexpr int CHANNELS = 1;
-    constexpr AVSampleFormat SAMPLE_FORMAT = AV_SAMPLE_FMT_FLTP;
-    constexpr int CAPTURE_BITS_PER_SAMPLE = 16;
-    constexpr int MICROPHONE_INDEX = 0;
-    constexpr int SPEAKER_INDEX = 1;
-}
-
-// 视频全局配置常量
-namespace video {
-    constexpr AVPixelFormat DEFAULT_PIXEL_FORMAT = AV_PIX_FMT_NV12;
-    constexpr int DEFAULT_FPS = 30;
-}
-
-} // namespace av
-
-#endif // AV_BASE_TYPES_H

+ 0 - 172
AV/code/capture/capture_abstract_capturer.cpp

@@ -1,172 +0,0 @@
-#include "capture_abstract_capturer.h"
-#include "../base/logger.h"
-#include <chrono>
-
-namespace av {
-namespace capture {
-
-AbstractCapturer::AbstractCapturer() {
-    stats_.startTime = std::chrono::steady_clock::now();
-    lastFrameTime_ = std::chrono::steady_clock::now();
-    lastFpsCalcTime_ = std::chrono::steady_clock::now();
-    AV_LOGGER_DEBUG("创建抽象采集器");
-}
-
-AbstractCapturer::~AbstractCapturer() {
-    AV_LOGGER_DEBUG("抽象采集器已销毁");
-}
-
-void AbstractCapturer::setState(CapturerState state) {
-    CapturerState oldState = state_.exchange(state);
-    if (oldState != state) {
-        AV_LOGGER_INFOF("采集器状态变更: {} -> {}", 
-                       static_cast<int>(oldState), static_cast<int>(state));
-    }
-}
-
-void AbstractCapturer::onFrameCaptured(const AVFramePtr& frame) {
-    if (!frame) {
-        AV_LOGGER_WARNING("采集到空帧");
-        return;
-    }
-    
-    auto now = std::chrono::steady_clock::now();
-    double captureTime = std::chrono::duration<double, std::milli>(now - lastFrameTime_).count();
-    lastFrameTime_ = now;
-    
-    // 计算数据大小
-    size_t dataSize = 0;
-    if (frame->data[0]) {
-        for (int i = 0; i < AV_NUM_DATA_POINTERS && frame->data[i]; ++i) {
-            dataSize += frame->linesize[i] * frame->height;
-        }
-    }
-    
-    updateStats(true, captureTime, dataSize);
-    calculateFPS();
-    
-    if (frameCallback_) {
-        frameCallback_(frame);
-    }
-}
-
-void AbstractCapturer::onError(ErrorCode error, const std::string& message) {
-    updateStats(false, 0.0);
-    
-    AV_LOGGER_ERRORF("采集器错误: {} - {}", static_cast<int>(error), message);
-    
-    if (errorCallback_) {
-        errorCallback_(error, message);
-    }
-}
-
-void AbstractCapturer::updateStats(bool success, double captureTime, size_t dataSize) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (success) {
-        stats_.capturedFrames++;
-        stats_.totalBytes += dataSize;
-        
-        // 更新平均采集时间
-        if (stats_.capturedFrames == 1) {
-            stats_.avgCaptureTime = captureTime;
-        } else {
-            stats_.avgCaptureTime = (stats_.avgCaptureTime * (stats_.capturedFrames - 1) + captureTime) / stats_.capturedFrames;
-        }
-    } else {
-        stats_.errorCount++;
-    }
-}
-
-void AbstractCapturer::calculateFPS() {
-    frameCountForFps_++;
-    
-    auto now = std::chrono::steady_clock::now();
-    auto elapsed = std::chrono::duration<double>(now - lastFpsCalcTime_).count();
-    
-    // 每秒计算一次FPS
-    if (elapsed >= 1.0) {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.fps = frameCountForFps_ / elapsed;
-        
-        frameCountForFps_ = 0;
-        lastFpsCalcTime_ = now;
-    }
-}
-
-CapturerStats AbstractCapturer::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    return stats_;
-}
-
-void AbstractCapturer::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = CapturerStats{};
-    stats_.startTime = std::chrono::steady_clock::now();
-    
-    frameCountForFps_ = 0;
-    lastFpsCalcTime_ = std::chrono::steady_clock::now();
-    
-    AV_LOGGER_DEBUG("采集器统计信息已重置");
-}
-
-// CapturerFactory 实现
-bool CapturerFactory::isCapturerSupported(CapturerType type) {
-    switch (type) {
-        case CapturerType::VIDEO_CAMERA:
-        case CapturerType::VIDEO_SCREEN:
-        case CapturerType::AUDIO_MIC:
-        case CapturerType::AUDIO_SYSTEM:
-        case CapturerType::AUDIO_LOOPBACK:
-            return true;
-        default:
-            return false;
-    }
-}
-
-std::vector<CapturerType> CapturerFactory::getAvailableCapturerTypes() {
-    std::vector<CapturerType> types;
-    
-    // 检查各种采集器类型的可用性
-    if (isCapturerSupported(CapturerType::VIDEO_CAMERA)) {
-        types.push_back(CapturerType::VIDEO_CAMERA);
-    }
-    
-    if (isCapturerSupported(CapturerType::VIDEO_SCREEN)) {
-        types.push_back(CapturerType::VIDEO_SCREEN);
-    }
-    
-    if (isCapturerSupported(CapturerType::AUDIO_MIC)) {
-        types.push_back(CapturerType::AUDIO_MIC);
-    }
-    
-    if (isCapturerSupported(CapturerType::AUDIO_SYSTEM)) {
-        types.push_back(CapturerType::AUDIO_SYSTEM);
-    }
-    
-    if (isCapturerSupported(CapturerType::AUDIO_LOOPBACK)) {
-        types.push_back(CapturerType::AUDIO_LOOPBACK);
-    }
-    
-    return types;
-}
-
-std::string CapturerFactory::getCapturerTypeName(CapturerType type) {
-    switch (type) {
-        case CapturerType::VIDEO_CAMERA:
-            return "摄像头";
-        case CapturerType::VIDEO_SCREEN:
-            return "屏幕录制";
-        case CapturerType::AUDIO_MIC:
-            return "麦克风";
-        case CapturerType::AUDIO_SYSTEM:
-            return "系统音频";
-        case CapturerType::AUDIO_LOOPBACK:
-            return "音频回环";
-        default:
-            return "未知";
-    }
-}
-
-} // namespace capture
-} // namespace av

+ 0 - 238
AV/code/capture/capture_abstract_capturer.h

@@ -1,238 +0,0 @@
-#ifndef AV_CAPTURE_ABSTRACT_CAPTURER_H
-#define AV_CAPTURE_ABSTRACT_CAPTURER_H
-
-#include "../base/types.h"
-#include "../base/media_common.h"
-#include <memory>
-#include <functional>
-#include <mutex>
-#include <atomic>
-#include <string>
-#include <vector>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavutil/frame.h>
-}
-
-namespace av {
-namespace capture {
-
-/**
- * 采集器状态
- */
-enum class CapturerState {
-    IDLE,           // 空闲
-    INITIALIZED,    // 已初始化
-    STARTED,        // 已启动
-    STOPPED,        // 已停止
-    ERROR           // 错误状态
-};
-
-/**
- * 采集器类型
- */
-enum class CapturerType {
-    VIDEO_CAMERA,   // 摄像头
-    VIDEO_SCREEN,   // 屏幕录制
-    VIDEO_WINDOW,   // 窗口采集
-    AUDIO_MIC,      // 麦克风
-    AUDIO_SYSTEM,   // 系统音频
-    AUDIO_LOOPBACK  // 音频回环
-};
-
-/**
- * 采集器参数基类
- */
-struct CapturerParams {
-    CapturerType type;
-    MediaType mediaType;
-    std::string deviceId;       // 设备ID
-    std::string deviceName;     // 设备名称
-    bool autoStart = false;     // 自动启动
-    
-    CapturerParams(CapturerType t, MediaType mt) : type(t), mediaType(mt) {}
-    virtual ~CapturerParams() = default;
-};
-
-/**
- * 采集器统计信息
- */
-struct CapturerStats {
-    uint64_t capturedFrames = 0;    // 已采集帧数
-    uint64_t droppedFrames = 0;     // 丢弃帧数
-    uint64_t totalBytes = 0;        // 总字节数
-    uint64_t errorCount = 0;        // 错误次数
-    double avgCaptureTime = 0.0;    // 平均采集时间(ms)
-    double fps = 0.0;               // 实际帧率
-    std::chrono::steady_clock::time_point startTime; // 开始时间
-};
-
-/**
- * 抽象采集器基类
- * 定义所有采集器的通用接口
- */
-class AbstractCapturer {
-public:
-    /**
-     * 帧回调函数类型
-     */
-    using FrameCallback = std::function<void(const AVFramePtr&)>;
-    
-    /**
-     * 错误回调函数类型
-     */
-    using ErrorCallback = std::function<void(ErrorCode, const std::string&)>;
-    
-public:
-    AbstractCapturer();
-    virtual ~AbstractCapturer();
-    
-    /**
-     * 初始化采集器
-     * @param params 采集器参数
-     * @return 错误码
-     */
-    virtual ErrorCode initialize(const CapturerParams& params) = 0;
-    
-    /**
-     * 启动采集
-     * @return 错误码
-     */
-    virtual ErrorCode start() = 0;
-    
-    /**
-     * 停止采集
-     * @return 错误码
-     */
-    virtual ErrorCode stop() = 0;
-    
-    /**
-     * 暂停采集
-     * @return 错误码
-     */
-    virtual ErrorCode pause() = 0;
-    
-    /**
-     * 恢复采集
-     * @return 错误码
-     */
-    virtual ErrorCode resume() = 0;
-    
-    /**
-     * 重置采集器
-     * @return 错误码
-     */
-    virtual ErrorCode reset() = 0;
-    
-    /**
-     * 关闭采集器
-     * @return 错误码
-     */
-    virtual ErrorCode close() = 0;
-    
-    // 状态查询
-    CapturerState getState() const { return state_; }
-    bool isRunning() const { return state_ == CapturerState::STARTED; }
-    bool isPaused() const { return paused_; }
-    
-    // 回调设置
-    void setFrameCallback(const FrameCallback& callback) { frameCallback_ = callback; }
-    void setErrorCallback(const ErrorCallback& callback) { errorCallback_ = callback; }
-    
-    // 统计信息
-    virtual CapturerStats getStats() const;
-    virtual void resetStats();
-    
-    // 设备信息
-    virtual std::vector<std::string> getAvailableDevices() const = 0;
-    virtual std::string getCurrentDevice() const = 0;
-    
-    // 参数验证
-    virtual bool validateParams(const CapturerParams& params) = 0;
-    
-protected:
-    /**
-     * 设置采集器状态
-     * @param state 新状态
-     */
-    void setState(CapturerState state);
-    
-    /**
-     * 触发帧回调
-     * @param frame 采集到的帧
-     */
-    void onFrameCaptured(const AVFramePtr& frame);
-    
-    /**
-     * 触发错误回调
-     * @param error 错误码
-     * @param message 错误消息
-     */
-    void onError(ErrorCode error, const std::string& message);
-    
-    /**
-     * 更新统计信息
-     * @param success 是否成功
-     * @param captureTime 采集时间
-     * @param dataSize 数据大小
-     */
-    void updateStats(bool success, double captureTime, size_t dataSize = 0);
-    
-    /**
-     * 计算实际帧率
-     */
-    void calculateFPS();
-    
-protected:
-    // 状态管理
-    std::atomic<CapturerState> state_{CapturerState::IDLE};
-    std::atomic<bool> paused_{false};
-    
-    // 回调函数
-    FrameCallback frameCallback_;
-    ErrorCallback errorCallback_;
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    CapturerStats stats_;
-    
-    // 帧率计算
-    std::chrono::steady_clock::time_point lastFrameTime_;
-    std::chrono::steady_clock::time_point lastFpsCalcTime_;
-    uint64_t frameCountForFps_ = 0;
-    
-    // 线程安全
-    mutable std::mutex captureMutex_;
-};
-
-/**
- * 采集器工厂基类
- */
-class CapturerFactory {
-public:
-    /**
-     * 检查采集器是否支持
-     * @param type 采集器类型
-     * @return 是否支持
-     */
-    static bool isCapturerSupported(CapturerType type);
-    
-    /**
-     * 获取可用的采集器类型
-     * @return 采集器类型列表
-     */
-    static std::vector<CapturerType> getAvailableCapturerTypes();
-    
-    /**
-     * 获取采集器类型名称
-     * @param type 采集器类型
-     * @return 类型名称
-     */
-    static std::string getCapturerTypeName(CapturerType type);
-};
-
-} // namespace capture
-} // namespace av
-
-#endif // AV_CAPTURE_ABSTRACT_CAPTURER_H

+ 0 - 975
AV/code/capture/capture_audio_capturer.cpp

@@ -1,975 +0,0 @@
-#include "capture_audio_capturer.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <algorithm>
-#include <cmath>
-
-#ifdef _WIN32
-#include <windows.h>
-#include <mmdeviceapi.h>
-#include <audioclient.h>
-#include <endpointvolume.h>
-#pragma comment(lib, "ole32.lib")
-#endif
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavdevice/avdevice.h>
-#include <libswresample/swresample.h>
-#include <libavutil/opt.h>
-#include <libavutil/channel_layout.h>
-}
-
-namespace av {
-namespace capture {
-
-AudioCapturer::AudioCapturer() : audioParams_(CapturerType::AUDIO_MIC) {
-    AV_LOGGER_DEBUG("创建音频采集器");
-    
-    // 注册设备
-    avdevice_register_all();
-    
-    lastLevelUpdate_ = std::chrono::steady_clock::now();
-}
-
-AudioCapturer::~AudioCapturer() {
-    close();
-    AV_LOGGER_DEBUG("音频采集器已销毁");
-}
-
-ErrorCode AudioCapturer::initialize(const CapturerParams& params) {
-    if (params.mediaType != MediaType::AUDIO) {
-        AV_LOGGER_ERROR("参数媒体类型不是音频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    audioParams_ = static_cast<const AudioCaptureParams&>(params);
-    
-    if (!validateParams(audioParams_)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    ErrorCode result = ErrorCode::SUCCESS;
-    
-    if (audioParams_.type == CapturerType::AUDIO_MIC) {
-        result = initializeMicrophone();
-    } else if (audioParams_.type == CapturerType::AUDIO_SYSTEM || 
-               audioParams_.type == CapturerType::AUDIO_LOOPBACK) {
-        result = initializeSystemAudio();
-    } else {
-        AV_LOGGER_ERROR("不支持的音频采集器类型");
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    if (result == ErrorCode::SUCCESS) {
-        setState(CapturerState::INITIALIZED);
-        AV_LOGGER_INFOF("音频采集器初始化成功: {}Hz, {}ch, {}", 
-                       audioParams_.sampleRate, audioParams_.channels,
-                       av_get_sample_fmt_name(audioParams_.sampleFormat));
-    }
-    
-    return result;
-}
-
-ErrorCode AudioCapturer::start() {
-    std::lock_guard<std::mutex> lock(captureMutex_);
-    
-    if (getState() != CapturerState::INITIALIZED) {
-        AV_LOGGER_ERROR("采集器状态无效,无法启动");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStop_ = false;
-    
-    // 启动采集线程
-    try {
-        captureThread_ = std::thread(&AudioCapturer::captureThreadFunc, this);
-        setState(CapturerState::STARTED);
-        
-        AV_LOGGER_INFO("音频采集已启动");
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("启动音频采集线程失败: {}", e.what());
-        return ErrorCode::THREAD_ERROR;
-    }
-}
-
-ErrorCode AudioCapturer::stop() {
-    std::lock_guard<std::mutex> lock(captureMutex_);
-    
-    if (getState() != CapturerState::STARTED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    shouldStop_ = true;
-    
-    // 唤醒暂停的线程
-    {
-        std::lock_guard<std::mutex> pauseLock(pauseMutex_);
-        paused_ = false;
-        pauseCondition_.notify_all();
-    }
-    
-    // 等待线程结束
-    if (captureThread_.joinable()) {
-        captureThread_.join();
-    }
-    
-    setState(CapturerState::STOPPED);
-    AV_LOGGER_INFO("音频采集已停止");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioCapturer::pause() {
-    if (getState() != CapturerState::STARTED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    paused_ = true;
-    AV_LOGGER_INFO("音频采集已暂停");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioCapturer::resume() {
-    if (getState() != CapturerState::STARTED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    {
-        std::lock_guard<std::mutex> lock(pauseMutex_);
-        paused_ = false;
-        pauseCondition_.notify_all();
-    }
-    
-    AV_LOGGER_INFO("音频采集已恢复");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioCapturer::reset() {
-    ErrorCode result = stop();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 清空帧队列
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        while (!frameQueue_.empty()) {
-            frameQueue_.pop();
-        }
-    }
-    
-    resetStats();
-    audioLevel_ = 0.0f;
-    setState(CapturerState::INITIALIZED);
-    
-    AV_LOGGER_INFO("音频采集器已重置");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioCapturer::close() {
-    stop();
-    
-    // 清理资源
-    cleanupResampler();
-    cleanupAudioProcessing();
-    
-    if (codecCtx_) {
-        avcodec_free_context(&codecCtx_);
-        codecCtx_ = nullptr;
-    }
-    
-    if (formatCtx_) {
-        avformat_close_input(&formatCtx_);
-        formatCtx_ = nullptr;
-    }
-    
-    codec_ = nullptr;
-    audioStreamIndex_ = -1;
-    
-    setState(CapturerState::IDLE);
-    AV_LOGGER_INFO("音频采集器已关闭");
-    
-    return ErrorCode::SUCCESS;
-}
-
-std::vector<std::string> AudioCapturer::getAvailableDevices() const {
-    std::vector<std::string> devices;
-    auto deviceInfos = getDetailedDeviceInfo();
-    
-    for (const auto& info : deviceInfos) {
-        devices.push_back(info.name);
-    }
-    
-    return devices;
-}
-
-std::string AudioCapturer::getCurrentDevice() const {
-    return audioParams_.deviceName;
-}
-
-std::vector<AudioDeviceInfo> AudioCapturer::getDetailedDeviceInfo() const {
-    std::lock_guard<std::mutex> lock(deviceCacheMutex_);
-    
-    if (!devicesCached_) {
-        if (audioParams_.type == CapturerType::AUDIO_MIC) {
-            cachedDevices_ = enumerateMicrophones();
-        } else {
-            cachedDevices_ = enumerateSystemAudioDevices();
-        }
-        devicesCached_ = true;
-    }
-    
-    return cachedDevices_;
-}
-
-ErrorCode AudioCapturer::setAudioParams(int sampleRate, int channels, AVSampleFormat sampleFormat) {
-    if (getState() == CapturerState::STARTED) {
-        AV_LOGGER_ERROR("无法在采集过程中修改音频参数");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    audioParams_.sampleRate = sampleRate;
-    audioParams_.channels = channels;
-    audioParams_.sampleFormat = sampleFormat;
-    
-    AV_LOGGER_INFOF("音频参数已更新: {}Hz, {}ch, {}", 
-                   sampleRate, channels, av_get_sample_fmt_name(sampleFormat));
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioCapturer::setVolume(float volume) {
-    if (volume < 0.0f || volume > 2.0f) {
-        AV_LOGGER_ERROR("音量值超出范围 (0.0-2.0)");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    currentVolume_ = volume;
-    audioParams_.volume = volume;
-    
-    AV_LOGGER_INFOF("音量已设置为: {:.2f}", volume);
-    
-    return ErrorCode::SUCCESS;
-}
-
-float AudioCapturer::getVolume() const {
-    return currentVolume_;
-}
-
-ErrorCode AudioCapturer::setNoiseReduction(bool enable) {
-    noiseReductionEnabled_ = enable;
-    audioParams_.enableNoiseReduction = enable;
-    
-    AV_LOGGER_INFOF("Noise reduction {}", enable ? "enabled" : "disabled");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioCapturer::setEchoCancellation(bool enable) {
-    echoCancellationEnabled_ = enable;
-    audioParams_.enableEchoCancellation = enable;
-    
-    AV_LOGGER_INFOF("Echo cancellation {}", enable ? "enabled" : "disabled");
-    
-    return ErrorCode::SUCCESS;
-}
-
-AudioCaptureParams AudioCapturer::getCurrentParams() const {
-    return audioParams_;
-}
-
-float AudioCapturer::getAudioLevel() const {
-    return audioLevel_.load();
-}
-
-bool AudioCapturer::validateParams(const CapturerParams& params) {
-    const auto& audioParams = static_cast<const AudioCaptureParams&>(params);
-    
-    if (audioParams.sampleRate <= 0 || audioParams.sampleRate > 192000) {
-        AV_LOGGER_ERROR("采样率无效");
-        return false;
-    }
-    
-    if (audioParams.channels <= 0 || audioParams.channels > 8) {
-        AV_LOGGER_ERROR("声道数无效");
-        return false;
-    }
-    
-    if (audioParams.bufferSize <= 0 || audioParams.bufferSize > 8192) {
-        AV_LOGGER_ERROR("缓冲区大小无效");
-        return false;
-    }
-    
-    if (audioParams.volume < 0.0f || audioParams.volume > 2.0f) {
-        AV_LOGGER_ERROR("音量值无效");
-        return false;
-    }
-    
-    return true;
-}
-
-ErrorCode AudioCapturer::initializeMicrophone() {
-    AV_LOGGER_INFOF("初始化麦克风采集器: 索引={}", audioParams_.micIndex);
-    
-#ifdef _WIN32
-    return setupDirectSoundMicrophone();
-#elif defined(__linux__)
-    return setupALSAMicrophone();
-#elif defined(__APPLE__)
-    return setupCoreAudioMicrophone();
-#else
-    AV_LOGGER_ERROR("当前平台不支持麦克风采集");
-    return ErrorCode::NOT_SUPPORTED;
-#endif
-}
-
-ErrorCode AudioCapturer::initializeSystemAudio() {
-    AV_LOGGER_INFO("初始化系统音频采集器");
-    
-#ifdef _WIN32
-    return setupWASAPISystemAudio();
-#elif defined(__linux__)
-    return setupPulseAudioCapture();
-#elif defined(__APPLE__)
-    return setupCoreAudioSystemCapture();
-#else
-    AV_LOGGER_ERROR("当前平台不支持系统音频采集");
-    return ErrorCode::NOT_SUPPORTED;
-#endif
-}
-
-ErrorCode AudioCapturer::openInputDevice() {
-    const AVInputFormat* inputFormat = getPlatformInputFormat();
-    if (!inputFormat) {
-        AV_LOGGER_ERROR("获取音频输入格式失败");
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    std::string deviceName = getPlatformDeviceName();
-    if (deviceName.empty()) {
-        AV_LOGGER_ERROR("获取音频设备名称失败");
-        return ErrorCode::DEVICE_NOT_FOUND;
-    }
-    
-    AV_LOGGER_INFOF("打开音频输入设备: {} (格式: {})", deviceName, inputFormat->name);
-    
-    // 设置输入选项
-    AVDictionary* options = nullptr;
-    
-    // 设置音频参数
-    av_dict_set(&options, "sample_rate", std::to_string(audioParams_.sampleRate).c_str(), 0);
-    av_dict_set(&options, "channels", std::to_string(audioParams_.channels).c_str(), 0);
-    
-    // 设置缓冲区大小
-    av_dict_set(&options, "audio_buffer_size", std::to_string(audioParams_.bufferSize).c_str(), 0);
-    
-    // 注意:不要在实际打开设备时设置list_devices选项,这会导致AVERROR_EXIT
-    
-    // 打开输入
-    int ret = avformat_open_input(&formatCtx_, deviceName.c_str(), inputFormat, &options);
-    av_dict_free(&options);
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开音频输入设备失败: {} (设备: {})", 
-                        ffmpeg_utils::errorToString(ret), deviceName);
-        
-        // 如果是设备不存在错误,尝试多种回退方案
-        if (ret == AVERROR(EIO) || ret == AVERROR(ENOENT)) {
-            // 尝试1: 使用默认设备
-            AV_LOGGER_WARNING("尝试使用默认音频设备");
-            AVDictionary* defaultOptions = nullptr;
-            av_dict_set(&defaultOptions, "sample_rate", std::to_string(audioParams_.sampleRate).c_str(), 0);
-            av_dict_set(&defaultOptions, "channels", std::to_string(audioParams_.channels).c_str(), 0);
-            
-            ret = avformat_open_input(&formatCtx_, "audio=default", inputFormat, &defaultOptions);
-            av_dict_free(&defaultOptions);
-            
-            if (ret < 0) {
-                AV_LOGGER_WARNINGF("默认设备失败: {}, 尝试设备索引0", ffmpeg_utils::errorToString(ret));
-                
-                // 尝试2: 使用设备索引0
-                AVDictionary* indexOptions = nullptr;
-                av_dict_set(&indexOptions, "sample_rate", std::to_string(audioParams_.sampleRate).c_str(), 0);
-                av_dict_set(&indexOptions, "channels", std::to_string(audioParams_.channels).c_str(), 0);
-                
-                ret = avformat_open_input(&formatCtx_, "audio=0", inputFormat, &indexOptions);
-                av_dict_free(&indexOptions);
-                
-                if (ret < 0) {
-                     AV_LOGGER_WARNINGF("DirectShow设备索引0失败: {}, 尝试WASAPI", ffmpeg_utils::errorToString(ret));
-                     
-                     // 尝试3: 使用WASAPI
-                     const AVInputFormat* wasapiFormat = av_find_input_format("wasapi");
-                     if (wasapiFormat) {
-                         AVDictionary* wasapiOptions = nullptr;
-                         av_dict_set(&wasapiOptions, "sample_rate", std::to_string(audioParams_.sampleRate).c_str(), 0);
-                         av_dict_set(&wasapiOptions, "channels", std::to_string(audioParams_.channels).c_str(), 0);
-                         
-                         ret = avformat_open_input(&formatCtx_, "", wasapiFormat, &wasapiOptions);
-                         av_dict_free(&wasapiOptions);
-                         
-                         if (ret < 0) {
-                             AV_LOGGER_ERRORF("所有音频设备打开尝试都失败: {}", ffmpeg_utils::errorToString(ret));
-                             return static_cast<ErrorCode>(ret);
-                         }
-                         
-                         AV_LOGGER_INFO("成功打开WASAPI默认音频设备");
-                     } else {
-                         AV_LOGGER_ERRORF("WASAPI不可用,所有音频设备打开尝试都失败: {}", ffmpeg_utils::errorToString(ret));
-                         return static_cast<ErrorCode>(ret);
-                     }
-                 } else {
-                     AV_LOGGER_INFO("成功打开音频设备索引0");
-                 }
-            } else {
-                AV_LOGGER_INFO("成功打开默认音频设备");
-            }
-        } else {
-            return static_cast<ErrorCode>(ret);
-        }
-    }
-    
-    // 查找流信息
-    ret = avformat_find_stream_info(formatCtx_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("查找音频流信息失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 查找音频流
-    audioStreamIndex_ = av_find_best_stream(formatCtx_, AVMEDIA_TYPE_AUDIO, -1, -1, &codec_, 0);
-    if (audioStreamIndex_ < 0) {
-        AV_LOGGER_ERROR("未找到音频流");
-        return ErrorCode::STREAM_NOT_FOUND;
-    }
-    
-    // 创建解码上下文
-    codecCtx_ = avcodec_alloc_context3(codec_);
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("分配音频解码上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 复制流参数到解码上下文
-    ret = avcodec_parameters_to_context(codecCtx_, formatCtx_->streams[audioStreamIndex_]->codecpar);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("复制音频流参数失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 打开解码器
-    ret = avcodec_open2(codecCtx_, codec_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开音频解码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 设置音频重采样
-    return setupAudioResampling();
-}
-
-ErrorCode AudioCapturer::setupAudioResampling() {
-    AVSampleFormat srcFormat = codecCtx_->sample_fmt;
-    int srcSampleRate = codecCtx_->sample_rate;
-    int srcChannels = codecCtx_->ch_layout.nb_channels;
-    AVChannelLayout srcChannelLayout = codecCtx_->ch_layout;
-    
-    AVSampleFormat dstFormat = audioParams_.sampleFormat;
-    int dstSampleRate = audioParams_.sampleRate;
-    int dstChannels = audioParams_.channels;
-    AVChannelLayout dstChannelLayout;
-    av_channel_layout_default(&dstChannelLayout, dstChannels);
-    
-    needResampling_ = (srcFormat != dstFormat) ||
-                     (srcSampleRate != dstSampleRate) ||
-                     (srcChannels != dstChannels);
-    
-    if (needResampling_) {
-        AV_LOGGER_INFOF("需要音频重采样: {}Hz,{}ch,{} -> {}Hz,{}ch,{}", 
-                       srcSampleRate, srcChannels, av_get_sample_fmt_name(srcFormat),
-                       dstSampleRate, dstChannels, av_get_sample_fmt_name(dstFormat));
-        
-        swrCtx_ = swr_alloc();
-        if (!swrCtx_) {
-            AV_LOGGER_ERROR("分配音频重采样器失败");
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        // 设置重采样参数
-        av_opt_set_chlayout(swrCtx_, "in_chlayout", &srcChannelLayout, 0);
-        av_opt_set_int(swrCtx_, "in_sample_rate", srcSampleRate, 0);
-        av_opt_set_sample_fmt(swrCtx_, "in_sample_fmt", srcFormat, 0);
-        
-        av_opt_set_chlayout(swrCtx_, "out_chlayout", &dstChannelLayout, 0);
-        av_opt_set_int(swrCtx_, "out_sample_rate", dstSampleRate, 0);
-        av_opt_set_sample_fmt(swrCtx_, "out_sample_fmt", dstFormat, 0);
-        
-        // 初始化重采样器
-        int ret = swr_init(swrCtx_);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("初始化音频重采样器失败: {}", ffmpeg_utils::errorToString(ret));
-            cleanupResampler();
-            return static_cast<ErrorCode>(ret);
-        }
-        
-        // 创建重采样输出帧
-        resampledFrame_ = makeAVFrame();
-        if (!resampledFrame_) {
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        resampledFrame_->format = dstFormat;
-        resampledFrame_->sample_rate = dstSampleRate;
-        av_channel_layout_copy(&resampledFrame_->ch_layout, &dstChannelLayout);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-void AudioCapturer::captureThreadFunc() {
-    AV_LOGGER_INFO("音频采集线程已启动");
-    
-    while (!shouldStop_) {
-        // 检查暂停状态
-        {
-            std::unique_lock<std::mutex> lock(pauseMutex_);
-            pauseCondition_.wait(lock, [this] { return !paused_ || shouldStop_; });
-        }
-        
-        if (shouldStop_) {
-            break;
-        }
-        
-        ErrorCode result = captureFrame();
-        if (result != ErrorCode::SUCCESS) {
-            onError(result, "采集音频帧失败");
-            
-            // 短暂休眠后重试
-            std::this_thread::sleep_for(std::chrono::milliseconds(5));
-        }
-    }
-    
-    AV_LOGGER_INFO("音频采集线程已退出");
-}
-
-ErrorCode AudioCapturer::captureFrame() {
-    AVPacket* packet = av_packet_alloc();
-    if (!packet) {
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 读取包
-    int ret = av_read_frame(formatCtx_, packet);
-    if (ret < 0) {
-        av_packet_free(&packet);
-        if (ret == AVERROR_EOF) {
-            AV_LOGGER_WARNING("音频流结束");
-            return ErrorCode::END_OF_STREAM;
-        } else {
-            AV_LOGGER_ERRORF("读取音频帧失败: {}", ffmpeg_utils::errorToString(ret));
-            return static_cast<ErrorCode>(ret);
-        }
-    }
-    
-    // 检查是否是音频包
-    if (packet->stream_index != audioStreamIndex_) {
-        av_packet_free(&packet);
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 发送包到解码器
-    ret = avcodec_send_packet(codecCtx_, packet);
-    av_packet_free(&packet);
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("发送音频包到解码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 接收解码后的帧
-    AVFramePtr frame = makeAVFrame();
-    if (!frame) {
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    ret = avcodec_receive_frame(codecCtx_, frame.get());
-    if (ret == AVERROR(EAGAIN)) {
-        return ErrorCode::SUCCESS; // 需要更多输入
-    } else if (ret < 0) {
-        AV_LOGGER_ERRORF("接收音频解码帧失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 音频处理
-    AVFramePtr processedFrame = processAudioFrame(frame);
-    if (!processedFrame) {
-        return ErrorCode::PROCESSING_ERROR;
-    }
-    
-    // 计算音频电平
-    calculateAudioLevel(processedFrame);
-    
-    // 回调
-    onFrameCaptured(processedFrame);
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr AudioCapturer::processAudioFrame(const AVFramePtr& frame) {
-    if (!frame) {
-        return nullptr;
-    }
-    
-    AVFramePtr processedFrame = std::move(const_cast<AVFramePtr&>(frame));
-    
-    // 重采样
-    if (needResampling_) {
-        processedFrame = resampleAudioFrame(processedFrame);
-        if (!processedFrame) {
-            return nullptr;
-        }
-    }
-    
-    // 音量控制
-    if (currentVolume_ != 1.0f) {
-        processedFrame = applyVolumeControl(processedFrame);
-    }
-    
-    // 降噪处理
-    if (noiseReductionEnabled_) {
-        processedFrame = applyNoiseReduction(processedFrame);
-    }
-    
-    return processedFrame;
-}
-
-AVFramePtr AudioCapturer::resampleAudioFrame(const AVFramePtr& frame) {
-    if (!frame || !swrCtx_ || !resampledFrame_) {
-        return nullptr;
-    }
-    
-    // 计算输出采样数
-    int outSamples = swr_get_out_samples(swrCtx_, frame->nb_samples);
-    resampledFrame_->nb_samples = outSamples;
-    
-    // 重新分配缓冲区(如果需要)
-    if (av_frame_get_buffer(resampledFrame_.get(), 0) < 0) {
-        AV_LOGGER_ERROR("分配重采样缓冲区失败");
-        return nullptr;
-    }
-    
-    // 执行重采样
-    int convertedSamples = swr_convert(swrCtx_,
-                                      resampledFrame_->data, outSamples,
-                                      (const uint8_t**)frame->data, frame->nb_samples);
-    
-    if (convertedSamples < 0) {
-        AV_LOGGER_ERRORF("音频重采样失败: {}", ffmpeg_utils::errorToString(convertedSamples));
-        return nullptr;
-    }
-    
-    resampledFrame_->nb_samples = convertedSamples;
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(resampledFrame_.get(), frame.get());
-    
-    // 创建新的frame并复制数据
-    AVFramePtr outputFrame = makeAVFrame();
-    if (!outputFrame) {
-        return nullptr;
-    }
-    
-    av_frame_ref(outputFrame.get(), resampledFrame_.get());
-    return outputFrame;
-}
-
-AVFramePtr AudioCapturer::applyVolumeControl(const AVFramePtr& frame) {
-    if (!frame || currentVolume_ == 1.0f) {
-        return nullptr;
-    }
-    
-    // 简单的音量控制实现
-    AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
-    int channels = frame->ch_layout.nb_channels;
-    int samples = frame->nb_samples;
-    
-    if (format == AV_SAMPLE_FMT_S16) {
-        int16_t* data = reinterpret_cast<int16_t*>(frame->data[0]);
-        for (int i = 0; i < samples * channels; ++i) {
-            data[i] = static_cast<int16_t>(data[i] * currentVolume_);
-        }
-    } else if (format == AV_SAMPLE_FMT_FLT) {
-        float* data = reinterpret_cast<float*>(frame->data[0]);
-        for (int i = 0; i < samples * channels; ++i) {
-            data[i] *= currentVolume_;
-        }
-    }
-    
-    return nullptr;
-}
-
-AVFramePtr AudioCapturer::applyNoiseReduction(const AVFramePtr& frame) {
-    // 简单的降噪实现(实际应用中需要更复杂的算法)
-    if (!frame) {
-        return nullptr;
-    }
-    
-    // 这里可以实现噪声门限、频谱减法等降噪算法
-    // 目前只是一个占位符实现
-    
-    return nullptr;
-}
-
-void AudioCapturer::calculateAudioLevel(const AVFramePtr& frame) {
-    if (!frame) {
-        return;
-    }
-    
-    auto now = std::chrono::steady_clock::now();
-    auto elapsed = std::chrono::duration<double>(now - lastLevelUpdate_).count();
-    
-    if (elapsed < LEVEL_UPDATE_INTERVAL) {
-        return;
-    }
-    
-    std::lock_guard<std::mutex> lock(levelMutex_);
-    
-    AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
-    int channels = frame->ch_layout.nb_channels;
-    int samples = frame->nb_samples;
-    
-    double sum = 0.0;
-    int totalSamples = samples * channels;
-    
-    if (format == AV_SAMPLE_FMT_S16) {
-        const int16_t* data = reinterpret_cast<const int16_t*>(frame->data[0]);
-        for (int i = 0; i < totalSamples; ++i) {
-            sum += std::abs(data[i]) / 32768.0;
-        }
-    } else if (format == AV_SAMPLE_FMT_FLT) {
-        const float* data = reinterpret_cast<const float*>(frame->data[0]);
-        for (int i = 0; i < totalSamples; ++i) {
-            sum += std::abs(data[i]);
-        }
-    }
-    
-    float level = static_cast<float>(sum / totalSamples);
-    audioLevel_.store(std::min<float>(level, 1.0f));
-    
-    lastLevelUpdate_ = now;
-}
-
-void AudioCapturer::cleanupResampler() {
-    if (swrCtx_) {
-        swr_free(&swrCtx_);
-        swrCtx_ = nullptr;
-    }
-    
-    resampledFrame_.reset();
-    needResampling_ = false;
-}
-
-void AudioCapturer::cleanupAudioProcessing() {
-    // 清理音频处理相关资源
-    noiseReductionEnabled_ = false;
-    echoCancellationEnabled_ = false;
-    currentVolume_ = 1.0f;
-    audioLevel_ = 0.0f;
-}
-
-std::vector<AudioDeviceInfo> AudioCapturer::enumerateMicrophones() const {
-#ifdef _WIN32
-    return enumerateDirectSoundDevices();
-#elif defined(__linux__)
-    return enumerateALSADevices();
-#elif defined(__APPLE__)
-    return enumerateCoreAudioDevices();
-#else
-    return {};
-#endif
-}
-
-std::vector<AudioDeviceInfo> AudioCapturer::enumerateSystemAudioDevices() const {
-#ifdef _WIN32
-    return enumerateWASAPIDevices();
-#elif defined(__linux__)
-    return enumeratePulseAudioDevices();
-#elif defined(__APPLE__)
-    return enumerateCoreAudioDevices();
-#else
-    return {};
-#endif
-}
-
-const AVInputFormat* AudioCapturer::getPlatformInputFormat() const {
-#ifdef _WIN32
-    if (audioParams_.type == CapturerType::AUDIO_MIC) {
-        return av_find_input_format("dshow");
-    } else {
-        return av_find_input_format("dshow"); // WASAPI通过dshow访问
-    }
-#elif defined(__linux__)
-    if (audioParams_.type == CapturerType::AUDIO_MIC) {
-        return av_find_input_format("alsa");
-    } else {
-        return av_find_input_format("pulse");
-    }
-#elif defined(__APPLE__)
-    return av_find_input_format("avfoundation");
-#endif
-    
-    return nullptr;
-}
-
-std::string AudioCapturer::getPlatformDeviceName() const {
-#ifdef _WIN32
-    if (audioParams_.type == CapturerType::AUDIO_MIC) {
-        if (!audioParams_.deviceName.empty()) {
-            return "audio=" + audioParams_.deviceName;
-        } else {
-            // 尝试获取可用设备列表中的第一个设备
-            auto devices = enumerateDirectSoundDevices();
-            if (!devices.empty() && audioParams_.micIndex < devices.size()) {
-                // 使用设备的实际名称
-                return "audio=" + devices[audioParams_.micIndex].name;
-            } else {
-                // 回退到设备索引
-                return "audio=" + std::to_string(audioParams_.micIndex);
-            }
-        }
-    } else {
-        return "audio=" + (audioParams_.audioDevice.empty() ? "@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\\wave_{00000000-0000-0000-0000-000000000000}" : audioParams_.audioDevice);
-    }
-#elif defined(__linux__)
-    if (audioParams_.type == CapturerType::AUDIO_MIC) {
-        if (!audioParams_.deviceName.empty()) {
-            return audioParams_.deviceName;
-        } else {
-            return "hw:" + std::to_string(audioParams_.micIndex);
-        }
-    } else {
-        return audioParams_.audioDevice.empty() ? "default" : audioParams_.audioDevice;
-    }
-#elif defined(__APPLE__)
-    if (audioParams_.type == CapturerType::AUDIO_MIC) {
-        return ":" + std::to_string(audioParams_.micIndex);
-    } else {
-        return ":none";
-    }
-#endif
-    
-    return "";
-}
-
-#ifdef _WIN32
-std::vector<AudioDeviceInfo> AudioCapturer::enumerateDirectSoundDevices() const {
-    std::vector<AudioDeviceInfo> devices;
-    
-    // 基于FFmpeg输出,我们知道有一个麦克风设备可用
-    // 添加已知的麦克风设备
-    AudioDeviceInfo micDevice;
-    micDevice.id = "0";
-    micDevice.name = "Microphone (High Definition Audio Device)";
-    micDevice.description = "High Definition Audio Device Microphone";
-    micDevice.isDefault = true;
-    micDevice.isInput = true;
-    micDevice.supportedSampleRates = {8000, 16000, 22050, 44100, 48000};
-    micDevice.supportedChannels = {1, 2};
-    micDevice.supportedFormats = {AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLT};
-    devices.push_back(micDevice);
-    
-    // 添加默认设备作为后备
-    AudioDeviceInfo defaultDevice;
-    defaultDevice.id = "default";
-    defaultDevice.name = "默认音频设备";
-    defaultDevice.description = "系统默认音频输入设备";
-    defaultDevice.isDefault = false;
-    defaultDevice.isInput = true;
-    defaultDevice.supportedSampleRates = {8000, 16000, 22050, 44100, 48000};
-    defaultDevice.supportedChannels = {1, 2};
-    defaultDevice.supportedFormats = {AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLT};
-    devices.push_back(defaultDevice);
-    
-    return devices;
-}
-
-std::vector<AudioDeviceInfo> AudioCapturer::enumerateWASAPIDevices() const {
-    std::vector<AudioDeviceInfo> devices;
-    
-    // 简化的WASAPI设备枚举
-    AudioDeviceInfo device;
-    device.id = "wasapi_default";
-    device.name = "默认系统音频";
-    device.description = "WASAPI系统音频设备";
-    device.isDefault = true;
-    device.isInput = false;
-    
-    // 添加常见采样率
-    device.supportedSampleRates = {44100, 48000, 96000};
-    
-    // 添加常见声道数
-    device.supportedChannels = {2, 6, 8};
-    
-    // 添加支持的采样格式
-    device.supportedFormats = {
-        AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_FLT
-    };
-    
-    devices.push_back(device);
-    
-    return devices;
-}
-
-ErrorCode AudioCapturer::setupDirectSoundMicrophone() {
-    AV_LOGGER_INFO("设置DirectSound麦克风");
-    return openInputDevice();
-}
-
-ErrorCode AudioCapturer::setupWASAPISystemAudio() {
-    AV_LOGGER_INFO("设置WASAPI系统音频");
-    return openInputDevice();
-}
-#endif
-
-// AudioCaptureFactory 实现
-std::unique_ptr<AudioCapturer> AudioCapturer::AudioCaptureFactory::createMicrophone(int micIndex) {
-    auto capturer = std::make_unique<AudioCapturer>();
-    
-    AudioCaptureParams params(CapturerType::AUDIO_MIC);
-    params.micIndex = micIndex;
-    
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建麦克风采集器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return capturer;
-}
-
-std::unique_ptr<AudioCapturer> AudioCapturer::AudioCaptureFactory::createSystemAudio(bool loopback) {
-    auto capturer = std::make_unique<AudioCapturer>();
-    
-    AudioCaptureParams params(loopback ? CapturerType::AUDIO_LOOPBACK : CapturerType::AUDIO_SYSTEM);
-    params.captureLoopback = loopback;
-    
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建系统音频采集器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return capturer;
-}
-
-std::unique_ptr<AudioCapturer> AudioCapturer::AudioCaptureFactory::createBestMicrophone() {
-    return createMicrophone(0); // 默认使用第一个麦克风
-}
-
-} // namespace capture
-} // namespace av

+ 0 - 257
AV/code/capture/capture_audio_capturer.h

@@ -1,257 +0,0 @@
-#ifndef AV_CAPTURE_AUDIO_CAPTURER_H
-#define AV_CAPTURE_AUDIO_CAPTURER_H
-
-#include "capture_abstract_capturer.h"
-#include <thread>
-#include <condition_variable>
-#include <queue>
-#include <atomic>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavdevice/avdevice.h>
-#include <libswresample/swresample.h>
-}
-
-namespace av {
-namespace capture {
-
-/**
- * 音频采集器参数
- */
-struct AudioCaptureParams : public CapturerParams {
-    int sampleRate = 44100;         // 采样率
-    int channels = 2;               // 声道数
-    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_S16; // 采样格式
-    int bufferSize = 1024;          // 缓冲区大小(采样数)
-    
-    // 麦克风特定参数
-    int micIndex = 0;               // 麦克风索引
-    std::string micFormat;          // 麦克风格式 (如 "dshow", "alsa")
-    float volume = 1.0f;            // 音量 (0.0-2.0)
-    bool enableNoiseReduction = false; // 降噪
-    bool enableEchoCancellation = false; // 回声消除
-    
-    // 系统音频特定参数
-    bool captureLoopback = false;   // 捕获回环音频
-    std::string audioDevice;        // 音频设备名称
-    
-    AudioCaptureParams(CapturerType type) : CapturerParams(type, MediaType::AUDIO) {}
-};
-
-/**
- * 音频设备信息
- */
-struct AudioDeviceInfo {
-    std::string id;                 // 设备ID
-    std::string name;               // 设备名称
-    std::string description;        // 设备描述
-    bool isDefault = false;         // 是否为默认设备
-    bool isInput = true;            // 是否为输入设备
-    std::vector<int> supportedSampleRates; // 支持的采样率
-    std::vector<int> supportedChannels;    // 支持的声道数
-    std::vector<AVSampleFormat> supportedFormats; // 支持的采样格式
-};
-
-/**
- * 音频采集器类
- * 支持麦克风和系统音频采集
- */
-class AudioCapturer : public AbstractCapturer {
-public:
-    AudioCapturer();
-    virtual ~AudioCapturer();
-    
-    // 基础接口实现
-    ErrorCode initialize(const CapturerParams& params) override;
-    ErrorCode start() override;
-    ErrorCode stop() override;
-    ErrorCode pause() override;
-    ErrorCode resume() override;
-    ErrorCode reset() override;
-    ErrorCode close() override;
-    
-    // 设备信息
-    std::vector<std::string> getAvailableDevices() const override;
-    std::string getCurrentDevice() const override;
-    
-    /**
-     * 获取详细设备信息
-     * @return 设备信息列表
-     */
-    std::vector<AudioDeviceInfo> getDetailedDeviceInfo() const;
-    
-    /**
-     * 设置音频参数
-     * @param sampleRate 采样率
-     * @param channels 声道数
-     * @param sampleFormat 采样格式
-     * @return 错误码
-     */
-    ErrorCode setAudioParams(int sampleRate, int channels, AVSampleFormat sampleFormat);
-    
-    /**
-     * 设置音量
-     * @param volume 音量 (0.0-2.0)
-     * @return 错误码
-     */
-    ErrorCode setVolume(float volume);
-    
-    /**
-     * 获取当前音量
-     * @return 音量值
-     */
-    float getVolume() const;
-    
-    /**
-     * 设置降噪
-     * @param enable 是否启用
-     * @return 错误码
-     */
-    ErrorCode setNoiseReduction(bool enable);
-    
-    /**
-     * 设置回声消除
-     * @param enable 是否启用
-     * @return 错误码
-     */
-    ErrorCode setEchoCancellation(bool enable);
-    
-    /**
-     * 获取当前音频参数
-     * @return 音频参数
-     */
-    AudioCaptureParams getCurrentParams() const;
-    
-    /**
-     * 获取音频电平
-     * @return 电平值 (0.0-1.0)
-     */
-    float getAudioLevel() const;
-    
-    /**
-     * 音频采集器工厂
-     */
-    class AudioCaptureFactory {
-    public:
-        /**
-         * 创建麦克风采集器
-         * @param micIndex 麦克风索引
-         * @return 采集器实例
-         */
-        static std::unique_ptr<AudioCapturer> createMicrophone(int micIndex = 0);
-        
-        /**
-         * 创建系统音频采集器
-         * @param loopback 是否为回环模式
-         * @return 采集器实例
-         */
-        static std::unique_ptr<AudioCapturer> createSystemAudio(bool loopback = false);
-        
-        /**
-         * 创建最佳麦克风采集器
-         * @return 采集器实例
-         */
-        static std::unique_ptr<AudioCapturer> createBestMicrophone();
-    };
-    
-protected:
-    bool validateParams(const CapturerParams& params) override;
-    
-private:
-    // 内部实现方法
-    ErrorCode initializeMicrophone();
-    ErrorCode initializeSystemAudio();
-    ErrorCode openInputDevice();
-    ErrorCode setupAudioParams();
-    ErrorCode setupAudioResampling();
-    ErrorCode setupAudioProcessing();
-    
-    // 采集线程
-    void captureThreadFunc();
-    ErrorCode captureFrame();
-    
-    // 音频处理
-    AVFramePtr processAudioFrame(const AVFramePtr& frame);
-    AVFramePtr resampleAudioFrame(const AVFramePtr& frame);
-    AVFramePtr applyVolumeControl(const AVFramePtr& frame);
-    AVFramePtr applyNoiseReduction(const AVFramePtr& frame);
-    void calculateAudioLevel(const AVFramePtr& frame);
-    
-    // 资源清理
-    void cleanupResampler();
-    void cleanupAudioProcessing();
-    
-    // 设备枚举
-    std::vector<AudioDeviceInfo> enumerateMicrophones() const;
-    std::vector<AudioDeviceInfo> enumerateSystemAudioDevices() const;
-    
-    // 平台特定实现
-#ifdef _WIN32
-    std::vector<AudioDeviceInfo> enumerateDirectSoundDevices() const;
-    std::vector<AudioDeviceInfo> enumerateWASAPIDevices() const;
-    ErrorCode setupDirectSoundMicrophone();
-    ErrorCode setupWASAPISystemAudio();
-#elif defined(__linux__)
-    std::vector<AudioDeviceInfo> enumerateALSADevices() const;
-    std::vector<AudioDeviceInfo> enumeratePulseAudioDevices() const;
-    ErrorCode setupALSAMicrophone();
-    ErrorCode setupPulseAudioCapture();
-#elif defined(__APPLE__)
-    std::vector<AudioDeviceInfo> enumerateCoreAudioDevices() const;
-    ErrorCode setupCoreAudioMicrophone();
-    ErrorCode setupCoreAudioSystemCapture();
-#endif
-    
-    // 获取平台特定的输入格式
-    const AVInputFormat* getPlatformInputFormat() const;
-    std::string getPlatformDeviceName() const;
-    
-private:
-    // 采集参数
-    AudioCaptureParams audioParams_;
-    
-    // FFmpeg 相关
-    AVFormatContext* formatCtx_ = nullptr;
-    AVCodecContext* codecCtx_ = nullptr;
-    const AVCodec* codec_ = nullptr;
-    int audioStreamIndex_ = -1;
-    
-    // 音频重采样
-    SwrContext* swrCtx_ = nullptr;
-    AVFramePtr resampledFrame_;
-    bool needResampling_ = false;
-    
-    // 音频处理
-    float currentVolume_ = 1.0f;
-    bool noiseReductionEnabled_ = false;
-    bool echoCancellationEnabled_ = false;
-    std::atomic<float> audioLevel_{0.0f};
-    
-    // 采集线程
-    std::thread captureThread_;
-    std::atomic<bool> shouldStop_{false};
-    std::condition_variable pauseCondition_;
-    std::mutex pauseMutex_;
-    
-    // 帧缓冲
-    std::queue<AVFramePtr> frameQueue_;
-    std::mutex queueMutex_;
-    std::condition_variable queueCondition_;
-    static constexpr size_t MAX_QUEUE_SIZE = 20;
-    
-    // 设备信息缓存
-    mutable std::vector<AudioDeviceInfo> cachedDevices_;
-    mutable std::mutex deviceCacheMutex_;
-    mutable bool devicesCached_ = false;
-    
-    // 音频电平计算
-    mutable std::mutex levelMutex_;
-    std::chrono::steady_clock::time_point lastLevelUpdate_;
-    static constexpr double LEVEL_UPDATE_INTERVAL = 0.1; // 100ms
-};
-
-} // namespace capture
-} // namespace av
-
-#endif // AV_CAPTURE_AUDIO_CAPTURER_H

+ 0 - 849
AV/code/capture/capture_video_capturer.cpp

@@ -1,849 +0,0 @@
-#include "capture_video_capturer.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <algorithm>
-#include <sstream>
-
-#ifdef _WIN32
-#include <windows.h>
-#include <dshow.h>
-#pragma comment(lib, "strmiids.lib")
-#endif
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavdevice/avdevice.h>
-#include <libswscale/swscale.h>
-#include <libavutil/imgutils.h>
-#include <libavutil/opt.h>
-}
-
-namespace av {
-namespace capture {
-
-VideoCapturer::VideoCapturer() : videoParams_(CapturerType::VIDEO_CAMERA) {
-    AV_LOGGER_DEBUG("创建视频采集器");
-    
-    // 注册设备
-    avdevice_register_all();
-}
-
-VideoCapturer::~VideoCapturer() {
-    close();
-    AV_LOGGER_DEBUG("视频采集器已销毁");
-}
-
-ErrorCode VideoCapturer::initialize(const CapturerParams& params) {
-    if (params.mediaType != MediaType::VIDEO) {
-        AV_LOGGER_ERROR("参数媒体类型不是视频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    videoParams_ = static_cast<const VideoCaptureParams&>(params);
-    
-    if (!validateParams(videoParams_)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    ErrorCode result = ErrorCode::SUCCESS;
-    
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        result = initializeCamera();
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        result = initializeScreen();
-    } else if (videoParams_.type == CapturerType::VIDEO_WINDOW) {
-        result = initializeWindow();
-    } else {
-        AV_LOGGER_ERROR("不支持的视频采集器类型");
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    if (result == ErrorCode::SUCCESS) {
-        setState(CapturerState::INITIALIZED);
-        AV_LOGGER_INFOF("视频采集器初始化成功: {}x{}@{}fps", 
-                       videoParams_.width, videoParams_.height, videoParams_.fps);
-    }
-    
-    return result;
-}
-
-ErrorCode VideoCapturer::start() {
-    std::lock_guard<std::mutex> lock(captureMutex_);
-    
-    if (getState() != CapturerState::INITIALIZED) {
-        AV_LOGGER_ERROR("采集器状态无效,无法启动");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStop_ = false;
-    
-    // 启动采集线程
-    try {
-        captureThread_ = std::thread(&VideoCapturer::captureThreadFunc, this);
-        setState(CapturerState::STARTED);
-        
-        AV_LOGGER_INFO("视频采集已启动");
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("启动采集线程失败: {}", e.what());
-        return ErrorCode::THREAD_ERROR;
-    }
-}
-
-ErrorCode VideoCapturer::stop() {
-    std::lock_guard<std::mutex> lock(captureMutex_);
-    
-    if (getState() != CapturerState::STARTED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    shouldStop_ = true;
-    
-    // 唤醒暂停的线程
-    {
-        std::lock_guard<std::mutex> pauseLock(pauseMutex_);
-        paused_ = false;
-        pauseCondition_.notify_all();
-    }
-    
-    // 等待线程结束
-    if (captureThread_.joinable()) {
-        captureThread_.join();
-    }
-    
-    setState(CapturerState::STOPPED);
-    AV_LOGGER_INFO("视频采集已停止");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoCapturer::pause() {
-    if (getState() != CapturerState::STARTED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    paused_ = true;
-    AV_LOGGER_INFO("视频采集已暂停");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoCapturer::resume() {
-    if (getState() != CapturerState::STARTED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    {
-        std::lock_guard<std::mutex> lock(pauseMutex_);
-        paused_ = false;
-        pauseCondition_.notify_all();
-    }
-    
-    AV_LOGGER_INFO("视频采集已恢复");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoCapturer::reset() {
-    ErrorCode result = stop();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 清空帧队列
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        while (!frameQueue_.empty()) {
-            frameQueue_.pop();
-        }
-    }
-    
-    resetStats();
-    setState(CapturerState::INITIALIZED);
-    
-    AV_LOGGER_INFO("视频采集器已重置");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoCapturer::close() {
-    stop();
-    
-    // 清理资源
-    cleanupConverter();
-    
-    if (codecCtx_) {
-        avcodec_free_context(&codecCtx_);
-        codecCtx_ = nullptr;
-    }
-    
-    if (formatCtx_) {
-        avformat_close_input(&formatCtx_);
-        formatCtx_ = nullptr;
-    }
-    
-    codec_ = nullptr;
-    videoStreamIndex_ = -1;
-    
-    setState(CapturerState::IDLE);
-    AV_LOGGER_INFO("视频采集器已关闭");
-    
-    return ErrorCode::SUCCESS;
-}
-
-std::vector<std::string> VideoCapturer::getAvailableDevices() const {
-    std::vector<std::string> devices;
-    auto deviceInfos = getDetailedDeviceInfo();
-    
-    for (const auto& info : deviceInfos) {
-        devices.push_back(info.name);
-    }
-    
-    return devices;
-}
-
-std::string VideoCapturer::getCurrentDevice() const {
-    return videoParams_.deviceName;
-}
-
-std::vector<VideoDeviceInfo> VideoCapturer::getDetailedDeviceInfo() const {
-    std::lock_guard<std::mutex> lock(deviceCacheMutex_);
-    
-    if (!devicesCached_) {
-        if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-            cachedDevices_ = enumerateCameras();
-        } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-            cachedDevices_ = enumerateScreens();
-        } else if (videoParams_.type == CapturerType::VIDEO_WINDOW) {
-            cachedDevices_ = enumerateWindows();
-        }
-        devicesCached_ = true;
-    }
-    
-    return cachedDevices_;
-}
-
-ErrorCode VideoCapturer::setVideoParams(int width, int height, int fps) {
-    if (getState() == CapturerState::STARTED) {
-        AV_LOGGER_ERROR("无法在采集过程中修改参数");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    videoParams_.width = width;
-    videoParams_.height = height;
-    videoParams_.fps = fps;
-    
-    AV_LOGGER_INFOF("视频参数已更新: {}x{}@{}fps", width, height, fps);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoCapturer::setPixelFormat(AVPixelFormat format) {
-    if (getState() == CapturerState::STARTED) {
-        AV_LOGGER_ERROR("无法在采集过程中修改像素格式");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    videoParams_.pixelFormat = format;
-    
-    AV_LOGGER_INFOF("像素格式已更新: {}", av_get_pix_fmt_name(format));
-    
-    return ErrorCode::SUCCESS;
-}
-
-VideoCaptureParams VideoCapturer::getCurrentParams() const {
-    return videoParams_;
-}
-
-bool VideoCapturer::validateParams(const CapturerParams& params) {
-    const auto& videoParams = static_cast<const VideoCaptureParams&>(params);
-    
-    if (videoParams.width <= 0 || videoParams.height <= 0) {
-        AV_LOGGER_ERROR("视频分辨率无效");
-        return false;
-    }
-    
-    if (videoParams.fps <= 0 || videoParams.fps > 120) {
-        AV_LOGGER_ERROR("帧率无效");
-        return false;
-    }
-    
-    if (videoParams.type == CapturerType::VIDEO_CAMERA) {
-        if (videoParams.cameraIndex < 0) {
-            AV_LOGGER_ERROR("摄像头索引无效");
-            return false;
-        }
-    } else if (videoParams.type == CapturerType::VIDEO_SCREEN) {
-        if (videoParams.screenIndex < 0) {
-            AV_LOGGER_ERROR("屏幕索引无效");
-            return false;
-        }
-    } else if (videoParams.type == CapturerType::VIDEO_WINDOW) {
-        if (videoParams.windowTitle.empty() && !videoParams.windowHandle) {
-            AV_LOGGER_ERROR("窗口标题和窗口句柄都为空");
-            return false;
-        }
-    }
-    
-    return true;
-}
-
-ErrorCode VideoCapturer::initializeCamera() {
-    AV_LOGGER_INFOF("初始化摄像头采集器: 索引={}", videoParams_.cameraIndex);
-    
-#ifdef _WIN32
-    return setupDirectShowCamera();
-#elif defined(__linux__)
-    return setupV4L2Camera();
-#elif defined(__APPLE__)
-    return setupAVFoundationCamera();
-#else
-    AV_LOGGER_ERROR("当前平台不支持摄像头采集");
-    return ErrorCode::NOT_SUPPORTED;
-#endif
-}
-
-ErrorCode VideoCapturer::initializeScreen() {
-    AV_LOGGER_INFOF("初始化屏幕录制: 索引={}", videoParams_.screenIndex);
-    
-#ifdef _WIN32
-    return setupGDIScreenCapture();
-#elif defined(__linux__)
-    return setupX11ScreenCapture();
-#elif defined(__APPLE__)
-    return setupCoreGraphicsScreenCapture();
-#else
-    AV_LOGGER_ERROR("当前平台不支持屏幕录制");
-    return ErrorCode::NOT_SUPPORTED;
-#endif
-}
-
-ErrorCode VideoCapturer::initializeWindow() {
-    AV_LOGGER_INFOF("初始化窗口采集: 标题={}", videoParams_.windowTitle);
-    
-#ifdef _WIN32
-    return setupGDIWindowCapture();
-#else
-    AV_LOGGER_ERROR("当前平台不支持窗口采集");
-    return ErrorCode::NOT_SUPPORTED;
-#endif
-}
-
-ErrorCode VideoCapturer::openInputDevice() {
-    const AVInputFormat* inputFormat = getPlatformInputFormat();
-    if (!inputFormat) {
-        AV_LOGGER_ERROR("获取输入格式失败");
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    std::string deviceName = getPlatformDeviceName();
-    if (deviceName.empty()) {
-        AV_LOGGER_ERROR("获取设备名称失败");
-        return ErrorCode::DEVICE_NOT_FOUND;
-    }
-    
-    AV_LOGGER_INFOF("打开输入设备: {} (格式: {})", deviceName, inputFormat->name);
-    
-    // 设置输入选项
-    AVDictionary* options = nullptr;
-    
-    // 设置视频参数
-    av_dict_set(&options, "video_size", 
-                (std::to_string(videoParams_.width) + "x" + std::to_string(videoParams_.height)).c_str(), 0);
-    av_dict_set(&options, "framerate", std::to_string(videoParams_.fps).c_str(), 0);
-    
-    if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        // 屏幕录制特定选项
-        if (videoParams_.captureCursor) {
-            av_dict_set(&options, "draw_mouse", "1", 0);
-        }
-        
-        if (videoParams_.offsetX != 0 || videoParams_.offsetY != 0) {
-            av_dict_set(&options, "offset_x", std::to_string(videoParams_.offsetX).c_str(), 0);
-            av_dict_set(&options, "offset_y", std::to_string(videoParams_.offsetY).c_str(), 0);
-        }
-    } else if (videoParams_.type == CapturerType::VIDEO_WINDOW) {
-        // 窗口采集特定选项
-        if (videoParams_.captureCursor) {
-            av_dict_set(&options, "draw_mouse", "1", 0);
-        }
-        
-        if (videoParams_.offsetX != 0 || videoParams_.offsetY != 0) {
-            av_dict_set(&options, "offset_x", std::to_string(videoParams_.offsetX).c_str(), 0);
-            av_dict_set(&options, "offset_y", std::to_string(videoParams_.offsetY).c_str(), 0);
-        }
-    }
-    
-    // 打开输入
-    int ret = avformat_open_input(&formatCtx_, deviceName.c_str(), inputFormat, &options);
-    av_dict_free(&options);
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开输入设备失败: {} (设备: {})", 
-                        ffmpeg_utils::errorToString(ret), deviceName);
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 查找流信息
-    ret = avformat_find_stream_info(formatCtx_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("查找流信息失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 查找视频流
-    videoStreamIndex_ = av_find_best_stream(formatCtx_, AVMEDIA_TYPE_VIDEO, -1, -1, &codec_, 0);
-    if (videoStreamIndex_ < 0) {
-        AV_LOGGER_ERROR("未找到视频流");
-        return ErrorCode::STREAM_NOT_FOUND;
-    }
-    
-    // 创建解码上下文
-    codecCtx_ = avcodec_alloc_context3(codec_);
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("分配解码上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 复制流参数到解码上下文
-    ret = avcodec_parameters_to_context(codecCtx_, formatCtx_->streams[videoStreamIndex_]->codecpar);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("复制流参数失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 打开解码器
-    ret = avcodec_open2(codecCtx_, codec_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开解码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 设置像素格式转换
-    return setupPixelFormatConversion();
-}
-
-ErrorCode VideoCapturer::setupPixelFormatConversion() {
-    AVPixelFormat srcFormat = codecCtx_->pix_fmt;
-    AVPixelFormat dstFormat = videoParams_.pixelFormat;
-    
-    needConversion_ = (srcFormat != dstFormat);
-    
-    if (needConversion_) {
-        AV_LOGGER_INFOF("需要像素格式转换: {} -> {}", 
-                       av_get_pix_fmt_name(srcFormat), 
-                       av_get_pix_fmt_name(dstFormat));
-        
-        swsCtx_ = sws_getContext(
-            codecCtx_->width, codecCtx_->height, srcFormat,
-            videoParams_.width, videoParams_.height, dstFormat,
-            SWS_BILINEAR, nullptr, nullptr, nullptr
-        );
-        
-        if (!swsCtx_) {
-            AV_LOGGER_ERROR("创建像素格式转换上下文失败");
-            return ErrorCode::CONVERSION_FAILED;
-        }
-        
-        // 创建转换后的帧
-        convertedFrame_ = makeAVFrame();
-        if (!convertedFrame_) {
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        convertedFrame_->format = dstFormat;
-        convertedFrame_->width = videoParams_.width;
-        convertedFrame_->height = videoParams_.height;
-        
-        int ret = av_frame_get_buffer(convertedFrame_.get(), 32);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("分配转换帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-            return static_cast<ErrorCode>(ret);
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-void VideoCapturer::captureThreadFunc() {
-    AV_LOGGER_INFO("视频采集线程已启动");
-    
-    while (!shouldStop_) {
-        // 检查暂停状态
-        {
-            std::unique_lock<std::mutex> lock(pauseMutex_);
-            pauseCondition_.wait(lock, [this] { return !paused_ || shouldStop_; });
-        }
-        
-        if (shouldStop_) {
-            break;
-        }
-        
-        ErrorCode result = captureFrame();
-        if (result != ErrorCode::SUCCESS) {
-            onError(result, "采集帧失败");
-            
-            // 短暂休眠后重试
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-        }
-    }
-    
-    AV_LOGGER_INFO("视频采集线程已退出");
-}
-
-ErrorCode VideoCapturer::captureFrame() {
-    AVPacket* packet = av_packet_alloc();
-    if (!packet) {
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 读取包
-    int ret = av_read_frame(formatCtx_, packet);
-    if (ret < 0) {
-        if (ret == AVERROR_EOF) {
-            AV_LOGGER_WARNING("到达文件末尾");
-            return ErrorCode::END_OF_STREAM;
-        } else {
-            AV_LOGGER_ERRORF("读取帧失败: {}", ffmpeg_utils::errorToString(ret));
-            return static_cast<ErrorCode>(ret);
-        }
-    }
-    
-    // 检查是否是视频包
-    if (packet->stream_index != videoStreamIndex_) {
-        av_packet_free(&packet);
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 发送包到解码器
-    ret = avcodec_send_packet(codecCtx_, packet);
-    av_packet_free(&packet);
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("发送包到解码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 接收解码后的帧
-    AVFramePtr frame = makeAVFrame();
-    if (!frame) {
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    ret = avcodec_receive_frame(codecCtx_, frame.get());
-    if (ret == AVERROR(EAGAIN)) {
-        return ErrorCode::SUCCESS; // 需要更多输入
-    } else if (ret < 0) {
-        AV_LOGGER_ERRORF("接收解码帧失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 像素格式转换
-    AVFramePtr outputFrame;
-    if (needConversion_) {
-        outputFrame = convertPixelFormat(frame);
-        if (!outputFrame) {
-            return ErrorCode::CONVERSION_FAILED;
-        }
-    } else {
-        outputFrame = std::move(frame);
-    }
-    
-    // 添加到队列或直接回调
-    onFrameCaptured(outputFrame);
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr VideoCapturer::convertPixelFormat(const AVFramePtr& srcFrame) {
-    if (!srcFrame || !swsCtx_ || !convertedFrame_) {
-        return nullptr;
-    }
-    
-    // 执行像素格式转换
-    int ret = sws_scale(swsCtx_,
-                       srcFrame->data, srcFrame->linesize, 0, srcFrame->height,
-                       convertedFrame_->data, convertedFrame_->linesize);
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("像素格式转换失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(convertedFrame_.get(), srcFrame.get());
-    
-    // 创建新的frame并复制数据
-    AVFramePtr outputFrame = makeAVFrame();
-    if (!outputFrame) {
-        return nullptr;
-    }
-    
-    av_frame_ref(outputFrame.get(), convertedFrame_.get());
-    return outputFrame;
-}
-
-void VideoCapturer::cleanupConverter() {
-    if (swsCtx_) {
-        sws_freeContext(swsCtx_);
-        swsCtx_ = nullptr;
-    }
-    
-    convertedFrame_.reset();
-    needConversion_ = false;
-}
-
-std::vector<VideoDeviceInfo> VideoCapturer::enumerateCameras() const {
-#ifdef _WIN32
-    return enumerateDirectShowDevices();
-#elif defined(__linux__)
-    return enumerateV4L2Devices();
-#elif defined(__APPLE__)
-    return enumerateAVFoundationDevices();
-#else
-    return {};
-#endif
-}
-
-std::vector<VideoDeviceInfo> VideoCapturer::enumerateScreens() const {
-    std::vector<VideoDeviceInfo> screens;
-    
-    // 简单的屏幕枚举实现
-    VideoDeviceInfo screen;
-    screen.id = "desktop";
-    screen.name = "桌面";
-    screen.description = "主显示器";
-    
-    // 添加常见分辨率
-    screen.supportedResolutions = {
-        {1920, 1080}, {1680, 1050}, {1600, 900}, {1440, 900},
-        {1366, 768}, {1280, 1024}, {1280, 800}, {1024, 768}
-    };
-    
-    // 添加常见帧率
-    screen.supportedFps = {15, 24, 30, 60};
-    
-    // 添加支持的像素格式
-    screen.supportedFormats = {
-        AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_YUV420P
-    };
-    
-    screens.push_back(screen);
-    
-    return screens;
-}
-
-std::vector<VideoDeviceInfo> VideoCapturer::enumerateWindows() const {
-#ifdef _WIN32
-    return enumerateWindowsWindows();
-#else
-    return {};
-#endif
-}
-
-const AVInputFormat* VideoCapturer::getPlatformInputFormat() const {
-#ifdef _WIN32
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        return av_find_input_format("dshow");
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        return av_find_input_format("gdigrab");
-    } else if (videoParams_.type == CapturerType::VIDEO_WINDOW) {
-        return av_find_input_format("gdigrab");
-    }
-#elif defined(__linux__)
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        return av_find_input_format("v4l2");
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        return av_find_input_format("x11grab");
-    }
-#elif defined(__APPLE__)
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        return av_find_input_format("avfoundation");
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        return av_find_input_format("avfoundation");
-    }
-#endif
-    
-    return nullptr;
-}
-
-std::string VideoCapturer::getPlatformDeviceName() const {
-#ifdef _WIN32
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        if (!videoParams_.deviceName.empty()) {
-            return "video=" + videoParams_.deviceName;
-        } else {
-            return "video=" + std::to_string(videoParams_.cameraIndex);
-        }
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        return "desktop";
-    } else if (videoParams_.type == CapturerType::VIDEO_WINDOW) {
-        if (!videoParams_.windowTitle.empty()) {
-            return "title=" + videoParams_.windowTitle;
-        } else if (videoParams_.windowHandle) {
-            return "hwnd=" + std::to_string(reinterpret_cast<uintptr_t>(videoParams_.windowHandle));
-        } else {
-            return "desktop"; // 回退到桌面捕获
-        }
-    }
-#elif defined(__linux__)
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        if (!videoParams_.deviceName.empty()) {
-            return videoParams_.deviceName;
-        } else {
-            return "/dev/video" + std::to_string(videoParams_.cameraIndex);
-        }
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        return ":0.0";
-    }
-#elif defined(__APPLE__)
-    if (videoParams_.type == CapturerType::VIDEO_CAMERA) {
-        return std::to_string(videoParams_.cameraIndex);
-    } else if (videoParams_.type == CapturerType::VIDEO_SCREEN) {
-        return "Capture screen 0";
-    }
-#endif
-    
-    return "";
-}
-
-#ifdef _WIN32
-std::vector<VideoDeviceInfo> VideoCapturer::enumerateDirectShowDevices() const {
-    std::vector<VideoDeviceInfo> devices;
-    
-    // 简化的DirectShow设备枚举
-    // 实际实现需要使用COM接口
-    VideoDeviceInfo device;
-    device.id = "0";
-    device.name = "默认摄像头";
-    device.description = "DirectShow摄像头设备";
-    
-    // 添加常见分辨率
-    device.supportedResolutions = {
-        {1920, 1080}, {1280, 720}, {960, 540}, {640, 480}, {320, 240}
-    };
-    
-    // 添加常见帧率
-    device.supportedFps = {15, 24, 30, 60};
-    
-    // 添加支持的像素格式
-    device.supportedFormats = {
-        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUYV422, AV_PIX_FMT_BGR24
-    };
-    
-    devices.push_back(device);
-    
-    return devices;
-}
-
-ErrorCode VideoCapturer::setupDirectShowCamera() {
-    AV_LOGGER_INFO("设置DirectShow摄像头");
-    return openInputDevice();
-}
-
-ErrorCode VideoCapturer::setupGDIScreenCapture() {
-    AV_LOGGER_INFO("设置GDI屏幕录制");
-    return openInputDevice();
-}
-
-std::vector<VideoDeviceInfo> VideoCapturer::enumerateWindowsWindows() const {
-    std::vector<VideoDeviceInfo> windows;
-    
-    // 简化的窗口枚举实现
-    // 实际实现需要使用EnumWindows API
-    VideoDeviceInfo window;
-    window.id = "notepad";
-    window.name = "记事本";
-    window.description = "Windows记事本窗口";
-    
-    // 窗口采集支持的分辨率取决于窗口大小
-    window.supportedResolutions = {
-        {1920, 1080}, {1280, 720}, {800, 600}, {640, 480}
-    };
-    
-    // 添加常见帧率
-    window.supportedFps = {15, 24, 30, 60};
-    
-    // 添加支持的像素格式
-    window.supportedFormats = {
-        AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_YUV420P
-    };
-    
-    windows.push_back(window);
-    
-    return windows;
-}
-
-ErrorCode VideoCapturer::setupGDIWindowCapture() {
-    AV_LOGGER_INFOF("设置GDI窗口采集: {}", videoParams_.windowTitle);
-    return openInputDevice();
-}
-#endif
-
-// VideoCaptureFactory 实现
-std::unique_ptr<VideoCapturer> VideoCapturer::VideoCaptureFactory::createCamera(int cameraIndex) {
-    auto capturer = std::make_unique<VideoCapturer>();
-    
-    VideoCaptureParams params(CapturerType::VIDEO_CAMERA);
-    params.cameraIndex = cameraIndex;
-    
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建摄像头采集器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return capturer;
-}
-
-std::unique_ptr<VideoCapturer> VideoCapturer::VideoCaptureFactory::createScreen(int screenIndex) {
-    auto capturer = std::make_unique<VideoCapturer>();
-    
-    VideoCaptureParams params(CapturerType::VIDEO_SCREEN);
-    params.screenIndex = screenIndex;
-    
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建屏幕录制采集器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return capturer;
-}
-
-std::unique_ptr<VideoCapturer> VideoCapturer::VideoCaptureFactory::createBestCamera() {
-    return createCamera(0); // 默认使用第一个摄像头
-}
-
-std::unique_ptr<VideoCapturer> VideoCapturer::VideoCaptureFactory::createWindow(const std::string& windowTitle) {
-    auto capturer = std::make_unique<VideoCapturer>();
-    
-    VideoCaptureParams params(CapturerType::VIDEO_WINDOW);
-    params.windowTitle = windowTitle;
-    
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建窗口采集器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return capturer;
-}
-
-std::unique_ptr<VideoCapturer> VideoCapturer::VideoCaptureFactory::createWindowByHandle(void* windowHandle) {
-    auto capturer = std::make_unique<VideoCapturer>();
-    
-    VideoCaptureParams params(CapturerType::VIDEO_WINDOW);
-    params.windowHandle = windowHandle;
-    
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建窗口采集器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return capturer;
-}
-
-} // namespace capture
-} // namespace av

+ 0 - 232
AV/code/capture/capture_video_capturer.h

@@ -1,232 +0,0 @@
-#ifndef AV_CAPTURE_VIDEO_CAPTURER_H
-#define AV_CAPTURE_VIDEO_CAPTURER_H
-
-#include "capture_abstract_capturer.h"
-#include <thread>
-#include <condition_variable>
-#include <queue>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavdevice/avdevice.h>
-#include <libswscale/swscale.h>
-}
-
-namespace av {
-namespace capture {
-
-/**
- * 视频采集器参数
- */
-struct VideoCaptureParams : public CapturerParams {
-    int width = 1920;               // 视频宽度
-    int height = 1080;              // 视频高度
-    int fps = 30;                   // 帧率
-    AVPixelFormat pixelFormat = AV_PIX_FMT_YUV420P; // 像素格式
-    bool useHardwareAccel = true;   // 使用硬件加速
-    
-    // 摄像头特定参数
-    int cameraIndex = 0;            // 摄像头索引
-    std::string cameraFormat;       // 摄像头格式 (如 "dshow", "v4l2")
-    
-    // 屏幕录制特定参数
-    int screenIndex = 0;            // 屏幕索引
-    int offsetX = 0;                // X偏移
-    int offsetY = 0;                // Y偏移
-    bool captureCursor = true;      // 捕获鼠标光标
-    
-    // 窗口采集特定参数
-    std::string windowTitle;        // 窗口标题
-    std::string windowClassName;    // 窗口类名
-    void* windowHandle = nullptr;   // 窗口句柄 (HWND on Windows)
-    bool followWindow = true;       // 跟随窗口移动
-    bool captureClientArea = true;  // 只捕获客户区
-    
-    VideoCaptureParams(CapturerType type) : CapturerParams(type, MediaType::VIDEO) {}
-};
-
-/**
- * 设备信息
- */
-struct VideoDeviceInfo {
-    std::string id;                 // 设备ID
-    std::string name;               // 设备名称
-    std::string description;        // 设备描述
-    std::vector<std::pair<int, int>> supportedResolutions; // 支持的分辨率
-    std::vector<int> supportedFps;  // 支持的帧率
-    std::vector<AVPixelFormat> supportedFormats; // 支持的像素格式
-};
-
-/**
- * 视频采集器类
- * 支持摄像头和屏幕录制
- */
-class VideoCapturer : public AbstractCapturer {
-public:
-    VideoCapturer();
-    virtual ~VideoCapturer();
-    
-    // 基础接口实现
-    ErrorCode initialize(const CapturerParams& params) override;
-    ErrorCode start() override;
-    ErrorCode stop() override;
-    ErrorCode pause() override;
-    ErrorCode resume() override;
-    ErrorCode reset() override;
-    ErrorCode close() override;
-    
-    // 设备信息
-    std::vector<std::string> getAvailableDevices() const override;
-    std::string getCurrentDevice() const override;
-    
-    /**
-     * 获取详细设备信息
-     * @return 设备信息列表
-     */
-    std::vector<VideoDeviceInfo> getDetailedDeviceInfo() const;
-    
-    /**
-     * 设置采集参数
-     * @param width 宽度
-     * @param height 高度
-     * @param fps 帧率
-     * @return 错误码
-     */
-    ErrorCode setVideoParams(int width, int height, int fps);
-    
-    /**
-     * 设置像素格式
-     * @param format 像素格式
-     * @return 错误码
-     */
-    ErrorCode setPixelFormat(AVPixelFormat format);
-    
-    /**
-     * 获取当前视频参数
-     * @return 视频参数
-     */
-    VideoCaptureParams getCurrentParams() const;
-    
-    /**
-     * 视频采集器工厂
-     */
-    class VideoCaptureFactory {
-    public:
-        /**
-         * 创建摄像头采集器
-         * @param cameraIndex 摄像头索引
-         * @return 采集器实例
-         */
-        static std::unique_ptr<VideoCapturer> createCamera(int cameraIndex = 0);
-        
-        /**
-         * 创建屏幕录制采集器
-         * @param screenIndex 屏幕索引
-         * @return 采集器实例
-         */
-        static std::unique_ptr<VideoCapturer> createScreen(int screenIndex = 0);
-        
-        /**
-         * 创建最佳摄像头采集器
-         * @return 采集器实例
-         */
-        static std::unique_ptr<VideoCapturer> createBestCamera();
-        
-        /**
-         * 创建窗口采集器
-         * @param windowTitle 窗口标题
-         * @return 采集器实例
-         */
-        static std::unique_ptr<VideoCapturer> createWindow(const std::string& windowTitle);
-        
-        /**
-         * 创建窗口采集器(通过句柄)
-         * @param windowHandle 窗口句柄
-         * @return 采集器实例
-         */
-        static std::unique_ptr<VideoCapturer> createWindowByHandle(void* windowHandle);
-    };
-    
-protected:
-    bool validateParams(const CapturerParams& params) override;
-    
-private:
-    // 内部实现方法
-    ErrorCode initializeCamera();
-    ErrorCode initializeScreen();
-    ErrorCode initializeWindow();
-    ErrorCode openInputDevice();
-    ErrorCode setupVideoParams();
-    ErrorCode setupPixelFormatConversion();
-    
-    // 采集线程
-    void captureThreadFunc();
-    ErrorCode captureFrame();
-    
-    // 格式转换
-    AVFramePtr convertPixelFormat(const AVFramePtr& srcFrame);
-    void cleanupConverter();
-    
-    // 设备枚举
-    std::vector<VideoDeviceInfo> enumerateCameras() const;
-    std::vector<VideoDeviceInfo> enumerateScreens() const;
-    std::vector<VideoDeviceInfo> enumerateWindows() const;
-    
-    // 平台特定实现
-#ifdef _WIN32
-    std::vector<VideoDeviceInfo> enumerateDirectShowDevices() const;
-    std::vector<VideoDeviceInfo> enumerateWindowsWindows() const;
-    ErrorCode setupDirectShowCamera();
-    ErrorCode setupGDIScreenCapture();
-    ErrorCode setupGDIWindowCapture();
-#elif defined(__linux__)
-    std::vector<VideoDeviceInfo> enumerateV4L2Devices() const;
-    ErrorCode setupV4L2Camera();
-    ErrorCode setupX11ScreenCapture();
-#elif defined(__APPLE__)
-    std::vector<VideoDeviceInfo> enumerateAVFoundationDevices() const;
-    ErrorCode setupAVFoundationCamera();
-    ErrorCode setupCoreGraphicsScreenCapture();
-#endif
-    
-    // 获取平台特定的输入格式
-    const AVInputFormat* getPlatformInputFormat() const;
-    std::string getPlatformDeviceName() const;
-    
-private:
-    // 采集参数
-    VideoCaptureParams videoParams_;
-    
-    // FFmpeg 相关
-    AVFormatContext* formatCtx_ = nullptr;
-    AVCodecContext* codecCtx_ = nullptr;
-    const AVCodec* codec_ = nullptr;
-    int videoStreamIndex_ = -1;
-    
-    // 像素格式转换
-    SwsContext* swsCtx_ = nullptr;
-    AVFramePtr convertedFrame_;
-    bool needConversion_ = false;
-    
-    // 采集线程
-    std::thread captureThread_;
-    std::atomic<bool> shouldStop_{false};
-    std::condition_variable pauseCondition_;
-    std::mutex pauseMutex_;
-    
-    // 帧缓冲
-    std::queue<AVFramePtr> frameQueue_;
-    std::mutex queueMutex_;
-    std::condition_variable queueCondition_;
-    static constexpr size_t MAX_QUEUE_SIZE = 10;
-    
-    // 设备信息缓存
-    mutable std::vector<VideoDeviceInfo> cachedDevices_;
-    mutable std::mutex deviceCacheMutex_;
-    mutable bool devicesCached_ = false;
-};
-
-} // namespace capture
-} // namespace av
-
-#endif // AV_CAPTURE_VIDEO_CAPTURER_H

+ 0 - 456
AV/code/codec/codec_abstract_codec.cpp

@@ -1,456 +0,0 @@
-#include "codec_abstract_codec.h"
-#include "codec_video_encoder.h"
-#include "codec_audio_encoder.h"
-#include "codec_video_decoder.h"
-#include "codec_audio_decoder.h"
-#include "../base/media_common.h"
-#include "../base/logger.h"
-#include <chrono>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavutil/opt.h>
-}
-
-namespace av {
-namespace codec {
-
-AbstractCodec::AbstractCodec(MediaType mediaType, CodecType codecType)
-    : mediaType_(mediaType)
-    , codecType_(codecType)
-    , state_(CodecState::IDLE)
-    , codec_(nullptr) {
-    AV_LOGGER_DEBUGF("创建{}编解码器, 媒体类型: {}", 
-                  codecType == CodecType::ENCODER ? "编码" : "解码",
-                  static_cast<int>(mediaType));
-}
-
-AbstractCodec::~AbstractCodec() {
-    if (state_ != CodecState::CLOSED && state_ != CodecState::IDLE) {
-        AV_LOGGER_WARNING("编解码器析构时状态不正确,强制关闭");
-        close();
-    }
-    AV_LOGGER_DEBUG("编解码器已析构");
-}
-
-ErrorCode AbstractCodec::reset() {
-    AV_LOGGER_DEBUG("重置编解码器");
-    
-    if (state_ == CodecState::IDLE || state_ == CodecState::CLOSED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 先刷新缓冲区
-    ErrorCode result = flush();
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("刷新编解码器失败: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    // 重置统计信息
-    resetStatistics();
-    
-    setState(CodecState::OPENED);
-    return ErrorCode::SUCCESS;
-}
-
-void AbstractCodec::resetStatistics() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = Statistics{};
-    AV_LOGGER_DEBUG("统计信息已重置");
-}
-
-void AbstractCodec::setState(CodecState state) {
-    std::unique_lock<std::shared_mutex> lock(stateMutex_);
-    if (state_ != state) {
-        AV_LOGGER_DEBUGF("编解码器状态变更: {} -> {}", 
-                      static_cast<int>(state_), static_cast<int>(state));
-        state_ = state;
-    }
-}
-
-void AbstractCodec::reportError(ErrorCode error, const std::string& message) {
-    setState(CodecState::ERROR);
-    
-    // 更新错误统计
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.errorCount++;
-    }
-    
-    std::string fullMessage = message.empty() ? 
-        ffmpeg_utils::errorToString(static_cast<int>(error)) : message;
-    
-    AV_LOGGER_ERRORF("编解码器错误: {} ({})", fullMessage, static_cast<int>(error));
-    
-    if (errorCallback_) {
-        errorCallback_(error, fullMessage);
-    }
-}
-
-void AbstractCodec::updateStats(bool success, double processTime, uint64_t bytes) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    if (success) {
-        stats_.processedFrames++;
-        stats_.totalBytes += bytes;
-        
-        // 更新平均处理时间
-        if (stats_.processedFrames == 1) {
-            stats_.avgProcessTime = processTime;
-        } else {
-            stats_.avgProcessTime = (stats_.avgProcessTime * (stats_.processedFrames - 1) + processTime) / stats_.processedFrames;
-        }
-    } else {
-        stats_.droppedFrames++;
-    }
-}
-
-// CodecFactory 实现
-std::unique_ptr<AbstractEncoder> CodecFactory::createEncoder(MediaType mediaType, const std::string& codecName) {
-    AV_LOGGER_INFOF("创建编码器: {} (媒体类型: {})", codecName, static_cast<int>(mediaType));
-    
-    // 查找编码器
-    const AVCodec* codec = avcodec_find_encoder_by_name(codecName.c_str());
-    if (!codec) {
-        AV_LOGGER_ERRORF("未找到编码器: {}", codecName);
-        return nullptr;
-    }
-    
-    // 检查媒体类型匹配
-    AVMediaType expectedType = (mediaType == MediaType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
-    if (codec->type != expectedType) {
-        AV_LOGGER_ERRORF("编码器媒体类型不匹配: {} (期望: {}, 实际: {})", 
-                      codecName, expectedType, codec->type);
-        return nullptr;
-    }
-    
-    // 根据媒体类型创建具体的编码器实例
-    try {
-        if (mediaType == MediaType::VIDEO) {
-            auto encoder = std::make_unique<VideoEncoder>();
-            AV_LOGGER_INFOF("成功创建视频编码器: {}", codecName);
-            return std::move(encoder);
-        } else if (mediaType == MediaType::AUDIO) {
-            auto encoder = std::make_unique<AudioEncoder>();
-            AV_LOGGER_INFOF("成功创建音频编码器: {}", codecName);
-            return std::move(encoder);
-        } else {
-            AV_LOGGER_ERRORF("不支持的媒体类型: {}", static_cast<int>(mediaType));
-            return nullptr;
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("创建编码器实例失败: {}", e.what());
-        return nullptr;
-    }
-}
-
-std::unique_ptr<AbstractDecoder> CodecFactory::createDecoder(MediaType mediaType, const std::string& codecName) {
-    AV_LOGGER_INFOF("创建解码器: {} (媒体类型: {})", codecName, static_cast<int>(mediaType));
-    
-    // 查找解码器
-    const AVCodec* codec = avcodec_find_decoder_by_name(codecName.c_str());
-    if (!codec) {
-        AV_LOGGER_ERRORF("未找到解码器: {}", codecName);
-        return nullptr;
-    }
-    
-    // 检查媒体类型匹配
-    AVMediaType expectedType = (mediaType == MediaType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
-    if (codec->type != expectedType) {
-        AV_LOGGER_ERRORF("解码器媒体类型不匹配: {} (期望: {}, 实际: {})", 
-                      codecName, expectedType, codec->type);
-        return nullptr;
-    }
-    
-    // 根据媒体类型创建具体的解码器实例
-    try {
-        if (mediaType == MediaType::VIDEO) {
-            auto decoder = std::make_unique<VideoDecoder>();
-            AV_LOGGER_INFOF("成功创建视频解码器: {}", codecName);
-            return std::move(decoder);
-        } else if (mediaType == MediaType::AUDIO) {
-            auto decoder = std::make_unique<AudioDecoder>();
-            AV_LOGGER_INFOF("成功创建音频解码器: {}", codecName);
-            return std::move(decoder);
-        } else {
-            AV_LOGGER_ERRORF("不支持的媒体类型: {}", static_cast<int>(mediaType));
-            return nullptr;
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("创建解码器实例失败: {}", e.what());
-        return nullptr;
-    }
-}
-
-std::vector<std::string> CodecFactory::getSupportedEncoders(MediaType mediaType) {
-    std::vector<std::string> encoders;
-    
-    AVMediaType avMediaType = (mediaType == MediaType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
-    
-    void* iter = nullptr;
-    const AVCodec* codec = nullptr;
-    
-    while ((codec = av_codec_iterate(&iter)) != nullptr) {
-        if (av_codec_is_encoder(codec) && codec->type == avMediaType) {
-            encoders.emplace_back(codec->name);
-        }
-    }
-    
-    AV_LOGGER_INFOF("找到 {} 个{}编码器", encoders.size(), 
-                 mediaType == MediaType::VIDEO ? "视频" : "音频");
-    
-    return encoders;
-}
-
-std::vector<std::string> CodecFactory::getSupportedDecoders(MediaType mediaType) {
-    std::vector<std::string> decoders;
-    
-    AVMediaType avMediaType = (mediaType == MediaType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
-    
-    void* iter = nullptr;
-    const AVCodec* codec = nullptr;
-    
-    while ((codec = av_codec_iterate(&iter)) != nullptr) {
-        if (av_codec_is_decoder(codec) && codec->type == avMediaType) {
-            decoders.emplace_back(codec->name);
-        }
-    }
-    
-    AV_LOGGER_INFOF("找到 {} 个{}解码器", decoders.size(), 
-                 mediaType == MediaType::VIDEO ? "视频" : "音频");
-    
-    return decoders;
-}
-
-bool CodecFactory::isCodecSupported(const std::string& codecName, CodecType type, MediaType mediaType) {
-    const AVCodec* codec = nullptr;
-    
-    if (type == CodecType::ENCODER) {
-        codec = avcodec_find_encoder_by_name(codecName.c_str());
-    } else {
-        codec = avcodec_find_decoder_by_name(codecName.c_str());
-    }
-    
-    if (!codec) {
-        return false;
-    }
-    
-    AVMediaType expectedType = (mediaType == MediaType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
-    return codec->type == expectedType;
-}
-
-void AbstractCodec::close() {
-    AV_LOGGER_DEBUG("关闭编解码器");
-    
-    // 使用RAII确保异常安全
-    try {
-        std::unique_lock<std::shared_mutex> stateLock(stateMutex_);
-        if (state_ == CodecState::CLOSED || state_ == CodecState::IDLE) {
-            return;
-        }
-        
-        // 设置状态为关闭中,防止其他操作
-        state_ = CodecState::CLOSED;
-        stateLock.unlock();
-        
-        // 获取资源锁进行清理
-        std::lock_guard<std::mutex> resourceLock(resourceMutex_);
-        
-        // 释放编解码上下文
-        if (codecCtx_) {
-            AVCodecContext* ctx = codecCtx_.release();
-            avcodec_free_context(&ctx);
-        }
-        
-        codec_ = nullptr;
-        
-        AV_LOGGER_DEBUG("编解码器已关闭");
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("关闭编解码器时发生异常: {}", e.what());
-        // 确保状态被设置为错误
-        try {
-            setState(CodecState::ERROR);
-        } catch (...) {
-            // 忽略setState可能的异常,因为我们已经在异常处理中
-        }
-    } catch (...) {
-        AV_LOGGER_ERROR("关闭编解码器时发生未知异常");
-        try {
-            setState(CodecState::ERROR);
-        } catch (...) {
-            // 忽略setState可能的异常
-        }
-    }
-}
-
-ErrorCode AbstractCodec::flush() {
-    AV_LOGGER_DEBUG("刷新编解码器缓冲区");
-    
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        AV_LOGGER_WARNING("编解码器未打开,无法刷新");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("编解码上下文为空");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 刷新编解码器
-    avcodec_flush_buffers(codecCtx_.get());
-    
-    AV_LOGGER_DEBUG("编解码器缓冲区已刷新");
-    return ErrorCode::SUCCESS;
-}
-
-// 错误码转换工具实现
-ErrorCode AbstractCodec::convertFFmpegError(int ffmpegError) {
-    if (ffmpegError >= 0) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 根据FFmpeg错误码映射到项目中已定义的错误码
-    switch (ffmpegError) {
-        case AVERROR(EINVAL):
-            return ErrorCode::INVALID_PARAMS;
-        case AVERROR(ENOMEM):
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        case AVERROR(EAGAIN):
-            return ErrorCode::PROCESSING_ERROR;  // 使用PROCESSING_ERROR代替RESOURCE_BUSY
-        case AVERROR_EOF:
-            return ErrorCode::END_OF_STREAM;
-        case AVERROR(ENOSYS):
-            return ErrorCode::NOT_SUPPORTED;
-        case AVERROR(EPIPE):
-            return ErrorCode::OPERATION_FAILED;  // 使用OPERATION_FAILED代替BROKEN_PIPE
-        case AVERROR(EIO):
-            return ErrorCode::FILE_OPERATION_FAILED;  // 使用FILE_OPERATION_FAILED代替IO_ERROR
-        case AVERROR(EACCES):
-            return ErrorCode::FILE_OPEN_FAILED;  // 使用FILE_OPEN_FAILED代替ACCESS_DENIED
-        case AVERROR_DECODER_NOT_FOUND:
-            return ErrorCode::CODEC_NOT_FOUND;  // 使用CODEC_NOT_FOUND代替DECODER_NOT_FOUND
-        case AVERROR_ENCODER_NOT_FOUND:
-            return ErrorCode::CODEC_NOT_FOUND;  // 使用CODEC_NOT_FOUND代替ENCODER_NOT_FOUND
-        case AVERROR_DEMUXER_NOT_FOUND:
-            return ErrorCode::NOT_FOUND;  // 使用通用NOT_FOUND
-        case AVERROR_MUXER_NOT_FOUND:
-            return ErrorCode::NOT_FOUND;  // 使用通用NOT_FOUND
-        case AVERROR_PROTOCOL_NOT_FOUND:
-            return ErrorCode::NOT_FOUND;  // 使用通用NOT_FOUND
-        case AVERROR_STREAM_NOT_FOUND:
-            return ErrorCode::STREAM_NOT_FOUND;
-        case AVERROR_BUG:
-            return ErrorCode::UNKNOWN_ERROR;  // 使用UNKNOWN_ERROR代替INTERNAL_ERROR
-        case AVERROR_UNKNOWN:
-            return ErrorCode::UNKNOWN_ERROR;
-        case AVERROR_EXPERIMENTAL:
-            return ErrorCode::NOT_SUPPORTED;
-        case AVERROR_INPUT_CHANGED:
-            return ErrorCode::FORMAT_NOT_SUPPORTED;  // 使用FORMAT_NOT_SUPPORTED代替FORMAT_CHANGED
-        case AVERROR_OUTPUT_CHANGED:
-            return ErrorCode::FORMAT_NOT_SUPPORTED;  // 使用FORMAT_NOT_SUPPORTED代替FORMAT_CHANGED
-        case AVERROR_BSF_NOT_FOUND:
-            return ErrorCode::NOT_FOUND;  // 使用通用NOT_FOUND代替FILTER_NOT_FOUND
-        case AVERROR_BUG2:
-            return ErrorCode::UNKNOWN_ERROR;  // 使用UNKNOWN_ERROR代替INTERNAL_ERROR
-        case AVERROR_BUFFER_TOO_SMALL:
-            return ErrorCode::MEMORY_ALLOC_FAILED;  // 使用MEMORY_ALLOC_FAILED代替BUFFER_TOO_SMALL
-        case AVERROR_EXTERNAL:
-            return ErrorCode::OPERATION_FAILED;  // 使用OPERATION_FAILED代替EXTERNAL_ERROR
-        case AVERROR_INVALIDDATA:
-            return ErrorCode::INVALID_PARAMS;  // 使用INVALID_PARAMS代替INVALID_DATA
-        case AVERROR_PATCHWELCOME:
-            return ErrorCode::NOT_SUPPORTED;  // 使用NOT_SUPPORTED代替NOT_IMPLEMENTED
-        default:
-            // 对于未映射的错误,记录原始错误码
-            AV_LOGGER_WARNING("未映射的FFmpeg错误码,使用通用错误");
-            return ErrorCode::UNKNOWN_ERROR;
-    }
-}
-
-std::string AbstractCodec::getErrorDescription(ErrorCode error) {
-    switch (error) {
-        case ErrorCode::SUCCESS:
-            return "成功";
-        case ErrorCode::INVALID_PARAMS:
-            return "无效参数";
-        case ErrorCode::INVALID_PATH:
-            return "无效路径";
-        case ErrorCode::CODEC_NOT_FOUND:
-            return "编解码器未找到";
-        case ErrorCode::CODEC_OPEN_FAILED:
-            return "编解码器打开失败";
-        case ErrorCode::ENCODE_FAILED:
-            return "编码失败";
-        case ErrorCode::DECODE_FAILED:
-            return "解码失败";
-        case ErrorCode::MEMORY_ALLOC_FAILED:
-            return "内存分配失败";
-        case ErrorCode::FILE_OPEN_FAILED:
-            return "文件打开失败";
-        case ErrorCode::FILE_EXISTS:
-            return "文件已存在";
-        case ErrorCode::FILE_OPERATION_FAILED:
-            return "文件操作失败";
-        case ErrorCode::INVALID_STATE:
-            return "无效状态";
-        case ErrorCode::NOT_STARTED:
-            return "未开始";
-        case ErrorCode::NOT_PAUSED:
-            return "未暂停";
-        case ErrorCode::ALREADY_INITIALIZED:
-            return "已经初始化";
-        case ErrorCode::NOT_INITIALIZED:
-            return "未初始化";
-        case ErrorCode::ALREADY_STARTED:
-            return "已经开始";
-        case ErrorCode::ALREADY_PAUSED:
-            return "已经暂停";
-        case ErrorCode::CONVERSION_FAILED:
-            return "转换失败";
-        case ErrorCode::FORMAT_NOT_SUPPORTED:
-            return "格式不支持";
-        case ErrorCode::NOT_SUPPORTED:
-            return "不支持的操作";
-        case ErrorCode::HARDWARE_ERROR:
-            return "硬件错误";
-        case ErrorCode::DEVICE_NOT_FOUND:
-            return "设备未找到";
-        case ErrorCode::STREAM_NOT_FOUND:
-            return "流未找到";
-        case ErrorCode::STREAM_EXISTS:
-            return "流已存在";
-        case ErrorCode::STREAM_CREATE_FAILED:
-            return "流创建失败";
-        case ErrorCode::END_OF_STREAM:
-            return "流结束";
-        case ErrorCode::THREAD_ERROR:
-            return "线程错误";
-        case ErrorCode::QUEUE_FULL:
-            return "队列满";
-        case ErrorCode::SYNC_ERROR:
-            return "同步错误";
-        case ErrorCode::ALREADY_EXISTS:
-            return "已存在";
-        case ErrorCode::NOT_FOUND:
-            return "未找到";
-        case ErrorCode::TIMEOUT:
-            return "超时";
-        case ErrorCode::COPY_FAILED:
-            return "拷贝失败";
-        case ErrorCode::PROCESSING_ERROR:
-            return "处理错误";
-        case ErrorCode::INITIALIZATION_FAILED:
-            return "初始化失败";
-        case ErrorCode::OPERATION_FAILED:
-            return "操作失败";
-        case ErrorCode::UNKNOWN_ERROR:
-            return "未知错误";
-        default:
-            return "未知错误码: " + std::to_string(static_cast<int>(error));
-    }
-}
-
-} // namespace codec
-} // namespace av

+ 0 - 344
AV/code/codec/codec_abstract_codec.h

@@ -1,344 +0,0 @@
-#pragma once
-
-#include "../base/types.h"
-#include <memory>
-#include <functional>
-#include <vector>
-#include <string>
-#include <shared_mutex>
-#include <mutex>
-
-namespace av {
-namespace codec {
-
-/**
- * 编解码器状态
- */
-enum class CodecState {
-    IDLE,       // 空闲
-    OPENED,     // 已打开
-    RUNNING,    // 运行中
-    FLUSHING,   // 刷新中
-    CLOSED,     // 已关闭
-    ERROR       // 错误
-};
-
-/**
- * 编解码器类型
- */
-enum class CodecType {
-    ENCODER,    // 编码器
-    DECODER     // 解码器
-};
-
-/**
- * 抽象编解码器基类
- * 提供编解码器的通用接口和状态管理
- */
-class AbstractCodec {
-public:
-    AbstractCodec(MediaType mediaType, CodecType codecType);
-    virtual ~AbstractCodec();
-
-    // 禁止拷贝
-    AbstractCodec(const AbstractCodec&) = delete;
-    AbstractCodec& operator=(const AbstractCodec&) = delete;
-
-    /**
-     * 打开编解码器
-     * @param params 编解码参数
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode open(const CodecParams& params) = 0;
-
-    /**
-     * 关闭编解码器
-     */
-    virtual void close() = 0;
-
-    /**
-     * 刷新编解码器缓冲区
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode flush() = 0;
-
-    /**
-     * 重置编解码器
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode reset();
-
-    // 状态查询(线程安全)
-    CodecState getState() const { 
-        std::shared_lock<std::shared_mutex> lock(stateMutex_);
-        return state_; 
-    }
-    MediaType getMediaType() const { return mediaType_; }
-    CodecType getCodecType() const { return codecType_; }
-    bool isOpened() const { 
-        std::shared_lock<std::shared_mutex> lock(stateMutex_);
-        return state_ == CodecState::OPENED || state_ == CodecState::RUNNING; 
-    }
-    bool isRunning() const { 
-        std::shared_lock<std::shared_mutex> lock(stateMutex_);
-        return state_ == CodecState::RUNNING; 
-    }
-    bool hasError() const { 
-        std::shared_lock<std::shared_mutex> lock(stateMutex_);
-        return state_ == CodecState::ERROR; 
-    }
-
-    // 参数获取
-    const CodecParams& getParams() const { return params_; }
-
-    // 统计信息
-    struct Statistics {
-        uint64_t processedFrames = 0;   // 处理的帧数
-        uint64_t droppedFrames = 0;     // 丢弃的帧数
-        uint64_t errorCount = 0;        // 错误次数
-        double avgProcessTime = 0.0;    // 平均处理时间(ms)
-        uint64_t totalBytes = 0;        // 总字节数
-    };
-    
-    Statistics getStatistics() const { 
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        return stats_; 
-    }
-    void resetStatistics();
-
-    // 回调函数设置
-    using ErrorCallback = std::function<void(ErrorCode error, const std::string& message)>;
-    void setErrorCallback(ErrorCallback callback) { errorCallback_ = std::move(callback); }
-    
-    // 错误码转换工具
-    static ErrorCode convertFFmpegError(int ffmpegError);
-    static std::string getErrorDescription(ErrorCode error);
-
-protected:
-    // RAII资源管理包装器
-    template<typename T, typename Deleter>
-    class ResourceGuard {
-    private:
-        T* resource_;
-        Deleter deleter_;
-        bool released_;
-        
-    public:
-        explicit ResourceGuard(T* resource, Deleter deleter) 
-            : resource_(resource), deleter_(deleter), released_(false) {}
-            
-        ~ResourceGuard() {
-            if (!released_ && resource_) {
-                deleter_(resource_);
-            }
-        }
-        
-        // 禁止拷贝
-        ResourceGuard(const ResourceGuard&) = delete;
-        ResourceGuard& operator=(const ResourceGuard&) = delete;
-        
-        // 允许移动
-        ResourceGuard(ResourceGuard&& other) noexcept
-            : resource_(other.resource_), deleter_(std::move(other.deleter_)), released_(other.released_) {
-            other.released_ = true;
-        }
-        
-        ResourceGuard& operator=(ResourceGuard&& other) noexcept {
-            if (this != &other) {
-                if (!released_ && resource_) {
-                    deleter_(resource_);
-                }
-                resource_ = other.resource_;
-                deleter_ = std::move(other.deleter_);
-                released_ = other.released_;
-                other.released_ = true;
-            }
-            return *this;
-        }
-        
-        T* get() const { return resource_; }
-        T* release() { released_ = true; return resource_; }
-        void reset(T* newResource = nullptr) {
-            if (!released_ && resource_) {
-                deleter_(resource_);
-            }
-            resource_ = newResource;
-            released_ = false;
-        }
-        
-        explicit operator bool() const { return resource_ != nullptr && !released_; }
-    };
-    
-    // 状态管理助手,确保状态一致性
-    class StateGuard {
-    private:
-        AbstractCodec* codec_;
-        CodecState originalState_;
-        CodecState targetState_;
-        bool committed_;
-        
-    public:
-        StateGuard(AbstractCodec* codec, CodecState targetState)
-            : codec_(codec), targetState_(targetState), committed_(false) {
-            if (codec_) {
-                originalState_ = codec_->getState();
-                codec_->setState(targetState_);
-            }
-        }
-        
-        ~StateGuard() {
-            if (!committed_ && codec_) {
-                codec_->setState(originalState_);
-            }
-        }
-        
-        void commit() { committed_ = true; }
-        
-        // 禁止拷贝和移动
-        StateGuard(const StateGuard&) = delete;
-        StateGuard& operator=(const StateGuard&) = delete;
-        StateGuard(StateGuard&&) = delete;
-        StateGuard& operator=(StateGuard&&) = delete;
-    };
-    
-    /**
-     * 设置编解码器状态
-     */
-    void setState(CodecState state);
-
-    /**
-     * 报告错误
-     */
-    void reportError(ErrorCode error, const std::string& message = "");
-
-    /**
-     * 更新统计信息
-     */
-    void updateStats(bool success, double processTime, uint64_t bytes = 0);
-
-    /**
-     * 验证参数有效性
-     */
-    virtual bool validateParams(const CodecParams& params) = 0;
-
-protected:
-    MediaType mediaType_;           // 媒体类型
-    CodecType codecType_;           // 编解码器类型
-    CodecState state_;              // 当前状态
-    CodecParams params_;            // 编解码参数
-    Statistics stats_;              // 统计信息
-    ErrorCallback errorCallback_;   // 错误回调
-    
-    // FFmpeg相关
-    AVCodecContextPtr codecCtx_;    // 编解码上下文
-    const AVCodec* codec_;          // 编解码器
-    
-    // 线程安全机制
-    mutable std::shared_mutex stateMutex_;    // 状态读写锁
-    mutable std::mutex statsMutex_;           // 统计信息锁
-    mutable std::mutex resourceMutex_;        // 资源操作锁
-};
-
-/**
- * 抽象编码器基类
- */
-class AbstractEncoder : public AbstractCodec {
-public:
-    AbstractEncoder(MediaType mediaType) : AbstractCodec(mediaType, CodecType::ENCODER) {}
-    virtual ~AbstractEncoder() = default;
-
-    /**
-     * 编码一帧数据
-     * @param frame 输入帧
-     * @param packets 输出包列表
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode encode(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) = 0;
-
-    /**
-     * 结束编码(刷新缓冲区)
-     * @param packets 输出包列表
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode finishEncode(std::vector<AVPacketPtr>& packets) = 0;
-
-    // 编码器特有的回调
-    using FrameCallback = std::function<void(const AVFramePtr& frame)>;
-    using PacketCallback = std::function<void(const AVPacketPtr& packet)>;
-    
-    void setFrameCallback(FrameCallback callback) { frameCallback_ = std::move(callback); }
-    void setPacketCallback(PacketCallback callback) { packetCallback_ = std::move(callback); }
-
-protected:
-    FrameCallback frameCallback_;   // 帧回调
-    PacketCallback packetCallback_; // 包回调
-};
-
-/**
- * 抽象解码器基类
- */
-class AbstractDecoder : public AbstractCodec {
-public:
-    AbstractDecoder(MediaType mediaType) : AbstractCodec(mediaType, CodecType::DECODER) {}
-    virtual ~AbstractDecoder() = default;
-
-    /**
-     * 解码一个包
-     * @param packet 输入包
-     * @param frames 输出帧列表
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) = 0;
-
-    /**
-     * 结束解码(刷新缓冲区)
-     * @param frames 输出帧列表
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode finishDecode(std::vector<AVFramePtr>& frames) = 0;
-
-    // 解码器特有的回调
-    using PacketCallback = std::function<void(const AVPacketPtr& packet)>;
-    using FrameCallback = std::function<void(const AVFramePtr& frame)>;
-    
-    void setPacketCallback(PacketCallback callback) { packetCallback_ = std::move(callback); }
-    void setFrameCallback(FrameCallback callback) { frameCallback_ = std::move(callback); }
-
-protected:
-    PacketCallback packetCallback_; // 包回调
-    FrameCallback frameCallback_;   // 帧回调
-};
-
-/**
- * 编解码器工厂类
- */
-class CodecFactory {
-public:
-    /**
-     * 创建编码器
-     */
-    static std::unique_ptr<AbstractEncoder> createEncoder(MediaType mediaType, const std::string& codecName);
-
-    /**
-     * 创建解码器
-     */
-    static std::unique_ptr<AbstractDecoder> createDecoder(MediaType mediaType, const std::string& codecName);
-
-    /**
-     * 获取支持的编码器列表
-     */
-    static std::vector<std::string> getSupportedEncoders(MediaType mediaType);
-
-    /**
-     * 获取支持的解码器列表
-     */
-    static std::vector<std::string> getSupportedDecoders(MediaType mediaType);
-
-    /**
-     * 检查编解码器是否支持
-     */
-    static bool isCodecSupported(const std::string& codecName, CodecType type, MediaType mediaType);
-};
-
-} // namespace codec
-} // namespace av

+ 0 - 597
AV/code/codec/codec_audio_decoder.cpp

@@ -1,597 +0,0 @@
-#include "codec_audio_decoder.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <algorithm>
-#include <sstream>
-#include <thread>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavutil/channel_layout.h>
-#include <libavutil/opt.h>
-#include <libswresample/swresample.h>
-}
-
-namespace av {
-namespace codec {
-
-// 静态成员初始化
-std::vector<std::string> AudioDecoder::supportedDecoders_;
-std::once_flag AudioDecoder::decodersInitFlag_;
-
-AudioDecoder::AudioDecoder() : AbstractDecoder(MediaType::AUDIO) {
-    AV_LOGGER_DEBUG("创建音频解码器");
-}
-
-AudioDecoder::~AudioDecoder() {
-    close();
-    AV_LOGGER_DEBUG("音频解码器已销毁");
-}
-
-ErrorCode AudioDecoder::initialize(const CodecParams& params) {
-    if (params.type != MediaType::AUDIO) {
-        AV_LOGGER_ERROR("参数类型不是音频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    audioParams_ = static_cast<const AudioDecoderParams&>(params);
-    
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    setState(CodecState::IDLE);
-    AV_LOGGER_INFOF("音频解码器初始化成功: {}", audioParams_.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioDecoder::open(const CodecParams& params) {
-    std::lock_guard<std::mutex> lock(decodeMutex_);
-    
-    // 如果提供了参数,先初始化
-    if (params.type != MediaType::UNKNOWN) {
-        ErrorCode initResult = initialize(params);
-        if (initResult != ErrorCode::SUCCESS) {
-            return initResult;
-        }
-    }
-    
-    if (state_ != CodecState::IDLE) {
-        AV_LOGGER_ERROR("解码器状态无效,无法打开");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = initDecoder();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    setState(CodecState::OPENED);
-    AV_LOGGER_INFOF("音频解码器已打开: {} ({}Hz, {}ch, {})", 
-                   audioParams_.codecName, 
-                   codecCtx_->sample_rate,
-                   codecCtx_->ch_layout.nb_channels,
-                   av_get_sample_fmt_name(codecCtx_->sample_fmt));
-    
-    return ErrorCode::SUCCESS;
-}
-
-void AudioDecoder::close() {
-    std::lock_guard<std::mutex> lock(decodeMutex_);
-    
-    if (state_ == CodecState::IDLE) {
-        return;
-    }
-    
-    // 清理重采样器
-    cleanupResampler();
-    
-    codecCtx_.reset();
-    codec_ = nullptr;
-    needResampling_ = false;
-    
-    setState(CodecState::IDLE);
-    AV_LOGGER_DEBUG("音频解码器已关闭");
-}
-
-ErrorCode AudioDecoder::flush() {
-    std::lock_guard<std::mutex> lock(decodeMutex_);
-    
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (codecCtx_) {
-        avcodec_flush_buffers(codecCtx_.get());
-    }
-    
-    // 重置重采样器
-    if (swrCtx_) {
-        swr_close(swrCtx_);
-        needResampling_ = false;
-    }
-    
-    setState(CodecState::OPENED);
-    AV_LOGGER_DEBUG("音频解码器已重置");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioDecoder::reset() {
-    return flush();
-}
-
-ErrorCode AudioDecoder::decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
-    // 状态检查(使用基类的线程安全方法)
-    if (!isOpened()) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 只在处理过程中锁定,缩小锁的粒度
-    std::lock_guard<std::mutex> processLock(decodeMutex_);
-    
-    // 使用StateGuard确保异常安全的状态管理
-    StateGuard stateGuard(this, CodecState::RUNNING);
-    
-    auto startTime = std::chrono::high_resolution_clock::now();
-    
-    ErrorCode result = decodeFrame(packet, frames);
-    
-    // 只有在成功时才提交状态变更
-    if (result == ErrorCode::SUCCESS) {
-        stateGuard.commit();
-    }
-    
-    auto endTime = std::chrono::high_resolution_clock::now();
-    double processTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
-    
-    int totalSamples = 0;
-    for (const auto& frame : frames) {
-        if (frame) {
-            totalSamples += frame->nb_samples;
-        }
-    }
-    
-    updateStats(result == ErrorCode::SUCCESS, processTime, 
-                packet ? packet->size : 0, totalSamples);
-    
-    if (frameCallback_) {
-        for (const auto& frame : frames) {
-            frameCallback_(frame);
-        }
-    }
-    
-    return result;
-}
-
-ErrorCode AudioDecoder::finishDecode(std::vector<AVFramePtr>& frames) {
-    return decode(nullptr, frames); // 发送空包来刷新解码器
-}
-
-bool AudioDecoder::validateParams(const CodecParams& params) {
-    if (params.type != MediaType::AUDIO) {
-        AV_LOGGER_ERROR("参数媒体类型不是音频");
-        return false;
-    }
-    
-    const auto& audioParams = static_cast<const AudioDecoderParams&>(params);
-    
-    if (audioParams.codecName.empty()) {
-        AV_LOGGER_ERROR("解码器名称为空");
-        return false;
-    }
-    
-    if (audioParams.sampleRate <= 0) {
-        AV_LOGGER_ERROR("采样率无效");
-        return false;
-    }
-    
-    if (audioParams.channels <= 0) {
-        AV_LOGGER_ERROR("声道数无效");
-        return false;
-    }
-    
-    return true;
-}
-
-
-
-ErrorCode AudioDecoder::initDecoder() {
-    // 查找解码器
-    codec_ = avcodec_find_decoder_by_name(audioParams_.codecName.c_str());
-    if (!codec_) {
-        AV_LOGGER_ERRORF("未找到解码器: {}", audioParams_.codecName);
-        return ErrorCode::CODEC_NOT_FOUND;
-    }
-    
-    if (codec_->type != AVMEDIA_TYPE_AUDIO) {
-        AV_LOGGER_ERROR("解码器类型不是音频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 创建解码上下文
-    codecCtx_ = makeAVCodecContext(codec_);
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("分配解码上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 设置解码器参数
-    ErrorCode result = setupDecoderParams();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 打开解码器前的详细日志
-    AV_LOGGER_INFOF("准备打开音频解码器: {}", audioParams_.codecName);
-    AV_LOGGER_INFOF("解码器参数: 采样率: {}, 声道: {}, 格式: {}, 线程数: {}", 
-                   codecCtx_->sample_rate,
-                   codecCtx_->ch_layout.nb_channels,
-                   av_get_sample_fmt_name(codecCtx_->sample_fmt),
-                   codecCtx_->thread_count);
-    
-    // 打开解码器
-    int ret = avcodec_open2(codecCtx_.get(), codec_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开音频解码器失败: {} (错误码: {})", 
-                        ffmpeg_utils::errorToString(ret), ret);
-        
-        // 详细错误分析
-        if (ret == AVERROR(EINVAL)) {
-            AV_LOGGER_ERROR("解码器参数无效 - 可能的原因:");
-            AV_LOGGER_ERROR("  1. 不支持的采样格式或参数组合");
-            AV_LOGGER_ERROR("  2. 采样率或声道数不支持");
-        } else if (ret == AVERROR(ENOMEM)) {
-            AV_LOGGER_ERROR("内存不足 - 无法分配解码器资源");
-        }
-        
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFOF("音频解码器打开成功: {}", audioParams_.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioDecoder::setupDecoderParams() {
-    // 设置线程数
-    if (audioParams_.threadCount > 0) {
-        codecCtx_->thread_count = audioParams_.threadCount;
-    } else {
-        codecCtx_->thread_count = std::thread::hardware_concurrency();
-    }
-    
-    // 设置采样率(如果指定)
-    if (audioParams_.sampleRate > 0) {
-        codecCtx_->sample_rate = audioParams_.sampleRate;
-    }
-    
-    // 设置声道数(如果指定)
-    if (audioParams_.channels > 0) {
-        av_channel_layout_default(&codecCtx_->ch_layout, audioParams_.channels);
-    }
-    
-    // 设置采样格式(如果指定)
-    if (audioParams_.sampleFormat != AV_SAMPLE_FMT_NONE) {
-        codecCtx_->sample_fmt = audioParams_.sampleFormat;
-    }
-    
-    // 低延迟设置
-    if (audioParams_.lowLatency) {
-        codecCtx_->flags |= AV_CODEC_FLAG_LOW_DELAY;
-        codecCtx_->flags2 |= AV_CODEC_FLAG2_FAST;
-    }
-    
-    // 针对特定解码器的优化设置
-    if (audioParams_.codecName == "aac") {
-        // AAC 特定设置
-        av_opt_set(codecCtx_->priv_data, "dual_mono_mode", "stereo", 0);
-    } else if (audioParams_.codecName == "mp3" || audioParams_.codecName == "mp3float") {
-        // MP3 特定设置
-        if (audioParams_.lowLatency) {
-            av_opt_set_int(codecCtx_->priv_data, "skip_frame", 0, 0);
-        }
-    } else if (audioParams_.codecName == "opus") {
-        // Opus 特定设置
-        if (audioParams_.lowLatency) {
-            av_opt_set_int(codecCtx_->priv_data, "apply_phase_inv", 0, 0);
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioDecoder::decodeFrame(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
-    // 发送包到解码器
-    int ret = avcodec_send_packet(codecCtx_.get(), packet ? packet.get() : nullptr);
-    if (ret < 0 && ret != AVERROR_EOF && ret != AVERROR(EAGAIN)) {
-        AV_LOGGER_ERRORF("发送包到音频解码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // AVERROR(EAGAIN) 表示解码器暂时无法接受更多输入,这是正常情况
-    if (ret == AVERROR(EAGAIN)) {
-        AV_LOGGER_DEBUGF("解码器暂时无法接受更多输入 (EAGAIN),继续接收帧");
-    }
-    
-    // 接收解码后的帧
-    return receiveFrames(frames);
-}
-
-ErrorCode AudioDecoder::receiveFrames(std::vector<AVFramePtr>& frames) {
-    while (true) {
-        AVFramePtr frame = makeAVFrame();
-        if (!frame) {
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        int ret = avcodec_receive_frame(codecCtx_.get(), frame.get());
-        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
-            break; // 需要更多输入或已结束
-        }
-        
-        if (ret < 0) {
-            ErrorCode error = AbstractCodec::convertFFmpegError(ret);
-            AV_LOGGER_ERRORF("接收音频解码帧失败: {} ({})", 
-                           AbstractCodec::getErrorDescription(error), 
-                           ffmpeg_utils::errorToString(ret));
-            return error;
-        }
-        
-        // 格式转换(如果需要)
-        auto convertedFrame = convertFrame(std::move(frame));
-        if (convertedFrame) {
-            frames.push_back(std::move(convertedFrame));
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr AudioDecoder::convertFrame(AVFramePtr frame) {
-    if (!frame) {
-        return nullptr;
-    }
-    
-    // 检查是否需要重采样
-    bool needConvert = (frame->format != audioParams_.sampleFormat) ||
-                      (frame->sample_rate != audioParams_.sampleRate) ||
-                      (frame->ch_layout.nb_channels != audioParams_.channels);
-    
-    if (!needConvert) {
-        return std::move(frame); // 格式已经匹配,直接返回
-    }
-    
-    // 设置重采样器
-    ErrorCode result = setupResampler(frame.get());
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("设置重采样器失败");
-        return nullptr;
-    }
-    
-    // 创建输出帧
-    AVFramePtr outFrame = makeAVFrame();
-    if (!outFrame) {
-        return nullptr;
-    }
-    
-    outFrame->format = audioParams_.sampleFormat;
-    outFrame->sample_rate = audioParams_.sampleRate;
-    av_channel_layout_default(&outFrame->ch_layout, audioParams_.channels);
-    
-    // 计算输出采样数
-    int outSamples = swr_get_out_samples(swrCtx_, frame->nb_samples);
-    outFrame->nb_samples = outSamples;
-    
-    // 分配输出缓冲区
-    if (av_frame_get_buffer(outFrame.get(), 0) < 0) {
-        AV_LOGGER_ERROR("分配音频输出缓冲区失败");
-        return nullptr;
-    }
-    
-    // 执行重采样
-    int convertedSamples = swr_convert(swrCtx_,
-                                      outFrame->data, outSamples,
-                                      (const uint8_t**)frame->data, frame->nb_samples);
-    
-    if (convertedSamples < 0) {
-        AV_LOGGER_ERRORF("音频重采样失败: {}", ffmpeg_utils::errorToString(convertedSamples));
-        return nullptr;
-    }
-    
-    outFrame->nb_samples = convertedSamples;
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(outFrame.get(), frame.get());
-    
-    return outFrame;
-}
-
-ErrorCode AudioDecoder::setupResampler(const AVFrame* inputFrame) {
-    if (!inputFrame) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 检查是否需要重新配置重采样器
-    bool needReconfigure = !swrCtx_ ||
-                          !needResampling_ ||
-                          (inputFrame->format != codecCtx_->sample_fmt) ||
-                          (inputFrame->sample_rate != codecCtx_->sample_rate) ||
-                          (inputFrame->ch_layout.nb_channels != codecCtx_->ch_layout.nb_channels);
-    
-    if (!needReconfigure) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 清理旧的重采样器
-    cleanupResampler();
-    
-    // 创建新的重采样器
-    swrCtx_ = swr_alloc();
-    if (!swrCtx_) {
-        AV_LOGGER_ERROR("分配重采样器失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 设置输入参数
-    av_opt_set_chlayout(swrCtx_, "in_chlayout", &inputFrame->ch_layout, 0);
-    av_opt_set_int(swrCtx_, "in_sample_rate", inputFrame->sample_rate, 0);
-    av_opt_set_sample_fmt(swrCtx_, "in_sample_fmt", static_cast<AVSampleFormat>(inputFrame->format), 0);
-    
-    // 设置输出参数
-    AVChannelLayout out_ch_layout;
-    av_channel_layout_default(&out_ch_layout, audioParams_.channels);
-    av_opt_set_chlayout(swrCtx_, "out_chlayout", &out_ch_layout, 0);
-    av_opt_set_int(swrCtx_, "out_sample_rate", audioParams_.sampleRate, 0);
-    av_opt_set_sample_fmt(swrCtx_, "out_sample_fmt", audioParams_.sampleFormat, 0);
-    
-    // 初始化重采样器
-    int ret = swr_init(swrCtx_);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("初始化重采样器失败: {}", ffmpeg_utils::errorToString(ret));
-        cleanupResampler();
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    needResampling_ = true;
-    
-    AV_LOGGER_INFOF("重采样器配置成功: {}Hz,{}ch,{} -> {}Hz,{}ch,{}",
-                   inputFrame->sample_rate, inputFrame->ch_layout.nb_channels, 
-                   av_get_sample_fmt_name(static_cast<AVSampleFormat>(inputFrame->format)),
-                   audioParams_.sampleRate, audioParams_.channels,
-                   av_get_sample_fmt_name(audioParams_.sampleFormat));
-    
-    return ErrorCode::SUCCESS;
-}
-
-void AudioDecoder::cleanupResampler() {
-    if (swrCtx_) {
-        swr_free(&swrCtx_);
-        swrCtx_ = nullptr;
-    }
-    needResampling_ = false;
-}
-
-void AudioDecoder::updateStats(bool success, double decodeTime, size_t dataSize, int samples) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (success) {
-        stats_.decodedFrames++;
-        stats_.totalSamples += samples;
-        stats_.totalBytes += dataSize;
-        stats_.totalDecodeTime += decodeTime;
-        
-        // 如果启用了重采样,更新重采样帧数
-        if (isResamplingEnabled()) {
-            stats_.resampledFrames++;
-        }
-        
-        // 更新平均解码时间
-        if (stats_.decodedFrames == 1) {
-            stats_.avgDecodeTime = decodeTime;
-        } else {
-            stats_.avgDecodeTime = stats_.totalDecodeTime / stats_.decodedFrames;
-        }
-    } else {
-        stats_.errorCount++;
-    }
-}
-
-AudioDecoder::DecoderStats AudioDecoder::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    return stats_;
-}
-
-void AudioDecoder::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = DecoderStats{};
-}
-
-std::string AudioDecoder::getDecoderName() const {
-    return audioParams_.codecName;
-}
-
-bool AudioDecoder::isResamplingEnabled() const {
-    return audioParams_.enableResampling && needResampling_;
-}
-
-std::vector<std::string> AudioDecoder::getSupportedDecoders() {
-    std::call_once(decodersInitFlag_, findUsableDecoders);
-    return supportedDecoders_;
-}
-
-bool AudioDecoder::isDecoderSupported(const std::string& codecName) {
-    auto decoders = getSupportedDecoders();
-    return std::find(decoders.begin(), decoders.end(), codecName) != decoders.end();
-}
-
-std::string AudioDecoder::getRecommendedDecoder(const std::string& codecName) {
-    auto decoders = getSupportedDecoders();
-    
-    if (!codecName.empty()) {
-        // 查找指定编解码格式的解码器
-        if (std::find(decoders.begin(), decoders.end(), codecName) != decoders.end()) {
-            return codecName;
-        }
-        
-        // 查找相关的解码器
-        for (const auto& decoder : decoders) {
-            if (decoder.find(codecName) != std::string::npos) {
-                return decoder;
-            }
-        }
-    }
-    
-    // 返回默认推荐的解码器
-    const char* preferredDecoders[] = {"aac", "mp3", "opus", "vorbis", "flac"};
-    for (const char* preferred : preferredDecoders) {
-        if (std::find(decoders.begin(), decoders.end(), preferred) != decoders.end()) {
-            return preferred;
-        }
-    }
-    
-    return decoders.empty() ? "" : decoders[0];
-}
-
-void AudioDecoder::findUsableDecoders() {
-    AV_LOGGER_INFO("查找可用的音频解码器...");
-    
-    // 测试所有音频解码器
-    for (const char* decoder : AUDIO_DECODERS) {
-        if (decoder && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::AUDIO)) {
-            supportedDecoders_.emplace_back(decoder);
-            AV_LOGGER_INFOF("找到音频解码器: {}", decoder);
-        }
-    }
-    
-    AV_LOGGER_INFOF("总共找到 {} 个可用的音频解码器", supportedDecoders_.size());
-}
-
-// AudioDecoderFactory 实现
-std::unique_ptr<AudioDecoder> AudioDecoder::AudioDecoderFactory::create(const std::string& codecName) {
-    auto decoder = std::make_unique<AudioDecoder>();
-    
-    if (!codecName.empty()) {
-        if (!CodecFactory::isCodecSupported(codecName, CodecType::DECODER, MediaType::AUDIO)) {
-            AV_LOGGER_ERRORF("不支持的音频解码器: {}", codecName);
-            return nullptr;
-        }
-    }
-    
-    return decoder;
-}
-
-std::unique_ptr<AudioDecoder> AudioDecoder::AudioDecoderFactory::createBest() {
-    std::string codecName = AudioDecoder::getRecommendedDecoder();
-    
-    if (codecName.empty()) {
-        AV_LOGGER_ERROR("未找到可用的音频解码器");
-        return nullptr;
-    }
-    
-    return create(codecName);
-}
-
-} // namespace codec
-} // namespace av

+ 0 - 208
AV/code/codec/codec_audio_decoder.h

@@ -1,208 +0,0 @@
-#ifndef AV_CODEC_AUDIO_DECODER_H
-#define AV_CODEC_AUDIO_DECODER_H
-
-#include "codec_abstract_codec.h"
-#include <vector>
-#include <string>
-#include <memory>
-#include <mutex>
-#include <functional>
-#include <chrono>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavutil/samplefmt.h>
-#include <libswresample/swresample.h>
-}
-
-namespace av {
-namespace codec {
-
-/**
- * 音频解码器参数
- */
-struct AudioDecoderParams : public CodecParams {
-    std::string codecName;          // 解码器名称 (如 "aac", "mp3", "opus")
-    int sampleRate = 44100;         // 采样率
-    int channels = 2;               // 声道数
-    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_S16; // 采样格式
-    int threadCount = 0;            // 线程数 (0=自动)
-    bool lowLatency = false;        // 低延迟模式
-    bool enableResampling = true;   // 启用重采样
-    
-    AudioDecoderParams() {
-        type = MediaType::AUDIO;
-    }
-};
-
-/**
- * 音频解码器类
- * 提供音频解码功能,支持多种音频格式
- */
-class AudioDecoder : public AbstractDecoder {
-public:
-    /**
-     * 解码统计信息
-     */
-    struct DecoderStats {
-        uint64_t decodedFrames = 0;     // 已解码帧数
-        uint64_t resampledFrames = 0;   // 重采样帧数
-        uint64_t totalSamples = 0;      // 总采样数
-        uint64_t totalBytes = 0;        // 总字节数
-        uint64_t errorCount = 0;        // 错误次数
-        double avgDecodeTime = 0.0;     // 平均解码时间(ms)
-        double totalDecodeTime = 0.0;   // 总解码时间(ms)
-    };
-    
-    /**
-     * 帧回调函数类型
-     */
-    using FrameCallback = std::function<void(const AVFramePtr&)>;
-    
-public:
-    AudioDecoder();
-    virtual ~AudioDecoder();
-    
-    // 基础接口实现
-    ErrorCode open(const CodecParams& params) override;
-    void close() override;
-    ErrorCode flush() override;
-    ErrorCode reset() override;
-    
-    // 初始化方法
-    ErrorCode initialize(const CodecParams& params);
-    
-    /**
-     * 解码音频包
-     * @param packet 输入音频包 (nullptr表示刷新解码器)
-     * @param frames 输出解码后的音频帧
-     * @return 错误码
-     */
-    ErrorCode decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) override;
-    
-    /**
-     * 完成解码,刷新解码器缓冲区
-     * @param frames 输出剩余的音频帧
-     * @return 错误码
-     */
-    ErrorCode finishDecode(std::vector<AVFramePtr>& frames) override;
-    
-    /**
-     * 设置帧回调函数
-     * @param callback 回调函数
-     */
-    void setFrameCallback(const FrameCallback& callback) { frameCallback_ = callback; }
-    
-    // 状态查询
-    std::string getDecoderName() const;
-    bool isResamplingEnabled() const;
-    DecoderStats getStats() const;
-    void resetStats();
-    
-    // 静态工具方法
-    static std::vector<std::string> getSupportedDecoders();
-    static bool isDecoderSupported(const std::string& codecName);
-    static std::string getRecommendedDecoder(const std::string& codecName = "");
-    
-    /**
-     * 音频解码器工厂
-     */
-    class AudioDecoderFactory {
-    public:
-        /**
-         * 创建指定解码器
-         * @param codecName 解码器名称
-         * @return 解码器实例
-         */
-        static std::unique_ptr<AudioDecoder> create(const std::string& codecName);
-        
-        /**
-         * 创建最佳解码器
-         * @return 解码器实例
-         */
-        static std::unique_ptr<AudioDecoder> createBest();
-    };
-    
-protected:
-    bool validateParams(const CodecParams& params) override;
-    
-private:
-    // 内部实现方法
-    ErrorCode initDecoder();
-    ErrorCode setupDecoderParams();
-    ErrorCode decodeFrame(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames);
-    ErrorCode receiveFrames(std::vector<AVFramePtr>& frames);
-    
-    // 音频格式转换
-    AVFramePtr convertFrame(AVFramePtr frame);
-    ErrorCode setupResampler(const AVFrame* inputFrame);
-    void cleanupResampler();
-    
-    // 统计更新
-    void updateStats(bool success, double decodeTime, size_t dataSize, int samples);
-    
-    // 静态方法
-    static void findUsableDecoders();
-    
-private:
-    // 解码器相关
-    const AVCodec* codec_ = nullptr;
-    AVCodecContextPtr codecCtx_;
-    AudioDecoderParams audioParams_;
-    
-    // 音频重采样
-    SwrContext* swrCtx_ = nullptr;
-    bool needResampling_ = false;
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    DecoderStats stats_;
-    
-    // 回调函数
-    FrameCallback frameCallback_;
-    
-    // 线程安全
-    std::mutex decodeMutex_;
-    
-    // 静态成员
-    static std::vector<std::string> supportedDecoders_;
-    static std::once_flag decodersInitFlag_;
-    
-public:
-    // 支持的音频解码器列表
-    static constexpr const char* AUDIO_DECODERS[] = {
-        // 常用音频解码器
-        "aac",
-        "mp3",
-        "mp3float",
-        "opus",
-        "vorbis",
-        "flac",
-        "pcm_s16le",
-        "pcm_s24le",
-        "pcm_s32le",
-        "pcm_f32le",
-        "pcm_f64le",
-        "ac3",
-        "eac3",
-        "dts",
-        "truehd",
-        "wmav1",
-        "wmav2",
-        "wmalossless",
-        "wmapro",
-        "g722",
-        "g726",
-        "adpcm_ima_wav",
-        "adpcm_ms",
-        "alac",
-        "ape",
-        "wavpack",
-        nullptr
-    };
-};
-
-} // namespace codec
-} // namespace av
-
-#endif // AV_CODEC_AUDIO_DECODER_H

+ 0 - 1223
AV/code/codec/codec_audio_encoder.cpp

@@ -1,1223 +0,0 @@
-#include "codec_audio_encoder.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <algorithm>
-#include <chrono>
-
-namespace av {
-namespace codec {
-
-// 静态成员初始化
-std::vector<std::string> AudioEncoder::supportedEncoders_;
-std::once_flag AudioEncoder::encodersInitFlag_;
-
-// AudioResampler 实现
-AudioResampler::AudioResampler()
-    : swrCtx_(nullptr)
-    , srcFormat_(AV_SAMPLE_FMT_NONE)
-    , dstFormat_(AV_SAMPLE_FMT_NONE)
-    , srcSampleRate_(0)
-    , dstSampleRate_(0)
-    , dstFrameSize_(0)
-    , initialized_(false) {
-    av_channel_layout_default(&srcLayout_, 0);
-    av_channel_layout_default(&dstLayout_, 0);
-}
-
-AudioResampler::~AudioResampler() {
-    if (swrCtx_) {
-        swr_free(&swrCtx_);
-    }
-    av_channel_layout_uninit(&srcLayout_);
-    av_channel_layout_uninit(&dstLayout_);
-}
-
-bool AudioResampler::init(const AVChannelLayout& srcLayout, AVSampleFormat srcFormat, int srcSampleRate,
-                         const AVChannelLayout& dstLayout, AVSampleFormat dstFormat, int dstSampleRate) {
-    if (swrCtx_) {
-        swr_free(&swrCtx_);
-    }
-    
-    av_channel_layout_uninit(&srcLayout_);
-    av_channel_layout_uninit(&dstLayout_);
-    
-    // 复制声道布局
-    if (av_channel_layout_copy(&srcLayout_, &srcLayout) < 0 ||
-        av_channel_layout_copy(&dstLayout_, &dstLayout) < 0) {
-        AV_LOGGER_ERROR("复制声道布局失败");
-        return false;
-    }
-    
-    srcFormat_ = srcFormat;
-    dstFormat_ = dstFormat;
-    srcSampleRate_ = srcSampleRate;
-    dstSampleRate_ = dstSampleRate;
-    
-    // 创建重采样上下文
-    int ret = swr_alloc_set_opts2(&swrCtx_,
-                                  &dstLayout_, dstFormat_, dstSampleRate_,
-                                  &srcLayout_, srcFormat_, srcSampleRate_,
-                                  0, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("创建重采样上下文失败: {}", ffmpeg_utils::errorToString(ret));
-        return false;
-    }
-    
-    // 初始化重采样器
-    ret = swr_init(swrCtx_);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("初始化重采样器失败: {}", ffmpeg_utils::errorToString(ret));
-        swr_free(&swrCtx_);
-        return false;
-    }
-    
-    // 计算输出帧大小
-    dstFrameSize_ = av_rescale_rnd(1024, dstSampleRate_, srcSampleRate_, AV_ROUND_UP);
-    
-    // 创建输出帧
-    dstFrame_ = makeAVFrame();
-    if (!dstFrame_) {
-        AV_LOGGER_ERROR("分配输出帧失败");
-        return false;
-    }
-    
-    dstFrame_->format = dstFormat_;
-    dstFrame_->sample_rate = dstSampleRate_;
-    av_channel_layout_copy(&dstFrame_->ch_layout, &dstLayout_);
-    dstFrame_->nb_samples = dstFrameSize_;
-    
-    ret = av_frame_get_buffer(dstFrame_.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("分配帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-        return false;
-    }
-    
-    initialized_ = true;
-    return true;
-}
-
-AVFramePtr AudioResampler::resample(const AVFramePtr& srcFrame) {
-    if (!initialized_) {
-        AV_LOGGER_ERROR("AudioResampler not initialized");
-        return nullptr;
-    }
-    
-    if (!srcFrame) {
-        AV_LOGGER_ERROR("Source frame is null");
-        return nullptr;
-    }
-    
-    if (!swrCtx_) {
-        AV_LOGGER_ERROR("SwrContext is null");
-        return nullptr;
-    }
-    
-    if (!dstFrame_) {
-        AV_LOGGER_ERROR("Destination frame is null");
-        return nullptr;
-    }
-    
-    // 验证源帧的有效性
-    if (srcFrame->nb_samples <= 0) {
-        AV_LOGGER_ERRORF("Invalid source frame samples: {}", srcFrame->nb_samples);
-        return nullptr;
-    }
-    
-    if (!srcFrame->data[0]) {
-        AV_LOGGER_ERROR("Source frame data is null");
-        return nullptr;
-    }
-    
-    // 计算输出样本数
-    int dstSamples = av_rescale_rnd(srcFrame->nb_samples, dstSampleRate_, srcSampleRate_, AV_ROUND_UP);
-    if (dstSamples <= 0) {
-        AV_LOGGER_ERRORF("Invalid calculated destination samples: {}", dstSamples);
-        return nullptr;
-    }
-    
-    AV_LOGGER_DEBUGF("Resampling: src_samples={}, dst_samples={}, src_rate={}, dst_rate={}", 
-                     srcFrame->nb_samples, dstSamples, srcSampleRate_, dstSampleRate_);
-    
-    // 确保输出帧有足够的空间
-    if (dstFrame_->nb_samples < dstSamples) {
-        AV_LOGGER_DEBUGF("Reallocating destination frame buffer: {} -> {}", dstFrame_->nb_samples, dstSamples);
-        
-        av_frame_unref(dstFrame_.get());
-        
-        // 重新设置帧格式信息(av_frame_unref 会清除这些信息)
-        dstFrame_->format = dstFormat_;
-        dstFrame_->sample_rate = dstSampleRate_;
-        int ret = av_channel_layout_copy(&dstFrame_->ch_layout, &dstLayout_);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("复制声道布局失败: {}", ffmpeg_utils::errorToString(ret));
-            return nullptr;
-        }
-        dstFrame_->nb_samples = dstSamples;
-        
-        ret = av_frame_get_buffer(dstFrame_.get(), 0);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("重新分配帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-            return nullptr;
-        }
-        
-        AV_LOGGER_DEBUGF("Frame buffer reallocated successfully: format={}, rate={}, channels={}, samples={}", 
-                         dstFrame_->format, dstFrame_->sample_rate, dstFrame_->ch_layout.nb_channels, dstFrame_->nb_samples);
-    }
-    
-    // 验证目标帧的有效性
-    if (!dstFrame_->data[0]) {
-        AV_LOGGER_ERROR("Destination frame data is null after allocation");
-        return nullptr;
-    }
-    
-    // 执行重采样
-    AV_LOGGER_DEBUG("Executing swr_convert...");
-    int convertedSamples = swr_convert(swrCtx_,
-                                       dstFrame_->data, dstSamples,
-                                       const_cast<const uint8_t**>(srcFrame->data), srcFrame->nb_samples);
-    
-    if (convertedSamples < 0) {
-        AV_LOGGER_ERRORF("音频重采样失败: {}", ffmpeg_utils::errorToString(convertedSamples));
-        return nullptr;
-    }
-    
-    dstFrame_->nb_samples = convertedSamples;
-    
-    // 创建输出帧的副本
-    AVFramePtr outputFrame = makeAVFrame();
-    if (!outputFrame) {
-        AV_LOGGER_ERROR("分配输出帧失败");
-        return nullptr;
-    }
-    
-    // 复制重采样后的数据
-    outputFrame->format = dstFrame_->format;
-    outputFrame->sample_rate = dstFrame_->sample_rate;
-    av_channel_layout_copy(&outputFrame->ch_layout, &dstFrame_->ch_layout);
-    outputFrame->nb_samples = convertedSamples;
-    
-    int ret = av_frame_get_buffer(outputFrame.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("分配输出帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 复制音频数据
-    ret = av_frame_copy(outputFrame.get(), dstFrame_.get());
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("复制帧数据失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(outputFrame.get(), srcFrame.get());
-    
-    // 调整时间戳
-    if (srcFrame->pts != AV_NOPTS_VALUE) {
-        outputFrame->pts = av_rescale_q(srcFrame->pts, {1, srcSampleRate_}, {1, dstSampleRate_});
-    }
-    
-    return outputFrame;
-}
-
-std::vector<AVFramePtr> AudioResampler::flush() {
-    std::vector<AVFramePtr> frames;
-    
-    if (!initialized_) {
-        return frames;
-    }
-    
-    while (true) {
-        AVFramePtr frame = makeAVFrame();
-        if (!frame) {
-            break;
-        }
-        
-        frame->format = dstFormat_;
-        frame->sample_rate = dstSampleRate_;
-        av_channel_layout_copy(&frame->ch_layout, &dstLayout_);
-        frame->nb_samples = dstFrameSize_;
-        
-        int ret = av_frame_get_buffer(frame.get(), 0);
-        if (ret < 0) {
-            break;
-        }
-        
-        int convertedSamples = swr_convert(swrCtx_,
-                                           frame->data, dstFrameSize_,
-                                           nullptr, 0);
-        
-        if (convertedSamples <= 0) {
-            break;
-        }
-        
-        frame->nb_samples = convertedSamples;
-        frames.push_back(std::move(frame));
-    }
-    
-    return frames;
-}
-
-// AudioEncoder 实现
-AudioEncoder::AudioEncoder()
-    : AbstractEncoder(MediaType::AUDIO), bufferedSamples_(0) {
-    AV_LOGGER_DEBUG("创建音频编码器");
-}
-
-AudioEncoder::~AudioEncoder() {
-    close();
-    AV_LOGGER_DEBUG("音频编码器已销毁");
-}
-
-ErrorCode AudioEncoder::open(const CodecParams& params) {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ != CodecState::IDLE && state_ != CodecState::CLOSED) {
-        AV_LOGGER_WARNING("编码器已打开,先关闭再重新打开");
-        close();
-    }
-    
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    audioParams_ = static_cast<const AudioEncoderParams&>(params);
-    params_ = params;
-    
-    ErrorCode result = initEncoder();
-    if (result != ErrorCode::SUCCESS) {
-        close();
-        return result;
-    }
-    
-    // 初始化帧缓冲区
-    result = initFrameBuffer();
-    if (result != ErrorCode::SUCCESS) {
-        close();
-        return result;
-    }
-    
-    setState(CodecState::OPENED);
-    AV_LOGGER_INFOF("音频编码器已打开: {} ({}Hz, {}ch, {}kbps)", 
-                 audioParams_.codecName, audioParams_.sampleRate, 
-                 audioParams_.channels, audioParams_.bitRate / 1000);
-    
-    return ErrorCode::SUCCESS;
-}
-
-void AudioEncoder::close() {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ == CodecState::CLOSED || state_ == CodecState::IDLE) {
-        return;
-    }
-    
-    // 清理资源
-    resampler_.reset();
-    convertedFrame_.reset();
-    
-    // 清理帧缓冲区
-    clearBuffer();
-    
-    // 清理编解码上下文
-    codecCtx_.reset();
-    codec_ = nullptr;
-    
-    setState(CodecState::CLOSED);
-    AV_LOGGER_DEBUG("音频编码器已关闭");
-}
-
-ErrorCode AudioEncoder::flush() {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    setState(CodecState::FLUSHING);
-    
-    // 发送空帧来刷新编码器
-    int ret = avcodec_send_frame(codecCtx_.get(), nullptr);
-    if (ret < 0 && ret != AVERROR_EOF) {
-        AV_LOGGER_ERRORF("刷新编码器失败: {}", ffmpeg_utils::errorToString(ret));
-        reportError(static_cast<ErrorCode>(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    setState(CodecState::OPENED);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioEncoder::encode(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) {
-    // 状态检查(使用基类的线程安全方法)
-    if (!isOpened()) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 只在处理过程中锁定,缩小锁的粒度
-    std::lock_guard<std::mutex> processLock(encodeMutex_);
-    
-    // 使用StateGuard确保异常安全的状态管理
-    StateGuard stateGuard(this, CodecState::RUNNING);
-    
-    auto startTime = std::chrono::high_resolution_clock::now();
-    
-    ErrorCode result = ErrorCode::SUCCESS;
-    
-    if (frame) {
-        // 检查是否需要使用帧缓冲机制
-        if (codecCtx_->frame_size > 0 && frame->nb_samples != codecCtx_->frame_size) {
-            AV_LOGGER_DEBUGF("使用帧缓冲机制处理大帧: 输入={}, 期望={}", 
-                           frame->nb_samples, codecCtx_->frame_size);
-            
-            // 将大帧添加到缓冲区
-            result = addToBuffer(frame);
-            if (result != ErrorCode::SUCCESS) {
-                return result;
-            }
-            
-            // 从缓冲区提取标准大小的帧进行编码
-            while (bufferedSamples_ >= codecCtx_->frame_size) {
-                AVFramePtr smallFrame = extractFrameFromBuffer();
-                if (smallFrame) {
-                    // 使用move语义明确转移所有权,避免潜在的双重释放
-                    ErrorCode encodeResult = encodeFrame(std::move(smallFrame), packets);
-                    if (encodeResult != ErrorCode::SUCCESS) {
-                        result = encodeResult;
-                        break;
-                    }
-                } else {
-                    break;
-                }
-            }
-        } else {
-            // 直接编码(帧大小匹配)
-            result = encodeFrame(frame, packets);
-        }
-    } else {
-        // 编码空帧(用于刷新)
-        result = encodeFrame(frame, packets);
-    }
-    
-    auto endTime = std::chrono::high_resolution_clock::now();
-    double processTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
-    
-    updateStats(result == ErrorCode::SUCCESS, processTime, 
-                frame ? frame->nb_samples * audioParams_.channels * av_get_bytes_per_sample(static_cast<AVSampleFormat>(frame->format)) : 0);
-    
-    if (frameCallback_ && frame) {
-        frameCallback_(frame);
-    }
-    
-    for (const auto& packet : packets) {
-        if (packetCallback_) {
-            packetCallback_(packet);
-        }
-    }
-    
-    // 只有在成功时才提交状态变更
-    if (result == ErrorCode::SUCCESS) {
-        stateGuard.commit();
-    }
-    
-    return result;
-}
-
-ErrorCode AudioEncoder::finishEncode(std::vector<AVPacketPtr>& packets) {
-    // 不需要额外的锁,因为调用者已经持有锁
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 发送空帧来刷新编码器
-    int ret = avcodec_send_frame(codecCtx_.get(), nullptr);
-    if (ret < 0 && ret != AVERROR_EOF) {
-        AV_LOGGER_ERRORF("刷新编码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 接收剩余的包
-    return receivePackets(packets);
-}
-
-bool AudioEncoder::validateParams(const CodecParams& params) {
-    if (params.type != MediaType::AUDIO) {
-        AV_LOGGER_ERROR("参数媒体类型不是音频");
-        return false;
-    }
-    
-    const auto& audioParams = static_cast<const AudioEncoderParams&>(params);
-    
-    if (audioParams.sampleRate <= 0) {
-        AV_LOGGER_ERROR("采样率无效");
-        return false;
-    }
-    
-    if (audioParams.channels <= 0) {
-        AV_LOGGER_ERROR("声道数无效");
-        return false;
-    }
-    
-    if (audioParams.bitRate <= 0) {
-        AV_LOGGER_ERROR("比特率无效");
-        return false;
-    }
-    
-    if (audioParams.codecName.empty()) {
-        AV_LOGGER_ERROR("编码器名称为空");
-        return false;
-    }
-    
-    return true;
-}
-
-ErrorCode AudioEncoder::initEncoder() {
-    // 查找编码器
-    codec_ = avcodec_find_encoder_by_name(audioParams_.codecName.c_str());
-    if (!codec_) {
-        AV_LOGGER_ERRORF("未找到编码器: {}", audioParams_.codecName);
-        return ErrorCode::CODEC_NOT_FOUND;
-    }
-    
-    if (codec_->type != AVMEDIA_TYPE_AUDIO) {
-        AV_LOGGER_ERROR("编码器类型不是音频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 创建编码上下文
-    codecCtx_ = makeAVCodecContext(codec_);
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("分配编码上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 设置编码器参数
-    ErrorCode result = setupEncoderParams();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 打开编码器
-    int ret = avcodec_open2(codecCtx_.get(), codec_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开编码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioEncoder::setupEncoderParams() {
-    codecCtx_->bit_rate = audioParams_.bitRate;
-    codecCtx_->sample_rate = audioParams_.sampleRate;
-    
-    // 设置声道布局
-    ErrorCode result = setupChannelLayout();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 设置采样格式
-    codecCtx_->sample_fmt = getBestSampleFormat();
-    
-    // 设置帧大小
-    if (codec_->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE) {
-        codecCtx_->frame_size = audioParams_.frameSize;
-    }
-    
-    // 设置配置文件
-    if (!audioParams_.profile.empty()) {
-        av_opt_set(codecCtx_->priv_data, "profile", audioParams_.profile.c_str(), 0);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioEncoder::setupChannelLayout() {
-    // 设置声道布局
-    if (audioParams_.channelLayout.nb_channels > 0) {
-        av_channel_layout_copy(&codecCtx_->ch_layout, &audioParams_.channelLayout);
-    } else {
-        // 根据声道数设置默认布局
-        av_channel_layout_default(&codecCtx_->ch_layout, audioParams_.channels);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr AudioEncoder::convertFrame(const AVFramePtr& frame) {
-    if (!frame) {
-        return nullptr;
-    }
-    
-    // 检查是否需要转换
-    bool needConvert = false;
-    
-    if (frame->format != codecCtx_->sample_fmt) {
-        needConvert = true;
-    }
-    
-    if (frame->sample_rate != codecCtx_->sample_rate) {
-        needConvert = true;
-    }
-    
-    if (av_channel_layout_compare(&frame->ch_layout, &codecCtx_->ch_layout) != 0) {
-        needConvert = true;
-    }
-    
-    if (!needConvert) {
-        // 创建一个新的独立帧副本,避免引用计数问题
-        AVFramePtr resultFrame = makeAVFrame();
-        if (!resultFrame) {
-            return nullptr;
-        }
-        
-        // 手动复制帧属性
-        resultFrame->format = frame->format;
-        resultFrame->sample_rate = frame->sample_rate;
-        resultFrame->nb_samples = frame->nb_samples;
-        resultFrame->pts = frame->pts;
-        
-        int ret = av_channel_layout_copy(&resultFrame->ch_layout, &frame->ch_layout);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("复制声道布局失败: {}", ffmpeg_utils::errorToString(ret));
-            return nullptr;
-        }
-        
-        // 分配新的数据缓冲区
-        ret = av_frame_get_buffer(resultFrame.get(), 0);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("分配帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-            return nullptr;
-        }
-        
-        // 复制音频数据
-        ret = av_frame_copy(resultFrame.get(), frame.get());
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("复制帧数据失败: {}", ffmpeg_utils::errorToString(ret));
-            return nullptr;
-        }
-        
-        // 复制帧属性
-        ret = av_frame_copy_props(resultFrame.get(), frame.get());
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("复制帧属性失败: {}", ffmpeg_utils::errorToString(ret));
-            return nullptr;
-        }
-        
-        // 最终验证创建的帧副本
-        if (!isValidFrame(resultFrame)) {
-            AV_LOGGER_ERROR("创建的帧副本无效");
-            return nullptr;
-        }
-        
-        AV_LOGGER_DEBUG("创建了不需要转换的帧的独立副本");
-        return resultFrame;
-    }
-    
-    // 创建重采样器
-    if (!resampler_) {
-        resampler_ = std::make_unique<AudioResampler>();
-        if (!resampler_->init(frame->ch_layout, static_cast<AVSampleFormat>(frame->format), frame->sample_rate,
-                             codecCtx_->ch_layout, codecCtx_->sample_fmt, codecCtx_->sample_rate)) {
-            AV_LOGGER_ERROR("初始化音频重采样器失败");
-            resampler_.reset(); // 确保失败时清理
-            return nullptr;
-        }
-        AV_LOGGER_INFO("音频重采样器初始化成功");
-    }
-    
-    // 双重检查重采样器状态
-    if (!resampler_) {
-        AV_LOGGER_ERROR("重采样器为空");
-        return nullptr;
-    }
-    
-    AV_LOGGER_DEBUGF("开始重采样: format={}, rate={}, channels={}", 
-                     frame->format, frame->sample_rate, frame->ch_layout.nb_channels);
-    
-    return resampler_->resample(frame);
-}
-
-ErrorCode AudioEncoder::encodeFrame(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) {
-    AVFramePtr processedFrame;
-    
-    if (frame) {
-        // 格式转换
-        processedFrame = convertFrame(frame);
-        if (!processedFrame) {
-            AV_LOGGER_ERROR("音频帧格式转换失败");
-            return ErrorCode::CONVERSION_FAILED;
-        }
-        
-        // 调试:输出帧信息
-        AV_LOGGER_DEBUGF("重采样输出帧信息: format={}, rate={}, channels={}, samples={}", 
-                         processedFrame->format, processedFrame->sample_rate, 
-                         processedFrame->ch_layout.nb_channels, processedFrame->nb_samples);
-        
-        // 调试:输出编码器期望的信息
-        AV_LOGGER_DEBUGF("编码器期望格式: format={}, rate={}, channels={}, frame_size={}", 
-                         codecCtx_->sample_fmt, codecCtx_->sample_rate, 
-                         codecCtx_->ch_layout.nb_channels, codecCtx_->frame_size);
-        
-        // 检查帧大小是否匹配
-        if (codecCtx_->frame_size > 0 && processedFrame->nb_samples != codecCtx_->frame_size) {
-            AV_LOGGER_ERRORF("帧大小不匹配: 输入={}, 编码器期望={}", 
-                           processedFrame->nb_samples, codecCtx_->frame_size);
-        }
-        
-        // 检查格式是否匹配
-        if (processedFrame->format != codecCtx_->sample_fmt) {
-            AV_LOGGER_ERRORF("采样格式不匹配: 输入={}, 编码器期望={}", 
-                           processedFrame->format, codecCtx_->sample_fmt);
-        }
-        
-        // 检查采样率是否匹配
-        if (processedFrame->sample_rate != codecCtx_->sample_rate) {
-            AV_LOGGER_ERRORF("采样率不匹配: 输入={}, 编码器期望={}", 
-                           processedFrame->sample_rate, codecCtx_->sample_rate);
-        }
-        
-        // 检查声道数是否匹配
-        if (processedFrame->ch_layout.nb_channels != codecCtx_->ch_layout.nb_channels) {
-            AV_LOGGER_ERRORF("声道数不匹配: 输入={}, 编码器期望={}", 
-                           processedFrame->ch_layout.nb_channels, codecCtx_->ch_layout.nb_channels);
-        }
-    }
-    
-    // 验证processedFrame的有效性
-    if (processedFrame) {
-        // 检查帧数据指针的有效性
-        if (!processedFrame->data || !processedFrame->data[0]) {
-            AV_LOGGER_ERROR("处理后的帧数据指针无效");
-            return ErrorCode::INVALID_PARAMS;
-        }
-        
-        // 检查帧大小是否合理
-        if (processedFrame->nb_samples <= 0 || processedFrame->nb_samples > 100000) {
-            AV_LOGGER_ERRORF("处理后的帧大小异常: {}", processedFrame->nb_samples);
-            return ErrorCode::INVALID_PARAMS;
-        }
-        
-        // 检查声道数是否合理
-        if (processedFrame->ch_layout.nb_channels <= 0 || processedFrame->ch_layout.nb_channels > 32) {
-            AV_LOGGER_ERRORF("处理后的帧声道数异常: {}", processedFrame->ch_layout.nb_channels);
-            return ErrorCode::INVALID_PARAMS;
-        }
-        
-        AV_LOGGER_DEBUGF("即将发送帧到编码器: samples={}, format={}, rate={}, channels={}, data_ptr={}", 
-                         processedFrame->nb_samples, processedFrame->format, 
-                         processedFrame->sample_rate, processedFrame->ch_layout.nb_channels,
-                         static_cast<void*>(processedFrame->data[0]));
-    } else {
-        AV_LOGGER_DEBUG("发送空帧到编码器(flush)");
-    }
-    
-    // 最后一次验证:确保编码器和帧都有效
-    if (!codecCtx_ || !codecCtx_.get()) {
-        AV_LOGGER_ERROR("编码器上下文无效");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (processedFrame) {
-        // 最终检查:确保帧完全有效
-        if (!isValidFrame(processedFrame)) {
-            AV_LOGGER_ERROR("检测到无效的帧数据");
-            return ErrorCode::INVALID_PARAMS;
-        }
-        AV_LOGGER_DEBUG("最终验证通过,帧数据有效");
-    }
-    
-    // 发送帧到编码器
-    AV_LOGGER_DEBUG("开始调用avcodec_send_frame...");
-    
-    // 在调用FFmpeg之前进行最后的安全检查
-    if (processedFrame) {
-        // 确保AVFrame结构本身的完整性
-        if (processedFrame.get() == nullptr) {
-            AV_LOGGER_ERROR("严重错误:processedFrame智能指针为null");
-            return ErrorCode::INVALID_PARAMS;
-        }
-        
-        // 检查AVFrame内部指针是否被破坏
-        if (!processedFrame->data || !processedFrame->data[0]) {
-            AV_LOGGER_ERROR("严重错误:即将发送的帧数据指针为空");
-            return ErrorCode::INVALID_PARAMS;
-        }
-        
-        AV_LOGGER_DEBUGF("FFmpeg调用前最终检查通过: frame_ptr={}, data_ptr={}", 
-                         static_cast<void*>(processedFrame.get()),
-                         static_cast<void*>(processedFrame->data[0]));
-    }
-    
-    int ret = avcodec_send_frame(codecCtx_.get(), processedFrame ? processedFrame.get() : nullptr);
-    AV_LOGGER_DEBUGF("avcodec_send_frame返回: {}", ret);
-    
-    if (ret < 0) {
-        ErrorCode error = AbstractCodec::convertFFmpegError(ret);
-        AV_LOGGER_ERRORF("发送帧到编码器失败: {} ({})", 
-                       AbstractCodec::getErrorDescription(error), 
-                       ffmpeg_utils::errorToString(ret));
-        if (processedFrame) {
-            AV_LOGGER_ERRORF("失败的帧信息: samples={}, format={}, rate={}, channels={}", 
-                           processedFrame->nb_samples, processedFrame->format,
-                           processedFrame->sample_rate, processedFrame->ch_layout.nb_channels);
-        }
-        return error;
-    }
-    
-    // 接收编码后的包
-    return receivePackets(packets);
-}
-
-ErrorCode AudioEncoder::receivePackets(std::vector<AVPacketPtr>& packets) {
-    while (true) {
-        AVPacketPtr packet = makeAVPacket();
-        if (!packet) {
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        int ret = avcodec_receive_packet(codecCtx_.get(), packet.get());
-        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
-            break; // 需要更多输入或已结束
-        }
-        
-        if (ret < 0) {
-            ErrorCode error = AbstractCodec::convertFFmpegError(ret);
-            AV_LOGGER_ERRORF("接收编码包失败: {} ({})", 
-                           AbstractCodec::getErrorDescription(error), 
-                           ffmpeg_utils::errorToString(ret));
-            return error;
-        }
-        
-        packets.push_back(std::move(packet));
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVSampleFormat AudioEncoder::getBestSampleFormat() const {
-    if (!codec_->sample_fmts) {
-        return audioParams_.sampleFormat;
-    }
-    
-    // 首先尝试使用指定的格式
-    for (const AVSampleFormat* fmt = codec_->sample_fmts; *fmt != AV_SAMPLE_FMT_NONE; fmt++) {
-        if (*fmt == audioParams_.sampleFormat) {
-            return *fmt;
-        }
-    }
-    
-    // 返回第一个支持的格式
-    return codec_->sample_fmts[0];
-}
-
-int AudioEncoder::getBestSampleRate() const {
-    if (!codec_->supported_samplerates) {
-        return audioParams_.sampleRate;
-    }
-    
-    // 首先尝试使用指定的采样率
-    for (const int* rate = codec_->supported_samplerates; *rate != 0; rate++) {
-        if (*rate == audioParams_.sampleRate) {
-            return *rate;
-        }
-    }
-    
-    // 返回第一个支持的采样率
-    return codec_->supported_samplerates[0];
-}
-
-std::vector<std::string> AudioEncoder::getSupportedEncoders() {
-    std::call_once(encodersInitFlag_, findSupportedEncoders);
-    return supportedEncoders_;
-}
-
-std::string AudioEncoder::getRecommendedEncoder() {
-    auto encoders = getSupportedEncoders();
-    
-    // 优先选择高质量编码器
-    const char* preferredEncoders[] = {"libfdk_aac", "aac", "libopus", "opus", "libmp3lame", "mp3"};
-    
-    for (const char* encoder : preferredEncoders) {
-        if (std::find(encoders.begin(), encoders.end(), encoder) != encoders.end()) {
-            return encoder;
-        }
-    }
-    
-    return encoders.empty() ? "" : encoders[0];
-}
-
-bool AudioEncoder::isSampleFormatSupported(const std::string& codecName, AVSampleFormat format) {
-    const AVCodec* codec = avcodec_find_encoder_by_name(codecName.c_str());
-    if (!codec || !codec->sample_fmts) {
-        return false;
-    }
-    
-    for (const AVSampleFormat* fmt = codec->sample_fmts; *fmt != AV_SAMPLE_FMT_NONE; fmt++) {
-        if (*fmt == format) {
-            return true;
-        }
-    }
-    
-    return false;
-}
-
-bool AudioEncoder::isSampleRateSupported(const std::string& codecName, int sampleRate) {
-    const AVCodec* codec = avcodec_find_encoder_by_name(codecName.c_str());
-    if (!codec) {
-        return false;
-    }
-    
-    if (!codec->supported_samplerates) {
-        return true; // 支持所有采样率
-    }
-    
-    for (const int* rate = codec->supported_samplerates; *rate != 0; rate++) {
-        if (*rate == sampleRate) {
-            return true;
-        }
-    }
-    
-    return false;
-}
-
-bool AudioEncoder::isChannelLayoutSupported(const std::string& codecName, const AVChannelLayout& layout) {
-    const AVCodec* codec = avcodec_find_encoder_by_name(codecName.c_str());
-    if (!codec) {
-        return false;
-    }
-    
-    if (!codec->ch_layouts) {
-        return true; // 支持所有声道布局
-    }
-    
-    for (const AVChannelLayout* ch_layout = codec->ch_layouts; ch_layout->nb_channels != 0; ch_layout++) {
-        if (av_channel_layout_compare(ch_layout, &layout) == 0) {
-            return true;
-        }
-    }
-    
-    return false;
-}
-
-void AudioEncoder::findSupportedEncoders() {
-    AV_LOGGER_INFO("查找可用的音频编码器...");
-    
-    for (const char* encoder : AUDIO_ENCODERS) {
-        if (CodecFactory::isCodecSupported(encoder, CodecType::ENCODER, MediaType::AUDIO)) {
-            supportedEncoders_.emplace_back(encoder);
-            AV_LOGGER_INFOF("找到音频编码器: {}", encoder);
-        }
-    }
-    
-    AV_LOGGER_INFOF("总共找到 {} 个可用的音频编码器", supportedEncoders_.size());
-}
-
-// 帧缓冲和拆分方法实现
-ErrorCode AudioEncoder::initFrameBuffer() {
-    if (!codecCtx_ || codecCtx_->frame_size <= 0) {
-        return ErrorCode::SUCCESS; // 不需要缓冲区
-    }
-    
-    // 初始化临时帧
-    tempFrame_ = makeAVFrame();
-    if (!tempFrame_) {
-        AV_LOGGER_ERROR("分配临时帧失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 设置临时帧格式
-    tempFrame_->format = codecCtx_->sample_fmt;
-    tempFrame_->sample_rate = codecCtx_->sample_rate;
-    av_channel_layout_copy(&tempFrame_->ch_layout, &codecCtx_->ch_layout);
-    tempFrame_->nb_samples = codecCtx_->frame_size;
-    
-    // 分配临时帧缓冲区
-    int ret = av_frame_get_buffer(tempFrame_.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("分配临时帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 计算缓冲区大小(支持最大帧大小的数据)
-    int bytesPerSample = av_get_bytes_per_sample(codecCtx_->sample_fmt);
-    int maxBufferSize = codecCtx_->frame_size * codecCtx_->ch_layout.nb_channels * bytesPerSample * 100; // 支持100倍大小
-    frameBuffer_.reserve(maxBufferSize);
-    
-    bufferedSamples_ = 0;
-    
-    AV_LOGGER_DEBUGF("帧缓冲初始化完成: frame_size={}, channels={}, format={}, buffer_capacity={}", 
-                     codecCtx_->frame_size, codecCtx_->ch_layout.nb_channels, codecCtx_->sample_fmt, maxBufferSize);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioEncoder::addToBuffer(const AVFramePtr& frame) {
-    if (!frame || !frame->data[0]) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 计算数据大小
-    int bytesPerSample = av_get_bytes_per_sample(static_cast<AVSampleFormat>(frame->format));
-    int channels = frame->ch_layout.nb_channels;
-    int frameDataSize = frame->nb_samples * channels * bytesPerSample;
-    
-    AV_LOGGER_DEBUGF("添加到缓冲区: samples={}, bytes={}, buffered_samples={}", 
-                     frame->nb_samples, frameDataSize, bufferedSamples_);
-    
-    // 检查缓冲区容量
-    if (frameBuffer_.size() + frameDataSize > frameBuffer_.capacity()) {
-        AV_LOGGER_ERROR("缓冲区容量不足");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 将音频数据添加到缓冲区
-    // 注意:这里假设音频格式是交错的(interleaved),对于平面(planar)格式需要特殊处理
-    if (av_sample_fmt_is_planar(static_cast<AVSampleFormat>(frame->format))) {
-        AV_LOGGER_ERROR("暂不支持平面音频格式的缓冲处理");
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    const uint8_t* srcData = frame->data[0];
-    frameBuffer_.insert(frameBuffer_.end(), srcData, srcData + frameDataSize);
-    bufferedSamples_ += frame->nb_samples;
-    
-    AV_LOGGER_DEBUGF("缓冲区更新: total_samples={}, buffer_size={}", 
-                     bufferedSamples_, frameBuffer_.size());
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr AudioEncoder::extractFrameFromBuffer() {
-    if (!tempFrame_ || bufferedSamples_ < codecCtx_->frame_size) {
-        return nullptr;
-    }
-    
-    int bytesPerSample = av_get_bytes_per_sample(codecCtx_->sample_fmt);
-    int channels = codecCtx_->ch_layout.nb_channels;
-    int frameDataSize = codecCtx_->frame_size * channels * bytesPerSample;
-    
-    if (frameBuffer_.size() < frameDataSize) {
-        AV_LOGGER_ERROR("缓冲区数据不足");
-        return nullptr;
-    }
-    
-    // 创建输出帧(手动设置格式信息)
-    AVFramePtr outputFrame = makeAVFrame();
-    if (!outputFrame) {
-        return nullptr;
-    }
-    
-    // 手动设置帧格式信息(避免使用av_frame_ref导致缓冲区共享)
-    outputFrame->format = codecCtx_->sample_fmt;
-    outputFrame->sample_rate = codecCtx_->sample_rate;
-    int ret = av_channel_layout_copy(&outputFrame->ch_layout, &codecCtx_->ch_layout);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("复制声道布局失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    outputFrame->nb_samples = codecCtx_->frame_size;
-    
-    // 分配新的缓冲区
-    ret = av_frame_get_buffer(outputFrame.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("分配输出帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 验证分配的缓冲区是否有效
-    if (!outputFrame->data || !outputFrame->data[0]) {
-        AV_LOGGER_ERROR("分配的帧缓冲区无效");
-        return nullptr;
-    }
-    
-    AV_LOGGER_DEBUGF("成功分配帧缓冲区: format={}, samples={}, channels={}, data_ptr={}", 
-                     outputFrame->format, outputFrame->nb_samples, 
-                     outputFrame->ch_layout.nb_channels, static_cast<void*>(outputFrame->data[0]));
-    
-    // 安全检查:确保数据足够
-    if (frameBuffer_.size() < frameDataSize || !outputFrame->data[0]) {
-        AV_LOGGER_ERROR("数据复制前检查失败");
-        return nullptr;
-    }
-    
-    // 复制数据
-    AV_LOGGER_DEBUGF("准备复制音频数据: src_ptr={}, dst_ptr={}, size={}", 
-                     static_cast<const void*>(frameBuffer_.data()),
-                     static_cast<void*>(outputFrame->data[0]),
-                     frameDataSize);
-    
-    // 验证源和目标指针的有效性
-    if (!frameBuffer_.data() || !outputFrame->data[0]) {
-        AV_LOGGER_ERROR("内存复制:源或目标指针无效");
-        return nullptr;
-    }
-    
-    memcpy(outputFrame->data[0], frameBuffer_.data(), frameDataSize);
-    
-    AV_LOGGER_DEBUG("音频数据复制完成");
-    
-    // 设置时间戳(简化处理)
-    outputFrame->pts = AV_NOPTS_VALUE;
-    
-    // 最终验证帧的完整性
-    if (!isValidFrame(outputFrame)) {
-        AV_LOGGER_ERROR("提取的帧无效,丢弃");
-        return nullptr;
-    }
-    
-    // 安全检查:确保缓冲区操作安全
-    if (frameDataSize > frameBuffer_.size()) {
-        AV_LOGGER_ERROR("缓冲区数据不足,无法移除");
-        return nullptr;
-    }
-    
-    // 从缓冲区移除已使用的数据
-    frameBuffer_.erase(frameBuffer_.begin(), frameBuffer_.begin() + frameDataSize);
-    bufferedSamples_ -= codecCtx_->frame_size;
-    
-    AV_LOGGER_DEBUGF("从缓冲区提取帧: samples={}, remaining_samples={}, remaining_bytes={}", 
-                     codecCtx_->frame_size, bufferedSamples_, frameBuffer_.size());
-    
-    // 再次验证帧的有效性(防御性编程)
-    if (!outputFrame->data[0]) {
-        AV_LOGGER_ERROR("严重错误:帧数据在返回前变为空指针");
-        return nullptr;
-    }
-    
-    return outputFrame;
-}
-
-void AudioEncoder::clearBuffer() {
-    frameBuffer_.clear();
-    bufferedSamples_ = 0;
-    tempFrame_.reset();
-    AV_LOGGER_DEBUG("帧缓冲区已清除");
-}
-
-// AudioEncoderFactory 实现
-std::unique_ptr<AudioEncoder> AudioEncoderFactory::create(const std::string& codecName) {
-    auto encoder = std::make_unique<AudioEncoder>();
-    
-    if (!codecName.empty()) {
-        if (!CodecFactory::isCodecSupported(codecName, CodecType::ENCODER, MediaType::AUDIO)) {
-            AV_LOGGER_ERRORF("不支持的编码器: {}", codecName);
-            return nullptr;
-        }
-    }
-    
-    return encoder;
-}
-
-std::unique_ptr<AudioEncoder> AudioEncoderFactory::createBest() {
-    std::string codecName = AudioEncoder::getRecommendedEncoder();
-    
-    if (codecName.empty()) {
-        AV_LOGGER_ERROR("未找到可用的音频编码器");
-        return nullptr;
-    }
-    
-    return create(codecName);
-}
-
-std::unique_ptr<AudioEncoder> AudioEncoderFactory::createLossless() {
-    auto encoders = AudioEncoder::getSupportedEncoders();
-    
-    // 优先选择无损编码器
-    const char* losslessEncoders[] = {"flac", "pcm_s24le", "pcm_s16le"};
-    
-    for (const char* encoder : losslessEncoders) {
-        if (std::find(encoders.begin(), encoders.end(), encoder) != encoders.end()) {
-            return create(encoder);
-        }
-    }
-    
-    AV_LOGGER_WARNING("未找到无损音频编码器,使用默认编码器");
-    return createBest();
-}
-
-// 帧验证工具实现
-bool AudioEncoder::isValidFrame(const AVFramePtr& frame) {
-    return isValidFramePointer(frame.get());
-}
-
-bool AudioEncoder::isValidFramePointer(const AVFrame* frame) {
-    if (!frame) {
-        return false;
-    }
-    
-    // 检查基本属性
-    if (frame->nb_samples <= 0) {
-        AV_LOGGER_ERROR("帧样本数无效");
-        return false;
-    }
-    
-    if (frame->format < 0) {
-        AV_LOGGER_ERROR("帧格式无效");
-        return false;
-    }
-    
-    if (frame->sample_rate <= 0) {
-        AV_LOGGER_ERROR("帧采样率无效");
-        return false;
-    }
-    
-    if (frame->ch_layout.nb_channels <= 0) {
-        AV_LOGGER_ERROR("帧声道数无效");
-        return false;
-    }
-    
-    // 检查数据指针
-    if (!frame->data[0]) {
-        AV_LOGGER_ERROR("帧数据指针为空");
-        return false;
-    }
-    
-    // 通用的指针有效性检查
-    uintptr_t ptr = reinterpret_cast<uintptr_t>(frame->data[0]);
-    
-    // 检查常见的无效指针模式
-    if (ptr == 0) {
-        AV_LOGGER_ERROR("帧数据指针为NULL");
-        return false;
-    }
-    
-    if (ptr == UINTPTR_MAX || ptr == (UINTPTR_MAX - 1)) {
-        AV_LOGGER_ERRORF("帧数据指针为无效值: 0x{:x}", ptr);
-        return false;
-    }
-    
-    // 检查是否在合理的地址范围内(避免空指针附近的地址)
-    if (ptr < 0x1000) {
-        AV_LOGGER_ERRORF("帧数据指针在低地址空间: 0x{:x}", ptr);
-        return false;
-    }
-    
-    // 在64位系统上,检查是否在用户空间范围内
-    #if defined(_WIN64) || defined(__x86_64__) || defined(__aarch64__)
-    if (ptr > 0x7FFFFFFFFFFF) {  // 用户空间上限
-        AV_LOGGER_ERRORF("帧数据指针超出用户空间: 0x{:x}", ptr);
-        return false;
-    }
-    #endif
-    
-    // 检查linesize是否合理
-    if (frame->linesize[0] <= 0) {
-        AV_LOGGER_ERROR("帧linesize无效");
-        return false;
-    }
-    
-    // 对于音频,检查数据大小是否合理
-    int expected_size = frame->nb_samples * frame->ch_layout.nb_channels * 
-                       av_get_bytes_per_sample(static_cast<AVSampleFormat>(frame->format));
-    if (expected_size <= 0 || expected_size > 100 * 1024 * 1024) { // 100MB上限
-        AV_LOGGER_ERRORF("帧数据大小不合理: {} bytes", expected_size);
-        return false;
-    }
-    
-    return true;
-}
-
-} // namespace codec
-} // namespace av

+ 0 - 213
AV/code/codec/codec_audio_encoder.h

@@ -1,213 +0,0 @@
-#pragma once
-
-#include "codec_abstract_codec.h"
-#include "../base/media_common.h"
-#include <mutex>
-#include <memory>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavutil/channel_layout.h>
-#include <libavutil/opt.h>
-#include <libavformat/avformat.h>
-#include <libswresample/swresample.h>
-}
-
-namespace av {
-namespace codec {
-
-/**
- * 音频编码器参数
- */
-struct AudioEncoderParams : public CodecParams {
-    int bitRate = 128000;                           // 比特率 (bps)
-    int sampleRate = 44100;                         // 采样率
-    int channels = 2;                               // 声道数
-    AVChannelLayout channelLayout = AV_CHANNEL_LAYOUT_STEREO; // 声道布局
-    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_FLTP; // 采样格式
-    int frameSize = 1024;                           // 帧大小
-    std::string profile = "";                       // 编码配置文件
-    
-    AudioEncoderParams() {
-        type = MediaType::AUDIO;
-        codecName = "aac";  // 默认使用AAC编码器
-    }
-};
-
-/**
- * 音频重采样器
- */
-class AudioResampler {
-public:
-    AudioResampler();
-    ~AudioResampler();
-    
-    /**
-     * 初始化重采样器
-     */
-    bool init(const AVChannelLayout& srcLayout, AVSampleFormat srcFormat, int srcSampleRate,
-              const AVChannelLayout& dstLayout, AVSampleFormat dstFormat, int dstSampleRate);
-    
-    /**
-     * 重采样音频帧
-     */
-    AVFramePtr resample(const AVFramePtr& srcFrame);
-    
-    /**
-     * 刷新重采样器缓冲区
-     */
-    std::vector<AVFramePtr> flush();
-    
-    /**
-     * 获取输出帧大小
-     */
-    int getOutputFrameSize() const { return dstFrameSize_; }
-    
-private:
-    struct SwrContext* swrCtx_;
-    AVChannelLayout srcLayout_;
-    AVChannelLayout dstLayout_;
-    AVSampleFormat srcFormat_;
-    AVSampleFormat dstFormat_;
-    int srcSampleRate_;
-    int dstSampleRate_;
-    int dstFrameSize_;
-    AVFramePtr dstFrame_;
-    bool initialized_;
-};
-
-/**
- * 音频编码器实现
- */
-class AudioEncoder : public AbstractEncoder {
-public:
-    AudioEncoder();
-    ~AudioEncoder() override;
-
-    // AbstractCodec 接口实现
-    ErrorCode open(const CodecParams& params) override;
-    void close() override;
-    ErrorCode flush() override;
-
-    // AbstractEncoder 接口实现
-    ErrorCode encode(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) override;
-    ErrorCode finishEncode(std::vector<AVPacketPtr>& packets) override;
-
-    // 音频编码器特有功能
-    const AudioEncoderParams& getAudioParams() const { return audioParams_; }
-    
-    // 获取支持的编码器列表
-    static std::vector<std::string> getSupportedEncoders();
-    
-    // 获取推荐的编码器
-    static std::string getRecommendedEncoder();
-    
-    // 检查编码器是否支持指定的采样格式
-    static bool isSampleFormatSupported(const std::string& codecName, AVSampleFormat format);
-    
-    // 检查编码器是否支持指定的采样率
-    static bool isSampleRateSupported(const std::string& codecName, int sampleRate);
-    
-    // 帧验证工具
-    static bool isValidFrame(const AVFramePtr& frame);
-    static bool isValidFramePointer(const AVFrame* frame);
-    
-    // 检查编码器是否支持指定的声道布局
-    static bool isChannelLayoutSupported(const std::string& codecName, const AVChannelLayout& layout);
-
-protected:
-    bool validateParams(const CodecParams& params) override;
-
-private:
-    // 初始化编码器
-    ErrorCode initEncoder();
-    
-    // 设置编码器参数
-    ErrorCode setupEncoderParams();
-    
-    // 设置声道布局
-    ErrorCode setupChannelLayout();
-    
-    // 转换音频帧格式
-    AVFramePtr convertFrame(const AVFramePtr& frame);
-    
-    // 帧缓冲和拆分相关方法
-    ErrorCode initFrameBuffer();
-    ErrorCode addToBuffer(const AVFramePtr& frame);
-    AVFramePtr extractFrameFromBuffer();
-    void clearBuffer();
-    
-    // 编码单个帧
-    ErrorCode encodeFrame(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets);
-    
-    // 接收编码后的包
-    ErrorCode receivePackets(std::vector<AVPacketPtr>& packets);
-    
-    // 获取编码器支持的最佳采样格式
-    AVSampleFormat getBestSampleFormat() const;
-    
-    // 获取编码器支持的最佳采样率
-    int getBestSampleRate() const;
-    
-    // 查找可用的编码器
-    static void findSupportedEncoders();
-
-private:
-    AudioEncoderParams audioParams_;        // 音频编码参数
-    
-    // 音频重采样
-    std::unique_ptr<AudioResampler> resampler_;
-    AVFramePtr convertedFrame_;             // 转换后的帧
-    
-    // 帧缓冲机制(用于处理大帧拆分)
-    std::vector<uint8_t> frameBuffer_;      // 音频数据缓冲区
-    int bufferedSamples_;                   // 缓冲区中的样本数
-    AVFramePtr tempFrame_;                  // 临时帧(用于拆分)
-    
-    // 线程安全
-    std::mutex encodeMutex_;
-    
-    // 支持的编码器列表
-    static std::vector<std::string> supportedEncoders_;
-    static std::once_flag encodersInitFlag_;
-    
-    // 常用音频编码器
-    static constexpr const char* AUDIO_ENCODERS[] = {
-        "aac",
-        "libfdk_aac",
-        "mp3",
-        "libmp3lame",
-        "opus",
-        "libopus",
-        "vorbis",
-        "libvorbis",
-        "flac",
-        "pcm_s16le",
-        "pcm_s24le",
-        "pcm_s32le",
-    };
-};
-
-/**
- * 音频编码器工厂
- */
-class AudioEncoderFactory {
-public:
-    /**
-     * 创建音频编码器
-     */
-    static std::unique_ptr<AudioEncoder> create(const std::string& codecName = "");
-    
-    /**
-     * 创建最佳音频编码器(自动选择)
-     */
-    static std::unique_ptr<AudioEncoder> createBest();
-    
-    /**
-     * 创建无损音频编码器
-     */
-    static std::unique_ptr<AudioEncoder> createLossless();
-};
-
-} // namespace codec
-} // namespace av

+ 0 - 687
AV/code/codec/codec_video_decoder.cpp

@@ -1,687 +0,0 @@
-#include "codec_video_decoder.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <algorithm>
-#include <sstream>
-#include <thread>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavutil/hwcontext.h>
-#include <libavutil/pixdesc.h>
-#include <libavutil/opt.h>
-#include <libswscale/swscale.h>
-}
-
-namespace av {
-namespace codec {
-
-// 静态成员初始化
-std::vector<std::string> VideoDecoder::supportedDecoders_;
-std::once_flag VideoDecoder::decodersInitFlag_;
-
-VideoDecoder::VideoDecoder() : AbstractDecoder(MediaType::VIDEO) {
-    AV_LOGGER_DEBUG("创建视频解码器");
-}
-
-VideoDecoder::~VideoDecoder() {
-    close();
-    AV_LOGGER_DEBUG("视频解码器已销毁");
-}
-
-ErrorCode VideoDecoder::initialize(const CodecParams& params) {
-    if (params.type != MediaType::VIDEO) {
-        AV_LOGGER_ERROR("参数类型不是视频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    videoParams_ = static_cast<const VideoDecoderParams&>(params);
-    
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    setState(CodecState::IDLE);
-    AV_LOGGER_INFOF("视频解码器初始化成功: {}", videoParams_.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoDecoder::setStreamParameters(const AVCodecParameters* codecpar) {
-    if (!codecpar) {
-        AV_LOGGER_ERROR("流参数为空");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
-        AV_LOGGER_ERROR("流类型不是视频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 保存流参数以便后续使用
-    streamCodecpar_ = codecpar;
-    
-    AV_LOGGER_INFOF("设置流参数: 编解码器ID={}, 尺寸={}x{}, 格式={}", 
-                   static_cast<int>(codecpar->codec_id),
-                   codecpar->width, codecpar->height, 
-                   static_cast<int>(codecpar->format));
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoDecoder::open(const CodecParams& params) {
-    std::lock_guard<std::mutex> lock(decodeMutex_);
-    
-    // 如果提供了参数,先初始化
-    if (params.type != MediaType::UNKNOWN) {
-        ErrorCode initResult = initialize(params);
-        if (initResult != ErrorCode::SUCCESS) {
-            return initResult;
-        }
-    }
-    
-    if (state_ != CodecState::IDLE) {
-        AV_LOGGER_ERROR("解码器状态无效,无法打开");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = initDecoder();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    setState(CodecState::OPENED);
-    AV_LOGGER_INFOF("视频解码器已打开: {} ({}x{})", 
-                   videoParams_.codecName, 
-                   codecCtx_->width, codecCtx_->height);
-    
-    return ErrorCode::SUCCESS;
-}
-
-void VideoDecoder::close() {
-    std::lock_guard<std::mutex> lock(decodeMutex_);
-    
-    if (state_ == CodecState::IDLE) {
-        return;
-    }
-    
-    // 清理硬件资源
-    if (hwDeviceCtx_) {
-        av_buffer_unref(&hwDeviceCtx_);
-        hwDeviceCtx_ = nullptr;
-    }
-    
-    hwFrame_.reset();
-    codecCtx_.reset();
-    codec_ = nullptr;
-    isHardwareDecoder_ = false;
-    
-    setState(CodecState::IDLE);
-    AV_LOGGER_DEBUG("视频解码器已关闭");
-}
-
-ErrorCode VideoDecoder::flush() {
-    std::lock_guard<std::mutex> lock(decodeMutex_);
-    
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (codecCtx_) {
-        avcodec_flush_buffers(codecCtx_.get());
-        
-        // 视频解码器flush完成,解码器状态已重置
-        AV_LOGGER_DEBUG("视频解码器缓冲区已清空");
-    }
-    
-    setState(CodecState::OPENED);
-    AV_LOGGER_DEBUG("视频解码器已重置");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoDecoder::reset() {
-    return flush();
-}
-
-ErrorCode VideoDecoder::decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
-    // 状态检查(使用基类的线程安全方法)
-    if (!isOpened()) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 只在处理过程中锁定,缩小锁的粒度
-    std::lock_guard<std::mutex> processLock(decodeMutex_);
-    
-    setState(CodecState::RUNNING);
-    
-    auto startTime = std::chrono::high_resolution_clock::now();
-    
-    ErrorCode result = decodeFrame(packet, frames);
-    
-    auto endTime = std::chrono::high_resolution_clock::now();
-    double processTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
-    
-    updateStats(result == ErrorCode::SUCCESS, processTime, 
-                packet ? packet->size : 0);
-    
-    if (frameCallback_) {
-        for (const auto& frame : frames) {
-            frameCallback_(frame);
-        }
-    }
-    
-    return result;
-}
-
-ErrorCode VideoDecoder::finishDecode(std::vector<AVFramePtr>& frames) {
-    return decode(nullptr, frames); // 发送空包来刷新解码器
-}
-
-bool VideoDecoder::validateParams(const CodecParams& params) {
-    if (params.type != MediaType::VIDEO) {
-        AV_LOGGER_ERROR("参数媒体类型不是视频");
-        return false;
-    }
-    
-    const auto& videoParams = static_cast<const VideoDecoderParams&>(params);
-    
-    if (videoParams.codecName.empty()) {
-        AV_LOGGER_ERROR("解码器名称为空");
-        return false;
-    }
-    
-    return true;
-}
-
-ErrorCode VideoDecoder::initDecoder() {
-    // 查找解码器
-    codec_ = avcodec_find_decoder_by_name(videoParams_.codecName.c_str());
-    if (!codec_) {
-        AV_LOGGER_ERRORF("未找到解码器: {}", videoParams_.codecName);
-        return ErrorCode::CODEC_NOT_FOUND;
-    }
-    
-    if (codec_->type != AVMEDIA_TYPE_VIDEO) {
-        AV_LOGGER_ERROR("解码器类型不是视频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 创建解码上下文
-    codecCtx_ = makeAVCodecContext(codec_);
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("分配解码上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 如果有流参数,复制到解码器上下文
-    if (streamCodecpar_) {
-        int ret = avcodec_parameters_to_context(codecCtx_.get(), streamCodecpar_);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("复制流参数到解码器上下文失败: {}", ffmpeg_utils::errorToString(ret));
-            return static_cast<ErrorCode>(ret);
-        }
-        AV_LOGGER_INFO("成功复制流参数到解码器上下文");
-    }
-    
-    // 设置硬件加速
-    if (videoParams_.hardwareAccel && isHardwareDecoder(videoParams_.codecName)) {
-        ErrorCode result = setupHardwareAcceleration();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_WARNING("硬件加速设置失败,回退到软件解码");
-            isHardwareDecoder_ = false;
-            
-            // 清理硬件资源
-            if (hwDeviceCtx_) {
-                av_buffer_unref(&hwDeviceCtx_);
-                hwDeviceCtx_ = nullptr;
-            }
-        }
-    }
-    
-    // 设置解码器参数
-    ErrorCode result = setupDecoderParams();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 打开解码器前的详细日志
-    AV_LOGGER_INFOF("准备打开解码器: {}", videoParams_.codecName);
-    AV_LOGGER_INFOF("解码器参数: 线程数: {}, 像素格式: {}", 
-                   codecCtx_->thread_count, 
-                   static_cast<int>(codecCtx_->pix_fmt));
-    
-    if (isHardwareDecoder_) {
-        AV_LOGGER_INFOF("硬件解码器状态: 设备上下文={}", 
-                       hwDeviceCtx_ ? "已创建" : "未创建");
-    }
-    
-    // 打开解码器
-    int ret = avcodec_open2(codecCtx_.get(), codec_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开解码器失败: {} (错误码: {})", 
-                        ffmpeg_utils::errorToString(ret), ret);
-        
-        // 详细错误分析
-        if (ret == AVERROR(EINVAL)) {
-            AV_LOGGER_ERROR("解码器参数无效 - 可能的原因:");
-            AV_LOGGER_ERROR("  1. 不支持的像素格式或参数组合");
-            AV_LOGGER_ERROR("  2. 硬件解码器参数配置错误");
-            AV_LOGGER_ERROR("  3. 硬件设备上下文与解码器不匹配");
-        } else if (ret == AVERROR(EBUSY)) {
-            AV_LOGGER_ERROR("硬件设备忙碌 - 可能被其他进程占用");
-        } else if (ret == AVERROR(ENOMEM)) {
-            AV_LOGGER_ERROR("内存不足 - 无法分配解码器资源");
-        }
-        
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFOF("解码器打开成功: {}", videoParams_.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoDecoder::setupDecoderParams() {
-    // 设置视频尺寸
-    if (videoParams_.width > 0 && videoParams_.height > 0) {
-        codecCtx_->width = videoParams_.width;
-        codecCtx_->height = videoParams_.height;
-        AV_LOGGER_INFOF("设置视频尺寸: {}x{}", videoParams_.width, videoParams_.height);
-    }
-    
-    // 设置像素格式(如果指定)
-    if (videoParams_.pixelFormat != AV_PIX_FMT_NONE) {
-        codecCtx_->pix_fmt = videoParams_.pixelFormat;
-        AV_LOGGER_INFOF("设置像素格式: {}", static_cast<int>(videoParams_.pixelFormat));
-    }
-    
-    // 设置线程数
-    if (videoParams_.threadCount > 0) {
-        codecCtx_->thread_count = videoParams_.threadCount;
-    } else {
-        codecCtx_->thread_count = std::min(static_cast<int>(std::thread::hardware_concurrency()), 8);
-    }
-    AV_LOGGER_INFOF("设置解码线程数: {}", codecCtx_->thread_count);
-    
-    // 设置解码器类型
-    codecCtx_->codec_type = AVMEDIA_TYPE_VIDEO;
-    
-    // 低延迟设置
-    if (videoParams_.lowLatency) {
-        codecCtx_->flags |= AV_CODEC_FLAG_LOW_DELAY;
-        codecCtx_->flags2 |= AV_CODEC_FLAG2_FAST;
-        AV_LOGGER_INFO("启用低延迟模式");
-    }
-    
-    // 针对不同解码器设置特定参数
-    if (videoParams_.codecName.find("cuvid") != std::string::npos) {
-        // NVIDIA CUVID 特定参数
-        if (codecCtx_->priv_data) {
-            av_opt_set_int(codecCtx_->priv_data, "surfaces", 8, 0);
-            
-            if (videoParams_.lowLatency) {
-                av_opt_set_int(codecCtx_->priv_data, "delay", 0, 0);
-            }
-        }
-    } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
-        // Intel QSV 特定参数
-        if (videoParams_.lowLatency && codecCtx_->priv_data) {
-            av_opt_set(codecCtx_->priv_data, "async_depth", "1", 0);
-        }
-    }
-    
-    AV_LOGGER_INFOF("解码器参数设置完成: 尺寸={}x{}, 格式={}, 线程数={}", 
-                   codecCtx_->width, codecCtx_->height, 
-                   static_cast<int>(codecCtx_->pix_fmt), codecCtx_->thread_count);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoDecoder::setupHardwareAcceleration() {
-    isHardwareDecoder_ = true;
-    
-    AVHWDeviceType hwType = getHardwareDeviceType();
-    if (hwType == AV_HWDEVICE_TYPE_NONE) {
-        AV_LOGGER_ERRORF("不支持的硬件解码器: {}", videoParams_.codecName);
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    AV_LOGGER_INFOF("开始设置硬件加速: 解码器={}, 设备类型={}", 
-                   videoParams_.codecName, static_cast<int>(hwType));
-    
-    // 创建硬件设备上下文
-    AV_LOGGER_INFO("创建硬件设备上下文...");
-    int ret = av_hwdevice_ctx_create(&hwDeviceCtx_, hwType, nullptr, nullptr, 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("创建硬件设备上下文失败: {} (解码器: {}, 错误码: {})", 
-                        ffmpeg_utils::errorToString(ret), videoParams_.codecName, ret);
-        
-        // 特定错误处理
-        if (ret == AVERROR(ENOENT)) {
-            AV_LOGGER_ERROR("硬件设备不存在或驱动未安装");
-            if (hwType == AV_HWDEVICE_TYPE_CUDA) {
-                AV_LOGGER_ERROR("请检查NVIDIA驱动和CUDA是否正确安装");
-            }
-        } else if (ret == AVERROR(EBUSY)) {
-            AV_LOGGER_ERROR("硬件设备正在被其他进程使用");
-        } else if (ret == AVERROR(EINVAL)) {
-            AV_LOGGER_ERROR("硬件设备参数无效");
-        } else if (ret == AVERROR(ENOMEM)) {
-            AV_LOGGER_ERROR("内存不足,无法创建硬件设备上下文");
-        }
-        
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFOF("硬件设备上下文创建成功: {}", videoParams_.codecName);
-    
-    // 设置硬件设备上下文到解码器
-    codecCtx_->hw_device_ctx = av_buffer_ref(hwDeviceCtx_);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoDecoder::decodeFrame(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
-    // 发送包到解码器
-    int ret = avcodec_send_packet(codecCtx_.get(), packet ? packet.get() : nullptr);
-    if (ret < 0 && ret != AVERROR_EOF) {
-        AV_LOGGER_ERRORF("发送包到解码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 接收解码后的帧
-    return receiveFrames(frames);
-}
-
-ErrorCode VideoDecoder::receiveFrames(std::vector<AVFramePtr>& frames) {
-    while (true) {
-        AVFramePtr frame = makeAVFrame();
-        if (!frame) {
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        int ret = avcodec_receive_frame(codecCtx_.get(), frame.get());
-        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
-            break; // 需要更多输入或已结束
-        }
-        
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("接收解码帧失败: {}", ffmpeg_utils::errorToString(ret));
-            return static_cast<ErrorCode>(ret);
-        }
-        
-        // 处理硬件帧
-        AVFramePtr processedFrame;
-        if (isHardwareDecoder_) {
-            processedFrame = transferFromHardware(std::move(frame));
-            if (!processedFrame) {
-                AV_LOGGER_ERROR("硬件帧传输失败");
-                continue;
-            }
-        } else {
-            processedFrame = std::move(frame);
-        }
-        
-        // 格式转换(如果需要)
-        auto convertedFrame = convertFrame(processedFrame);
-        if (convertedFrame) {
-            frames.push_back(std::move(convertedFrame));
-        } else {
-            frames.push_back(std::move(processedFrame));
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr VideoDecoder::convertFrame(const AVFramePtr& frame) {
-    if (!frame) {
-        return nullptr;
-    }
-    
-    // 如果格式已经匹配,直接返回
-    if (frame->format == videoParams_.pixelFormat) {
-        return nullptr; // 不需要转换,返回nullptr表示使用原帧
-    }
-    
-    // 创建转换后的帧
-    AVFramePtr convertedFrame = makeAVFrame();
-    if (!convertedFrame) {
-        return nullptr;
-    }
-    
-    convertedFrame->format = videoParams_.pixelFormat;
-    convertedFrame->width = frame->width;
-    convertedFrame->height = frame->height;
-    
-    if (av_frame_get_buffer(convertedFrame.get(), 32) < 0) {
-        AV_LOGGER_ERROR("分配转换帧缓冲区失败");
-        return nullptr;
-    }
-    
-    // 使用 swscale 进行格式转换
-    SwsContext* swsCtx = sws_getContext(
-        frame->width, frame->height, static_cast<AVPixelFormat>(frame->format),
-        convertedFrame->width, convertedFrame->height, videoParams_.pixelFormat,
-        SWS_BILINEAR, nullptr, nullptr, nullptr
-    );
-    
-    if (!swsCtx) {
-        AV_LOGGER_ERROR("创建像素格式转换上下文失败");
-        return nullptr;
-    }
-    
-    sws_scale(swsCtx, frame->data, frame->linesize, 0, frame->height,
-              convertedFrame->data, convertedFrame->linesize);
-    
-    sws_freeContext(swsCtx);
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(convertedFrame.get(), frame.get());
-    
-    return convertedFrame;
-}
-
-AVFramePtr VideoDecoder::transferFromHardware(AVFramePtr hwFrame) {
-    if (!hwFrame || !isHardwareDecoder_) {
-        return std::move(hwFrame);
-    }
-    
-    // 创建软件帧
-    AVFramePtr swFrame = makeAVFrame();
-    if (!swFrame) {
-        return nullptr;
-    }
-    
-    // 从硬件传输到软件
-    int ret = av_hwframe_transfer_data(swFrame.get(), hwFrame.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("从硬件传输数据失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(swFrame.get(), hwFrame.get());
-    
-    return swFrame;
-}
-
-AVHWDeviceType VideoDecoder::getHardwareDeviceType() const {
-    if (videoParams_.codecName.find("cuvid") != std::string::npos) {
-        return AV_HWDEVICE_TYPE_CUDA;
-    } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
-        return AV_HWDEVICE_TYPE_QSV;
-    } else if (videoParams_.codecName.find("d3d11va") != std::string::npos) {
-        return AV_HWDEVICE_TYPE_D3D11VA;
-    } else if (videoParams_.codecName.find("videotoolbox") != std::string::npos) {
-        return AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
-    }
-    
-    return AV_HWDEVICE_TYPE_NONE;
-}
-
-AVPixelFormat VideoDecoder::getHardwarePixelFormat() const {
-    if (videoParams_.codecName.find("cuvid") != std::string::npos) {
-        return AV_PIX_FMT_CUDA;
-    } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
-        return AV_PIX_FMT_QSV;
-    } else if (videoParams_.codecName.find("d3d11va") != std::string::npos) {
-        return AV_PIX_FMT_D3D11;
-    } else if (videoParams_.codecName.find("videotoolbox") != std::string::npos) {
-        return AV_PIX_FMT_VIDEOTOOLBOX;
-    }
-    
-    AV_LOGGER_ERRORF("未知的硬件解码器: {}", videoParams_.codecName);
-    return AV_PIX_FMT_NONE;
-}
-
-void VideoDecoder::updateStats(bool success, double decodeTime, size_t dataSize) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (success) {
-        stats_.decodedFrames++;
-        stats_.totalBytes += dataSize;
-        
-        // 更新平均解码时间
-        if (stats_.decodedFrames == 1) {
-            stats_.avgDecodeTime = decodeTime;
-        } else {
-            stats_.avgDecodeTime = (stats_.avgDecodeTime * (stats_.decodedFrames - 1) + decodeTime) / stats_.decodedFrames;
-        }
-    } else {
-        stats_.errorCount++;
-    }
-}
-
-VideoDecoder::DecoderStats VideoDecoder::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    return stats_;
-}
-
-void VideoDecoder::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = DecoderStats{};
-}
-
-std::string VideoDecoder::getDecoderName() const {
-    return videoParams_.codecName;
-}
-
-std::vector<std::string> VideoDecoder::getSupportedDecoders() {
-    std::call_once(decodersInitFlag_, findUsableDecoders);
-    return supportedDecoders_;
-}
-
-bool VideoDecoder::isHardwareDecoder(const std::string& codecName) {
-    for (const char* hwDecoder : HARDWARE_DECODERS) {
-        if (hwDecoder != nullptr && codecName == hwDecoder) {
-            return true;
-        }
-    }
-    return false;
-}
-
-std::string VideoDecoder::getRecommendedDecoder(const std::string& codecName) {
-    auto decoders = getSupportedDecoders();
-    
-    if (!codecName.empty()) {
-        // 查找指定编解码格式的最佳解码器
-        std::string baseCodec = codecName;
-        
-        // 优先选择硬件解码器
-        for (const char* hwDecoder : HARDWARE_DECODERS) {
-            if (hwDecoder != nullptr) {
-                std::string hwDecoderName = hwDecoder;
-                if (hwDecoderName.find(baseCodec) != std::string::npos &&
-                    std::find(decoders.begin(), decoders.end(), hwDecoderName) != decoders.end()) {
-                    return hwDecoderName;
-                }
-            }
-        }
-        
-        // 回退到软件解码器
-        if (std::find(decoders.begin(), decoders.end(), baseCodec) != decoders.end()) {
-            return baseCodec;
-        }
-    }
-    
-    // 返回第一个可用的硬件解码器
-    for (const char* hwDecoder : HARDWARE_DECODERS) {
-        if (hwDecoder != nullptr && std::find(decoders.begin(), decoders.end(), hwDecoder) != decoders.end()) {
-            return hwDecoder;
-        }
-    }
-    
-    // 回退到软件解码器
-    for (const char* swDecoder : SOFTWARE_DECODERS) {
-        if (swDecoder != nullptr && std::find(decoders.begin(), decoders.end(), swDecoder) != decoders.end()) {
-            return swDecoder;
-        }
-    }
-    
-    return decoders.empty() ? "" : decoders[0];
-}
-
-void VideoDecoder::findUsableDecoders() {
-    AV_LOGGER_INFO("查找可用的视频解码器...");
-    
-    // 测试硬件解码器
-    for (const char* decoder : HARDWARE_DECODERS) {
-        if (decoder != nullptr && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::VIDEO)) {
-            supportedDecoders_.emplace_back(decoder);
-            AV_LOGGER_INFOF("找到硬件解码器: {}", decoder);
-        }
-    }
-    
-    // 测试软件解码器
-    for (const char* decoder : SOFTWARE_DECODERS) {
-        if (decoder != nullptr && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::VIDEO)) {
-            supportedDecoders_.emplace_back(decoder);
-            AV_LOGGER_INFOF("找到软件解码器: {}", decoder);
-        }
-    }
-    
-    AV_LOGGER_INFOF("总共找到 {} 个可用的视频解码器", supportedDecoders_.size());
-}
-
-// VideoDecoderFactory 实现
-std::unique_ptr<VideoDecoder> VideoDecoder::VideoDecoderFactory::create(const std::string& codecName) {
-    auto decoder = std::make_unique<VideoDecoder>();
-    
-    if (!codecName.empty()) {
-        if (!CodecFactory::isCodecSupported(codecName, CodecType::DECODER, MediaType::VIDEO)) {
-            AV_LOGGER_ERRORF("不支持的解码器: {}", codecName);
-            return nullptr;
-        }
-    }
-    
-    return decoder;
-}
-
-std::unique_ptr<VideoDecoder> VideoDecoder::VideoDecoderFactory::createBest(bool preferHardware) {
-    std::string codecName;
-    
-    if (preferHardware) {
-        codecName = VideoDecoder::getRecommendedDecoder();
-    } else {
-        // 优先选择软件解码器
-        auto decoders = VideoDecoder::getSupportedDecoders();
-        for (const char* swDecoder : VideoDecoder::SOFTWARE_DECODERS) {
-            if (swDecoder != nullptr && std::find(decoders.begin(), decoders.end(), swDecoder) != decoders.end()) {
-                codecName = swDecoder;
-                break;
-            }
-        }
-    }
-    
-    if (codecName.empty()) {
-        AV_LOGGER_ERROR("未找到可用的视频解码器");
-        return nullptr;
-    }
-    
-    return create(codecName);
-}
-
-} // namespace codec
-} // namespace av

+ 0 - 161
AV/code/codec/codec_video_decoder.h

@@ -1,161 +0,0 @@
-#pragma once
-
-#include "codec_abstract_codec.h"
-#include <vector>
-#include <memory>
-#include <mutex>
-#include <chrono>
-
-namespace av {
-namespace codec {
-
-// 视频解码器参数
-struct VideoDecoderParams : public CodecParams {
-    std::string codecName;      // 解码器名称 (如 "h264", "hevc", "vp9")
-    int width = 0;              // 视频宽度(可选,用于验证)
-    int height = 0;             // 视频高度(可选,用于验证)
-    AVPixelFormat pixelFormat = AV_PIX_FMT_YUV420P; // 输出像素格式
-    bool hardwareAccel = true;  // 是否启用硬件加速
-    int threadCount = 0;        // 解码线程数(0为自动)
-    bool lowLatency = false;    // 低延迟模式
-    
-    VideoDecoderParams() {
-        type = MediaType::VIDEO;
-    }
-};
-
-// 视频解码器类
-class VideoDecoder : public AbstractDecoder {
-public:
-    VideoDecoder();
-    ~VideoDecoder() override;
-    
-    // 基础接口实现
-    ErrorCode open(const CodecParams& params) override;
-    void close() override;
-    ErrorCode flush() override;
-    ErrorCode reset() override;
-    
-    // 初始化方法
-    ErrorCode initialize(const CodecParams& params);
-    
-    // 从流参数设置解码器
-    ErrorCode setStreamParameters(const AVCodecParameters* codecpar);
-    
-    // 解码接口
-    ErrorCode decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) override;
-    ErrorCode finishDecode(std::vector<AVFramePtr>& frames) override;
-    
-    // 状态查询
-    bool isHardwareDecoder() const { return isHardwareDecoder_; }
-    std::string getDecoderName() const;
-    
-    // 统计信息
-    struct DecoderStats {
-        uint64_t decodedFrames = 0;
-        uint64_t droppedFrames = 0;
-        uint64_t errorCount = 0;
-        double avgDecodeTime = 0.0;
-        uint64_t totalBytes = 0;
-    };
-    
-    DecoderStats getStats() const;
-    void resetStats();
-    
-    // 静态工具方法
-    static std::vector<std::string> getSupportedDecoders();
-    static bool isHardwareDecoder(const std::string& codecName);
-    static std::string getRecommendedDecoder(const std::string& codecName = "");
-    
-    // 解码器工厂
-    class VideoDecoderFactory {
-    public:
-        static std::unique_ptr<VideoDecoder> create(const std::string& codecName = "");
-        static std::unique_ptr<VideoDecoder> createBest(bool preferHardware = true);
-    };
-    
-protected:
-    bool validateParams(const CodecParams& params) override;
-    
-private:
-    // 内部实现方法
-    ErrorCode initDecoder();
-    ErrorCode setupDecoderParams();
-    ErrorCode setupHardwareAcceleration();
-    ErrorCode setupHardwareFrameContext();
-    
-    // 流参数
-    const AVCodecParameters* streamCodecpar_ = nullptr;
-    
-    ErrorCode decodeFrame(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames);
-    ErrorCode receiveFrames(std::vector<AVFramePtr>& frames);
-    
-    AVFramePtr convertFrame(const AVFramePtr& frame);
-    AVFramePtr transferFromHardware(AVFramePtr hwFrame);
-    
-    // 硬件加速相关
-    AVHWDeviceType getHardwareDeviceType() const;
-    AVPixelFormat getHardwarePixelFormat() const;
-    
-    // 统计相关
-    void updateStats(bool success, double decodeTime, size_t dataSize);
-    
-    // 静态方法实现
-    static void findUsableDecoders();
-    
-private:
-    VideoDecoderParams videoParams_;
-    
-    // FFmpeg 对象
-    const AVCodec* codec_ = nullptr;
-    AVCodecContextPtr codecCtx_;
-    AVBufferRef* hwDeviceCtx_ = nullptr;
-    AVFramePtr hwFrame_;
-    
-    // 硬件加速相关
-    bool isHardwareDecoder_ = false;
-    
-
-    
-    // 线程安全
-    mutable std::mutex decodeMutex_;
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    DecoderStats stats_;
-    std::chrono::high_resolution_clock::time_point lastStatsUpdate_;
-    
-    // 静态成员
-    static std::vector<std::string> supportedDecoders_;
-    static std::once_flag decodersInitFlag_;
-    
-    // 支持的解码器列表
-    static constexpr const char* HARDWARE_DECODERS[] = {
-        "h264_cuvid",      // NVIDIA CUDA
-        "hevc_cuvid",      // NVIDIA CUDA HEVC
-        "h264_qsv",        // Intel Quick Sync Video
-        "hevc_qsv",        // Intel Quick Sync Video HEVC
-        "h264_d3d11va",    // Direct3D 11 Video Acceleration
-        "hevc_d3d11va",    // Direct3D 11 Video Acceleration HEVC
-        "h264_videotoolbox", // Apple VideoToolbox
-        "hevc_videotoolbox", // Apple VideoToolbox HEVC
-        "vp9_cuvid",       // NVIDIA CUDA VP9
-        "av1_cuvid",       // NVIDIA CUDA AV1
-        nullptr
-    };
-    
-    static constexpr const char* SOFTWARE_DECODERS[] = {
-        "h264",            // H.264/AVC
-        "hevc",            // H.265/HEVC
-        "vp8",             // VP8
-        "vp9",             // VP9
-        "av1",             // AV1
-        "mpeg2video",      // MPEG-2
-        "mpeg4",           // MPEG-4
-        "mjpeg",           // Motion JPEG
-        nullptr
-    };
-};
-
-} // namespace codec
-} // namespace av

+ 0 - 911
AV/code/codec/codec_video_encoder.cpp

@@ -1,911 +0,0 @@
-#include "codec_video_encoder.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <chrono>
-
-extern "C" {
-#include <libswscale/swscale.h>
-#include <libavutil/imgutils.h>
-#include <libavutil/pixdesc.h>
-}
-
-namespace av {
-namespace codec {
-
-// 静态成员初始化
-std::vector<std::string> VideoEncoder::supportedEncoders_;
-std::once_flag VideoEncoder::encodersInitFlag_;
-
-// PixelFormatConverter 实现
-PixelFormatConverter::PixelFormatConverter(AVPixelFormat srcFormat, AVPixelFormat dstFormat)
-    : swsCtx_(nullptr)
-    , srcFormat_(srcFormat)
-    , dstFormat_(dstFormat)
-    , width_(0)
-    , height_(0) {
-}
-
-PixelFormatConverter::~PixelFormatConverter() {
-    if (swsCtx_) {
-        sws_freeContext(swsCtx_);
-    }
-}
-
-bool PixelFormatConverter::setSize(int width, int height) {
-    if (width_ == width && height_ == height && swsCtx_) {
-        return true;
-    }
-    
-    width_ = width;
-    height_ = height;
-    
-    if (swsCtx_) {
-        sws_freeContext(swsCtx_);
-    }
-    
-    swsCtx_ = sws_getContext(
-        width, height, srcFormat_,
-        width, height, dstFormat_,
-        SWS_BILINEAR, nullptr, nullptr, nullptr
-    );
-    
-    if (!swsCtx_) {
-        AV_LOGGER_ERRORF("创建像素格式转换器失败: {}x{} format:{} -> {}",
-                         width, height,
-                         static_cast<int>(srcFormat_),
-                         static_cast<int>(dstFormat_));
-        return false;
-    }
-    
-    // 创建目标帧
-    dstFrame_ = makeAVFrame();
-    if (!dstFrame_) {
-        AV_LOGGER_ERROR("分配目标帧失败");
-        return false;
-    }
-    
-    dstFrame_->format = dstFormat_;
-    dstFrame_->width = width;
-    dstFrame_->height = height;
-    
-    if (av_frame_get_buffer(dstFrame_.get(), 32) < 0) {
-        AV_LOGGER_ERROR("分配帧缓冲区失败");
-        return false;
-    }
-    
-    return true;
-}
-
-AVFramePtr PixelFormatConverter::convert(const AVFramePtr& srcFrame) {
-    if (!srcFrame || !swsCtx_) {
-        return nullptr;
-    }
-    
-    if (!setSize(srcFrame->width, srcFrame->height)) {
-        return nullptr;
-    }
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(dstFrame_.get(), srcFrame.get());
-    
-    // 执行格式转换
-    int ret = sws_scale(
-        swsCtx_,
-        srcFrame->data, srcFrame->linesize,
-        0, srcFrame->height,
-        dstFrame_->data, dstFrame_->linesize
-    );
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("像素格式转换失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 创建一个新的帧来返回,完全独立的副本
-    AVFramePtr resultFrame = makeAVFrame();
-    if (!resultFrame) {
-        return nullptr;
-    }
-    
-    // 复制帧格式信息
-    resultFrame->format = dstFrame_->format;
-    resultFrame->width = dstFrame_->width;
-    resultFrame->height = dstFrame_->height;
-    
-    // 分配新的缓冲区
-    if (av_frame_get_buffer(resultFrame.get(), 32) < 0) {
-        return nullptr;
-    }
-    
-    // 复制帧数据(避免引用计数问题)
-    if (av_frame_copy(resultFrame.get(), dstFrame_.get()) < 0) {
-        return nullptr;
-    }
-    
-    // 复制帧属性
-    if (av_frame_copy_props(resultFrame.get(), dstFrame_.get()) < 0) {
-        return nullptr;
-    }
-    
-    return resultFrame;
-}
-
-// VideoEncoder 实现
-VideoEncoder::VideoEncoder()
-    : AbstractEncoder(MediaType::VIDEO)
-    , isHardwareEncoder_(false)
-    , hwDeviceCtx_(nullptr) {
-    AV_LOGGER_DEBUG("创建视频编码器");
-}
-
-VideoEncoder::~VideoEncoder() {
-    close();
-    AV_LOGGER_DEBUG("视频编码器已销毁");
-}
-
-ErrorCode VideoEncoder::open(const CodecParams& params) {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ != CodecState::IDLE && state_ != CodecState::CLOSED) {
-        AV_LOGGER_WARNING("编码器已打开,先关闭再重新打开");
-        close();
-    }
-    
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    videoParams_ = static_cast<const VideoEncoderParams&>(params);
-    params_ = params;
-    
-    ErrorCode result = initEncoder();
-    if (result != ErrorCode::SUCCESS) {
-        close();
-        return result;
-    }
-    
-    setState(CodecState::OPENED);
-    AV_LOGGER_INFOF("视频编码器已打开: {} ({}x{} @ {}fps)", 
-                 videoParams_.codecName, videoParams_.width, 
-                 videoParams_.height, videoParams_.fps);
-    
-    return ErrorCode::SUCCESS;
-}
-
-void VideoEncoder::close() {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ == CodecState::CLOSED || state_ == CodecState::IDLE) {
-        return;
-    }
-    
-    // 清理硬件资源
-    if (hwDeviceCtx_) {
-        av_buffer_unref(&hwDeviceCtx_);
-        hwDeviceCtx_ = nullptr;
-    }
-    
-    hwFrame_.reset();
-    convertedFrame_.reset();
-    converter_.reset();
-    
-    // 清理编解码上下文
-    codecCtx_.reset();
-    codec_ = nullptr;
-    
-    setState(CodecState::CLOSED);
-    AV_LOGGER_DEBUG("视频编码器已关闭");
-}
-
-ErrorCode VideoEncoder::flush() {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    setState(CodecState::FLUSHING);
-    
-    // 发送空帧来刷新编码器
-    int ret = avcodec_send_frame(codecCtx_.get(), nullptr);
-    if (ret < 0 && ret != AVERROR_EOF) {
-        AV_LOGGER_ERRORF("刷新编码器失败: {}", ffmpeg_utils::errorToString(ret));
-        reportError(static_cast<ErrorCode>(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    setState(CodecState::OPENED);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoEncoder::encode(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) {
-    std::lock_guard<std::mutex> lock(encodeMutex_);
-    
-    if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    setState(CodecState::RUNNING);
-    
-    auto startTime = std::chrono::high_resolution_clock::now();
-    
-    ErrorCode result = encodeFrame(frame, packets);
-    
-    auto endTime = std::chrono::high_resolution_clock::now();
-    double processTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
-    
-    updateStats(result == ErrorCode::SUCCESS, processTime, 
-                frame ? frame->width * frame->height * 3 / 2 : 0);
-    
-    if (frameCallback_ && frame) {
-        frameCallback_(frame);
-    }
-    
-    for (const auto& packet : packets) {
-        if (packetCallback_) {
-            packetCallback_(packet);
-        }
-    }
-    
-    return result;
-}
-
-ErrorCode VideoEncoder::finishEncode(std::vector<AVPacketPtr>& packets) {
-    return flush();
-}
-
-bool VideoEncoder::validateParams(const CodecParams& params) {
-    if (params.type != MediaType::VIDEO) {
-        AV_LOGGER_ERROR("参数媒体类型不是视频");
-        return false;
-    }
-    
-    const auto& videoParams = static_cast<const VideoEncoderParams&>(params);
-    
-    if (videoParams.width <= 0 || videoParams.height <= 0) {
-        AV_LOGGER_ERROR("视频尺寸无效");
-        return false;
-    }
-    
-    if (videoParams.fps <= 0) {
-        AV_LOGGER_ERROR("帧率无效");
-        return false;
-    }
-    
-    if (videoParams.bitRate <= 0) {
-        AV_LOGGER_ERROR("比特率无效");
-        return false;
-    }
-    
-    if (videoParams.codecName.empty()) {
-        AV_LOGGER_ERROR("编码器名称为空");
-        return false;
-    }
-    
-    return true;
-}
-
-ErrorCode VideoEncoder::initEncoder() {
-    // 查找编码器
-    codec_ = avcodec_find_encoder_by_name(videoParams_.codecName.c_str());
-    if (!codec_) {
-        AV_LOGGER_ERRORF("未找到编码器: {}", videoParams_.codecName);
-        return ErrorCode::CODEC_NOT_FOUND;
-    }
-    
-    if (codec_->type != AVMEDIA_TYPE_VIDEO) {
-        AV_LOGGER_ERROR("编码器类型不是视频");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 创建编码上下文
-    codecCtx_ = makeAVCodecContext(codec_);
-    if (!codecCtx_) {
-        AV_LOGGER_ERROR("分配编码上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 设置硬件加速
-    if (videoParams_.hardwareAccel && isHardwareEncoder(videoParams_.codecName)) {
-        ErrorCode result = setupHardwareAcceleration();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_WARNING("硬件加速设置失败,回退到软件编码");
-            isHardwareEncoder_ = false;
-            
-            // 清理硬件资源
-            if (hwDeviceCtx_) {
-                av_buffer_unref(&hwDeviceCtx_);
-                hwDeviceCtx_ = nullptr;
-            }
-        }
-    }
-    
-    // 设置编码器参数(在硬件加速设置之后)
-    ErrorCode result = setupEncoderParams();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 打开编码器前的详细日志
-    AV_LOGGER_INFOF("准备打开编码器: {}", videoParams_.codecName);
-    AV_LOGGER_INFOF("编码器参数: {}x{}, 比特率: {}, 帧率: {}, 像素格式: {}", 
-                   codecCtx_->width, codecCtx_->height, codecCtx_->bit_rate, 
-                   codecCtx_->framerate.num, static_cast<int>(codecCtx_->pix_fmt));
-    
-    if (isHardwareEncoder_) {
-        AV_LOGGER_INFOF("硬件编码器状态: 设备上下文={}, 帧上下文={}", 
-                       hwDeviceCtx_ ? "已创建" : "未创建",
-                       codecCtx_->hw_frames_ctx ? "已设置" : "未设置");
-    }
-    
-    // 验证编码器参数
-    if (codecCtx_->width <= 0 || codecCtx_->height <= 0) {
-        AV_LOGGER_ERROR("无效的视频尺寸参数");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (codecCtx_->bit_rate <= 0) {
-        AV_LOGGER_ERROR("无效的比特率参数");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 打开编码器
-    int ret = avcodec_open2(codecCtx_.get(), codec_, nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("打开编码器失败: {} (错误码: {})", ffmpeg_utils::errorToString(ret), ret);
-        
-        // 详细错误分析
-        if (ret == AVERROR(EINVAL)) {
-            AV_LOGGER_ERROR("编码器参数无效 - 可能的原因:");
-            AV_LOGGER_ERROR("  1. 不支持的像素格式或分辨率组合");
-            AV_LOGGER_ERROR("  2. 硬件编码器参数配置错误");
-            AV_LOGGER_ERROR("  3. 硬件设备上下文与编码器不匹配");
-        } else if (ret == AVERROR(EBUSY)) {
-            AV_LOGGER_ERROR("硬件设备忙碌 - 可能被其他进程占用");
-        } else if (ret == AVERROR(ENOMEM)) {
-            AV_LOGGER_ERROR("内存不足 - 无法分配编码器资源");
-        }
-        
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFOF("编码器打开成功: {}", videoParams_.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoEncoder::setupEncoderParams() {
-    codecCtx_->bit_rate = videoParams_.bitRate;
-    codecCtx_->width = videoParams_.width;
-    codecCtx_->height = videoParams_.height;
-    codecCtx_->time_base = {1, videoParams_.fps};
-    codecCtx_->framerate = {videoParams_.fps, 1};
-    codecCtx_->gop_size = videoParams_.gopSize;
-    codecCtx_->max_b_frames = videoParams_.maxBFrames;
-    
-    // 设置像素格式
-    if (isHardwareEncoder_) {
-        AVPixelFormat hwPixFmt = getHardwarePixelFormat();
-        if (hwPixFmt == AV_PIX_FMT_NONE) {
-            AV_LOGGER_ERRORF("获取硬件像素格式失败,编码器: {}", videoParams_.codecName);
-            return ErrorCode::NOT_SUPPORTED;
-        }
-        codecCtx_->pix_fmt = hwPixFmt;
-        AV_LOGGER_INFOF("设置硬件编码器像素格式: {} ({})", 
-                       static_cast<int>(hwPixFmt), av_get_pix_fmt_name(hwPixFmt));
-    } else {
-        codecCtx_->pix_fmt = videoParams_.pixelFormat;
-        AV_LOGGER_INFOF("设置软件编码器像素格式: {} ({})", 
-                       static_cast<int>(videoParams_.pixelFormat), 
-                       av_get_pix_fmt_name(videoParams_.pixelFormat));
-    }
-    
-    // 针对不同编码器设置特定参数
-    if (videoParams_.codecName == "h264_nvenc") {
-        AV_LOGGER_INFO("设置NVENC编码器参数...");
-        
-        // NVENC 特定参数 - 使用更保守的设置
-        int ret;
-        ret = av_opt_set(codecCtx_->priv_data, "preset", "medium", 0);
-        AV_LOGGER_INFOF("Set preset=medium: {}", ret == 0 ? "success" : "failed");
-        
-        ret = av_opt_set(codecCtx_->priv_data, "profile", "main", 0);
-        AV_LOGGER_INFOF("Set profile=main: {}", ret == 0 ? "success" : "failed");
-        
-        ret = av_opt_set(codecCtx_->priv_data, "rc", "vbr", 0);
-        AV_LOGGER_INFOF("Set rc=vbr: {}", ret == 0 ? "success" : "failed");
-        
-        ret = av_opt_set_int(codecCtx_->priv_data, "surfaces", 16, 0);
-        AV_LOGGER_INFOF("Set surfaces=16: {}", ret == 0 ? "success" : "failed");
-        
-        ret = av_opt_set_int(codecCtx_->priv_data, "delay", 0, 0);
-        AV_LOGGER_INFOF("Set delay=0: {}", ret == 0 ? "success" : "failed");
-        
-        if (videoParams_.lowLatency) {
-            AV_LOGGER_INFO("启用低延迟模式");
-            ret = av_opt_set(codecCtx_->priv_data, "preset", "fast", 0);
-            AV_LOGGER_INFOF("Set preset=fast: {}", ret == 0 ? "success" : "failed");
-            
-            ret = av_opt_set(codecCtx_->priv_data, "tune", "ll", 0);
-            AV_LOGGER_INFOF("Set tune=ll: {}", ret == 0 ? "success" : "failed");
-        }
-    } else if (videoParams_.codecName == "h264_qsv") {
-        // QSV 特定参数
-        av_opt_set(codecCtx_->priv_data, "preset", "fast", 0);
-        av_opt_set(codecCtx_->priv_data, "profile", "high", 0);
-        
-        if (videoParams_.lowLatency) {
-            av_opt_set(codecCtx_->priv_data, "preset", "veryfast", 0);
-        }
-    } else if (videoParams_.codecName == "h264_amf") {
-        // AMF 特定参数
-        av_opt_set(codecCtx_->priv_data, "quality", "speed", 0);
-        av_opt_set(codecCtx_->priv_data, "profile", "high", 0);
-        
-        if (videoParams_.lowLatency) {
-            av_opt_set(codecCtx_->priv_data, "usage", "lowlatency", 0);
-        }
-    } else {
-        // 软件编码器参数
-        if (!videoParams_.preset.empty()) {
-            av_opt_set(codecCtx_->priv_data, "preset", videoParams_.preset.c_str(), 0);
-        }
-        
-        if (!videoParams_.tune.empty()) {
-            av_opt_set(codecCtx_->priv_data, "tune", videoParams_.tune.c_str(), 0);
-        }
-        
-        if (videoParams_.lowLatency) {
-            av_opt_set(codecCtx_->priv_data, "preset", "ultrafast", 0);
-            av_opt_set(codecCtx_->priv_data, "tune", "zerolatency", 0);
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoEncoder::setupHardwareAcceleration() {
-    isHardwareEncoder_ = true;
-    
-    AVHWDeviceType hwType = getHardwareDeviceType();
-    if (hwType == AV_HWDEVICE_TYPE_NONE) {
-        AV_LOGGER_ERRORF("不支持的硬件编码器: {}", videoParams_.codecName);
-        return ErrorCode::NOT_SUPPORTED;
-    }
-    
-    AV_LOGGER_INFOF("开始设置硬件加速: 编码器={}, 设备类型={}", 
-                   videoParams_.codecName, static_cast<int>(hwType));
-    
-    // 对于CUDA设备,检查可用性
-    if (hwType == AV_HWDEVICE_TYPE_CUDA) {
-        AV_LOGGER_INFO("检查CUDA设备可用性...");
-        // 这里可以添加CUDA设备检查逻辑
-    }
-    
-    // 创建硬件设备上下文
-    AV_LOGGER_INFO("创建硬件设备上下文...");
-    int ret = av_hwdevice_ctx_create(&hwDeviceCtx_, hwType, nullptr, nullptr, 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("创建硬件设备上下文失败: {} (编码器: {}, 错误码: {})", 
-                        ffmpeg_utils::errorToString(ret), videoParams_.codecName, ret);
-        
-        // 特定错误处理
-        if (ret == AVERROR(ENOENT)) {
-            AV_LOGGER_ERROR("硬件设备不存在或驱动未安装");
-            if (hwType == AV_HWDEVICE_TYPE_CUDA) {
-                AV_LOGGER_ERROR("请检查NVIDIA驱动和CUDA是否正确安装");
-            }
-        } else if (ret == AVERROR(EBUSY)) {
-            AV_LOGGER_ERROR("硬件设备正在被其他进程使用");
-        } else if (ret == AVERROR(EINVAL)) {
-            AV_LOGGER_ERROR("硬件设备参数无效");
-        } else if (ret == AVERROR(ENOMEM)) {
-            AV_LOGGER_ERROR("内存不足,无法创建硬件设备上下文");
-        }
-        
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFOF("硬件设备上下文创建成功: {}", videoParams_.codecName);
-    
-    // 设置硬件帧上下文
-    return setupHardwareFrameContext();
-}
-
-ErrorCode VideoEncoder::setupHardwareFrameContext() {
-    AVBufferRef* hwFramesRef = av_hwframe_ctx_alloc(hwDeviceCtx_);
-    if (!hwFramesRef) {
-        AV_LOGGER_ERROR("分配硬件帧上下文失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    AVHWFramesContext* framesCtx = reinterpret_cast<AVHWFramesContext*>(hwFramesRef->data);
-    framesCtx->format = getHardwarePixelFormat();
-    
-    // 设置软件格式 - 统一使用NV12格式,这是大多数硬件编码器的首选格式
-    framesCtx->sw_format = AV_PIX_FMT_NV12;
-    
-    framesCtx->width = videoParams_.width;
-    framesCtx->height = videoParams_.height;
-    framesCtx->initial_pool_size = 8;  // 增加池大小以提高稳定性
-    
-    AV_LOGGER_INFOF("设置硬件帧上下文: {}x{}, 硬件格式: {}, 软件格式: {}, 池大小: {}", 
-                   framesCtx->width, framesCtx->height, 
-                   static_cast<int>(framesCtx->format), 
-                   static_cast<int>(framesCtx->sw_format),
-                   framesCtx->initial_pool_size);
-    
-    int ret = av_hwframe_ctx_init(hwFramesRef);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("初始化硬件帧上下文失败: {}", ffmpeg_utils::errorToString(ret));
-        av_buffer_unref(&hwFramesRef);
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    codecCtx_->hw_frames_ctx = av_buffer_ref(hwFramesRef);
-    av_buffer_unref(&hwFramesRef);
-    
-    AV_LOGGER_INFO("硬件帧上下文初始化成功");
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr VideoEncoder::convertFrame(const AVFramePtr& frame) {
-    if (!frame) {
-        AV_LOGGER_ERROR("输入帧为空");
-        return nullptr;
-    }
-    
-    // 对于YUV420P格式,直接使用软件编码,避免不必要的格式转换
-    // 让OpenGL直接处理原始YUV数据进行显示
-    if (frame->format == AV_PIX_FMT_YUV420P) {
-        // AV_LOGGER_DEBUG("检测到YUV420P格式,直接使用软件编码,避免格式转换");
-
-        // 创建一个新的独立帧副本
-        AVFramePtr resultFrame = makeAVFrame();
-        if (!resultFrame) {
-            AV_LOGGER_ERROR("创建结果帧失败");
-            return nullptr;
-        }
-        
-        // 复制帧格式信息
-        resultFrame->format = frame->format;
-        resultFrame->width = frame->width;
-        resultFrame->height = frame->height;
-        resultFrame->pts = frame->pts;
-        
-        // 分配新的缓冲区
-        if (av_frame_get_buffer(resultFrame.get(), 32) < 0) {
-            AV_LOGGER_ERROR("分配帧缓冲区失败");
-            return nullptr;
-        }
-        
-        // 复制帧数据(避免引用计数问题)
-        if (av_frame_copy(resultFrame.get(), frame.get()) < 0) {
-            AV_LOGGER_ERROR("复制帧数据失败");
-            return nullptr;
-        }
-        
-        // 复制帧属性
-        if (av_frame_copy_props(resultFrame.get(), frame.get()) < 0) {
-            AV_LOGGER_ERROR("复制帧属性失败");
-            return nullptr;
-        }
-        
-        return resultFrame;
-    }
-    
-    AVPixelFormat targetFormat;
-    if (isHardwareEncoder_) {
-        // 对于硬件编码器,暂时使用软件编码避免格式转换问题
-        AV_LOGGER_WARNING("硬件编码器检测到,但为避免格式转换问题,使用软件编码");
-        targetFormat = static_cast<AVPixelFormat>(frame->format); // 使用输入格式
-    } else {
-        targetFormat = videoParams_.pixelFormat;
-    }
-    
-    AV_LOGGER_DEBUGF("帧格式转换: {}x{} format:{} -> {}", 
-                     frame->width, frame->height,
-                     static_cast<int>(frame->format),
-                     static_cast<int>(targetFormat));
-    
-    // 如果格式已经匹配,创建新帧返回
-    if (frame->format == targetFormat) {
-        // 创建一个新的独立帧副本
-        AVFramePtr resultFrame = makeAVFrame();
-        if (!resultFrame) {
-            AV_LOGGER_ERROR("创建结果帧失败");
-            return nullptr;
-        }
-        
-        // 复制帧格式信息
-        resultFrame->format = frame->format;
-        resultFrame->width = frame->width;
-        resultFrame->height = frame->height;
-        resultFrame->pts = frame->pts;
-        
-        // 分配新的缓冲区
-        if (av_frame_get_buffer(resultFrame.get(), 32) < 0) {
-            AV_LOGGER_ERROR("分配帧缓冲区失败");
-            return nullptr;
-        }
-        
-        // 复制帧数据(避免引用计数问题)
-        if (av_frame_copy(resultFrame.get(), frame.get()) < 0) {
-            AV_LOGGER_ERROR("复制帧数据失败");
-            return nullptr;
-        }
-        
-        // 复制帧属性
-        if (av_frame_copy_props(resultFrame.get(), frame.get()) < 0) {
-            AV_LOGGER_ERROR("复制帧属性失败");
-            return nullptr;
-        }
-        
-        return resultFrame;
-    }
-    
-    // 对于其他格式转换需求,仅在必要时进行
-    AV_LOGGER_WARNING("检测到格式转换需求,建议优化数据流避免不必要的转换");
-
-    // 创建转换器
-    if (!converter_ || 
-        converter_->srcFormat_ != static_cast<AVPixelFormat>(frame->format) ||
-        converter_->dstFormat_ != targetFormat) {
-        AV_LOGGER_DEBUGF("创建新的像素格式转换器: {} -> {}",
-                         static_cast<int>(frame->format),
-                         static_cast<int>(targetFormat));
-        converter_ = std::make_unique<PixelFormatConverter>(
-            static_cast<AVPixelFormat>(frame->format), targetFormat);
-    }
-    
-    auto result = converter_->convert(frame);
-    if (!result) {
-        AV_LOGGER_ERRORF("像素格式转换失败: {} -> {}",
-                         static_cast<int>(frame->format),
-                         static_cast<int>(targetFormat));
-    }
-    
-    return result;
-}
-
-AVFramePtr VideoEncoder::transferToHardware(const AVFramePtr& frame) {
-    if (!isHardwareEncoder_ || !frame) {
-        // 创建一个新的独立帧副本
-        if (frame) {
-            AVFramePtr resultFrame = makeAVFrame();
-            if (!resultFrame) {
-                return nullptr;
-            }
-            
-            // 复制帧格式信息
-            resultFrame->format = frame->format;
-            resultFrame->width = frame->width;
-            resultFrame->height = frame->height;
-            resultFrame->pts = frame->pts;
-            
-            // 分配新的缓冲区
-            if (av_frame_get_buffer(resultFrame.get(), 32) < 0) {
-                return nullptr;
-            }
-            
-            // 复制帧数据(避免引用计数问题)
-            if (av_frame_copy(resultFrame.get(), frame.get()) < 0) {
-                return nullptr;
-            }
-            
-            // 复制帧属性
-            if (av_frame_copy_props(resultFrame.get(), frame.get()) < 0) {
-                return nullptr;
-            }
-            
-            return resultFrame;
-        }
-        return nullptr;
-    }
-    
-    // 分配硬件帧
-    hwFrame_ = makeAVFrame();
-    if (!hwFrame_) {
-        AV_LOGGER_ERROR("分配硬件帧失败");
-        return nullptr;
-    }
-    
-    int ret = av_hwframe_get_buffer(codecCtx_->hw_frames_ctx, hwFrame_.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("获取硬件帧缓冲区失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 传输数据到硬件
-    ret = av_hwframe_transfer_data(hwFrame_.get(), frame.get(), 0);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("传输数据到硬件失败: {}", ffmpeg_utils::errorToString(ret));
-        return nullptr;
-    }
-    
-    // 复制时间戳等信息
-    av_frame_copy_props(hwFrame_.get(), frame.get());
-    
-    return std::move(hwFrame_);
-}
-
-ErrorCode VideoEncoder::encodeFrame(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) {
-    AVFramePtr processedFrame;
-    
-    if (frame) {
-        // 格式转换
-        auto convertedFrame = convertFrame(frame);
-        if (!convertedFrame) {
-            AV_LOGGER_ERROR("帧格式转换失败");
-            return ErrorCode::CONVERSION_FAILED;
-        }
-        processedFrame = std::move(convertedFrame);
-        
-        // 硬件传输
-        auto hwFrame = transferToHardware(processedFrame);
-        if (!hwFrame) {
-            AV_LOGGER_ERROR("硬件传输失败");
-            return ErrorCode::HARDWARE_ERROR;
-        }
-        processedFrame = std::move(hwFrame);
-    }
-    
-    // 发送帧到编码器
-    int ret = avcodec_send_frame(codecCtx_.get(), processedFrame ? processedFrame.get() : nullptr);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("发送帧到编码器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 接收编码后的包
-    return receivePackets(packets);
-}
-
-ErrorCode VideoEncoder::receivePackets(std::vector<AVPacketPtr>& packets) {
-    while (true) {
-        AVPacketPtr packet = makeAVPacket();
-        if (!packet) {
-            return ErrorCode::MEMORY_ALLOC_FAILED;
-        }
-        
-        int ret = avcodec_receive_packet(codecCtx_.get(), packet.get());
-        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
-            break; // 需要更多输入或已结束
-        }
-        
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("接收编码包失败: {}", ffmpeg_utils::errorToString(ret));
-            return static_cast<ErrorCode>(ret);
-        }
-        
-        packets.push_back(std::move(packet));
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVHWDeviceType VideoEncoder::getHardwareDeviceType() const {
-    if (videoParams_.codecName == "h264_nvenc") {
-        return AV_HWDEVICE_TYPE_CUDA;
-    } else if (videoParams_.codecName == "h264_qsv") {
-        return AV_HWDEVICE_TYPE_QSV;
-    } else if (videoParams_.codecName == "h264_amf") {
-        return AV_HWDEVICE_TYPE_D3D11VA;
-    } else if (videoParams_.codecName == "h264_videotoolbox") {
-        return AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
-    }
-    
-    return AV_HWDEVICE_TYPE_NONE;
-}
-
-AVPixelFormat VideoEncoder::getHardwarePixelFormat() const {
-    if (videoParams_.codecName == "h264_nvenc") {
-        return AV_PIX_FMT_CUDA;
-    } else if (videoParams_.codecName == "h264_qsv") {
-        return AV_PIX_FMT_QSV;
-    } else if (videoParams_.codecName == "h264_amf") {
-        return AV_PIX_FMT_D3D11;
-    } else if (videoParams_.codecName == "h264_videotoolbox") {
-        return AV_PIX_FMT_VIDEOTOOLBOX;
-    }
-    
-    AV_LOGGER_ERRORF("未知的硬件编码器: {}", videoParams_.codecName);
-    return AV_PIX_FMT_NONE;
-}
-
-std::vector<std::string> VideoEncoder::getSupportedEncoders() {
-    std::call_once(encodersInitFlag_, findUsableEncoders);
-    return supportedEncoders_;
-}
-
-bool VideoEncoder::isHardwareEncoder(const std::string& codecName) {
-    for (const char* hwEncoder : HARDWARE_ENCODERS) {
-        if (codecName == hwEncoder) {
-            return true;
-        }
-    }
-    return false;
-}
-
-std::string VideoEncoder::getRecommendedEncoder() {
-    auto encoders = getSupportedEncoders();
-    
-    // 优先选择硬件编码器
-    for (const char* hwEncoder : HARDWARE_ENCODERS) {
-        if (std::find(encoders.begin(), encoders.end(), hwEncoder) != encoders.end()) {
-            return hwEncoder;
-        }
-    }
-    
-    // 回退到软件编码器
-    for (const char* swEncoder : SOFTWARE_ENCODERS) {
-        if (std::find(encoders.begin(), encoders.end(), swEncoder) != encoders.end()) {
-            return swEncoder;
-        }
-    }
-    
-    return encoders.empty() ? "" : encoders[0];
-}
-
-void VideoEncoder::findUsableEncoders() {
-    AV_LOGGER_INFO("查找可用的视频编码器...");
-    
-    // 测试硬件编码器
-    for (const char* encoder : HARDWARE_ENCODERS) {
-        if (CodecFactory::isCodecSupported(encoder, CodecType::ENCODER, MediaType::VIDEO)) {
-            supportedEncoders_.emplace_back(encoder);
-            AV_LOGGER_INFOF("找到硬件编码器: {}", encoder);
-        }
-    }
-    
-    // 测试软件编码器
-    for (const char* encoder : SOFTWARE_ENCODERS) {
-        if (CodecFactory::isCodecSupported(encoder, CodecType::ENCODER, MediaType::VIDEO)) {
-            supportedEncoders_.emplace_back(encoder);
-            AV_LOGGER_INFOF("找到软件编码器: {}", encoder);
-        }
-    }
-    
-    AV_LOGGER_INFOF("总共找到 {} 个可用的视频编码器", supportedEncoders_.size());
-}
-
-// VideoEncoderFactory 实现
-std::unique_ptr<VideoEncoder> VideoEncoderFactory::create(const std::string& codecName) {
-    auto encoder = std::make_unique<VideoEncoder>();
-    
-    if (!codecName.empty()) {
-        if (!CodecFactory::isCodecSupported(codecName, CodecType::ENCODER, MediaType::VIDEO)) {
-            AV_LOGGER_ERRORF("不支持的编码器: {}", codecName);
-            return nullptr;
-        }
-    }
-    
-    return encoder;
-}
-
-std::unique_ptr<VideoEncoder> VideoEncoderFactory::createBest(bool preferHardware) {
-    std::string codecName;
-    
-    if (preferHardware) {
-        codecName = VideoEncoder::getRecommendedEncoder();
-    } else {
-        // 优先选择软件编码器
-        auto encoders = VideoEncoder::getSupportedEncoders();
-        for (const char* swEncoder : VideoEncoder::SOFTWARE_ENCODERS) {
-            if (std::find(encoders.begin(), encoders.end(), swEncoder) != encoders.end()) {
-                codecName = swEncoder;
-                break;
-            }
-        }
-    }
-    
-    if (codecName.empty()) {
-        AV_LOGGER_ERROR("未找到可用的视频编码器");
-        return nullptr;
-    }
-    
-    return create(codecName);
-}
-
-} // namespace codec
-} // namespace av

+ 0 - 178
AV/code/codec/codec_video_encoder.h

@@ -1,178 +0,0 @@
-#pragma once
-
-#include "codec_abstract_codec.h"
-#include "../base/media_common.h"
-#include <mutex>
-#include <memory>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-#include <libavutil/hwcontext.h>
-#include <libavutil/opt.h>
-#include <libavformat/avformat.h>
-}
-
-namespace av {
-namespace codec {
-
-/**
- * 视频编码器参数
- */
-struct VideoEncoderParams : public CodecParams {
-    int bitRate = 2000000;          // 比特率 (bps)
-    int width = 1920;               // 宽度
-    int height = 1080;              // 高度
-    int fps = 30;                   // 帧率
-    int gopSize = 30;               // GOP大小
-    int maxBFrames = 0;             // B帧数量
-    std::string preset = "medium";  // 编码预设
-    std::string tune = "";          // 调优参数
-    bool lowLatency = false;        // 低延迟模式
-    bool hardwareAccel = true;      // 硬件加速
-    AVPixelFormat pixelFormat = AV_PIX_FMT_YUV420P; // 像素格式
-    
-    VideoEncoderParams() {
-        type = MediaType::VIDEO;
-    }
-};
-
-/**
- * 像素格式转换器
- */
-class PixelFormatConverter {
-    friend class VideoEncoder;
-    
-public:
-    PixelFormatConverter(AVPixelFormat srcFormat, AVPixelFormat dstFormat);
-    ~PixelFormatConverter();
-    
-    bool setSize(int width, int height);
-    AVFramePtr convert(const AVFramePtr& srcFrame);
-    
-private:
-    struct SwsContext* swsCtx_;
-    AVPixelFormat srcFormat_;
-    AVPixelFormat dstFormat_;
-    int width_;
-    int height_;
-    AVFramePtr dstFrame_;
-};
-
-/**
- * 视频编码器实现
- */
-class VideoEncoder : public AbstractEncoder {
-public:
-    VideoEncoder();
-    ~VideoEncoder() override;
-
-    // AbstractCodec 接口实现
-    ErrorCode open(const CodecParams& params) override;
-    void close() override;
-    ErrorCode flush() override;
-
-    // AbstractEncoder 接口实现
-    ErrorCode encode(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) override;
-    ErrorCode finishEncode(std::vector<AVPacketPtr>& packets) override;
-
-    // 视频编码器特有功能
-    const VideoEncoderParams& getVideoParams() const { return videoParams_; }
-    
-    // 获取支持的编码器列表
-    static std::vector<std::string> getSupportedEncoders();
-    
-    // 检查编码器是否支持硬件加速
-    static bool isHardwareEncoder(const std::string& codecName);
-    
-    // 获取推荐的编码器
-    static std::string getRecommendedEncoder();
-    
-    // 硬件编码器名称
-    static constexpr const char* HARDWARE_ENCODERS[] = {
-        "h264_nvenc",   // NVIDIA
-        "h264_qsv",     // Intel Quick Sync
-        "h264_amf",     // AMD
-        "h264_videotoolbox", // Apple
-    };
-    
-    // 软件编码器名称
-    static constexpr const char* SOFTWARE_ENCODERS[] = {
-        "libx264",
-        "libx265",
-    };
-
-protected:
-    bool validateParams(const CodecParams& params) override;
-
-private:
-    // 初始化编码器
-    ErrorCode initEncoder();
-    
-    // 设置编码器参数
-    ErrorCode setupEncoderParams();
-    
-    // 设置硬件加速
-    ErrorCode setupHardwareAcceleration();
-    
-    // 设置硬件帧上下文
-    ErrorCode setupHardwareFrameContext();
-    
-    // 转换帧格式
-    AVFramePtr convertFrame(const AVFramePtr& frame);
-    
-    // 转换到硬件帧
-    AVFramePtr transferToHardware(const AVFramePtr& frame);
-    
-    // 编码单个帧
-    ErrorCode encodeFrame(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets);
-    
-    // 接收编码后的包
-    ErrorCode receivePackets(std::vector<AVPacketPtr>& packets);
-    
-    // 获取硬件设备类型
-    AVHWDeviceType getHardwareDeviceType() const;
-    
-    // 获取硬件像素格式
-    AVPixelFormat getHardwarePixelFormat() const;
-    
-    // 查找可用的编码器
-    static void findUsableEncoders();
-
-private:
-    VideoEncoderParams videoParams_;        // 视频编码参数
-    
-    // 硬件加速相关
-    bool isHardwareEncoder_;                // 是否硬件编码器
-    AVBufferRef* hwDeviceCtx_;              // 硬件设备上下文
-    AVFramePtr hwFrame_;                    // 硬件帧缓冲
-    
-    // 格式转换
-    std::unique_ptr<PixelFormatConverter> converter_;
-    AVFramePtr convertedFrame_;             // 转换后的帧
-    
-    // 线程安全
-    std::mutex encodeMutex_;
-    
-    // 支持的编码器列表
-    static std::vector<std::string> supportedEncoders_;
-    static std::once_flag encodersInitFlag_;
-};
-
-/**
- * 视频编码器工厂
- */
-class VideoEncoderFactory {
-public:
-    /**
-     * 创建视频编码器
-     */
-    static std::unique_ptr<VideoEncoder> create(const std::string& codecName = "");
-    
-    /**
-     * 创建最佳视频编码器(自动选择硬件/软件)
-     */
-    static std::unique_ptr<VideoEncoder> createBest(bool preferHardware = true);
-};
-
-} // namespace codec
-} // namespace av

+ 0 - 529
AV/code/muxer/muxer_abstract_muxer.cpp

@@ -1,529 +0,0 @@
-#include "muxer_abstract_muxer.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <cmath>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavutil/opt.h>
-#include <libavutil/time.h>
-}
-
-namespace av {
-namespace muxer {
-
-AbstractMuxer::AbstractMuxer() {
-    AV_LOGGER_DEBUG("创建抽象复用器");
-    
-    stats_.startTime = std::chrono::steady_clock::now();
-    lastStatsUpdate_ = stats_.startTime;
-}
-
-AbstractMuxer::~AbstractMuxer() {
-    close();
-    AV_LOGGER_DEBUG("抽象复用器已销毁");
-}
-
-ErrorCode AbstractMuxer::pause() {
-    if (getState() != MuxerState::STARTED) {
-        AV_LOGGER_ERROR("复用器状态无效,无法暂停");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    setState(MuxerState::PAUSED);
-    AV_LOGGER_INFO("复用器已暂停");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::resume() {
-    if (getState() != MuxerState::PAUSED) {
-        AV_LOGGER_ERROR("复用器状态无效,无法恢复");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    setState(MuxerState::STARTED);
-    AV_LOGGER_INFO("复用器已恢复");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::reset() {
-    ErrorCode result = stop();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 清理流信息
-    {
-        std::lock_guard<std::mutex> lock(streamsMutex_);
-        streams_.clear();
-        streamMap_.clear();
-    }
-    
-    // 重置统计信息
-    resetStats();
-    
-    setState(MuxerState::INITIALIZED);
-    AV_LOGGER_INFO("复用器已重置");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::removeStream(int streamIndex) {
-    std::lock_guard<std::mutex> lock(streamsMutex_);
-    
-    auto it = std::find_if(streams_.begin(), streams_.end(),
-                          [streamIndex](const StreamInfo& info) {
-                              return info.index == streamIndex;
-                          });
-    
-    if (it == streams_.end()) {
-        AV_LOGGER_ERRORF("流索引 {} 不存在", streamIndex);
-        return ErrorCode::STREAM_NOT_FOUND;
-    }
-    
-    streams_.erase(it);
-    streamMap_.erase(streamIndex);
-    
-    AV_LOGGER_INFOF("已移除流: 索引={}", streamIndex);
-    
-    return ErrorCode::SUCCESS;
-}
-
-std::vector<StreamInfo> AbstractMuxer::getStreams() const {
-    std::lock_guard<std::mutex> lock(streamsMutex_);
-    return streams_;
-}
-
-StreamInfo AbstractMuxer::getStreamInfo(int streamIndex) const {
-    std::lock_guard<std::mutex> lock(streamsMutex_);
-    
-    auto it = std::find_if(streams_.begin(), streams_.end(),
-                          [streamIndex](const StreamInfo& info) {
-                              return info.index == streamIndex;
-                          });
-    
-    if (it != streams_.end()) {
-        return *it;
-    }
-    
-    return StreamInfo(); // 返回空的流信息
-}
-
-MuxerStats AbstractMuxer::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    MuxerStats stats = stats_;
-    
-    // 计算持续时间
-    auto now = std::chrono::steady_clock::now();
-    stats.duration = std::chrono::duration<double>(now - stats_.startTime).count();
-    
-    return stats;
-}
-
-void AbstractMuxer::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    stats_ = MuxerStats();
-    stats_.startTime = std::chrono::steady_clock::now();
-    lastStatsUpdate_ = stats_.startTime;
-    
-    AV_LOGGER_DEBUG("复用器统计信息已重置");
-}
-
-std::string AbstractMuxer::getLastError() const {
-    return lastError_;
-}
-
-std::vector<std::string> AbstractMuxer::getSupportedFormats() {
-    std::vector<std::string> formats;
-    
-    const AVOutputFormat* format = nullptr;
-    void* opaque = nullptr;
-    
-    while ((format = av_muxer_iterate(&opaque))) {
-        if (format->name) {
-            formats.push_back(format->name);
-        }
-    }
-    
-    std::sort(formats.begin(), formats.end());
-    
-    return formats;
-}
-
-std::vector<std::string> AbstractMuxer::getSupportedCodecs(const std::string& format) {
-    std::vector<std::string> codecs;
-    
-    const AVOutputFormat* outputFormat = av_guess_format(format.c_str(), nullptr, nullptr);
-    if (!outputFormat) {
-        AV_LOGGER_ERRORF("不支持的格式: {}", format);
-        return codecs;
-    }
-    
-    // 获取支持的视频编解码器
-    if (outputFormat->video_codec != AV_CODEC_ID_NONE) {
-        const AVCodec* codec = avcodec_find_encoder(outputFormat->video_codec);
-        if (codec && codec->name) {
-            codecs.push_back(std::string("video:") + codec->name);
-        }
-    }
-    
-    // 获取支持的音频编解码器
-    if (outputFormat->audio_codec != AV_CODEC_ID_NONE) {
-        const AVCodec* codec = avcodec_find_encoder(outputFormat->audio_codec);
-        if (codec && codec->name) {
-            codecs.push_back(std::string("audio:") + codec->name);
-        }
-    }
-    
-    // 遍历所有编解码器,查找支持该格式的
-    const AVCodec* codec = nullptr;
-    void* opaque = nullptr;
-    
-    while ((codec = av_codec_iterate(&opaque))) {
-        if (av_codec_is_encoder(codec)) {
-            // 检查编解码器是否支持该格式
-            if (avformat_query_codec(outputFormat, codec->id, FF_COMPLIANCE_NORMAL) == 1) {
-                std::string codecName = codec->name;
-                std::string prefix = (codec->type == AVMEDIA_TYPE_VIDEO) ? "video:" : "audio:";
-                std::string fullName = prefix + codecName;
-                
-                if (std::find(codecs.begin(), codecs.end(), fullName) == codecs.end()) {
-                    codecs.push_back(fullName);
-                }
-            }
-        }
-    }
-    
-    std::sort(codecs.begin(), codecs.end());
-    
-    return codecs;
-}
-
-bool AbstractMuxer::isFormatSupported(const std::string& format) {
-    const AVOutputFormat* outputFormat = av_guess_format(format.c_str(), nullptr, nullptr);
-    return outputFormat != nullptr;
-}
-
-std::string AbstractMuxer::getFormatFromExtension(const std::string& filename) {
-    const AVOutputFormat* format = av_guess_format(nullptr, filename.c_str(), nullptr);
-    if (format && format->name) {
-        return format->name;
-    }
-    
-    return "";
-}
-
-std::string AbstractMuxer::getDefaultExtension(const std::string& format) {
-    const AVOutputFormat* outputFormat = av_guess_format(format.c_str(), nullptr, nullptr);
-    if (outputFormat && outputFormat->extensions) {
-        std::string extensions = outputFormat->extensions;
-        size_t commaPos = extensions.find(',');
-        if (commaPos != std::string::npos) {
-            return extensions.substr(0, commaPos);
-        }
-        return extensions;
-    }
-    
-    return "";
-}
-
-void AbstractMuxer::setState(MuxerState state) {
-    MuxerState oldState = state_.exchange(state);
-    if (oldState != state) {
-        AV_LOGGER_DEBUGF("复用器状态变更: {} -> {}", 
-                        static_cast<int>(oldState), static_cast<int>(state));
-    }
-}
-
-void AbstractMuxer::onError(ErrorCode code, const std::string& message) {
-    lastError_ = message;
-    setState(MuxerState::ERROR_STATE);
-    
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.errorCount++;
-    }
-    
-    AV_LOGGER_ERRORF("复用器错误: {} (代码: {})", message, static_cast<int>(code));
-    
-    if (errorCallback_) {
-        errorCallback_(code, message);
-    }
-}
-
-void AbstractMuxer::updateStats(AVPacket* packet) {
-    if (!packet) {
-        return;
-    }
-    
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    stats_.totalPackets++;
-    stats_.totalBytes += packet->size;
-    stats_.lastPacketTime = std::chrono::steady_clock::now();
-    
-    // 更新流统计
-    stats_.streamPackets[packet->stream_index]++;
-    stats_.streamBytes[packet->stream_index] += packet->size;
-    
-    // 定期更新码率
-    auto now = std::chrono::steady_clock::now();
-    auto elapsed = std::chrono::duration<double>(now - lastStatsUpdate_).count();
-    
-    if (elapsed >= STATS_UPDATE_INTERVAL) {
-        updateBitrate();
-        lastStatsUpdate_ = now;
-        
-        // 触发统计回调
-        if (statsCallback_) {
-            MuxerStats currentStats = stats_;
-            currentStats.duration = std::chrono::duration<double>(now - stats_.startTime).count();
-            statsCallback_(currentStats);
-        }
-    }
-}
-
-void AbstractMuxer::updateBitrate() {
-    auto now = std::chrono::steady_clock::now();
-    double totalDuration = std::chrono::duration<double>(now - stats_.startTime).count();
-    
-    if (totalDuration > 0) {
-        stats_.averageBitrate = (stats_.totalBytes * 8.0) / totalDuration;
-        
-        // 计算当前码率(基于最近的数据)
-        double recentDuration = std::chrono::duration<double>(now - lastStatsUpdate_).count();
-        if (recentDuration > 0) {
-            static uint64_t lastTotalBytes = 0;
-            uint64_t recentBytes = stats_.totalBytes - lastTotalBytes;
-            stats_.currentBitrate = (recentBytes * 8.0) / recentDuration;
-            lastTotalBytes = stats_.totalBytes;
-        }
-    }
-}
-
-bool AbstractMuxer::validateParams(const MuxerParams& params) {
-    if (params.outputPath.empty()) {
-        AV_LOGGER_ERROR("输出路径不能为空");
-        return false;
-    }
-    
-    if (params.format.empty()) {
-        AV_LOGGER_ERROR("输出格式不能为空");
-        return false;
-    }
-    
-    if (!isFormatSupported(params.format)) {
-        AV_LOGGER_ERRORF("不支持的输出格式: {}", params.format);
-        return false;
-    }
-    
-    if (params.streams.empty()) {
-        AV_LOGGER_ERROR("至少需要一个流");
-        return false;
-    }
-    
-    // 验证流参数
-    for (const auto& stream : params.streams) {
-        if (stream.codecId == AV_CODEC_ID_NONE) {
-            AV_LOGGER_ERRORF("流 {} 的编解码器ID无效", stream.index);
-            return false;
-        }
-        
-        if (stream.type == StreamType::VIDEO) {
-            if (stream.width <= 0 || stream.height <= 0) {
-                AV_LOGGER_ERRORF("视频流 {} 的分辨率无效: {}x{}", 
-                               stream.index, stream.width, stream.height);
-                return false;
-            }
-            
-            if (stream.frameRate.num <= 0 || stream.frameRate.den <= 0) {
-                AV_LOGGER_ERRORF("视频流 {} 的帧率无效: {}/{}", 
-                               stream.index, stream.frameRate.num, stream.frameRate.den);
-                return false;
-            }
-        } else if (stream.type == StreamType::AUDIO) {
-            if (stream.sampleRate <= 0) {
-                AV_LOGGER_ERRORF("音频流 {} 的采样率无效: {}", 
-                               stream.index, stream.sampleRate);
-                return false;
-            }
-            
-            if (stream.channels <= 0) {
-                AV_LOGGER_ERRORF("音频流 {} 的声道数无效: {}", 
-                               stream.index, stream.channels);
-                return false;
-            }
-        }
-    }
-    
-    if (params.bufferSize <= 0) {
-        AV_LOGGER_ERROR("缓冲区大小必须大于0");
-        return false;
-    }
-    
-    if (params.maxDelay < 0) {
-        AV_LOGGER_ERROR("最大延迟不能为负数");
-        return false;
-    }
-    
-    return true;
-}
-
-std::string MuxerFactory::getTypeName(MuxerType type) const {
-    switch (type) {
-        case MuxerType::FILE_MUXER:
-            return "文件复用器";
-        case MuxerType::STREAM_MUXER:
-            return "流复用器";
-        case MuxerType::RTMP_MUXER:
-            return "RTMP推流";
-        case MuxerType::UDP_MUXER:
-            return "UDP推流";
-        case MuxerType::TCP_MUXER:
-            return "TCP推流";
-        case MuxerType::HLS_MUXER:
-            return "HLS分片";
-        case MuxerType::DASH_MUXER:
-            return "DASH分片";
-        default:
-            return "未知类型";
-    }
-}
-
-// 为纯虚函数提供默认实现
-ErrorCode AbstractMuxer::initialize(const MuxerParams& params) {
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 添加参数中的流到streams_容器
-    {
-        std::lock_guard<std::mutex> lock(streamsMutex_);
-        streams_.clear(); // 清空现有流
-        for (const auto& stream : params.streams) {
-            streams_.push_back(stream);
-            AV_LOGGER_INFOF("已添加流: 索引={}, 类型={}", stream.index, static_cast<int>(stream.type));
-        }
-    }
-    
-    setState(MuxerState::INITIALIZED);
-    AV_LOGGER_INFO("抽象复用器初始化完成");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::start() {
-    if (getState() != MuxerState::INITIALIZED) {
-        AV_LOGGER_ERROR("复用器状态无效,无法启动");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    setState(MuxerState::STARTED);
-    AV_LOGGER_INFO("抽象复用器已启动");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::stop() {
-    if (getState() != MuxerState::STARTED && getState() != MuxerState::PAUSED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    setState(MuxerState::STOPPED);
-    AV_LOGGER_INFO("抽象复用器已停止");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::close() {
-    stop();
-    setState(MuxerState::IDLE);
-    AV_LOGGER_INFO("抽象复用器已关闭");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::writePacket(AVPacket* packet) {
-    if (!packet) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    updateStats(packet);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::writeFrame(AVFrame* frame, int streamIndex) {
-    if (!frame) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::flush() {
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::addStream(const StreamInfo& streamInfo) {
-    std::lock_guard<std::mutex> lock(streamsMutex_);
-    
-    // 检查流索引是否已存在
-    auto it = std::find_if(streams_.begin(), streams_.end(),
-                          [&streamInfo](const StreamInfo& info) {
-                              return info.index == streamInfo.index;
-                          });
-    
-    if (it != streams_.end()) {
-        AV_LOGGER_ERRORF("流索引 {} 已存在", streamInfo.index);
-        return ErrorCode::STREAM_EXISTS;
-    }
-    
-    streams_.push_back(streamInfo);
-    AV_LOGGER_INFOF("已添加流: 索引={}, 类型={}", streamInfo.index, static_cast<int>(streamInfo.type));
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::setupOutput() {
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::writeHeader() {
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AbstractMuxer::writeTrailer() {
-    return ErrorCode::SUCCESS;
-}
-
-// 默认工厂实现
-class DefaultMuxerFactory : public MuxerFactory {
-public:
-    std::unique_ptr<AbstractMuxer> createMuxer(MuxerType type) override {
-        switch (type) {
-            case MuxerType::FILE_MUXER:
-                // 这里应该返回FileMuxer的实例,但为了避免循环依赖,暂时返回nullptr
-                return nullptr;
-            case MuxerType::STREAM_MUXER:
-                // 这里应该返回StreamMuxer的实例,但为了避免循环依赖,暂时返回nullptr
-                return nullptr;
-            default:
-                return nullptr;
-        }
-    }
-    
-    bool isTypeSupported(MuxerType type) const override {
-        return type == MuxerType::FILE_MUXER || type == MuxerType::STREAM_MUXER;
-    }
-    
-    std::vector<MuxerType> getSupportedTypes() const override {
-        return {MuxerType::FILE_MUXER, MuxerType::STREAM_MUXER};
-    }
-};
-
-std::unique_ptr<MuxerFactory> MuxerFactory::createFactory() {
-    return std::make_unique<DefaultMuxerFactory>();
-}
-
-} // namespace muxer
-} // namespace av

+ 0 - 247
AV/code/muxer/muxer_abstract_muxer.h

@@ -1,247 +0,0 @@
-#ifndef AV_MUXER_ABSTRACT_MUXER_H
-#define AV_MUXER_ABSTRACT_MUXER_H
-
-#include "../base/media_common.h"
-#include "../base/logger.h"
-#include <string>
-#include <vector>
-#include <memory>
-#include <functional>
-#include <atomic>
-#include <mutex>
-#include <chrono>
-#include <map>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavcodec/avcodec.h>
-#include <libavutil/avutil.h>
-#include <libavutil/channel_layout.h>
-}
-
-namespace av {
-namespace muxer {
-
-// 复用器状态
-enum class MuxerState {
-    IDLE = 0,           // 空闲状态
-    INITIALIZED,        // 已初始化
-    STARTED,            // 已启动
-    PAUSED,             // 已暂停
-    STOPPED,            // 已停止
-    ERROR_STATE         // 错误状态
-};
-
-// 复用器类型
-enum class MuxerType {
-    FILE_MUXER = 0,     // 文件复用器
-    STREAM_MUXER,       // 流复用器
-    RTMP_MUXER,         // RTMP推流
-    UDP_MUXER,          // UDP推流
-    TCP_MUXER,          // TCP推流
-    HLS_MUXER,          // HLS分片
-    DASH_MUXER          // DASH分片
-};
-
-// 流类型
-enum class StreamType {
-    VIDEO = 0,
-    AUDIO,
-    SUBTITLE,
-    DATA
-};
-
-// 流信息
-struct StreamInfo {
-    int index = -1;                     // 流索引
-    StreamType type = StreamType::VIDEO; // 流类型
-    AVCodecID codecId = AV_CODEC_ID_NONE; // 编解码器ID
-    std::string codecName;              // 编解码器名称
-    
-    // 视频流参数
-    int width = 0;
-    int height = 0;
-    AVRational frameRate = {0, 1};
-    AVPixelFormat pixelFormat = AV_PIX_FMT_NONE;
-    int64_t bitrate = 0;
-    
-    // 音频流参数
-    int sampleRate = 0;
-    int channels = 0;
-    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_NONE;
-    AVChannelLayout channelLayout = AV_CHANNEL_LAYOUT_MASK(0, 0);
-    
-    // 通用参数
-    AVRational timeBase = {1, 1000};
-    std::string metadata;               // 元数据
-    bool isDefault = false;             // 是否为默认流
-};
-
-// 复用器参数基类
-struct MuxerParams {
-    MuxerType type = MuxerType::FILE_MUXER;
-    MediaType mediaType = MediaType::VIDEO;
-    
-    std::string outputPath;             // 输出路径或URL
-    std::string format;                 // 输出格式 (mp4, flv, ts等)
-    
-    // 流配置
-    std::vector<StreamInfo> streams;    // 流信息列表
-    
-    // 通用选项
-    std::map<std::string, std::string> options; // 格式选项
-    std::map<std::string, std::string> metadata; // 元数据
-    
-    // 性能参数
-    int bufferSize = 1024 * 1024;       // 缓冲区大小
-    int maxDelay = 500000;              // 最大延迟(微秒)
-    bool lowLatency = false;            // 低延迟模式
-    
-    // 错误处理
-    int maxRetries = 3;                 // 最大重试次数
-    int retryDelay = 1000;              // 重试延迟(毫秒)
-    
-    MuxerParams(MuxerType t) : type(t) {}
-    virtual ~MuxerParams() = default;
-};
-
-// 复用器统计信息
-struct MuxerStats {
-    // 基础统计
-    uint64_t totalPackets = 0;          // 总包数
-    uint64_t totalBytes = 0;            // 总字节数
-    uint64_t droppedPackets = 0;        // 丢弃包数
-    uint64_t errorCount = 0;            // 错误计数
-    
-    // 性能统计
-    double averageWriteTime = 0.0;      // 平均写入时间(毫秒)
-    double currentBitrate = 0.0;        // 当前码率(bps)
-    double averageBitrate = 0.0;        // 平均码率(bps)
-    
-    // 时间统计
-    std::chrono::steady_clock::time_point startTime;
-    std::chrono::steady_clock::time_point lastPacketTime;
-    double duration = 0.0;              // 持续时间(秒)
-    
-    // 流统计
-    std::map<int, uint64_t> streamPackets; // 各流包数
-    std::map<int, uint64_t> streamBytes;   // 各流字节数
-};
-
-// 抽象复用器基类
-class AbstractMuxer {
-public:
-    AbstractMuxer();
-    virtual ~AbstractMuxer();
-    
-    // 基础接口
-    virtual ErrorCode initialize(const MuxerParams& params);
-    virtual ErrorCode start();
-    virtual ErrorCode stop();
-    virtual ErrorCode pause();
-    virtual ErrorCode resume();
-    virtual ErrorCode reset();
-    virtual ErrorCode close();
-    
-    // 写入接口
-    virtual ErrorCode writePacket(AVPacket* packet);
-    virtual ErrorCode writeFrame(AVFrame* frame, int streamIndex);
-    virtual ErrorCode flush();
-    
-    // 流管理
-    virtual ErrorCode addStream(const StreamInfo& streamInfo);
-    virtual ErrorCode removeStream(int streamIndex);
-    virtual std::vector<StreamInfo> getStreams() const;
-    virtual StreamInfo getStreamInfo(int streamIndex) const;
-    
-    // 状态查询
-    MuxerState getState() const { return state_.load(); }
-    bool isRunning() const { return getState() == MuxerState::STARTED; }
-    bool isPaused() const { return getState() == MuxerState::PAUSED; }
-    
-    // 统计信息
-    MuxerStats getStats() const;
-    void resetStats();
-    
-    // 错误处理
-    std::string getLastError() const;
-    
-    // 回调设置
-    using ErrorCallback = std::function<void(ErrorCode, const std::string&)>;
-    using ProgressCallback = std::function<void(double)>; // 进度百分比
-    using StatsCallback = std::function<void(const MuxerStats&)>;
-    
-    void setErrorCallback(ErrorCallback callback) { errorCallback_ = callback; }
-    void setProgressCallback(ProgressCallback callback) { progressCallback_ = callback; }
-    void setStatsCallback(StatsCallback callback) { statsCallback_ = callback; }
-    
-    // 静态工具方法
-    static std::vector<std::string> getSupportedFormats();
-    static std::vector<std::string> getSupportedCodecs(const std::string& format);
-    static bool isFormatSupported(const std::string& format);
-    static std::string getFormatFromExtension(const std::string& filename);
-    static std::string getDefaultExtension(const std::string& format);
-    
-protected:
-    // 状态管理
-    void setState(MuxerState state);
-    
-    // 错误处理
-    void onError(ErrorCode code, const std::string& message);
-    
-    // 统计更新
-    void updateStats(AVPacket* packet);
-    void updateBitrate();
-    
-    // 参数验证
-    virtual bool validateParams(const MuxerParams& params);
-    
-    // 内部实现方法
-    virtual ErrorCode setupOutput();
-    virtual ErrorCode writeHeader();
-    virtual ErrorCode writeTrailer();
-    
-    // 成员变量
-    std::atomic<MuxerState> state_{MuxerState::IDLE};
-    mutable std::mutex statsMutex_;
-    mutable std::mutex streamsMutex_;
-    
-    MuxerStats stats_;
-    std::vector<StreamInfo> streams_;
-    std::string lastError_;
-    
-    // 回调函数
-    ErrorCallback errorCallback_;
-    ProgressCallback progressCallback_;
-    StatsCallback statsCallback_;
-    
-    // FFmpeg相关
-    AVFormatContext* formatCtx_ = nullptr;
-    std::map<int, AVStream*> streamMap_; // 流索引映射
-    
-    // 性能监控
-    std::chrono::steady_clock::time_point lastStatsUpdate_;
-    static constexpr double STATS_UPDATE_INTERVAL = 1.0; // 统计更新间隔(秒)
-};
-
-// 复用器工厂抽象基类
-class MuxerFactory {
-public:
-    virtual ~MuxerFactory() = default;
-    
-    // 工厂方法
-    virtual std::unique_ptr<AbstractMuxer> createMuxer(MuxerType type) = 0;
-    
-    // 能力查询
-    virtual bool isTypeSupported(MuxerType type) const = 0;
-    virtual std::vector<MuxerType> getSupportedTypes() const = 0;
-    virtual std::string getTypeName(MuxerType type) const;
-    
-    // 静态工厂方法
-    static std::unique_ptr<MuxerFactory> createFactory();
-};
-
-} // namespace muxer
-} // namespace av
-
-#endif // AV_MUXER_ABSTRACT_MUXER_H

+ 0 - 891
AV/code/muxer/muxer_file_muxer.cpp

@@ -1,891 +0,0 @@
-#include "muxer_file_muxer.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <filesystem>
-#include <sstream>
-#include <iomanip>
-#include <algorithm>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavutil/opt.h>
-#include <libavutil/time.h>
-#include <libavutil/mathematics.h>
-}
-
-namespace av {
-namespace muxer {
-
-FileMuxer::FileMuxer() {
-    AV_LOGGER_DEBUG("创建文件复用器");
-    lastFlushTime_ = std::chrono::steady_clock::now();
-}
-
-FileMuxer::~FileMuxer() {
-    close();
-    AV_LOGGER_DEBUG("文件复用器已销毁");
-}
-
-ErrorCode FileMuxer::initialize(const MuxerParams& params) {
-    if (params.type != MuxerType::FILE_MUXER) {
-        AV_LOGGER_ERROR("参数类型不是文件复用器");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 先验证参数,再进行类型转换
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 安全地进行类型转换
-    try {
-        fileMuxerParams_ = static_cast<const FileMuxerParams&>(params);
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("参数类型转换失败: {}", e.what());
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 调用父类的initialize方法来处理streams
-    ErrorCode result = AbstractMuxer::initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 设置输出文件
-    if (!fileMuxerParams_.outputFile.empty()) {
-        currentOutputFile_ = fileMuxerParams_.outputFile;
-    } else {
-        currentOutputFile_ = fileMuxerParams_.outputPath;
-    }
-    
-    ErrorCode validateResult = validateFilePath(currentOutputFile_);
-    if (validateResult != ErrorCode::SUCCESS) {
-        return validateResult;
-    }
-    
-    // 设置分段
-    if (fileMuxerParams_.enableSegmentation) {
-        segmentationEnabled_ = true;
-        if (fileMuxerParams_.segmentPattern.empty()) {
-            // 生成默认分段模式
-            std::filesystem::path path(currentOutputFile_);
-            std::string stem = path.stem().string();
-            std::string ext = path.extension().string();
-            fileMuxerParams_.segmentPattern = stem + "_%03d" + ext;
-        }
-    }
-    
-    AV_LOGGER_INFOF("文件复用器初始化成功: {}", currentOutputFile_);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::start() {
-    if (getState() != MuxerState::INITIALIZED) {
-        AV_LOGGER_ERROR("复用器状态无效,无法启动");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = setupOutput();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    result = writeHeader();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 启动写入线程
-    shouldStopWriting_ = false;
-    try {
-        writeThread_ = std::thread(&FileMuxer::writeThreadFunc, this);
-        setState(MuxerState::STARTED);
-        
-        fileStartTime_ = std::chrono::steady_clock::now();
-        AV_LOGGER_INFO("文件复用器已启动");
-        
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("启动写入线程失败: {}", e.what());
-        return ErrorCode::THREAD_ERROR;
-    }
-}
-
-ErrorCode FileMuxer::stop() {
-    if (getState() != MuxerState::STARTED && getState() != MuxerState::PAUSED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 停止写入线程
-    shouldStopWriting_ = true;
-    queueCondition_.notify_all();
-    
-    if (writeThread_.joinable()) {
-        writeThread_.join();
-    }
-    
-    // 刷新剩余数据
-    flush();
-    
-    // 写入文件尾
-    ErrorCode result = writeTrailer();
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("写入文件尾失败: {}", static_cast<int>(result));
-    }
-    
-    setState(MuxerState::STOPPED);
-    AV_LOGGER_INFO("文件复用器已停止");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::close() {
-    stop();
-    
-    ErrorCode result = closeOutputFile();
-    
-    // 清空队列
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        while (!packetQueue_.empty()) {
-            packetQueue_.pop();
-        }
-    }
-    
-    setState(MuxerState::IDLE);
-    AV_LOGGER_INFO("文件复用器已关闭");
-    
-    return result;
-}
-
-ErrorCode FileMuxer::writePacket(AVPacket* packet) {
-    if (!packet) {
-        AV_LOGGER_ERROR("包指针为空");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (getState() != MuxerState::STARTED) {
-        AV_LOGGER_ERROR("复用器未启动,无法写入包");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 检查队列大小
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        if (packetQueue_.size() >= MAX_QUEUE_SIZE) {
-            AV_LOGGER_WARNING("包队列已满,丢弃包");
-            {
-                std::lock_guard<std::mutex> statsLock(statsMutex_);
-                stats_.droppedPackets++;
-            }
-            return ErrorCode::QUEUE_FULL;
-        }
-    }
-    
-    // 复制包
-    AVPacket* packetCopy = av_packet_alloc();
-    if (!packetCopy) {
-        AV_LOGGER_ERROR("分配包内存失败");
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    int ret = av_packet_ref(packetCopy, packet);
-    if (ret < 0) {
-        av_packet_free(&packetCopy);
-        AV_LOGGER_ERRORF("复制包失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 添加到队列
-    auto queueItem = std::make_unique<PacketQueueItem>(packetCopy, packet->stream_index);
-    
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        packetQueue_.push(std::move(queueItem));
-        queuedPackets_++;
-    }
-    
-    queueCondition_.notify_one();
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::writeFrame(AVFrame* frame, int streamIndex) {
-    if (!frame) {
-        AV_LOGGER_ERROR("帧指针为空");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 这里需要编码器将帧编码为包,然后调用writePacket
-    // 由于这是复用器,通常接收已编码的包
-    AV_LOGGER_WARNING("文件复用器不直接支持写入原始帧,请先编码为包");
-    
-    return ErrorCode::NOT_SUPPORTED;
-}
-
-ErrorCode FileMuxer::flush() {
-    if (!formatCtx_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::lock_guard<std::mutex> lock(fileMutex_);
-    
-    return flushInternal();
-}
-
-ErrorCode FileMuxer::flushInternal() {
-    if (!formatCtx_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 注意:此方法假设调用者已经持有fileMutex_锁
-    
-    int ret = av_write_frame(formatCtx_, nullptr); // 刷新
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("刷新复用器失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    if (formatCtx_->pb) {
-        avio_flush(formatCtx_->pb);
-    }
-    
-    lastFlushTime_ = std::chrono::steady_clock::now();
-    AV_LOGGER_DEBUG("复用器已刷新");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::addStream(const StreamInfo& streamInfo) {
-    if (getState() != MuxerState::INITIALIZED) {
-        AV_LOGGER_ERROR("只能在初始化状态下添加流");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    std::lock_guard<std::mutex> lock(streamsMutex_);
-    
-    // 检查流索引是否已存在
-    auto it = std::find_if(streams_.begin(), streams_.end(),
-                          [&streamInfo](const StreamInfo& info) {
-                              return info.index == streamInfo.index;
-                          });
-    
-    if (it != streams_.end()) {
-        AV_LOGGER_ERRORF("流索引 {} 已存在", streamInfo.index);
-        return ErrorCode::STREAM_EXISTS;
-    }
-    
-    streams_.push_back(streamInfo);
-    
-    AV_LOGGER_INFOF("已添加流: 索引={}, 类型={}, 编解码器={}", 
-                   streamInfo.index, static_cast<int>(streamInfo.type), 
-                   streamInfo.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::setOutputFile(const std::string& filename) {
-    if (getState() != MuxerState::IDLE && getState() != MuxerState::INITIALIZED) {
-        AV_LOGGER_ERROR("无法在运行时更改输出文件");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = validateFilePath(filename);
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    currentOutputFile_ = filename;
-    fileMuxerParams_.outputFile = filename;
-    
-    AV_LOGGER_INFOF("输出文件已设置为: {}", filename);
-    
-    return ErrorCode::SUCCESS;
-}
-
-std::string FileMuxer::getOutputFile() const {
-    return currentOutputFile_;
-}
-
-int64_t FileMuxer::getCurrentFileSize() const {
-    return currentFileSize_;
-}
-
-double FileMuxer::getCurrentDuration() const {
-    auto now = std::chrono::steady_clock::now();
-    return std::chrono::duration<double>(now - fileStartTime_).count();
-}
-
-ErrorCode FileMuxer::enableSegmentation(bool enable, int duration) {
-    if (getState() == MuxerState::STARTED) {
-        AV_LOGGER_ERROR("无法在运行时更改分段设置");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    segmentationEnabled_ = enable;
-    fileMuxerParams_.enableSegmentation = enable;
-    fileMuxerParams_.segmentDuration = duration;
-    
-    AV_LOGGER_INFOF("Segmentation {}: duration={}s", enable ? "enabled" : "disabled", duration);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::forceNewSegment() {
-    if (!segmentationEnabled_) {
-        AV_LOGGER_ERROR("分段功能未启用");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (getState() != MuxerState::STARTED) {
-        AV_LOGGER_ERROR("复用器未启动");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    return createNewSegment();
-}
-
-std::vector<std::string> FileMuxer::getSegmentFiles() const {
-    return segmentFiles_;
-}
-
-ErrorCode FileMuxer::setFastStart(bool enable) {
-    fileMuxerParams_.enableFastStart = enable;
-    
-    if (enable) {
-        fileMuxerParams_.movFlags |= 0x01; // AVFMT_FLAG_FASTSTART
-    } else {
-        fileMuxerParams_.movFlags &= ~0x01;
-    }
-    
-    AV_LOGGER_INFOF("Fast start {}", enable ? "enabled" : "disabled");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::setMovFlags(int flags) {
-    fileMuxerParams_.movFlags = flags;
-    AV_LOGGER_INFOF("MOV标志已设置为: 0x{:X}", flags);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::setupOutput() {
-    // 分配格式上下文
-    const char* formatName = fileMuxerParams_.format.empty() ? nullptr : fileMuxerParams_.format.c_str();
-    const char* filename = currentOutputFile_.c_str();
-    
-    int ret = avformat_alloc_output_context2(&formatCtx_, nullptr, formatName, filename);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("分配输出格式上下文失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    if (!formatCtx_->oformat) {
-        AV_LOGGER_ERROR("无法确定输出格式");
-        return ErrorCode::FORMAT_NOT_SUPPORTED;
-    }
-    
-    AV_LOGGER_INFOF("输出格式: {} ({})", formatCtx_->oformat->name, formatCtx_->oformat->long_name);
-    
-    // 设置流
-    ErrorCode result = setupStreams();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 设置元数据
-    for (const auto& meta : fileMuxerParams_.metadata) {
-        av_dict_set(&formatCtx_->metadata, meta.first.c_str(), meta.second.c_str(), 0);
-    }
-    
-    // 打开输出文件
-    return openOutputFile();
-}
-
-ErrorCode FileMuxer::writeHeader() {
-    if (!formatCtx_) {
-        AV_LOGGER_ERROR("格式上下文未初始化");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 设置格式选项
-    AVDictionary* options = nullptr;
-    
-    for (const auto& option : fileMuxerParams_.options) {
-        av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
-    }
-    
-    // 设置MOV标志
-    if (fileMuxerParams_.movFlags != 0) {
-        av_dict_set_int(&options, "movflags", fileMuxerParams_.movFlags, 0);
-    }
-    
-    // 写入文件头
-    int ret = avformat_write_header(formatCtx_, &options);
-    av_dict_free(&options);
-    
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("写入文件头失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFO("文件头已写入");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::writeTrailer() {
-    if (!formatCtx_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::lock_guard<std::mutex> lock(fileMutex_);
-    
-    int ret = av_write_trailer(formatCtx_);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("写入文件尾失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    AV_LOGGER_INFO("文件尾已写入");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::openOutputFile() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 检查是否需要覆盖文件
-    if (!fileMuxerParams_.overwrite && std::filesystem::exists(currentOutputFile_)) {
-        AV_LOGGER_ERRORF("文件已存在且不允许覆盖: {}", currentOutputFile_);
-        return ErrorCode::FILE_EXISTS;
-    }
-    
-    // 打开输出文件
-    if (!(formatCtx_->oformat->flags & AVFMT_NOFILE)) {
-        int ret = avio_open(&formatCtx_->pb, currentOutputFile_.c_str(), AVIO_FLAG_WRITE);
-        if (ret < 0) {
-            AV_LOGGER_ERRORF("打开输出文件失败: {} ({})", 
-                           ffmpeg_utils::errorToString(ret), currentOutputFile_);
-            return static_cast<ErrorCode>(ret);
-        }
-    }
-    
-    currentFileSize_ = 0;
-    AV_LOGGER_INFOF("输出文件已打开: {}", currentOutputFile_);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::closeOutputFile() {
-    if (!formatCtx_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::lock_guard<std::mutex> lock(fileMutex_);
-    
-    // 关闭文件
-    if (formatCtx_->pb && !(formatCtx_->oformat->flags & AVFMT_NOFILE)) {
-        avio_closep(&formatCtx_->pb);
-    }
-    
-    // 释放格式上下文
-    avformat_free_context(formatCtx_);
-    formatCtx_ = nullptr;
-    
-    // 清理流映射
-    streamMap_.clear();
-    
-    AV_LOGGER_INFO("输出文件已关闭");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::createNewSegment() {
-    if (!segmentationEnabled_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 写入当前段的尾部
-    ErrorCode result = writeTrailer();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 关闭当前文件
-    result = closeOutputFile();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 添加到段文件列表
-    segmentFiles_.push_back(currentOutputFile_);
-    
-    // 生成新的段文件名
-    currentSegmentIndex_++;
-    currentOutputFile_ = generateSegmentFilename(currentSegmentIndex_);
-    
-    // 重新设置输出
-    result = setupOutput();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 写入新段的头部
-    result = writeHeader();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    fileStartTime_ = std::chrono::steady_clock::now();
-    
-    AV_LOGGER_INFOF("创建新段: {}", currentOutputFile_);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode FileMuxer::setupStreams() {
-    std::lock_guard<std::mutex> lock(streamsMutex_);
-    
-    for (const auto& streamInfo : streams_) {
-        AVStream* stream = createAVStream(streamInfo);
-        if (!stream) {
-            AV_LOGGER_ERRORF("创建流失败: 索引={}", streamInfo.index);
-            return ErrorCode::STREAM_CREATE_FAILED;
-        }
-        
-        streamMap_[streamInfo.index] = stream;
-    }
-    
-    AV_LOGGER_INFOF("已设置 {} 个流", streams_.size());
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVStream* FileMuxer::createAVStream(const StreamInfo& streamInfo) {
-    if (!formatCtx_) {
-        return nullptr;
-    }
-    
-    AVStream* stream = avformat_new_stream(formatCtx_, nullptr);
-    if (!stream) {
-        AV_LOGGER_ERROR("创建新流失败");
-        return nullptr;
-    }
-    
-    stream->id = streamInfo.index;
-    stream->time_base = streamInfo.timeBase;
-    
-    // 设置编解码器参数
-    AVCodecParameters* codecpar = stream->codecpar;
-    codecpar->codec_id = streamInfo.codecId;
-    codecpar->codec_type = (streamInfo.type == StreamType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
-    
-    if (streamInfo.type == StreamType::VIDEO) {
-        codecpar->width = streamInfo.width;
-        codecpar->height = streamInfo.height;
-        codecpar->format = streamInfo.pixelFormat;
-        codecpar->bit_rate = streamInfo.bitrate;
-        
-        // 设置帧率
-        stream->avg_frame_rate = streamInfo.frameRate;
-        stream->r_frame_rate = streamInfo.frameRate;
-    } else if (streamInfo.type == StreamType::AUDIO) {
-        codecpar->sample_rate = streamInfo.sampleRate;
-        av_channel_layout_copy(&codecpar->ch_layout, &streamInfo.channelLayout);
-        codecpar->format = streamInfo.sampleFormat;
-        codecpar->bit_rate = streamInfo.bitrate;
-    }
-    
-    AV_LOGGER_INFOF("创建流成功: 索引={}, 类型={}", streamInfo.index, static_cast<int>(streamInfo.type));
-    
-    return stream;
-}
-
-ErrorCode FileMuxer::processPacket(AVPacket* packet) {
-    if (!packet || !formatCtx_) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 检查流索引
-    auto it = streamMap_.find(packet->stream_index);
-    if (it == streamMap_.end()) {
-        AV_LOGGER_ERRORF("未找到流索引: {}", packet->stream_index);
-        return ErrorCode::STREAM_NOT_FOUND;
-    }
-    
-    // 检查是否需要创建新段
-    if (shouldCreateNewSegment()) {
-        ErrorCode result = createNewSegment();
-        if (result != ErrorCode::SUCCESS) {
-            return result;
-        }
-    }
-    
-    return writePacketInternal(packet);
-}
-
-ErrorCode FileMuxer::writePacketInternal(AVPacket* packet) {
-    std::lock_guard<std::mutex> lock(fileMutex_);
-    
-    auto startTime = std::chrono::steady_clock::now();
-    
-    // 写入包
-    int ret = av_interleaved_write_frame(formatCtx_, packet);
-    if (ret < 0) {
-        AV_LOGGER_ERRORF("写入包失败: {}", ffmpeg_utils::errorToString(ret));
-        return static_cast<ErrorCode>(ret);
-    }
-    
-    // 更新统计信息
-    updateStats(packet);
-    currentFileSize_ += packet->size;
-    writtenPackets_++;
-    
-    // 更新平均写入时间
-    auto endTime = std::chrono::steady_clock::now();
-    double writeTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
-    averageWriteTime_ = (averageWriteTime_ * 0.9) + (writeTime * 0.1);
-    
-    // 定期刷新 - 使用内部刷新方法避免死锁
-    if (!fileMuxerParams_.syncMode) {
-        auto now = std::chrono::steady_clock::now();
-        auto elapsed = std::chrono::duration<double>(now - lastFlushTime_).count();
-        if (elapsed >= fileMuxerParams_.flushInterval) {
-            flushInternal();
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-void FileMuxer::writeThreadFunc() {
-    AV_LOGGER_INFO("写入线程已启动");
-    
-    while (!shouldStopWriting_) {
-        std::unique_ptr<PacketQueueItem> item;
-        
-        // 从队列获取包
-        {
-            std::unique_lock<std::mutex> lock(queueMutex_);
-            queueCondition_.wait(lock, [this] {
-                return !packetQueue_.empty() || shouldStopWriting_;
-            });
-            
-            if (shouldStopWriting_ && packetQueue_.empty()) {
-                break;
-            }
-            
-            if (!packetQueue_.empty()) {
-                item = std::move(packetQueue_.front());
-                packetQueue_.pop();
-            }
-        }
-        
-        if (item && item->packet) {
-            ErrorCode result = processPacket(item->packet);
-            if (result != ErrorCode::SUCCESS) {
-                onError(result, "写入包失败");
-            }
-        }
-    }
-    
-    // 处理剩余的包
-    while (true) {
-        std::unique_ptr<PacketQueueItem> item;
-        
-        {
-            std::lock_guard<std::mutex> lock(queueMutex_);
-            if (packetQueue_.empty()) {
-                break;
-            }
-            item = std::move(packetQueue_.front());
-            packetQueue_.pop();
-        }
-        
-        if (item && item->packet) {
-            processPacket(item->packet);
-        }
-    }
-    
-    AV_LOGGER_INFO("写入线程已退出");
-}
-
-std::string FileMuxer::generateSegmentFilename(int segmentIndex) {
-    if (fileMuxerParams_.segmentPattern.empty()) {
-        std::filesystem::path path(currentOutputFile_);
-        std::string stem = path.stem().string();
-        std::string ext = path.extension().string();
-        
-        std::ostringstream oss;
-        oss << stem << "_" << std::setfill('0') << std::setw(3) << segmentIndex << ext;
-        return oss.str();
-    } else {
-        char buffer[1024];
-        snprintf(buffer, sizeof(buffer), fileMuxerParams_.segmentPattern.c_str(), segmentIndex);
-        return std::string(buffer);
-    }
-}
-
-bool FileMuxer::shouldCreateNewSegment() const {
-    if (!segmentationEnabled_) {
-        return false;
-    }
-    
-    // 检查时长
-    if (fileMuxerParams_.segmentDuration > 0) {
-        double currentDuration = getCurrentDuration();
-        if (currentDuration >= fileMuxerParams_.segmentDuration) {
-            return true;
-        }
-    }
-    
-    // 检查文件大小
-    if (fileMuxerParams_.maxFileSize > 0) {
-        if (currentFileSize_ >= fileMuxerParams_.maxFileSize) {
-            return true;
-        }
-    }
-    
-    return false;
-}
-
-ErrorCode FileMuxer::validateFilePath(const std::string& path) {
-    if (path.empty()) {
-        AV_LOGGER_ERROR("文件路径不能为空");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    try {
-        std::filesystem::path filePath(path);
-        
-        // 检查父目录是否存在
-        std::filesystem::path parentDir = filePath.parent_path();
-        if (!parentDir.empty() && !std::filesystem::exists(parentDir)) {
-            // 尝试创建目录
-            std::filesystem::create_directories(parentDir);
-        }
-        
-        // 检查文件扩展名
-        std::string extension = filePath.extension().string();
-        if (extension.empty()) {
-            AV_LOGGER_WARNING("文件没有扩展名,可能导致格式检测问题");
-        }
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("文件路径验证失败: {}", e.what());
-        return ErrorCode::INVALID_PATH;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-bool FileMuxer::validateParams(const MuxerParams& params) {
-    if (!AbstractMuxer::validateParams(params)) {
-        return false;
-    }
-    
-    // 首先验证基础参数
-    if (params.outputPath.empty()) {
-        AV_LOGGER_ERROR("输出文件路径不能为空");
-        return false;
-    }
-    
-    // 如果参数类型正确,进行更详细的验证
-    if (params.type == MuxerType::FILE_MUXER) {
-        try {
-            const auto& fileParams = static_cast<const FileMuxerParams&>(params);
-            
-            if (fileParams.outputFile.empty() && fileParams.outputPath.empty()) {
-                AV_LOGGER_ERROR("输出文件路径不能为空");
-                return false;
-            }
-            
-            if (fileParams.segmentDuration < 0) {
-                AV_LOGGER_ERROR("分段时长不能为负数");
-                return false;
-            }
-            
-            if (fileParams.maxFileSize < 0) {
-                AV_LOGGER_ERROR("最大文件大小不能为负数");
-                return false;
-            }
-            
-            if (fileParams.flushInterval <= 0) {
-                AV_LOGGER_ERROR("刷新间隔必须大于0");
-                return false;
-            }
-        } catch (const std::exception& e) {
-            AV_LOGGER_ERRORF("参数验证时类型转换失败: {}", e.what());
-            return false;
-        }
-    }
-    
-    return true;
-}
-
-// FileMuxerFactory 实现
-std::unique_ptr<AbstractMuxer> FileMuxer::FileMuxerFactory::createMuxer(MuxerType type) {
-    if (type == MuxerType::FILE_MUXER) {
-        return std::make_unique<FileMuxer>();
-    }
-    
-    return nullptr;
-}
-
-bool FileMuxer::FileMuxerFactory::isTypeSupported(MuxerType type) const {
-    return type == MuxerType::FILE_MUXER;
-}
-
-std::vector<MuxerType> FileMuxer::FileMuxerFactory::getSupportedTypes() const {
-    return {MuxerType::FILE_MUXER};
-}
-
-std::unique_ptr<FileMuxer> FileMuxer::FileMuxerFactory::createFileMuxer(const std::string& filename) {
-    auto muxer = std::make_unique<FileMuxer>();
-    
-    FileMuxerParams params;
-    params.outputFile = filename;
-    params.format = AbstractMuxer::getFormatFromExtension(filename);
-    
-    ErrorCode result = muxer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建文件复用器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return muxer;
-}
-
-std::unique_ptr<FileMuxer> FileMuxer::FileMuxerFactory::createSegmentedMuxer(const std::string& pattern, int duration) {
-    auto muxer = std::make_unique<FileMuxer>();
-    
-    FileMuxerParams params;
-    params.outputFile = pattern;
-    params.enableSegmentation = true;
-    params.segmentDuration = duration;
-    params.segmentPattern = pattern;
-    
-    // 从模式中推断格式
-    std::string firstFile = pattern;
-    size_t pos = firstFile.find("%");
-    if (pos != std::string::npos) {
-        firstFile.replace(pos, firstFile.find('d', pos) - pos + 1, "001");
-    }
-    params.format = AbstractMuxer::getFormatFromExtension(firstFile);
-    
-    ErrorCode result = muxer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("创建分段复用器失败: {}", static_cast<int>(result));
-        return nullptr;
-    }
-    
-    return muxer;
-}
-
-} // namespace muxer
-} // namespace av

+ 0 - 197
AV/code/muxer/muxer_file_muxer.h

@@ -1,197 +0,0 @@
-#ifndef AV_MUXER_FILE_MUXER_H
-#define AV_MUXER_FILE_MUXER_H
-
-#include "muxer_abstract_muxer.h"
-#include <string>
-#include <memory>
-#include <thread>
-#include <queue>
-#include <condition_variable>
-#include <atomic>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavcodec/avcodec.h>
-#include <libavutil/avutil.h>
-}
-
-namespace av {
-namespace muxer {
-
-// 文件复用器参数
-struct FileMuxerParams : public MuxerParams {
-    std::string outputFile;             // 输出文件路径
-    bool overwrite = true;              // 是否覆盖已存在文件
-    
-    // 文件特定选项
-    int64_t maxFileSize = 0;            // 最大文件大小(字节,0表示无限制)
-    int maxDuration = 0;                // 最大录制时长(秒,0表示无限制)
-    bool enableSegmentation = false;    // 是否启用分段
-    int segmentDuration = 600;          // 分段时长(秒)
-    std::string segmentPattern;         // 分段文件名模式
-    
-    // 质量控制
-    bool enableFastStart = true;        // 启用快速开始(moov atom前置)
-    int movFlags = 0;                   // MOV标志
-    
-    // 同步选项
-    bool syncMode = false;              // 同步写入模式
-    int flushInterval = 5;              // 刷新间隔(秒)
-    
-    FileMuxerParams() : MuxerParams(MuxerType::FILE_MUXER) {}
-};
-
-// 包队列项
-struct PacketQueueItem {
-    AVPacket* packet = nullptr;
-    int streamIndex = -1;
-    std::chrono::steady_clock::time_point timestamp;
-    
-    PacketQueueItem() = default;
-    PacketQueueItem(AVPacket* pkt, int index) 
-        : packet(pkt), streamIndex(index), timestamp(std::chrono::steady_clock::now()) {}
-    
-    ~PacketQueueItem() {
-        if (packet) {
-            av_packet_free(&packet);
-        }
-    }
-    
-    // 禁用拷贝,只允许移动
-    PacketQueueItem(const PacketQueueItem&) = delete;
-    PacketQueueItem& operator=(const PacketQueueItem&) = delete;
-    
-    PacketQueueItem(PacketQueueItem&& other) noexcept
-        : packet(other.packet), streamIndex(other.streamIndex), timestamp(other.timestamp) {
-        other.packet = nullptr;
-    }
-    
-    PacketQueueItem& operator=(PacketQueueItem&& other) noexcept {
-        if (this != &other) {
-            if (packet) {
-                av_packet_free(&packet);
-            }
-            packet = other.packet;
-            streamIndex = other.streamIndex;
-            timestamp = other.timestamp;
-            other.packet = nullptr;
-        }
-        return *this;
-    }
-};
-
-// 文件复用器类
-class FileMuxer : public AbstractMuxer {
-public:
-    FileMuxer();
-    ~FileMuxer() override;
-    
-    // 基础接口实现
-    ErrorCode initialize(const MuxerParams& params) override;
-    ErrorCode start() override;
-    ErrorCode stop() override;
-    ErrorCode close() override;
-    
-    // 写入接口实现
-    ErrorCode writePacket(AVPacket* packet) override;
-    ErrorCode writeFrame(AVFrame* frame, int streamIndex) override;
-    ErrorCode flush() override;
-    
-    // 流管理实现
-    ErrorCode addStream(const StreamInfo& streamInfo) override;
-    
-    // 文件特定接口
-    ErrorCode setOutputFile(const std::string& filename);
-    std::string getOutputFile() const;
-    int64_t getCurrentFileSize() const;
-    double getCurrentDuration() const;
-    
-    // 分段控制
-    ErrorCode enableSegmentation(bool enable, int duration = 600);
-    ErrorCode forceNewSegment();
-    std::vector<std::string> getSegmentFiles() const;
-    
-    // 质量控制
-    ErrorCode setFastStart(bool enable);
-    ErrorCode setMovFlags(int flags);
-    
-    // 工厂类
-    class FileMuxerFactory : public MuxerFactory {
-    public:
-        std::unique_ptr<AbstractMuxer> createMuxer(MuxerType type) override;
-        bool isTypeSupported(MuxerType type) const override;
-        std::vector<MuxerType> getSupportedTypes() const override;
-        
-        // 文件复用器特定方法
-        static std::unique_ptr<FileMuxer> createFileMuxer(const std::string& filename);
-        static std::unique_ptr<FileMuxer> createSegmentedMuxer(const std::string& pattern, int duration);
-    };
-    
-protected:
-    // 内部实现方法
-    ErrorCode setupOutput() override;
-    ErrorCode writeHeader() override;
-    ErrorCode writeTrailer() override;
-    
-    // 文件操作
-    ErrorCode openOutputFile();
-    ErrorCode closeOutputFile();
-    ErrorCode createNewSegment();
-    
-    // 流设置
-    ErrorCode setupStreams();
-    AVStream* createAVStream(const StreamInfo& streamInfo);
-    
-    // 内部方法
-    ErrorCode processPacket(AVPacket* packet);
-    ErrorCode writePacketInternal(AVPacket* packet);
-    ErrorCode flushInternal(); // 内部刷新方法,假设已持有锁
-    
-    // 线程函数
-    void writeThreadFunc();
-    
-    // 工具方法
-    std::string generateSegmentFilename(int segmentIndex);
-    bool shouldCreateNewSegment() const;
-    ErrorCode validateFilePath(const std::string& path);
-    
-    // 参数验证
-    bool validateParams(const MuxerParams& params) override;
-    
-private:
-    FileMuxerParams fileMuxerParams_;
-    
-    // 文件信息
-    std::string currentOutputFile_;
-    int64_t currentFileSize_ = 0;
-    std::chrono::steady_clock::time_point fileStartTime_;
-    
-    // 分段相关
-    bool segmentationEnabled_ = false;
-    int currentSegmentIndex_ = 0;
-    std::vector<std::string> segmentFiles_;
-    
-    // 写入线程
-    std::thread writeThread_;
-    std::atomic<bool> shouldStopWriting_{false};
-    
-    // 包队列
-    std::queue<std::unique_ptr<PacketQueueItem>> packetQueue_;
-    mutable std::mutex queueMutex_;
-    std::condition_variable queueCondition_;
-    static constexpr size_t MAX_QUEUE_SIZE = 100;
-    
-    // 同步控制
-    mutable std::mutex fileMutex_;
-    std::chrono::steady_clock::time_point lastFlushTime_;
-    
-    // 性能监控
-    std::atomic<uint64_t> queuedPackets_{0};
-    std::atomic<uint64_t> writtenPackets_{0};
-    std::atomic<double> averageWriteTime_{0.0};
-};
-
-} // namespace muxer
-} // namespace av
-
-#endif // AV_MUXER_FILE_MUXER_H

+ 0 - 862
AV/code/muxer/muxer_stream_muxer.cpp

@@ -1,862 +0,0 @@
-#include "muxer_stream_muxer.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <sstream>
-#include <regex>
-
-extern "C" {
-#include <libavutil/opt.h>
-#include <libavutil/time.h>
-#include <libavformat/avio.h>
-}
-
-namespace av {
-namespace muxer {
-
-StreamMuxer::StreamMuxer() {
-    Logger::instance().info("StreamMuxer created");
-}
-
-StreamMuxer::~StreamMuxer() {
-    close();
-    Logger::instance().info("StreamMuxer destroyed");
-}
-
-ErrorCode StreamMuxer::initialize(const MuxerParams& params) {
-    if (!validateParams(params)) {
-        Logger::instance().error("Invalid stream muxer parameters");
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    streamParams_ = static_cast<const StreamMuxerParams&>(params);
-    
-    // 重置统计信息
-    connectionStats_ = ConnectionStats();
-    
-    // 设置初始状态
-    setConnectionState(ConnectionState::DISCONNECTED);
-    
-    Logger::instance().infof("StreamMuxer initialized with URL: {}", streamParams_.url);
-    return AbstractMuxer::initialize(params);
-}
-
-ErrorCode StreamMuxer::start() {
-    if (state_ != MuxerState::INITIALIZED) {
-        Logger::instance().error("StreamMuxer not initialized");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 建立连接
-    ErrorCode result = connect();
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to connect to stream");
-        return result;
-    }
-    
-    // 启动重连线程
-    if (streamParams_.enableAutoReconnect) {
-        shouldStopReconnect_ = false;
-        reconnectThread_ = std::thread(&StreamMuxer::reconnectThreadFunc, this);
-    }
-    
-    // 启动自适应码率监控
-    if (streamParams_.enableAdaptiveBitrate) {
-        shouldStopBitrateMonitor_ = false;
-        bitrateMonitorThread_ = std::thread(&StreamMuxer::monitorNetworkCondition, this);
-    }
-    
-    return AbstractMuxer::start();
-}
-
-ErrorCode StreamMuxer::stop() {
-    if (state_ != MuxerState::STARTED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 停止监控线程
-    shouldStopBitrateMonitor_ = true;
-    if (bitrateMonitorThread_.joinable()) {
-        bitrateMonitorThread_.join();
-    }
-    
-    // 停止重连线程
-    shouldStopReconnect_ = true;
-    reconnectCondition_.notify_all();
-    if (reconnectThread_.joinable()) {
-        reconnectThread_.join();
-    }
-    
-    // 断开连接
-    disconnect();
-    
-    return AbstractMuxer::stop();
-}
-
-ErrorCode StreamMuxer::close() {
-    stop();
-    
-    // 清理资源
-    connectionStats_ = ConnectionStats();
-    setConnectionState(ConnectionState::DISCONNECTED);
-    
-    return AbstractMuxer::close();
-}
-
-ErrorCode StreamMuxer::writePacket(AVPacket* packet) {
-    if (!packet) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (!isConnected()) {
-        Logger::instance().warning("Not connected, dropping packet");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    return processPacket(packet);
-}
-
-ErrorCode StreamMuxer::writeFrame(AVFrame* frame, int streamIndex) {
-    if (!frame || streamIndex < 0) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (!isConnected()) {
-        Logger::instance().warning("Not connected, dropping frame");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 将帧编码为包
-    AVPacket* packet = av_packet_alloc();
-    if (!packet) {
-        return ErrorCode::MEMORY_ALLOC_FAILED;
-    }
-    
-    // 这里需要编码器支持,暂时返回成功
-    av_packet_free(&packet);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::flush() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    int ret = av_write_trailer(formatCtx_);
-    if (ret < 0) {
-        Logger::instance().errorf("Failed to write trailer: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::OPERATION_FAILED;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::addStream(const StreamInfo& streamInfo) {
-    ErrorCode result = AbstractMuxer::addStream(streamInfo);
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    Logger::instance().infof("Added stream: type={}, codec={}", 
-                static_cast<int>(streamInfo.type), streamInfo.codecName);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::connect() {
-    if (connectionState_ == ConnectionState::CONNECTED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    setConnectionState(ConnectionState::CONNECTING);
-    
-    ErrorCode result = establishConnection();
-    if (result == ErrorCode::SUCCESS) {
-        setConnectionState(ConnectionState::CONNECTED);
-        connectionStats_.connectTime = std::chrono::steady_clock::now();
-        connectionStats_.lastDataTime = connectionStats_.connectTime;
-        Logger::instance().infof("Connected to stream: {}", streamParams_.url);
-    } else {
-        setConnectionState(ConnectionState::FAILED);
-        Logger::instance().errorf("Failed to connect to stream: {}", streamParams_.url);
-    }
-    
-    return result;
-}
-
-ErrorCode StreamMuxer::disconnect() {
-    if (connectionState_ == ConnectionState::DISCONNECTED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    ErrorCode result = closeConnection();
-    setConnectionState(ConnectionState::DISCONNECTED);
-    
-    Logger::instance().info("Disconnected from stream");
-    return result;
-}
-
-ErrorCode StreamMuxer::reconnect() {
-    Logger::instance().info("Attempting to reconnect...");
-    
-    setConnectionState(ConnectionState::RECONNECTING);
-    
-    // 先断开现有连接
-    closeConnection();
-    
-    // 等待一段时间
-    std::this_thread::sleep_for(std::chrono::milliseconds(streamParams_.reconnectDelay));
-    
-    // 重新连接
-    ErrorCode result = establishConnection();
-    if (result == ErrorCode::SUCCESS) {
-        setConnectionState(ConnectionState::CONNECTED);
-        connectionStats_.reconnectCount++;
-        connectionStats_.lastReconnectTime = std::chrono::steady_clock::now();
-        Logger::instance().info("Reconnected successfully");
-    } else {
-        setConnectionState(ConnectionState::FAILED);
-        Logger::instance().error("Reconnection failed");
-    }
-    
-    return result;
-}
-
-ConnectionState StreamMuxer::getConnectionState() const {
-    return connectionState_.load();
-}
-
-ConnectionStats StreamMuxer::getConnectionStats() const {
-    std::lock_guard<std::mutex> lock(connectionMutex_);
-    return connectionStats_;
-}
-
-bool StreamMuxer::isConnected() const {
-    return connectionState_ == ConnectionState::CONNECTED;
-}
-
-ErrorCode StreamMuxer::setUrl(const std::string& url) {
-    if (state_ != MuxerState::IDLE) {
-        Logger::instance().error("Cannot change URL while muxer is active");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (!validateUrl(url)) {
-        Logger::instance().errorf("Invalid URL: {}", url);
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    streamParams_.url = url;
-    Logger::instance().infof("URL set to: {}", url);
-    return ErrorCode::SUCCESS;
-}
-
-std::string StreamMuxer::getUrl() const {
-    return streamParams_.url;
-}
-
-ErrorCode StreamMuxer::enableAdaptiveBitrate(bool enable) {
-    adaptiveBitrateEnabled_ = enable;
-    
-    if (enable && state_ == MuxerState::STARTED && !bitrateMonitorThread_.joinable()) {
-        shouldStopBitrateMonitor_ = false;
-        bitrateMonitorThread_ = std::thread(&StreamMuxer::monitorNetworkCondition, this);
-    }
-    
-    Logger::instance().infof("Adaptive bitrate {}", enable ? "enabled" : "disabled");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::setBitrateRange(int minBitrate, int maxBitrate) {
-    if (minBitrate <= 0 || maxBitrate <= minBitrate) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    streamParams_.minBitrate = minBitrate;
-    streamParams_.maxBitrate = maxBitrate;
-    
-    Logger::instance().infof("Bitrate range set: {} - {} bps", minBitrate, maxBitrate);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::adjustBitrate(double factor) {
-    if (factor <= 0.0 || factor > 2.0) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    int newBitrate = static_cast<int>(currentBitrate_ * factor);
-    newBitrate = std::clamp(newBitrate, streamParams_.minBitrate, streamParams_.maxBitrate);
-    
-    if (newBitrate != currentBitrate_) {
-        currentBitrate_ = newBitrate;
-        if (bitrateCallback_) {
-            bitrateCallback_(newBitrate);
-        }
-        Logger::instance().infof("Bitrate adjusted to: {} bps", newBitrate);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::setProtocolOption(const std::string& key, const std::string& value) {
-    streamParams_.protocolOptions[key] = value;
-    Logger::instance().debugf("Protocol option set: {}={}", key, value);
-    return ErrorCode::SUCCESS;
-}
-
-std::string StreamMuxer::getProtocolOption(const std::string& key) const {
-    auto it = streamParams_.protocolOptions.find(key);
-    return (it != streamParams_.protocolOptions.end()) ? it->second : "";
-}
-
-// 内部实现方法
-ErrorCode StreamMuxer::setupOutput() {
-    // 根据协议设置输出格式
-    const char* formatName = nullptr;
-    switch (streamParams_.protocol) {
-        case StreamProtocol::RTMP:
-        case StreamProtocol::RTMPS:
-            formatName = "flv";
-            break;
-        case StreamProtocol::UDP:
-        case StreamProtocol::TCP:
-            formatName = "mpegts";
-            break;
-        case StreamProtocol::HTTP:
-        case StreamProtocol::HTTPS:
-            formatName = "hls";
-            break;
-        case StreamProtocol::SRT:
-        case StreamProtocol::RIST:
-            formatName = "mpegts";
-            break;
-        default:
-            formatName = "flv";
-            break;
-    }
-    
-    // 分配格式上下文
-    int ret = avformat_alloc_output_context2(&formatCtx_, NULL, formatName, streamParams_.url.c_str());
-    if (ret < 0) {
-        Logger::instance().errorf("Failed to allocate output context: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::INITIALIZATION_FAILED;
-    }
-    
-    // 设置协议特定选项
-    switch (streamParams_.protocol) {
-        case StreamProtocol::RTMP:
-        case StreamProtocol::RTMPS:
-            return setupRTMP();
-        case StreamProtocol::UDP:
-            return setupUDP();
-        case StreamProtocol::TCP:
-            return setupTCP();
-        case StreamProtocol::SRT:
-            return setupSRT();
-        default:
-            break;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::writeHeader() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 打开输出
-    int ret = avio_open(&formatCtx_->pb, streamParams_.url.c_str(), AVIO_FLAG_WRITE);
-    if (ret < 0) {
-        Logger::instance().errorf("Failed to open output: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::OPERATION_FAILED;
-    }
-    
-    // 写入头部
-    ret = avformat_write_header(formatCtx_, NULL);
-    if (ret < 0) {
-        Logger::instance().errorf("Failed to write header: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::OPERATION_FAILED;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::writeTrailer() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    int ret = av_write_trailer(formatCtx_);
-    if (ret < 0) {
-        Logger::instance().errorf("Failed to write trailer: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::OPERATION_FAILED;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::establishConnection() {
-    // 设置输出
-    ErrorCode result = setupOutput();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 写入头部
-    result = writeHeader();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::closeConnection() {
-    if (formatCtx_ && formatCtx_->pb) {
-        // 写入尾部
-        writeTrailer();
-        
-        // 关闭输出
-        avio_closep(&formatCtx_->pb);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::setupRTMP() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 设置RTMP选项
-    AVDictionary* options = NULL;
-    
-    // 连接超时
-    av_dict_set_int(&options, "timeout", streamParams_.connectTimeout * 1000, 0);
-    
-    // 直播模式
-    if (streamParams_.rtmpLive) {
-        av_dict_set(&options, "live", "1", 0);
-    }
-    
-    // 缓冲区大小
-    av_dict_set_int(&options, "buffer_size", streamParams_.sendBufferSize, 0);
-    
-    // 应用协议选项
-    for (const auto& option : streamParams_.protocolOptions) {
-        av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
-    }
-    
-    formatCtx_->metadata = options;
-    
-    Logger::instance().debug("RTMP setup completed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::setupUDP() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 设置UDP选项
-    AVDictionary* options = NULL;
-    
-    // 缓冲区大小
-    av_dict_set_int(&options, "buffer_size", streamParams_.sendBufferSize, 0);
-    
-    // 重用地址
-    if (streamParams_.reuseAddress) {
-        av_dict_set(&options, "reuse", "1", 0);
-    }
-    
-    // 本地地址和端口
-    if (!streamParams_.localAddress.empty()) {
-        av_dict_set(&options, "localaddr", streamParams_.localAddress.c_str(), 0);
-    }
-    if (streamParams_.localPort > 0) {
-        av_dict_set_int(&options, "localport", streamParams_.localPort, 0);
-    }
-    
-    // 应用协议选项
-    for (const auto& option : streamParams_.protocolOptions) {
-        av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
-    }
-    
-    formatCtx_->metadata = options;
-    
-    Logger::instance().debug("UDP setup completed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::setupTCP() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 设置TCP选项
-    AVDictionary* options = NULL;
-    
-    // 连接超时
-    av_dict_set_int(&options, "timeout", streamParams_.connectTimeout * 1000, 0);
-    
-    // 缓冲区大小
-    av_dict_set_int(&options, "buffer_size", streamParams_.sendBufferSize, 0);
-    
-    // 应用协议选项
-    for (const auto& option : streamParams_.protocolOptions) {
-        av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
-    }
-    
-    formatCtx_->metadata = options;
-    
-    Logger::instance().debug("TCP setup completed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::setupSRT() {
-    if (!formatCtx_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 设置SRT选项
-    AVDictionary* options = NULL;
-    
-    // 延迟
-    av_dict_set_int(&options, "latency", streamParams_.srtLatency * 1000, 0);
-    
-    // 密码
-    if (!streamParams_.srtPassphrase.empty()) {
-        av_dict_set(&options, "passphrase", streamParams_.srtPassphrase.c_str(), 0);
-    }
-    
-    // 应用协议选项
-    for (const auto& option : streamParams_.protocolOptions) {
-        av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
-    }
-    
-    formatCtx_->metadata = options;
-    
-    Logger::instance().debug("SRT setup completed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode StreamMuxer::processPacket(AVPacket* packet) {
-    if (!packet || !formatCtx_) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 发送包
-    ErrorCode result = sendPacket(packet);
-    if (result == ErrorCode::SUCCESS) {
-        // 更新统计信息
-        updateConnectionStats();
-        updateBandwidthStats(packet->size);
-        
-        // 更新包统计
-        stats_.totalPackets++;
-        stats_.totalBytes += packet->size;
-        connectionStats_.packetsSent++;
-        connectionStats_.bytesSent += packet->size;
-        connectionStats_.lastDataTime = std::chrono::steady_clock::now();
-    } else {
-        stats_.errorCount++;
-        Logger::instance().warning("Failed to send packet");
-    }
-    
-    return result;
-}
-
-ErrorCode StreamMuxer::sendPacket(AVPacket* packet) {
-    if (!packet || !formatCtx_) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    int ret = av_interleaved_write_frame(formatCtx_, packet);
-    if (ret < 0) {
-        Logger::instance().errorf("Failed to write packet: {}", ffmpeg_utils::errorToString(ret));
-        return ErrorCode::OPERATION_FAILED;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-void StreamMuxer::monitorNetworkCondition() {
-    Logger::instance().debug("Network condition monitoring started");
-    
-    while (!shouldStopBitrateMonitor_) {
-        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
-        
-        if (adaptiveBitrateEnabled_ && isConnected()) {
-            adjustBitrateBasedOnCondition();
-        }
-    }
-    
-    Logger::instance().debug("Network condition monitoring stopped");
-}
-
-void StreamMuxer::adjustBitrateBasedOnCondition() {
-    // 获取当前网络状态
-    double currentBandwidth = connectionStats_.currentBandwidth;
-    double rtt = connectionStats_.rtt;
-    
-    // 简单的自适应算法
-    double targetUtilization = 0.8; // 目标带宽利用率
-    double currentUtilization = (currentBitrate_ > 0) ? (currentBandwidth / currentBitrate_) : 0.0;
-    
-    if (currentUtilization < targetUtilization * 0.7) {
-        // 网络状况良好,可以提高码率
-        adjustBitrate(1.1);
-    } else if (currentUtilization > targetUtilization * 1.2 || rtt > 200.0) {
-        // 网络拥塞,降低码率
-        adjustBitrate(streamParams_.bitrateAdjustFactor);
-    }
-}
-
-void StreamMuxer::reconnectThreadFunc() {
-    Logger::instance().debug("Reconnect thread started");
-    
-    int attemptCount = 0;
-    
-    while (!shouldStopReconnect_) {
-        std::unique_lock<std::mutex> lock(reconnectMutex_);
-        
-        // 等待重连请求或停止信号
-        reconnectCondition_.wait(lock, [this] {
-            return shouldStopReconnect_ || reconnectRequested_ || shouldReconnect();
-        });
-        
-        if (shouldStopReconnect_) {
-            break;
-        }
-        
-        if (shouldReconnect() && attemptCount < streamParams_.maxReconnectAttempts) {
-            attemptCount++;
-            Logger::instance().infof("Reconnect attempt {}/{}", attemptCount, streamParams_.maxReconnectAttempts);
-            
-            lock.unlock();
-            
-            // 计算重连延迟
-            int delay = calculateReconnectDelay(attemptCount);
-            std::this_thread::sleep_for(std::chrono::milliseconds(delay));
-            
-            // 尝试重连
-            if (reconnect() == ErrorCode::SUCCESS) {
-                attemptCount = 0; // 重连成功,重置计数
-            }
-            
-            lock.lock();
-        }
-        
-        reconnectRequested_ = false;
-    }
-    
-    Logger::instance().debug("Reconnect thread stopped");
-}
-
-bool StreamMuxer::shouldReconnect() const {
-    ConnectionState state = connectionState_.load();
-    return (state == ConnectionState::FAILED || state == ConnectionState::DISCONNECTED) &&
-           streamParams_.enableAutoReconnect;
-}
-
-int StreamMuxer::calculateReconnectDelay(int attempt) const {
-    double delay = streamParams_.reconnectDelay;
-    for (int i = 1; i < attempt; ++i) {
-        delay *= streamParams_.reconnectBackoffFactor;
-    }
-    return static_cast<int>(std::min(delay, 30000.0)); // 最大30秒
-}
-
-void StreamMuxer::updateConnectionStats() {
-    auto now = std::chrono::steady_clock::now();
-    
-    // 更新统计信息的时间间隔检查
-    if (std::chrono::duration<double>(now - lastStatsUpdate_).count() < STATS_UPDATE_INTERVAL) {
-        return;
-    }
-    
-    std::lock_guard<std::mutex> lock(connectionMutex_);
-    
-    // 计算平均带宽
-    double totalBandwidth = 0.0;
-    int validSamples = 0;
-    for (int i = 0; i < 10; ++i) {
-        if (bandwidthSamples_[i] > 0) {
-            totalBandwidth += bandwidthSamples_[i];
-            validSamples++;
-        }
-    }
-    
-    if (validSamples > 0) {
-        connectionStats_.averageBandwidth = totalBandwidth / validSamples;
-    }
-    
-    lastStatsUpdate_ = now;
-}
-
-void StreamMuxer::updateBandwidthStats(size_t bytes) {
-    auto now = std::chrono::steady_clock::now();
-    
-    // 更新带宽统计的时间间隔检查
-    if (std::chrono::duration<double>(now - lastBandwidthUpdate_).count() < BANDWIDTH_UPDATE_INTERVAL) {
-        return;
-    }
-    
-    std::lock_guard<std::mutex> lock(connectionMutex_);
-    
-    // 计算当前带宽
-    double timeDiff = std::chrono::duration<double>(now - lastBandwidthUpdate_).count();
-    if (timeDiff > 0) {
-        uint64_t bytesDiff = connectionStats_.bytesSent - lastBytesSent_;
-        double bandwidth = (bytesDiff * 8.0) / timeDiff; // bps
-        
-        // 更新带宽采样
-        bandwidthSamples_[bandwidthSampleIndex_] = bandwidth;
-        bandwidthSampleIndex_ = (bandwidthSampleIndex_ + 1) % 10;
-        
-        connectionStats_.currentBandwidth = bandwidth;
-        lastBytesSent_ = connectionStats_.bytesSent;
-    }
-    
-    lastBandwidthUpdate_ = now;
-}
-
-void StreamMuxer::setConnectionState(ConnectionState state) {
-    ConnectionState oldState = connectionState_.exchange(state);
-    if (oldState != state) {
-        onConnectionStateChanged(state);
-    }
-}
-
-void StreamMuxer::onConnectionStateChanged(ConnectionState state) {
-    Logger::instance().infof("Connection state changed to: {}", static_cast<int>(state));
-    
-    if (connectionCallback_) {
-        connectionCallback_(state);
-    }
-    
-    // 根据状态变化触发相应操作
-    if (state == ConnectionState::FAILED && streamParams_.enableAutoReconnect) {
-        reconnectRequested_ = true;
-        reconnectCondition_.notify_one();
-    }
-}
-
-bool StreamMuxer::validateParams(const MuxerParams& params) {
-    if (!AbstractMuxer::validateParams(params)) {
-        return false;
-    }
-    
-    const StreamMuxerParams& streamParams = static_cast<const StreamMuxerParams&>(params);
-    
-    // 验证URL
-    if (!validateUrl(streamParams.url)) {
-        Logger::instance().errorf("Invalid URL: {}", streamParams.url);
-        return false;
-    }
-    
-    // 验证超时参数
-    if (streamParams.connectTimeout <= 0 || streamParams.sendTimeout <= 0) {
-        Logger::instance().error("Invalid timeout parameters");
-        return false;
-    }
-    
-    // 验证重连参数
-    if (streamParams.maxReconnectAttempts < 0 || streamParams.reconnectDelay < 0) {
-        Logger::instance().error("Invalid reconnect parameters");
-        return false;
-    }
-    
-    // 验证码率参数
-    if (streamParams.minBitrate <= 0 || streamParams.maxBitrate <= streamParams.minBitrate) {
-        Logger::instance().error("Invalid bitrate parameters");
-        return false;
-    }
-    
-    return true;
-}
-
-bool StreamMuxer::validateUrl(const std::string& url) const {
-    if (url.empty()) {
-        return false;
-    }
-    
-    // 简单的URL格式验证
-    std::regex urlPattern(R"(^(rtmp|rtmps|udp|tcp|http|https|srt|rist)://.*)");
-    return std::regex_match(url, urlPattern);
-}
-
-// 工厂类实现
-std::unique_ptr<AbstractMuxer> StreamMuxer::StreamMuxerFactory::createMuxer(MuxerType type) {
-    if (type == MuxerType::STREAM_MUXER) {
-        return std::make_unique<StreamMuxer>();
-    }
-    return nullptr;
-}
-
-bool StreamMuxer::StreamMuxerFactory::isTypeSupported(MuxerType type) const {
-    return type == MuxerType::STREAM_MUXER;
-}
-
-std::vector<MuxerType> StreamMuxer::StreamMuxerFactory::getSupportedTypes() const {
-    return {MuxerType::STREAM_MUXER};
-}
-
-std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createRTMPMuxer(const std::string& url) {
-    auto muxer = std::make_unique<StreamMuxer>();
-    
-    StreamMuxerParams params;
-    params.protocol = StreamProtocol::RTMP;
-    params.url = url;
-    params.rtmpLive = true;
-    
-    if (muxer->initialize(params) == ErrorCode::SUCCESS) {
-        return muxer;
-    }
-    
-    return nullptr;
-}
-
-std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createUDPMuxer(const std::string& address, int port) {
-    auto muxer = std::make_unique<StreamMuxer>();
-    
-    StreamMuxerParams params;
-    params.protocol = StreamProtocol::UDP;
-    params.url = "udp://" + address + ":" + std::to_string(port);
-    
-    if (muxer->initialize(params) == ErrorCode::SUCCESS) {
-        return muxer;
-    }
-    
-    return nullptr;
-}
-
-std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createTCPMuxer(const std::string& address, int port) {
-    auto muxer = std::make_unique<StreamMuxer>();
-    
-    StreamMuxerParams params;
-    params.protocol = StreamProtocol::TCP;
-    params.url = "tcp://" + address + ":" + std::to_string(port);
-    
-    if (muxer->initialize(params) == ErrorCode::SUCCESS) {
-        return muxer;
-    }
-    
-    return nullptr;
-}
-
-std::unique_ptr<StreamMuxer> StreamMuxer::StreamMuxerFactory::createSRTMuxer(const std::string& url) {
-    auto muxer = std::make_unique<StreamMuxer>();
-    
-    StreamMuxerParams params;
-    params.protocol = StreamProtocol::SRT;
-    params.url = url;
-    
-    if (muxer->initialize(params) == ErrorCode::SUCCESS) {
-        return muxer;
-    }
-    
-    return nullptr;
-}
-
-} // namespace muxer
-} // namespace av

+ 0 - 257
AV/code/muxer/muxer_stream_muxer.h

@@ -1,257 +0,0 @@
-#ifndef AV_MUXER_STREAM_MUXER_H
-#define AV_MUXER_STREAM_MUXER_H
-
-#include "muxer_abstract_muxer.h"
-#include <string>
-#include <memory>
-#include <thread>
-#include <queue>
-#include <condition_variable>
-#include <atomic>
-#include <chrono>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavcodec/avcodec.h>
-#include <libavutil/avutil.h>
-}
-
-namespace av {
-namespace muxer {
-
-// 流协议类型
-enum class StreamProtocol {
-    RTMP = 0,           // RTMP协议
-    RTMPS,              // RTMPS协议
-    UDP,                // UDP协议
-    TCP,                // TCP协议
-    HTTP,               // HTTP协议
-    HTTPS,              // HTTPS协议
-    SRT,                // SRT协议
-    RIST                // RIST协议
-};
-
-// 连接状态
-enum class ConnectionState {
-    DISCONNECTED = 0,   // 未连接
-    CONNECTING,         // 连接中
-    CONNECTED,          // 已连接
-    RECONNECTING,       // 重连中
-    FAILED              // 连接失败
-};
-
-// 流复用器参数
-struct StreamMuxerParams : public MuxerParams {
-    StreamProtocol protocol = StreamProtocol::RTMP;
-    std::string url;                    // 推流URL
-    
-    // 连接参数
-    int connectTimeout = 5000;          // 连接超时(毫秒)
-    int sendTimeout = 5000;             // 发送超时(毫秒)
-    int receiveTimeout = 5000;          // 接收超时(毫秒)
-    
-    // 重连参数
-    bool enableAutoReconnect = true;    // 启用自动重连
-    int maxReconnectAttempts = 5;       // 最大重连次数
-    int reconnectDelay = 2000;          // 重连延迟(毫秒)
-    double reconnectBackoffFactor = 1.5; // 重连退避因子
-    
-    // 缓冲参数
-    int sendBufferSize = 1024 * 1024;   // 发送缓冲区大小
-    int receiveBufferSize = 1024 * 1024; // 接收缓冲区大小
-    
-    // 质量控制
-    bool enableAdaptiveBitrate = false; // 启用自适应码率
-    int minBitrate = 500000;            // 最小码率(bps)
-    int maxBitrate = 5000000;           // 最大码率(bps)
-    double bitrateAdjustFactor = 0.8;   // 码率调整因子
-    
-    // 协议特定参数
-    std::map<std::string, std::string> protocolOptions; // 协议选项
-    
-    // RTMP特定参数
-    std::string rtmpApp;                // RTMP应用名
-    std::string rtmpStreamKey;          // RTMP流密钥
-    bool rtmpLive = true;               // RTMP直播模式
-    
-    // UDP/TCP特定参数
-    std::string localAddress;          // 本地地址
-    int localPort = 0;                  // 本地端口
-    bool reuseAddress = true;           // 重用地址
-    
-    // SRT特定参数
-    int srtLatency = 120;               // SRT延迟(毫秒)
-    std::string srtPassphrase;          // SRT密码
-    
-    StreamMuxerParams() : MuxerParams(MuxerType::STREAM_MUXER) {}
-};
-
-// 连接统计信息
-struct ConnectionStats {
-    ConnectionState state = ConnectionState::DISCONNECTED;
-    std::chrono::steady_clock::time_point connectTime;
-    std::chrono::steady_clock::time_point lastDataTime;
-    
-    // 网络统计
-    uint64_t bytesSent = 0;             // 已发送字节数
-    uint64_t bytesReceived = 0;         // 已接收字节数
-    uint64_t packetsSent = 0;           // 已发送包数
-    uint64_t packetsLost = 0;           // 丢失包数
-    
-    // 性能统计
-    double currentBandwidth = 0.0;      // 当前带宽(bps)
-    double averageBandwidth = 0.0;      // 平均带宽(bps)
-    double rtt = 0.0;                   // 往返时间(毫秒)
-    double jitter = 0.0;                // 抖动(毫秒)
-    
-    // 重连统计
-    int reconnectCount = 0;             // 重连次数
-    std::chrono::steady_clock::time_point lastReconnectTime;
-};
-
-// 流复用器类
-class StreamMuxer : public AbstractMuxer {
-public:
-    StreamMuxer();
-    ~StreamMuxer() override;
-    
-    // 基础接口实现
-    ErrorCode initialize(const MuxerParams& params) override;
-    ErrorCode start() override;
-    ErrorCode stop() override;
-    ErrorCode close() override;
-    
-    // 写入接口实现
-    ErrorCode writePacket(AVPacket* packet) override;
-    ErrorCode writeFrame(AVFrame* frame, int streamIndex) override;
-    ErrorCode flush() override;
-    
-    // 流管理实现
-    ErrorCode addStream(const StreamInfo& streamInfo) override;
-    
-    // 连接管理
-    ErrorCode connect();
-    ErrorCode disconnect();
-    ErrorCode reconnect();
-    
-    // 状态查询
-    ConnectionState getConnectionState() const;
-    ConnectionStats getConnectionStats() const;
-    bool isConnected() const;
-    
-    // 流特定接口
-    ErrorCode setUrl(const std::string& url);
-    std::string getUrl() const;
-    
-    // 自适应码率控制
-    ErrorCode enableAdaptiveBitrate(bool enable);
-    ErrorCode setBitrateRange(int minBitrate, int maxBitrate);
-    ErrorCode adjustBitrate(double factor);
-    
-    // 协议选项
-    ErrorCode setProtocolOption(const std::string& key, const std::string& value);
-    std::string getProtocolOption(const std::string& key) const;
-    
-    // 回调设置
-    using ConnectionCallback = std::function<void(ConnectionState)>;
-    using BitrateCallback = std::function<void(int)>; // 新码率
-    
-    void setConnectionCallback(ConnectionCallback callback) { connectionCallback_ = callback; }
-    void setBitrateCallback(BitrateCallback callback) { bitrateCallback_ = callback; }
-    
-    // 工厂类
-    class StreamMuxerFactory : public MuxerFactory {
-    public:
-        std::unique_ptr<AbstractMuxer> createMuxer(MuxerType type) override;
-        bool isTypeSupported(MuxerType type) const override;
-        std::vector<MuxerType> getSupportedTypes() const override;
-        
-        // 流复用器特定方法
-        static std::unique_ptr<StreamMuxer> createRTMPMuxer(const std::string& url);
-        static std::unique_ptr<StreamMuxer> createUDPMuxer(const std::string& address, int port);
-        static std::unique_ptr<StreamMuxer> createTCPMuxer(const std::string& address, int port);
-        static std::unique_ptr<StreamMuxer> createSRTMuxer(const std::string& url);
-    };
-    
-protected:
-    // 内部实现方法
-    ErrorCode setupOutput() override;
-    ErrorCode writeHeader() override;
-    ErrorCode writeTrailer() override;
-    
-    // 连接管理
-    ErrorCode establishConnection();
-    ErrorCode closeConnection();
-    
-    // 协议特定设置
-    ErrorCode setupRTMP();
-    ErrorCode setupUDP();
-    ErrorCode setupTCP();
-    ErrorCode setupSRT();
-    
-    // 包处理
-    ErrorCode processPacket(AVPacket* packet);
-    ErrorCode sendPacket(AVPacket* packet);
-    
-    // 自适应码率
-    void monitorNetworkCondition();
-    void adjustBitrateBasedOnCondition();
-    
-    // 重连逻辑
-    void reconnectThreadFunc();
-    bool shouldReconnect() const;
-    int calculateReconnectDelay(int attempt) const;
-    
-    // 统计更新
-    void updateConnectionStats();
-    void updateBandwidthStats(size_t bytes);
-    
-    // 状态管理
-    void setConnectionState(ConnectionState state);
-    void onConnectionStateChanged(ConnectionState state);
-    
-    // 参数验证
-    bool validateParams(const MuxerParams& params) override;
-    bool validateUrl(const std::string& url) const;
-    
-private:
-    StreamMuxerParams streamParams_;
-    
-    // 连接状态
-    std::atomic<ConnectionState> connectionState_{ConnectionState::DISCONNECTED};
-    ConnectionStats connectionStats_;
-    mutable std::mutex connectionMutex_;
-    
-    // 重连控制
-    std::thread reconnectThread_;
-    std::atomic<bool> shouldStopReconnect_{false};
-    std::atomic<bool> reconnectRequested_{false};
-    std::condition_variable reconnectCondition_;
-    std::mutex reconnectMutex_;
-    
-    // 自适应码率
-    std::atomic<bool> adaptiveBitrateEnabled_{false};
-    std::atomic<int> currentBitrate_{0};
-    std::thread bitrateMonitorThread_;
-    std::atomic<bool> shouldStopBitrateMonitor_{false};
-    
-    // 网络监控
-    std::chrono::steady_clock::time_point lastBandwidthUpdate_;
-    uint64_t lastBytesSent_ = 0;
-    double bandwidthSamples_[10] = {0}; // 带宽采样窗口
-    int bandwidthSampleIndex_ = 0;
-    
-    // 回调函数
-    ConnectionCallback connectionCallback_;
-    BitrateCallback bitrateCallback_;
-    
-    // 性能监控
-    std::chrono::steady_clock::time_point lastStatsUpdate_;
-    static constexpr double STATS_UPDATE_INTERVAL = 1.0; // 统计更新间隔(秒)
-    static constexpr double BANDWIDTH_UPDATE_INTERVAL = 0.5; // 带宽更新间隔(秒)
-};
-
-} // namespace muxer
-} // namespace av
-
-#endif // AV_MUXER_STREAM_MUXER_H

+ 0 - 668
AV/code/player/audio_output.cpp

@@ -1,668 +0,0 @@
-#include "audio_output.h"
-#include <QAudioDeviceInfo>
-#include <QDebug>
-#include "../base/logger.h"
-#include "../utils/utils_synchronizer_v2.h"
-#include "AV/code/base/media_common.h"
-#include <algorithm>
-#include <chrono>
-#include <cstring>
-#include <thread>
-
-extern "C" {
-#include <libavutil/channel_layout.h>
-#include <libavutil/avutil.h>
-#include <libavutil/time.h>
-#include <libavutil/opt.h>
-#include <libswresample/swresample.h>
-}
-
-namespace av {
-namespace player {
-
-AudioOutput::AudioOutput(QObject* parent)
-    : QObject(parent)
-    , m_audioOutput(nullptr)
-    , m_audioDevice(nullptr)
-    , m_sampleRate(44100)
-    , m_channels(2)
-    , m_inputFormat(AV_SAMPLE_FMT_S16)
-    , m_swrContext(nullptr)
-    , m_needResampling(false)
-    , m_volume(1.0)
-    , m_playbackSpeed(1.0)
-    , m_lastAudioPts(0.0)
-    , m_initialized(false)
-    , m_playing(false)
-{
-}
-
-AudioOutput::~AudioOutput()
-{
-    stop();
-    cleanupResampler();
-    
-    if (m_audioOutput) {
-        delete m_audioOutput;
-        m_audioOutput = nullptr;
-    }
-}
-
-bool AudioOutput::initialize(int sampleRate, int channels, AVSampleFormat sampleFormat)
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (m_initialized) {
-        av::Logger::instance().warning("Audio output already initialized");
-        return true;
-    }
-    
-    m_sampleRate = sampleRate;
-    m_channels = channels;
-    m_inputFormat = sampleFormat;
-    
-    // 设置Qt音频格式
-    m_audioFormat.setSampleRate(sampleRate);
-    m_audioFormat.setChannelCount(channels);
-    m_audioFormat.setSampleSize(16); // 输出16位
-    m_audioFormat.setCodec("audio/pcm");
-    m_audioFormat.setByteOrder(QAudioFormat::LittleEndian);
-    m_audioFormat.setSampleType(QAudioFormat::SignedInt);
-    
-    // 检查设备是否支持该格式
-    QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
-    if (!deviceInfo.isFormatSupported(m_audioFormat)) {
-        av::Logger::instance().warning("Audio format not supported, using nearest format");
-        m_audioFormat = deviceInfo.nearestFormat(m_audioFormat);
-        
-        // 验证获取的格式是否有效
-        if (m_audioFormat.sampleRate() <= 0 || m_audioFormat.channelCount() <= 0) {
-            av::Logger::instance().warning("Device returned invalid audio format, using fallback");
-            av::Logger::instance().warningf("Invalid format: {}Hz, {}ch", 
-                                           m_audioFormat.sampleRate(), 
-                                           m_audioFormat.channelCount());
-            
-            // 使用默认格式作为后备
-            m_audioFormat.setSampleRate(44100);
-            m_audioFormat.setChannelCount(2);
-            m_audioFormat.setSampleSize(16);
-            m_audioFormat.setCodec("audio/pcm");
-            m_audioFormat.setByteOrder(QAudioFormat::LittleEndian);
-            m_audioFormat.setSampleType(QAudioFormat::SignedInt);
-            
-            av::Logger::instance().info("Using fallback audio format: 44100Hz, 2ch, 16bit");
-        }
-        
-        // 记录实际使用的格式
-        av::Logger::instance().info("Using audio format: " + 
-            std::to_string(m_audioFormat.sampleRate()) + "Hz, " +
-            std::to_string(m_audioFormat.channelCount()) + "ch, " +
-            std::to_string(m_audioFormat.sampleSize()) + "bit");
-    }
-    
-    // 创建音频输出设备
-    m_audioOutput = new QAudioOutput(m_audioFormat, this);
-    if (!m_audioOutput) {
-        av::Logger::instance().error("Failed to create audio output device");
-        return false;
-    }
-    
-    // 设置缓冲区大小
-    m_audioOutput->setBufferSize(32768); // 32KB缓冲区
-    
-    // 连接状态变化信号
-    connect(m_audioOutput, &QAudioOutput::stateChanged,
-            this, &AudioOutput::onStateChanged);
-    
-    // 记录音频格式信息
-    av::Logger::instance().info("Audio format: " + 
-        std::to_string(m_audioFormat.sampleRate()) + "Hz, " +
-        std::to_string(m_audioFormat.channelCount()) + "ch, " +
-        std::to_string(m_audioFormat.sampleSize()) + "bit, " +
-        m_audioFormat.codec().toStdString());
-    
-    // 初始化重采样器(如果需要)
-    if (!initResampler()) {
-        av::Logger::instance().error("Failed to initialize audio resampler");
-        return false;
-    }
-    
-    m_initialized = true;
-    av::Logger::instance().info("Audio output initialized successfully");
-    
-    return true;
-}
-
-void AudioOutput::start()
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (!m_initialized || !m_audioOutput) {
-        av::Logger::instance().error("Audio output not initialized");
-        return;
-    }
-    
-    if (m_playing) {
-        return;
-    }
-    
-    av::Logger::instance().debug("Starting audio output device...");
-    av::Logger::instance().debug("Audio output state before start: " + std::to_string(m_audioOutput->state()));
-    
-    // 检查音频格式
-    QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
-    av::Logger::instance().debug("Default audio device: " + deviceInfo.deviceName().toStdString());
-    av::Logger::instance().debug("Audio format supported: " + std::to_string(deviceInfo.isFormatSupported(m_audioFormat)));
-    
-    // 确保音频输出设备处于正确状态
-    if (m_audioOutput->state() == QAudio::StoppedState) {
-        av::Logger::instance().debug("Resetting audio output device");
-        m_audioOutput->reset();
-        // 给设备一点时间重置
-        std::this_thread::sleep_for(std::chrono::milliseconds(50));
-    }
-    
-    // 如果设备不支持当前格式,尝试使用最接近的格式
-    if (!deviceInfo.isFormatSupported(m_audioFormat)) {
-        av::Logger::instance().warning("Audio format not supported, using nearest format");
-        QAudioFormat nearestFormat = deviceInfo.nearestFormat(m_audioFormat);
-        // m_audioOutput->setFormat(nearestFormat);
-        av::Logger::instance().info("Using nearest format: " + 
-            std::to_string(nearestFormat.sampleRate()) + "Hz, " +
-            std::to_string(nearestFormat.channelCount()) + "ch, " +
-            std::to_string(nearestFormat.sampleSize()) + "bit");
-    }
-    
-    // 尝试多次启动音频设备
-    int retryCount = 0;
-    const int maxRetries = 5; // 增加重试次数
-    bool deviceStarted = false;
-    
-    while (retryCount < maxRetries && !deviceStarted) {
-        if (retryCount > 0) {
-            av::Logger::instance().info("Retrying audio device start (attempt " + std::to_string(retryCount + 1) + "/" + std::to_string(maxRetries) + ")");
-            
-            // 重新创建音频输出设备
-            if (m_audioOutput) {
-                m_audioOutput->stop();
-                delete m_audioOutput;
-                m_audioOutput = nullptr;
-            }
-            
-            // 等待更长时间让系统释放音频资源
-            std::this_thread::sleep_for(std::chrono::milliseconds(500));
-            
-            m_audioOutput = new QAudioOutput(m_audioFormat, this);
-            if (!m_audioOutput) {
-                av::Logger::instance().error("Failed to recreate audio output device");
-                return;
-            }
-            
-            m_audioOutput->setBufferSize(32768);
-            connect(m_audioOutput, &QAudioOutput::stateChanged, this, &AudioOutput::onStateChanged);
-        }
-        
-        // 检查音频设备可用性
-        QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
-        if (deviceInfo.isNull()) {
-            av::Logger::instance().error("No audio output device available");
-            return;
-        }
-        
-        av::Logger::instance().debug("Starting audio device (attempt " + std::to_string(retryCount + 1) + ")");
-        m_audioDevice = m_audioOutput->start();
-        if (!m_audioDevice) {
-            av::Logger::instance().warning("Failed to start audio output device (attempt " + std::to_string(retryCount + 1) + ")");
-            retryCount++;
-            continue;
-        }
-        
-        av::Logger::instance().debug("Audio device started, waiting for active state...");
-        
-        // 写入一些静音数据来激活设备
-        QByteArray silentData(2048, 0); // 增加静音数据大小
-        qint64 written = m_audioDevice->write(silentData);
-        av::Logger::instance().debug("Written silent data: " + std::to_string(written) + " bytes");
-        
-        // 等待音频设备进入活动状态
-        int maxWaitMs = 2000; // 增加等待时间到2秒
-        int waitMs = 0;
-        while (m_audioOutput->state() != QAudio::ActiveState && waitMs < maxWaitMs) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(100));
-            waitMs += 100;
-            
-            if (waitMs % 500 == 0) {
-                av::Logger::instance().debug("Audio output state: " + std::to_string(m_audioOutput->state()) + 
-                    " (waited " + std::to_string(waitMs) + "ms)");
-                
-                // 尝试再次写入数据激活设备
-                if (m_audioDevice && m_audioOutput->state() == QAudio::IdleState) {
-                    QByteArray moreData(1024, 0);
-                    m_audioDevice->write(moreData);
-                }
-            }
-        }
-        
-        if (m_audioOutput->state() == QAudio::ActiveState) {
-            deviceStarted = true;
-            av::Logger::instance().info("Audio device successfully entered active state");
-        } else if (m_audioOutput->state() == QAudio::IdleState) {
-            // IdleState也可以接受,表示设备已准备好但暂时没有数据
-            deviceStarted = true;
-            av::Logger::instance().info("Audio device in idle state, ready for playback");
-        } else {
-            av::Logger::instance().warning("Audio device failed to enter active/idle state: " + std::to_string(m_audioOutput->state()) + " (attempt " + std::to_string(retryCount + 1) + ")");
-            m_audioDevice = nullptr;
-            retryCount++;
-        }
-    }
-    
-    if (!deviceStarted) {
-        av::Logger::instance().error("Failed to start audio device after " + std::to_string(maxRetries) + " attempts");
-        m_initialized = false;
-        return;
-    }
-    
-    av::Logger::instance().debug("Audio device entered active state");
-    
-    m_playing = true;
-    av::Logger::instance().info("Audio output started successfully");
-}
-
-void AudioOutput::stop()
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (!m_playing || !m_audioOutput) {
-        return;
-    }
-    
-    m_audioOutput->stop();
-    m_audioDevice = nullptr;
-    m_playing = false;
-    
-    av::Logger::instance().info("Audio output stopped");
-}
-
-void AudioOutput::pause()
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (!m_playing || !m_audioOutput) {
-        return;
-    }
-    
-    m_audioOutput->suspend();
-    av::Logger::instance().info("Audio output paused");
-}
-
-void AudioOutput::resume()
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (!m_playing || !m_audioOutput) {
-        return;
-    }
-    
-    m_audioOutput->resume();
-    av::Logger::instance().info("Audio output resumed");
-}
-
-bool AudioOutput::writeFrame(const AVFramePtr& frame)
-{
-    if (!frame || !m_playing || !m_audioDevice) {
-        av::Logger::instance().debug("Audio write failed: frame=" + std::to_string(frame != nullptr) + 
-            ", playing=" + std::to_string(m_playing) + ", device=" + std::to_string(m_audioDevice != nullptr));
-        return false;
-    }
-    
-    // 检查是否是EOF帧,EOF帧不需要处理,直接返回成功
-    if (!frame->data[0] && frame->nb_samples == 0) {
-        av::Logger::instance().debug("Received EOF frame in audio output, ignoring");
-        return true;
-    }
-    
-    // 检查音频设备状态 - 允许ActiveState和IdleState
-    if (m_audioOutput) {
-        QAudio::State currentState = m_audioOutput->state();
-        if (currentState != QAudio::ActiveState && currentState != QAudio::IdleState) {
-            av::Logger::instance().warning("Audio device not in playable state: " + std::to_string(currentState));
-            
-            // 尝试重新启动设备
-            if (currentState == QAudio::StoppedState) {
-                av::Logger::instance().info("Attempting to restart stopped audio device");
-                m_audioDevice = m_audioOutput->start();
-                if (!m_audioDevice) {
-                    av::Logger::instance().error("Failed to restart audio device");
-                    return false;
-                }
-                
-                // 写入静音数据激活设备
-                QByteArray silentData(1024, 0);
-                m_audioDevice->write(silentData);
-                
-                // 短暂等待设备状态更新
-                std::this_thread::sleep_for(std::chrono::milliseconds(50));
-                
-                currentState = m_audioOutput->state();
-                if (currentState != QAudio::ActiveState && currentState != QAudio::IdleState) {
-                    av::Logger::instance().error("Audio device restart failed, state: " + std::to_string(currentState));
-                    return false;
-                }
-            } else {
-                return false;
-            }
-        }
-    }
-    
-    // 使用Synchronizer进行时间同步
-    if (frame->pts != AV_NOPTS_VALUE /*&& m_synchronizer*/) {
-        // 使用原始PTS值和时间基准
-        int64_t audioPts = frame->pts;
-        double timeBase = 1.0 / AV_TIME_BASE;  // 假设使用AV_TIME_BASE作为时间基准
-
-        m_lastAudioPts = audioPts * timeBase; // 转换为秒用于记录
-    }
-
-    // 转换音频帧格式
-    QByteArray audioData = convertFrame(frame);
-    if (audioData.isEmpty()) {
-        av::Logger::instance().warning("Audio frame conversion failed");
-        return false;
-    }
-    
-    // 应用音量控制
-    applyVolume(audioData);
-    
-    // 写入音频设备 - 添加重试机制和异常处理
-    const int maxRetries = 10;
-    const int retryDelayMs = 5;
-    
-    for (int retry = 0; retry < maxRetries; ++retry) {
-        try {
-            qint64 bytesWritten = m_audioDevice->write(audioData);
-            if (bytesWritten == audioData.size()) {
-                av::Logger::instance().debug("Audio frame written successfully: " + 
-                    std::to_string(audioData.size()) + " bytes");
-                return true;
-            }
-            
-            // 写入不完整,记录警告并重试
-            av::Logger::instance().warning("Audio write incomplete (attempt " + 
-                std::to_string(retry + 1) + "/" + std::to_string(maxRetries) + "): " + 
-                std::to_string(bytesWritten) + "/" + std::to_string(audioData.size()));
-            
-            // 如果不是最后一次重试,等待一段时间再重试
-            if (retry < maxRetries - 1) {
-                std::this_thread::sleep_for(std::chrono::milliseconds(retryDelayMs));
-            }
-            
-        } catch (const std::exception& e) {
-            av::Logger::instance().error("Exception during audio write (attempt " + 
-                std::to_string(retry + 1) + "): " + std::string(e.what()));
-            
-            if (retry < maxRetries - 1) {
-                std::this_thread::sleep_for(std::chrono::milliseconds(retryDelayMs));
-            }
-        } catch (...) {
-            av::Logger::instance().error("Unknown exception during audio write (attempt " + 
-                std::to_string(retry + 1) + ")");
-            
-            if (retry < maxRetries - 1) {
-                std::this_thread::sleep_for(std::chrono::milliseconds(retryDelayMs));
-            }
-        }
-    }
-    
-    av::Logger::instance().error("Audio write failed after " + std::to_string(maxRetries) + " attempts");
-    return false;
-}
-
-void AudioOutput::setVolume(double volume)
-{
-    m_volume = std::clamp(volume, 0.0, 1.0);
-    
-    if (m_audioOutput) {
-        m_audioOutput->setVolume(m_volume);
-    }
-}
-
-double AudioOutput::getVolume() const
-{
-    return m_volume;
-}
-
-void AudioOutput::setPlaybackSpeed(double speed)
-{
-    speed = std::max(0.1, std::min(4.0, speed));
-    m_playbackSpeed = speed;
-
-    av::Logger::instance().debug("Audio playback speed set to: " + std::to_string(speed));
-}
-
-double AudioOutput::getPlaybackSpeed() const
-{
-    return m_playbackSpeed;
-}
-
-void AudioOutput::flush()
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (m_audioOutput) {
-        m_audioOutput->reset();
-    }
-}
-
-int AudioOutput::getBufferSize() const
-{
-    if (m_audioOutput) {
-        return m_audioOutput->bufferSize() * 1000 / 
-               (m_audioFormat.sampleRate() * m_audioFormat.channelCount() * 
-                m_audioFormat.sampleSize() / 8);
-    }
-    return 0;
-}
-
-bool AudioOutput::isPlaying() const
-{
-    return m_playing;
-}
-
-void AudioOutput::onStateChanged(QAudio::State state)
-{
-    switch (state) {
-    case QAudio::ActiveState:
-        av::Logger::instance().debug("Audio output state: Active");
-        break;
-    case QAudio::SuspendedState:
-        av::Logger::instance().debug("Audio output state: Suspended");
-        break;
-    case QAudio::StoppedState:
-        av::Logger::instance().debug("Audio output state: Stopped");
-        break;
-    case QAudio::IdleState:
-        av::Logger::instance().debug("Audio output state: Idle");
-        break;
-    }
-}
-
-bool AudioOutput::initResampler()
-{
-    // 检查是否需要重采样
-    bool needSampleRateConversion = (m_audioFormat.sampleRate() != m_sampleRate);
-    bool needChannelConversion = (m_audioFormat.channelCount() != m_channels);
-    bool needFormatConversion = (m_inputFormat != AV_SAMPLE_FMT_S16);
-    
-    m_needResampling = needSampleRateConversion || needChannelConversion || needFormatConversion;
-    
-    if (!m_needResampling) {
-        av::Logger::instance().info("No audio resampling needed");
-        return true;
-    }
-    
-    // 参数验证
-    if (m_sampleRate <= 0 || m_sampleRate > 192000) {
-        av::Logger::instance().errorf("Invalid input sample rate: {}", m_sampleRate);
-        return false;
-    }
-    
-    if (m_audioFormat.sampleRate() <= 0 || m_audioFormat.sampleRate() > 192000) {
-        av::Logger::instance().errorf("Invalid output sample rate: {}", m_audioFormat.sampleRate());
-        return false;
-    }
-    
-    if (m_channels <= 0 || m_channels > 32) {
-        av::Logger::instance().errorf("Invalid input channels: {}", m_channels);
-        return false;
-    }
-    
-    if (m_audioFormat.channelCount() <= 0 || m_audioFormat.channelCount() > 32) {
-        av::Logger::instance().errorf("Invalid output channels: {}", m_audioFormat.channelCount());
-        return false;
-    }
-    
-    // 记录参数信息用于调试
-    av::Logger::instance().infof("Resampler config: {}Hz,{}ch,{} -> {}Hz,{}ch,S16",
-                                m_sampleRate, m_channels, 
-                                av_get_sample_fmt_name(m_inputFormat),
-                                m_audioFormat.sampleRate(), m_audioFormat.channelCount());
-    
-    // 创建重采样上下文
-    m_swrContext = swr_alloc();
-    if (!m_swrContext) {
-        av::Logger::instance().error("Failed to allocate resampler context");
-        return false;
-    }
-    
-    // 设置输入参数
-    AVChannelLayout inputLayout;
-    av_channel_layout_default(&inputLayout, m_channels);
-    
-    // 设置输出参数
-    AVChannelLayout outputLayout;
-    av_channel_layout_default(&outputLayout, m_audioFormat.channelCount());
-    
-    // 使用分步设置方式替代swr_alloc_set_opts2
-    av_opt_set_chlayout(m_swrContext, "in_chlayout", &inputLayout, 0);
-    av_opt_set_int(m_swrContext, "in_sample_rate", m_sampleRate, 0);
-    av_opt_set_sample_fmt(m_swrContext, "in_sample_fmt", m_inputFormat, 0);
-    
-    av_opt_set_chlayout(m_swrContext, "out_chlayout", &outputLayout, 0);
-    av_opt_set_int(m_swrContext, "out_sample_rate", m_audioFormat.sampleRate(), 0);
-    av_opt_set_sample_fmt(m_swrContext, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
-    
-    // 初始化重采样器
-    int ret = swr_init(m_swrContext);
-    if (ret < 0) {
-        av::Logger::instance().errorf("Failed to initialize resampler: {}", 
-                                      ffmpeg_utils::errorToString(ret));
-        av::Logger::instance().errorf("Input: {}Hz, {}ch, {}", 
-                                      m_sampleRate, m_channels, 
-                                      av_get_sample_fmt_name(m_inputFormat));
-        av::Logger::instance().errorf("Output: {}Hz, {}ch, S16", 
-                                      m_audioFormat.sampleRate(), 
-                                      m_audioFormat.channelCount());
-        swr_free(&m_swrContext);
-        return false;
-    }
-    
-    av::Logger::instance().info("Audio resampler initialized successfully");
-    return true;
-}
-
-void AudioOutput::cleanupResampler()
-{
-    if (m_swrContext) {
-        swr_free(&m_swrContext);
-        m_swrContext = nullptr;
-    }
-}
-
-QByteArray AudioOutput::convertFrame(const AVFramePtr& frame)
-{
-    if (!frame) {
-        av::Logger::instance().error("convertFrame: null frame pointer");
-        return QByteArray();
-    }
-    
-    // 检查帧数据有效性
-    if (!frame->data[0] || frame->nb_samples <= 0) {
-        av::Logger::instance().error("convertFrame: invalid frame data, nb_samples=" + std::to_string(frame->nb_samples));
-        return QByteArray();
-    }
-    
-    av::Logger::instance().debug("convertFrame: input samples=" + std::to_string(frame->nb_samples) + 
-                                ", channels=" + std::to_string(m_channels) + 
-                                ", format=" + std::to_string(m_inputFormat) + 
-                                ", need_resampling=" + std::to_string(m_needResampling));
-    
-    if (!m_needResampling) {
-        // 直接复制数据
-        int dataSize = frame->nb_samples * m_channels * sizeof(int16_t);
-        av::Logger::instance().debug("convertFrame: direct copy, size=" + std::to_string(dataSize));
-        return QByteArray(reinterpret_cast<const char*>(frame->data[0]), dataSize);
-    }
-    
-    if (!m_swrContext) {
-        av::Logger::instance().error("convertFrame: resampler not initialized");
-        return QByteArray();
-    }
-    
-    // 计算输出采样数
-    int outputSamples = swr_get_out_samples(m_swrContext, frame->nb_samples);
-    if (outputSamples <= 0) {
-        av::Logger::instance().error("convertFrame: invalid output samples=" + std::to_string(outputSamples));
-        return QByteArray();
-    }
-    
-    // 分配输出缓冲区
-    int outputChannels = m_audioFormat.channelCount();
-    int outputDataSize = outputSamples * outputChannels * sizeof(int16_t);
-    QByteArray outputData(outputDataSize, 0);
-    
-    uint8_t* outputBuffer = reinterpret_cast<uint8_t*>(outputData.data());
-    
-    av::Logger::instance().debug("convertFrame: resampling " + std::to_string(frame->nb_samples) + 
-                                " -> " + std::to_string(outputSamples) + " samples");
-    
-    // 执行重采样
-    int convertedSamples = swr_convert(m_swrContext,
-                                      &outputBuffer, outputSamples,
-                                      const_cast<const uint8_t**>(frame->data), frame->nb_samples);
-    
-    if (convertedSamples < 0) {
-        char errorBuf[256];
-        av_strerror(convertedSamples, errorBuf, sizeof(errorBuf));
-        av::Logger::instance().error("convertFrame: resampling failed with error " + 
-                                    std::to_string(convertedSamples) + ": " + std::string(errorBuf));
-        return QByteArray();
-    }
-    
-    // 调整输出数据大小
-    int actualDataSize = convertedSamples * outputChannels * sizeof(int16_t);
-    outputData.resize(actualDataSize);
-    
-    av::Logger::instance().debug("convertFrame: successfully converted " + std::to_string(convertedSamples) + 
-                                " samples, output size=" + std::to_string(actualDataSize));
-    
-    return outputData;
-}
-
-void AudioOutput::applyVolume(QByteArray& data)
-{
-    if (std::abs(m_volume - 1.0) < 0.001) {
-        return; // 音量为1.0,无需调整
-    }
-    
-    int16_t* samples = reinterpret_cast<int16_t*>(data.data());
-    int sampleCount = data.size() / sizeof(int16_t);
-    
-    for (int i = 0; i < sampleCount; ++i) {
-        samples[i] = static_cast<int16_t>(samples[i] * m_volume);
-    }
-}
-
-} // namespace player
-} // namespace av
-

+ 0 - 169
AV/code/player/audio_output.h

@@ -1,169 +0,0 @@
-#ifndef AV_PLAYER_AUDIO_OUTPUT_H
-#define AV_PLAYER_AUDIO_OUTPUT_H
-
-#include <QAudioOutput>
-#include <QAudioFormat>
-#include <QIODevice>
-#include <QMutex>
-#include <QWaitCondition>
-#include <QThread>
-#include <memory>
-#include <atomic>
-#include <queue>
-#include <chrono>
-#include <thread>
-
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/samplefmt.h>
-#include <libswresample/swresample.h>
-}
-
-#include "../base/media_common.h"
-#include "../utils/utils_synchronizer_v2.h"
-
-namespace av {
-namespace player {
-
-/**
- * 音频输出设备类
- * 负责将解码后的音频帧输出到扬声器
- */
-class AudioOutput : public QObject
-{
-    Q_OBJECT
-
-public:
-    explicit AudioOutput(QObject* parent = nullptr);
-    ~AudioOutput();
-
-    /**
-     * 初始化音频输出设备
-     * @param sampleRate 采样率
-     * @param channels 声道数
-     * @param sampleFormat 采样格式
-     * @return 是否成功
-     */
-    bool initialize(int sampleRate, int channels, AVSampleFormat sampleFormat);
-
-    /**
-     * 开始播放
-     */
-    void start();
-
-    /**
-     * 停止播放
-     */
-    void stop();
-
-    /**
-     * 暂停播放
-     */
-    void pause();
-
-    /**
-     * 恢复播放
-     */
-    void resume();
-
-    /**
-     * 写入音频帧
-     * @param frame 音频帧
-     * @return 是否成功
-     */
-    bool writeFrame(const AVFramePtr& frame);
-
-    /**
-     * 设置音量
-     * @param volume 音量 (0.0 - 1.0)
-     */
-    void setVolume(double volume);
-
-    /**
-     * 获取音量
-     */
-    double getVolume() const;
-
-    /**
-     * 设置播放速度
-     * @param speed 播放速度 (0.5 - 4.0)
-     */
-    void setPlaybackSpeed(double speed);
-
-    /**
-     * 获取播放速度
-     */
-    double getPlaybackSpeed() const;
-
-    /**
-     * 清空缓冲区
-     */
-    void flush();
-
-    /**
-     * 获取缓冲区大小(毫秒)
-     */
-    int getBufferSize() const;
-
-    /**
-     * 是否正在播放
-     */
-    bool isPlaying() const;
-
-private slots:
-    void onStateChanged(QAudio::State state);
-
-private:
-    /**
-     * 初始化重采样器
-     */
-    bool initResampler();
-
-    /**
-     * 清理重采样器
-     */
-    void cleanupResampler();
-
-    /**
-     * 转换音频帧格式
-     */
-    QByteArray convertFrame(const AVFramePtr& frame);
-
-    /**
-     * 应用音量控制
-     */
-    void applyVolume(QByteArray& data);
-
-private:
-    QAudioOutput* m_audioOutput;
-    QIODevice* m_audioDevice;
-    QAudioFormat m_audioFormat;
-    
-    // 音频参数
-    int m_sampleRate;
-    int m_channels;
-    AVSampleFormat m_inputFormat;
-    
-    // 重采样器
-    SwrContext* m_swrContext;
-    bool m_needResampling;
-    
-    // 音量控制
-    std::atomic<double> m_volume;
-    
-    // 播放速度控制
-    std::atomic<double> m_playbackSpeed;
-    
-    // 状态
-    std::atomic<bool> m_initialized;
-    std::atomic<bool> m_playing;
-
-    double m_lastAudioPts; // 上一次的音频PTS
-
-    mutable QMutex m_mutex;
-};
-
-} // namespace player
-} // namespace av
-
-#endif // AV_PLAYER_AUDIO_OUTPUT_H

+ 0 - 8
AV/code/player/player.pri

@@ -1,8 +0,0 @@
-# PlayerV2 Core Components
-HEADERS += \
-    $$PWD/player_core_v2.h \
-    $$PWD/audio_output.h
-
-SOURCES += \
-    $$PWD/player_core_v2.cpp \
-    $$PWD/audio_output.cpp

+ 0 - 1892
AV/code/player/player_core_v2.cpp

@@ -1,1892 +0,0 @@
-#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>
-#include <cmath>
-
-namespace av {
-namespace player {
-PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
-    : m_state(PlayerState::Idle)
-    , 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_paused(false)
-    , m_initialized(false)
-    , m_frameCount(0)
-    , m_lastFrameCount(0)
-    , m_errorCount(0)
-    , m_buffering(false)
-    , m_bufferHealth(1.0)
-{
-    Logger::instance().info("PlayerCoreV2 created");
-
-    try {
-        // 初始化FFmpeg
-        if (!initializeFFmpeg()) {
-            Logger::instance().error("Failed to initialize FFmpeg");
-            setState(PlayerState::Error);
-            return;
-        }
-        
-        // 创建分离的视频和音频包队列 - 使用高容量队列以避免丢帧
-        m_videoPacketQueue = av::utils::PacketQueueFactory::createHighCapacityQueue(2000);  // 视频包队列,增大容量
-        if (!m_videoPacketQueue) {
-            Logger::instance().error("Failed to create video packet queue");
-            setState(PlayerState::Error);
-            return;
-        }
-        // 禁用丢包策略
-        m_videoPacketQueue->setDropPolicy(false, true);
-        
-        m_audioPacketQueue = av::utils::PacketQueueFactory::createHighCapacityQueue(2000);  // 音频包队列,增大容量
-        if (!m_audioPacketQueue) {
-            Logger::instance().error("Failed to create audio packet queue");
-            setState(PlayerState::Error);
-            return;
-        }
-        // 禁用丢包策略
-        m_audioPacketQueue->setDropPolicy(false, true);
-        
-        m_videoFrameQueue = av::utils::FrameQueueFactory::createHighCapacityQueue(100); // 增加视频帧队列容量并禁用丢帧
-        if (!m_videoFrameQueue) {
-            Logger::instance().error("Failed to create video frame queue");
-            setState(PlayerState::Error);
-            return;
-        }
-        // 禁用丢帧策略
-        m_videoFrameQueue->setDropPolicy(false, true);
-        
-        m_audioFrameQueue = av::utils::FrameQueueFactory::createHighCapacityQueue(400); // 增加音频帧队列容量并禁用丢帧
-        if (!m_audioFrameQueue) {
-            Logger::instance().error("Failed to create audio frame queue");
-            setState(PlayerState::Error);
-            return;
-        }
-        // 禁用丢帧策略
-        m_audioFrameQueue->setDropPolicy(false, true);
-        
-        // 创建改进的同步器
-        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, int64_t pts) {
-            std::lock_guard<std::mutex> lock(m_mutex);
-            m_stats.droppedFrames++;
-            if (m_eventCallback) {
-                m_eventCallback->onFrameDropped(m_stats.droppedFrames);
-            }
-        });
-
-        // 创建解码器
-        m_videoDecoder = std::make_unique<VideoDecoder>();
-        if (!m_videoDecoder) {
-            Logger::instance().error("Failed to create video decoder");
-            setState(PlayerState::Error);
-            return;
-        }
-        
-        m_audioDecoder = std::make_unique<AudioDecoder>();
-        if (!m_audioDecoder) {
-            Logger::instance().error("Failed to create audio decoder");
-            setState(PlayerState::Error);
-            return;
-        }
-        
-        // 创建音频输出设备
-        m_audioOutput = std::make_unique<AudioOutput>();
-        if (!m_audioOutput) {
-            Logger::instance().error("Failed to create audio output");
-            setState(PlayerState::Error);
-            return;
-        }
-        
-        // 初始化性能监控
-        m_lastStatsUpdate = std::chrono::steady_clock::now();
-        m_lastCpuMeasure = m_lastStatsUpdate;
-
-        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;
-    }
-    
-    // 注意:同步器的初始化已经在openMediaFile()中完成,这里不需要重复调用
-    // 因为initialize()会重新选择主时钟,可能覆盖之前设置的流信息
-    
-    setState(PlayerState::Stopped);
-    
-    // 如果有视频流,通知需要初始化渲染器
-    if (m_mediaInfo.hasVideo && m_eventCallback) {
-        AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
-        
-        m_eventCallback->onVideoRendererInitRequired(
-            videoStream->codecpar->width,
-            videoStream->codecpar->height
-        );
-        
-        Logger::instance().info("Video renderer initialization requested");
-    }
-    
-    // 通知媒体信息变化
-    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) {
-        ErrorCode syncResult = ErrorCode::SUCCESS;
-        if (m_state == PlayerState::Paused) {
-            // 从暂停状态恢复,调用resume方法
-            syncResult = m_synchronizer->resume();
-        } else {
-            // 从停止状态开始,调用start方法
-            syncResult = m_synchronizer->start();
-        }
-        
-        if (syncResult != ErrorCode::SUCCESS) {
-            Logger::instance().error("Failed to start/resume synchronizer");
-            return ErrorCode::SYNC_ERROR;
-        }
-    }
-
-    // 根据当前状态设置播放开始时间
-    if (m_state == PlayerState::Stopped) {
-        // 从停止状态开始播放,重置所有时间相关变量
-        m_baseTime = 0;
-        m_frameCount = 0;
-        m_lastFrameCount = 0;
-        m_playStartTime = std::chrono::steady_clock::now();
-        
-        // 重置统计信息
-        std::lock_guard<std::mutex> lock(m_mutex);
-        m_stats = PlaybackStats();
-        m_stats.playbackSpeed = m_playbackSpeed;
-    } else if (m_state == PlayerState::Paused) {
-        // 从暂停状态恢复播放,重新设置播放开始时间
-        // m_baseTime已经在pause()方法中正确更新,这里只需要重新设置开始时间
-        m_playStartTime = std::chrono::steady_clock::now();
-        
-        // 清除暂停标志并唤醒等待的线程,类似ffplay.c中的continue_read_thread机制
-        {
-            std::lock_guard<std::mutex> lock(m_pauseMutex);
-            m_paused = false;
-        }
-        m_pauseCondition.notify_all();
-    }
-    
-    // 启动音频输出设备
-    if (m_audioOutput && m_mediaInfo.hasAudio) {
-        if (m_state == PlayerState::Paused) {
-            // 从暂停状态恢复音频
-            try {
-                m_audioOutput->resume();
-            } catch (const std::exception& e) {
-                Logger::instance().error("Failed to resume audio output: " + std::string(e.what()));
-                // 尝试重新初始化音频设备
-                try {
-                    m_audioOutput->stop();
-                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
-                    m_audioOutput->start();
-                } catch (const std::exception& e2) {
-                    Logger::instance().error("Failed to restart audio output: " + std::string(e2.what()));
-                    Logger::instance().warning("Continuing playback without audio");
-                }
-            }
-        } else {
-            Logger::instance().info("Starting audio output device...");
-            try {
-                m_audioOutput->start();
-                
-                // 检查音频设备是否成功启动
-                if (!m_audioOutput->isPlaying()) {
-                    Logger::instance().error("Audio output device failed to start");
-                    // 不要因为音频失败而停止整个播放,继续播放视频
-                    Logger::instance().warning("Continuing playback without audio");
-                }
-            } catch (const std::exception& e) {
-                 Logger::instance().error("Exception starting audio output: " + std::string(e.what()));
-                 Logger::instance().warning("Continuing playback without audio");
-             }
-        }
-    }
-    
-    // 根据状态启动或恢复线程
-    if (m_state == PlayerState::Stopped) {
-        // 从停止状态开始,需要启动所有线程
-        
-        // 启动播放线程
-        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;
-        }
-        
-        // 启动解码线程
-        if (!startDecodeThreads()) {
-            Logger::instance().error("Failed to start decode threads");
-            return ErrorCode::THREAD_ERROR;
-        }
-        
-        // 启动读取线程
-        if (!startReadThread()) {
-            Logger::instance().error("Failed to start read 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;
-    }
-    // 设置暂停标志,让线程在内部循环中等待,而不是停止线程
-    // 类似ffplay.c中的paused标志机制
-    {
-        std::lock_guard<std::mutex> lock(m_pauseMutex);
-        Logger::instance().info("Setting m_paused to true");
-        m_paused = true;
-
-        m_videoPacketQueue->wakeup(); // 唤醒等待的解码线程
-
-        m_audioPacketQueue->wakeup(); // 唤醒等待的解码线程
-
-        m_videoFrameQueue->wakeup(); // 唤醒等待的播放线程
-
-        m_audioFrameQueue->wakeup(); // 唤醒等待的播放线程
-
-        Logger::instance().info("m_paused set to: " + std::to_string(m_paused.load()));
-    }
-    // 立即通知所有等待的线程检查暂停状态
-    Logger::instance().info("Notifying all threads about pause state change");
-    m_pauseCondition.notify_all();
-
-    // 暂停同步器
-    if (m_synchronizer && 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 (threads continue running)");
-    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();
-    }
-    
-    // 通知关闭视频渲染器
-    if (m_eventCallback) {
-        m_eventCallback->onVideoRendererCloseRequired();
-    }
-    
-    // 清除暂停标志并唤醒所有等待的线程
-    {
-        std::lock_guard<std::mutex> lock(m_pauseMutex);
-        m_paused = false;
-    }
-    m_pauseCondition.notify_all();
-    
-    // 停止所有线程
-    stopAllThreads();
-    
-    // 重置解码器
-    resetDecoders();
-    
-    // 清空队列
-    if (m_videoPacketQueue) m_videoPacketQueue->clear();
-    if (m_audioPacketQueue) m_audioPacketQueue->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_seekMinTime = INT64_MIN;  // 允许向前跳转的最小时间
-    m_seekMaxTime = INT64_MAX;  // 允许向后跳转的最大时间
-    m_seekFlags = AVSEEK_FLAG_BACKWARD;  // 默认向后跳转到关键帧
-    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("Precise seek initiated with avformat_seek_file support");
-    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_videoPacketQueue) stats.queuedPackets += m_videoPacketQueue->size();
-    if (m_audioPacketQueue) stats.queuedPackets += m_audioPacketQueue->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.audioVideoSyncError;
-        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_synchronizer) {
-        // 获取主时钟时间(秒),转换为微秒
-        double masterClockTime = m_synchronizer->getMasterClock();
-        // 确保时间值合理(非负且不是NaN)
-        if (masterClockTime >= 0.0 && !std::isnan(masterClockTime)) {
-            return static_cast<int64_t>(masterClockTime * 1000000);
-        }
-    }
-
-    // 回退到原来的计算方式(兼容性保证)
-    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::enableVideoStream(bool enable) {
-    if (m_videoStreamEnabled == enable) {
-        return; // 状态未变,不需要处理
-    }
-    
-    m_videoStreamEnabled = enable;
-    Logger::instance().info("Video stream " + std::string(enable ? "enabled" : "disabled"));
-    
-    // 如果播放器已经打开文件,需要更新同步器的流信息
-    if (m_formatContext && m_synchronizer) {
-        bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
-        bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
-        m_synchronizer->setStreamInfo(useAudio, useVideo);
-
-        // 如果正在播放,需要重新启动播放
-        if (m_state == PlayerState::Playing || m_state == PlayerState::Paused) {
-            // 停止当前播放
-            PlayerState oldState = m_state;
-            stop();
-            // 重新开始播放
-            openFile(m_mediaInfo.filename);
-            if (oldState == PlayerState::Playing) {
-                play();
-            }
-        }
-    }
-}
-
-void PlayerCoreV2::enableAudioStream(bool enable) {
-    if (m_audioStreamEnabled == enable) {
-        return; // 状态未变,不需要处理
-    }
-    
-    m_audioStreamEnabled = enable;
-    Logger::instance().info("Audio stream " + std::string(enable ? "enabled" : "disabled"));
-    
-    // 如果播放器已经打开文件,需要更新同步器的流信息
-    if (m_formatContext && m_synchronizer) {
-        bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
-        bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
-        m_synchronizer->setStreamInfo(useAudio, useVideo);
-        
-        // 如果正在播放,需要重新启动播放
-        if (m_state == PlayerState::Playing) {
-            // 暂停当前播放
-            pause();
-            // 重新开始播放
-            play();
-        }
-    }
-}
-
-bool PlayerCoreV2::isVideoStreamEnabled() const {
-    return m_videoStreamEnabled;
-}
-
-bool PlayerCoreV2::isAudioStreamEnabled() const {
-    return m_audioStreamEnabled;
-}
-
-void PlayerCoreV2::setSyncConfig(const SyncConfigV2& config) {
-    if (m_synchronizer) {
-        m_synchronizer->setConfig(config);
-    }
-}
-
-SyncConfigV2 PlayerCoreV2::getSyncConfig() const {
-    if (m_synchronizer) {
-        return m_synchronizer->getConfig();
-    }
-    return SyncConfigV2();
-}
-
-// void PlayerCoreV2::setOpenGLVideoRenderer(OpenGLVideoWidget* renderer) {
-//     m_openGLVideoRenderer = renderer;
-// }
-
-AVFramePtr PlayerCoreV2::getNextVideoFrame() {
-    if (!m_videoFrameQueue || m_state != PlayerState::Playing) {
-        return nullptr;
-    }
-    
-    return m_videoFrameQueue->pop();
-}
-
-AVFramePtr PlayerCoreV2::getNextAudioFrame() {
-    if (!m_audioFrameQueue || m_state != PlayerState::Playing) {
-        return nullptr;
-    }
-    
-    return m_audioFrameQueue->pop();
-}
-
-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) {
-        bool useAudio = m_mediaInfo.hasAudio && m_audioStreamEnabled;
-        bool useVideo = m_mediaInfo.hasVideo && m_videoStreamEnabled;
-        m_synchronizer->setStreamInfo(useAudio, useVideo);
-        Logger::instance().info("Synchronizer stream info set: hasAudio=" + std::to_string(useAudio) +
-                               ", hasVideo=" + std::to_string(useVideo));
-
-        // 在设置流信息后初始化同步器,确保主时钟选择基于正确的流信息
-        if (m_synchronizer->initialize() != ErrorCode::SUCCESS) {
-            Logger::instance().error("Failed to initialize synchronizer");
-            return false;
-        }
-        Logger::instance().info("Synchronizer initialized with correct stream info");
-    }
-
-    Logger::instance().info("Media file opened successfully: " + filename);
-    return true;
-}
-
-bool PlayerCoreV2::setupVideoDecoder() {
-    if (!m_mediaInfo.hasVideo || !m_videoDecoder) {
-        return false;
-    }
-    
-    AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
-    
-    // 查找解码器
-    const AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
-    if (!codec) {
-        Logger::instance().error("Video codec not found");
-        return false;
-    }
-    
-    Logger::instance().info("Found video codec: " + std::string(codec->name));
-    Logger::instance().info("Video stream info: width=" + std::to_string(videoStream->codecpar->width) + 
-                           ", height=" + std::to_string(videoStream->codecpar->height) + 
-                           ", format=" + std::to_string(videoStream->codecpar->format));
-    
-    // 创建视频解码器参数
-    VideoDecoderParams videoParams;
-    videoParams.codecName = codec->name;
-    videoParams.width = videoStream->codecpar->width;
-    videoParams.height = videoStream->codecpar->height;
-    videoParams.pixelFormat = static_cast<AVPixelFormat>(videoStream->codecpar->format);
-    videoParams.hardwareAccel = false; // 先禁用硬件加速来排除问题
-    videoParams.lowLatency = false;
-    
-    Logger::instance().info("Video decoder params: codec=" + videoParams.codecName + 
-                           ", size=" + std::to_string(videoParams.width) + "x" + std::to_string(videoParams.height) + 
-                           ", format=" + std::to_string(static_cast<int>(videoParams.pixelFormat)));
-    
-    // 初始化视频解码器
-    if (m_videoDecoder->initialize(videoParams) != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to initialize video decoder");
-        return false;
-    }
-    
-    // 设置流参数
-    if (m_videoDecoder->setStreamParameters(videoStream->codecpar) != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to set video decoder stream parameters");
-        return false;
-    }
-    
-    // 打开视频解码器
-    if (m_videoDecoder->open(videoParams) != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to open video decoder");
-        return false;
-    }
-    
-    Logger::instance().info("Video decoder setup successfully");
-    return true;
-}
-
-bool PlayerCoreV2::setupAudioDecoder() {
-    if (!m_mediaInfo.hasAudio || !m_audioDecoder) {
-        return false;
-    }
-    
-    AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
-    
-    // 查找解码器
-    const AVCodec* codec = avcodec_find_decoder(audioStream->codecpar->codec_id);
-    if (!codec) {
-        Logger::instance().error("Audio codec not found");
-        return false;
-    }
-    
-    // 分配解码器上下文
-    AVCodecContext* codecContext = avcodec_alloc_context3(codec);
-    if (!codecContext) {
-        Logger::instance().error("Failed to allocate audio codec context");
-        return false;
-    }
-    
-    // 复制流参数到解码器上下文
-    if (avcodec_parameters_to_context(codecContext, audioStream->codecpar) < 0) {
-        Logger::instance().error("Failed to copy audio codec parameters");
-        avcodec_free_context(&codecContext);
-        return false;
-    }
-    
-    // 打开解码器
-    if (avcodec_open2(codecContext, codec, nullptr) < 0) {
-        Logger::instance().error("Failed to open audio codec");
-        avcodec_free_context(&codecContext);
-        return false;
-    }
-    
-    // 创建音频解码器参数
-    AudioDecoderParams audioParams;
-    audioParams.codecName = codec->name;
-    audioParams.sampleRate = codecContext->sample_rate;
-    audioParams.channels = codecContext->ch_layout.nb_channels;
-    audioParams.sampleFormat = codecContext->sample_fmt;
-    audioParams.lowLatency = false;
-    audioParams.enableResampling = true;
-    
-    // 初始化音频解码器
-    if (m_audioDecoder->initialize(audioParams) != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to initialize audio decoder");
-        avcodec_free_context(&codecContext);
-        return false;
-    }
-    
-    // 打开音频解码器
-    if (m_audioDecoder->open(audioParams) != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to open audio decoder");
-        avcodec_free_context(&codecContext);
-        return false;
-    }
-    
-    // 初始化音频输出设备
-    if (m_audioOutput && !m_audioOutput->initialize(codecContext->sample_rate, 
-                                                   codecContext->ch_layout.nb_channels, 
-                                                   codecContext->sample_fmt)) {
-        Logger::instance().error("Failed to initialize audio output");
-        avcodec_free_context(&codecContext);
-        return false;
-    }
-    // 释放解码器上下文
-    avcodec_free_context(&codecContext);
-    
-    Logger::instance().info("Audio decoder setup successfully");
-    return true;
-}
-
-void PlayerCoreV2::resetDecoders() {
-    if (m_videoDecoder) {
-        m_videoDecoder->reset();
-    }
-    if (m_audioDecoder) {
-        m_audioDecoder->reset();
-    }
-}
-
-bool PlayerCoreV2::startReadThread() {
-    try {
-        // 确保之前的线程已经完全停止
-        if (m_readThread.joinable()) {
-            Logger::instance().warning("Read thread still running, waiting for it to stop...");
-            m_readThread.join();
-        }
-        
-        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) {
-            // 确保之前的视频解码线程已经完全停止
-            if (m_videoDecodeThread.joinable()) {
-                Logger::instance().warning("Video decode thread still running, waiting for it to stop...");
-                m_videoDecodeThread.join();
-            }
-            
-            m_videoDecodeThread = std::thread(&PlayerCoreV2::videoDecodeThreadFunc, this);
-            Logger::instance().info("Video decode thread started");
-        }
-        
-        if (m_mediaInfo.hasAudio) {
-            // 确保之前的音频解码线程已经完全停止
-            if (m_audioDecodeThread.joinable()) {
-                Logger::instance().warning("Audio decode thread still running, waiting for it to stop...");
-                m_audioDecodeThread.join();
-            }
-            
-            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 {
-        // 确保之前的视频播放线程已经完全停止
-        if (m_videoPlayThread.joinable()) {
-            Logger::instance().warning("Video play thread still running, waiting for it to stop...");
-            m_videoPlayThread.join();
-        }
-        
-        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 {
-        // 确保之前的音频播放线程已经完全停止
-        if (m_audioPlayThread.joinable()) {
-            Logger::instance().warning("Audio play thread still running, waiting for it to stop...");
-            m_audioPlayThread.join();
-        }
-        
-        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;
-    }
-
-    // 同步器会在内部自动更新
-    // 更新同步器统计信息
-    //m_synchronizer->updateStats();
-
-    // 获取同步器统计信息并更新播放器统计
-    std::lock_guard<std::mutex> lock(m_mutex);
-    auto syncStats = m_synchronizer->getStats();
-    m_stats.syncError = syncStats.audioVideoSyncError;
-    m_stats.avgSyncError = syncStats.avgSyncError;
-    m_stats.maxSyncError = syncStats.maxSyncError;
-    m_stats.droppedFrames = syncStats.droppedFrames;
-    m_stats.duplicatedFrames = syncStats.duplicatedFrames;
-}
-
-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() {
-    return 0.0;
-}
-
-double PlayerCoreV2::calculateMemoryUsage() {
-    return 0.0;
-}
-
-void PlayerCoreV2::stopAllThreads() {
-    Logger::instance().info("Stopping all threads...");
-    
-    m_threadsShouldStop = true;
-    
-    // 唤醒所有等待的队列,确保线程能够检查停止标志
-    flushBuffers();
-    
-    // 等待线程结束,添加超时保护
-    auto joinWithTimeout = [](std::thread& t, const std::string& name) {
-        if (t.joinable()) {
-            Logger::instance().info("Waiting for " + name + " to stop...");
-            t.join();
-            Logger::instance().info(name + " stopped");
-        }
-    };
-    
-    joinWithTimeout(m_readThread, "read thread");
-    joinWithTimeout(m_videoDecodeThread, "video decode thread");
-    joinWithTimeout(m_audioDecodeThread, "audio decode thread");
-    joinWithTimeout(m_videoPlayThread, "video play thread");
-    joinWithTimeout(m_audioPlayThread, "audio play thread");
-    
-    m_threadsRunning = false;
-    Logger::instance().info("All threads stopped successfully");
-}
-
-void PlayerCoreV2::flushBuffers() {
-    if (m_videoPacketQueue) {
-        m_videoPacketQueue->clear();
-        m_videoPacketQueue->wakeup(); // 唤醒等待的解码线程
-    }
-    if (m_audioPacketQueue) {
-        m_audioPacketQueue->clear();
-        m_audioPacketQueue->wakeup(); // 唤醒等待的解码线程
-    }
-    if (m_videoFrameQueue) {
-        m_videoFrameQueue->clear();
-        m_videoFrameQueue->wakeup(); // 唤醒等待的播放线程
-    }
-    if (m_audioFrameQueue) {
-        m_audioFrameQueue->clear();
-        m_audioFrameQueue->wakeup(); // 唤醒等待的播放线程
-    }
-}
-
-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) {
-        // 检查暂停状态,类似ffplay.c中的paused检查
-        bool pausedState = m_paused.load();
-        Logger::instance().debug("Read thread loop - m_paused: " + std::to_string(pausedState));
-        if (pausedState) {
-            Logger::instance().info("Read thread entering pause wait");
-            std::unique_lock<std::mutex> lock(m_pauseMutex);
-            m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
-            if (m_threadsShouldStop) {
-                break;
-            }
-            Logger::instance().info("Read thread exiting pause wait");
-            // 暂停状态结束后,继续下一次循环
-            continue;
-        }
-        
-        // 检查是否需要seek
-        if (m_seeking) {
-            std::unique_lock<std::mutex> lock(m_seekMutex);
-            
-            // 获取seek参数
-            int64_t seekMinTime = m_seekMinTime;
-            int64_t seekTarget = m_seekTarget;
-            int64_t seekMaxTime = m_seekMaxTime;
-            int flags = m_seekFlags;
-
-            Logger::instance().info("Performing precise seek - min: " + std::to_string(seekMinTime) + 
-                                   ", target: " + std::to_string(seekTarget) + 
-                                   ", max: " + std::to_string(seekMaxTime) + 
-                                   ", flags: " + std::to_string(flags));
-
-            // 首先尝试定位到最近的关键帧以确保视频解码正常
-            int ret = av_seek_frame(m_formatContext, -1, seekTarget, AVSEEK_FLAG_BACKWARD);
-            if (ret < 0) {
-                Logger::instance().warning("Video keyframe seek failed, trying precise seek");
-                // 如果关键帧定位失败,回退到精确seek
-                ret = avformat_seek_file(m_formatContext, -1, seekMinTime, seekTarget, seekMaxTime, flags);
-                if (ret < 0) {
-                    Logger::instance().error("All seek methods failed");
-                } else {
-                    Logger::instance().info("Fallback precise seek completed to: " + std::to_string(seekTarget));
-                }
-            } else {
-                Logger::instance().info("Keyframe seek completed successfully to target: " + std::to_string(seekTarget));
-            }
-            
-            // 清空缓冲区
-            flushBuffers();
-            
-            // 重置解码器
-            resetDecoders();
-
-            // 重置时间
-            if (flags & AVSEEK_FLAG_BYTE) {
-                m_synchronizer->setClock(av::utils::ClockType::EXTERNAL, NAN, 0);
-            } else {
-                m_synchronizer->setClock(av::utils::ClockType::EXTERNAL,
-                                         seekTarget / (double) AV_TIME_BASE,
-                                         0);
-            }
-            
-            m_seeking = false;
-            setState(m_state == PlayerState::Seeking ? PlayerState::Playing : m_state.load());
-
-            lock.unlock();
-            m_seekCondition.notify_all();
-        }
-        
-        // 检查队列是否接近容量上限 - 使用队列容量的90%作为警告阈值,但不丢弃包
-        bool videoQueueNearFull = m_videoPacketQueue && m_videoPacketQueue->size() > 800; 
-        bool audioQueueNearFull = m_audioPacketQueue && m_audioPacketQueue->size() > 800; 
-        if (videoQueueNearFull || audioQueueNearFull) { 
-            // 队列接近满,暂停一段时间让解码线程处理
-            Logger::instance().warning("Packet queue is getting large: Video=" + 
-                                    std::to_string(m_videoPacketQueue ? m_videoPacketQueue->size() : 0) + 
-                                    ", Audio=" + std::to_string(m_audioPacketQueue ? m_audioPacketQueue->size() : 0) + 
-                                    ". Slowing down read thread.");
-            std::this_thread::sleep_for(std::chrono::milliseconds(50));
-            continue;
-        }
-        
-        // 在读取数据包前检查暂停状态,避免在读取期间阻塞
-        if (m_paused.load()) {
-            Logger::instance().debug("Read thread detected pause before av_read_frame");
-            continue;
-        }
-        
-        // 读取数据包
-        int ret = av_read_frame(m_formatContext, packet);
-        if (ret < 0) {
-            if (ret == AVERROR_EOF) {
-                Logger::instance().info("End of file reached, sending EOF packets to queues");
-                
-                // 向视频和音频队列分别发送EOF标记,让解码线程知道文件结束
-                if (m_videoPacketQueue && m_mediaInfo.hasVideo) {
-                    AVPacket* eofPacket = av_packet_alloc();
-                    if (eofPacket) {
-                        eofPacket->data = nullptr;
-                        eofPacket->size = 0;
-                        eofPacket->stream_index = -1; // 特殊标记表示EOF
-                        m_videoPacketQueue->push(eofPacket);
-                        Logger::instance().info("EOF packet sent to video queue");
-                    }
-                }
-                
-                if (m_audioPacketQueue && m_mediaInfo.hasAudio) {
-                    AVPacket* eofPacket = av_packet_alloc();
-                    if (eofPacket) {
-                        eofPacket->data = nullptr;
-                        eofPacket->size = 0;
-                        eofPacket->stream_index = -1; // 特殊标记表示EOF
-                        m_audioPacketQueue->push(eofPacket);
-                        Logger::instance().info("EOF packet sent to audio queue");
-                    }
-                }
-                break;
-            } else {
-                Logger::instance().error("Error reading frame: " + std::to_string(ret));
-                std::this_thread::sleep_for(std::chrono::milliseconds(10));
-                continue;
-            }
-        }
-        
-        // 根据流索引将数据包分发到对应队列
-        if (packet->stream_index == m_mediaInfo.videoStreamIndex && m_videoStreamEnabled) {
-            // 视频包放入视频队列 - 不考虑队列是否已满,确保不丢包
-            if (m_videoPacketQueue) {
-                AVPacket* packetCopy = av_packet_alloc();
-                if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
-                    m_videoPacketQueue->push(packetCopy);
-                    
-                    // 记录队列大小,用于监控
-                    if (m_videoPacketQueue->size() % 100 == 0) {
-                        Logger::instance().debug("Video packet queue size: " + std::to_string(m_videoPacketQueue->size()));
-                    }
-                } else {
-                    av_packet_free(&packetCopy);
-                }
-            }
-        } else if (packet->stream_index == m_mediaInfo.audioStreamIndex && m_audioStreamEnabled) {
-            // 音频包放入音频队列 - 不考虑队列是否已满,确保不丢包
-            if (m_audioPacketQueue) {
-                AVPacket* packetCopy = av_packet_alloc();
-                if (packetCopy && av_packet_ref(packetCopy, packet) == 0) {
-                    m_audioPacketQueue->push(packetCopy);
-                    // 记录队列大小,用于监控
-                    if (m_audioPacketQueue->size() % 100 == 0) {
-                        Logger::instance().debug("Audio packet queue size: " + std::to_string(m_audioPacketQueue->size()));
-                    }
-                } else {
-                    av_packet_free(&packetCopy);
-                }
-            }
-        }
-        m_audioPacketQueue->wakeup();
-        m_videoPacketQueue->wakeup();
-
-        av_packet_unref(packet);
-    }
-    
-    av_packet_free(&packet);
-    Logger::instance().info("Read thread finished");
-}
-
-void PlayerCoreV2::videoDecodeThreadFunc() {
-    Logger::instance().info("Video decode thread started");
-    
-    int packetCount = 0;
-    int frameCount = 0;
-    while (!m_threadsShouldStop) {
-        // 检查暂停状态,类似ffplay.c中的paused检查
-        bool pausedState = m_paused.load();
-        Logger::instance().debug("Video decode thread loop - m_paused: "
-                                 + std::to_string(pausedState));
-        if (pausedState) {
-            Logger::instance().info("Video decode thread entering pause wait");
-            std::unique_lock<std::mutex> lock(m_pauseMutex);
-            m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
-            if (m_threadsShouldStop) {
-                break;
-            }
-            Logger::instance().info("Video decode thread exiting pause wait");
-            // 暂停状态结束后,继续下一次循环
-            continue;
-        }
-        if (!m_videoPacketQueue || !m_videoFrameQueue || !m_videoDecoder) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-        if (m_seeking) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-        Logger::instance().info("Video decode thread read Packet111");
-        // 从视频包队列获取包
-        AVPacket* packet = nullptr;
-        while (!m_threadsShouldStop && !packet) {
-            // 在 pop 操作前检查暂停状态,避免在 pop 期间阻塞
-            if (m_paused.load()) {
-                Logger::instance().debug("Video decode thread detected pause before pop");
-                break;
-            }
-            Logger::instance().info("Video decode thread read Packet");
-            packet = m_videoPacketQueue->pop(10); // 减少超时时间以提高seek响应速度
-            Logger::instance().infof("Video decode thread read Packet %d", packet);
-            if (packet) {
-                // 检查是否是EOF标记
-                if (packet->stream_index == -1 && packet->data == nullptr) {
-                    Logger::instance().info("Video decode thread received EOF packet");
-                    av_packet_free(&packet);
-                    
-                    // 向视频帧队列发送EOF标记
-                    if (m_videoFrameQueue) {
-                        AVFramePtr eofFrame = makeAVFrame();
-                        if (eofFrame) {
-                            eofFrame->data[0] = nullptr;
-                            eofFrame->width = 0;
-                            eofFrame->height = 0;
-                            eofFrame->pts = AV_NOPTS_VALUE;
-                            m_videoFrameQueue->push(std::move(eofFrame));
-                            Logger::instance().info("EOF frame sent to video frame queue");
-                        }
-                    }
-                    
-                    // 视频解码线程结束
-                    Logger::instance().info("Video decode thread finishing due to EOF");
-                    return;
-                }
-            }
-            if (!packet) {
-                std::this_thread::sleep_for(std::chrono::milliseconds(5));
-            }
-        }
-
-        if (!packet) {
-            Logger::instance().debug("Video decode thread: no more packets available");
-            continue;
-        }
-
-        packetCount++;
-        Logger::instance().debug("Video decode thread got packet #" + std::to_string(packetCount) + 
-                                ", size=" + std::to_string(packet->size) + 
-                                ", pts=" + std::to_string(packet->pts));
-        
-        // 解码视频帧
-        AVPacketPtr packetPtr(packet);
-        std::vector<AVFramePtr> frames;
-        ErrorCode decodeResult = m_videoDecoder->decode(packetPtr, frames);
-        
-        Logger::instance().debug("Video decode result: " + std::to_string(static_cast<int>(decodeResult)) + 
-                                ", frames count: " + std::to_string(frames.size()));
-        
-        if (decodeResult == ErrorCode::SUCCESS) {
-            for (auto& framePtr : frames) {
-                if (framePtr && !m_threadsShouldStop) {
-                    frameCount++;
-                    Logger::instance().debug("Processing video frame #" + std::to_string(frameCount) + 
-                                            ", width=" + std::to_string(framePtr->width) + 
-                                            ", height=" + std::to_string(framePtr->height) + 
-                                            ", pts=" + std::to_string(framePtr->pts));
-                    
-                    // 设置帧的时间戳(保持原始PTS,在播放时再转换)
-                    if (framePtr->pts != AV_NOPTS_VALUE) {
-                        Logger::instance().debug("Frame PTS: " + std::to_string(framePtr->pts));
-                    }
-                    
-                    // 将帧放入队列 - 不丢弃任何帧
-                    // 使用移动语义转移智能指针所有权
-                    m_videoFrameQueue->push(std::move(framePtr));
-                    m_frameCount++;
-                    Logger::instance().debug("Video frame pushed to queue, queue size: " + std::to_string(m_videoFrameQueue->size()));
-                    
-                    // 如果队列大小超过警告阈值,记录警告但不丢弃
-                    if (m_videoFrameQueue->size() > 80) {
-                        Logger::instance().warning("Video frame queue is getting large: " + std::to_string(m_videoFrameQueue->size()) + 
-                                                " frames. Performance may be affected.");
-                    }
-                }
-            }
-        } else {
-            Logger::instance().warning("Video decode failed with error: " + std::to_string(static_cast<int>(decodeResult)));
-        }
-    }
-
-    Logger::instance().info("Video decode thread finished, packets processed: "
-                            + std::to_string(packetCount)
-                            + ", frames decoded: " + std::to_string(frameCount));
-}
-
-void PlayerCoreV2::audioDecodeThreadFunc() {
-    Logger::instance().info("Audio decode thread started");
-    
-    int packetCount = 0;
-    int frameCount = 0;
-    while (!m_threadsShouldStop) {
-        // 检查暂停状态,类似ffplay.c中的paused检查
-        bool pausedState = m_paused.load();
-        Logger::instance().debug("Audio decode thread loop - m_paused: "
-                                 + std::to_string(pausedState));
-        if (pausedState) {
-            Logger::instance().info("Audio decode thread entering pause wait");
-            std::unique_lock<std::mutex> lock(m_pauseMutex);
-            m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
-            if (m_threadsShouldStop) {
-                break;
-            }
-            Logger::instance().info("Audio decode thread exiting pause wait");
-            // 暂停状态结束后,继续下一次循环
-            continue;
-        }
-
-        if (!m_audioPacketQueue || !m_audioFrameQueue || !m_audioDecoder) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-        if (m_seeking) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-        // 从音频包队列获取包
-        AVPacket* packet = nullptr;
-        while (!m_threadsShouldStop && !packet) {
-            // 在 pop 操作前检查暂停状态,避免在 pop 期间阻塞
-            if (m_paused.load()) {
-                Logger::instance().debug("Audio decode thread detected pause before pop");
-                break;
-            }
-            packet = m_audioPacketQueue->pop(10); // 减少超时时间以提高seek响应速度
-            if (packet) {
-                // 检查是否是EOF标记
-                if (packet->stream_index == -1 && packet->data == nullptr) {
-                    Logger::instance().info("Audio decode thread received EOF packet");
-                    av_packet_free(&packet);
-                    
-                    // 向音频帧队列发送EOF标记
-                    if (m_audioFrameQueue) {
-                        AVFramePtr eofFrame = makeAVFrame();
-                        if (eofFrame) {
-                            eofFrame->data[0] = nullptr;
-                            eofFrame->nb_samples = 0;
-                            eofFrame->pts = AV_NOPTS_VALUE;
-                            m_audioFrameQueue->push(std::move(eofFrame));
-                            Logger::instance().info("EOF frame sent to audio frame queue");
-                        }
-                    }
-                    
-                    // 音频解码线程结束
-                    Logger::instance().info("Audio decode thread finishing due to EOF");
-                    return;
-                }
-            }
-            if (!packet) {
-                std::this_thread::sleep_for(std::chrono::milliseconds(5));
-            }
-        }
-        
-        if (!packet) {
-            Logger::instance().debug("Audio decode thread: no more packets available");
-            continue;
-        }
-        
-        packetCount++;
-        Logger::instance().debug("Audio decode thread got packet #" + std::to_string(packetCount) + 
-                                ", size=" + std::to_string(packet->size) + 
-                                ", pts=" + std::to_string(packet->pts));
-        
-        // 解码音频帧
-        AVPacketPtr packetPtr(packet);
-        std::vector<AVFramePtr> frames;
-        ErrorCode decodeResult = m_audioDecoder->decode(packetPtr, frames);
-        
-        Logger::instance().debug("Audio decode result: " + std::to_string(static_cast<int>(decodeResult)) + 
-                                ", frames count: " + std::to_string(frames.size()));
-        
-        if (decodeResult == ErrorCode::SUCCESS) {
-            for (auto& framePtr : frames) {
-                if (framePtr && !m_threadsShouldStop) {
-                    frameCount++;
-                    Logger::instance().debug("Processing audio frame #" + std::to_string(frameCount) + 
-                                            ", nb_samples=" + std::to_string(framePtr->nb_samples) + 
-                                            ", pts=" + std::to_string(framePtr->pts));
-                    
-                    // 设置帧的时间戳(保持原始PTS,在播放时再转换)
-                    if (framePtr->pts != AV_NOPTS_VALUE) {
-                        Logger::instance().debug("Audio Frame PTS: " + std::to_string(framePtr->pts));
-                    }
-                    
-                    // 将帧放入队列 - 不丢弃任何帧
-                    // 使用移动语义转移智能指针所有权
-                    m_audioFrameQueue->push(std::move(framePtr));
-                    Logger::instance().debug("Audio frame pushed to queue, queue size: " + std::to_string(m_audioFrameQueue->size()));
-                    
-                    // 如果队列大小超过警告阈值,记录警告但不丢弃
-                    if (m_audioFrameQueue->size() > 300) {
-                        Logger::instance().warning("Audio frame queue is getting large: " + std::to_string(m_audioFrameQueue->size()) + 
-                                                " frames. Performance may be affected.");
-                    }
-                }
-            }
-        } 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");
-
-    // 用于计算帧持续时间的变量
-    AVFramePtr lastFrame = nullptr;
-
-    while (!m_threadsShouldStop) {
-        // 检查暂停状态,类似ffplay.c中的paused检查
-        bool pausedState = m_paused.load();
-        Logger::instance().debug("Video play thread loop - m_paused: "
-                                 + std::to_string(pausedState));
-        if (pausedState) {
-            Logger::instance().info("Video play thread entering pause wait");
-            std::unique_lock<std::mutex> lock(m_pauseMutex);
-            m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
-            if (m_threadsShouldStop) {
-                break;
-            }
-            Logger::instance().info("Video play thread exiting pause wait");
-            // 暂停状态结束后,继续下一次循环
-            continue;
-        }
-
-        if (!m_videoFrameQueue || !m_synchronizer) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-
-        // 在pop之前再次检查暂停状态,避免在pop期间阻塞
-        if (m_paused.load()) {
-            Logger::instance().debug("Video play thread detected pause before pop");
-            continue;
-        }
-
-        // 获取视频帧,使用更短的超时时间以提高暂停响应速度
-        AVFramePtr frame = m_videoFrameQueue->pop(1); // 使用1ms超时以快速响应暂停
-        if (!frame) {
-            // 检查是否应该继续等待
-            if (m_threadsShouldStop) {
-                break;
-            }
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-
-        // 获取帧后立即检查暂停状态,如果已暂停则释放帧并继续
-        bool pausedAfterPop = m_paused.load();
-        Logger::instance().debug("Video play thread after pop - m_paused: " + std::to_string(pausedAfterPop));
-        if (pausedAfterPop) {
-            Logger::instance().info("Video play thread releasing frame due to pause");
-            frame.reset(); // 智能指针自动释放
-            continue;
-        }
-
-        Logger::instance().debug("Video play thread got frame, pts=" + std::to_string(frame->pts));
-
-        // frame 本身就是智能指针,直接使用
-        AVFramePtr& framePtr = frame;
-        
-        // 使用同步器计算视频帧显示时间
-        double pts = frame->pts * av_q2d(m_formatContext->streams[m_mediaInfo.videoStreamIndex]->time_base);
-        
-        // 只在非暂停状态下更新时钟和处理帧
-        m_synchronizer->setClock(av::utils::ClockType::VIDEO, pts, 0);
-        
-        // 计算帧持续时间
-        double last_duration = 0.0;
-        if (lastFrame && lastFrame->pts != AV_NOPTS_VALUE && frame->pts != AV_NOPTS_VALUE) {
-            // 计算两帧之间的时间差
-            double last_pts = lastFrame->pts * av_q2d(m_formatContext->streams[m_mediaInfo.videoStreamIndex]->time_base);
-            last_duration = pts - last_pts;
-            if (last_duration < 0 || last_duration > 10.0) {
-                // 如果持续时间不合理,使用帧率的倒数作为默认值
-                last_duration = 1.0 / m_mediaInfo.fps;
-            }
-        } else {
-            // 如果没有上一帧,使用帧率的倒数作为默认值
-            last_duration = 1.0 / m_mediaInfo.fps;
-        }
-        
-        // 计算视频帧延迟并决定是否显示
-        FrameDecision decision = m_synchronizer->synchronizeVideo(pts, 0, last_duration);
-        
-        if (decision.action == FrameAction::DISPLAY) {
-            // 如果需要延迟显示,等待指定时间
-            if (decision.delay > 0.0) {
-                std::this_thread::sleep_for(
-                    std::chrono::microseconds(static_cast<int64_t>(decision.delay * 1000000)));
-            }
-
-            // 通知显示帧
-            if (m_eventCallback) {
-                m_eventCallback->onVideoFrameReady(framePtr.get());
-                Logger::instance().debug("Video frame ready for display, pts=" + std::to_string(pts) + ", delay=" + std::to_string(decision.delay));
-            }
-            
-            // 更新上一帧指针
-            lastFrame.reset(); // 智能指针自动释放旧帧
-            
-            // 创建当前帧的副本
-            AVFramePtr clonedFrame = makeAVFrame();
-            if (clonedFrame && av_frame_ref(clonedFrame.get(), frame.get()) == 0) {
-                lastFrame = std::move(clonedFrame);
-            }
-        } else if (decision.action == FrameAction::DROP) {
-            Logger::instance().debug("Video frame dropped due to sync, pts=" + std::to_string(pts) + ", error=" + std::to_string(decision.syncError));
-        }
-    }
-
-    // 清理最后一帧 - 智能指针自动清理
-    lastFrame.reset();
-
-    Logger::instance().info("Video play thread finished");
-}
-
-void PlayerCoreV2::audioPlayThreadFunc() {
-    Logger::instance().info("Audio play thread started");
-
-    int frameCount = 0;
-    while (!m_threadsShouldStop) {
-        // 检查暂停状态,类似ffplay.c中的paused检查
-        bool pausedState = m_paused.load();
-        Logger::instance().debug("Audio play thread loop - m_paused: "
-                                 + std::to_string(pausedState));
-        if (pausedState) {
-            Logger::instance().info("Audio play thread entering pause wait");
-            std::unique_lock<std::mutex> lock(m_pauseMutex);
-            m_pauseCondition.wait(lock, [this] { return !m_paused || m_threadsShouldStop; });
-            if (m_threadsShouldStop) {
-                break;
-            }
-            Logger::instance().info("Audio play thread exiting pause wait");
-            // 暂停状态结束后,继续下一次循环
-            continue;
-        }
-
-        if (!m_audioFrameQueue || !m_synchronizer || !m_audioOutput) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-
-        // 在pop之前再次检查暂停状态,避免在pop期间阻塞
-        if (m_paused.load()) {
-            Logger::instance().debug("Audio play thread detected pause before pop");
-            continue;
-        }
-
-        // 获取音频帧,使用更短的超时时间以提高暂停响应速度
-        AVFramePtr frame = m_audioFrameQueue->pop(1); // 使用1ms超时以快速响应暂停
-        if (!frame) {
-            // 检查是否应该继续等待
-            if (m_threadsShouldStop) {
-                break;
-            }
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            continue;
-        }
-        
-        // 获取帧后立即检查暂停状态,如果已暂停则释放帧并继续
-        bool pausedAfterPop = m_paused.load();
-        Logger::instance().debug("Audio play thread after pop - m_paused: " + std::to_string(pausedAfterPop));
-        if (pausedAfterPop) {
-            Logger::instance().info("Audio play thread releasing frame due to pause");
-            frame.reset(); // 智能指针自动释放
-            continue;
-        }
-        
-        // 检查是否是EOF帧
-        if (frame->data[0] == nullptr && frame->nb_samples == 0) {
-            Logger::instance().info("Audio play thread received EOF frame, playback completed");
-            frame.reset(); // 智能指针自动释放
-
-            // 通知播放完成
-            setState(PlayerState::Stopped);
-            Logger::instance().info("Audio playback finished naturally");
-            return;
-        }
-
-        frameCount++;
-        Logger::instance().debug("Audio play thread got frame #" + std::to_string(frameCount)
-                                 + ", pts=" + std::to_string(frame->pts)
-                                 + ", nb_samples=" + std::to_string(frame->nb_samples));
-
-        // frame 本身就是智能指针,直接使用
-        AVFramePtr& framePtr = frame;
-
-        // 计算音频PTS
-        double pts = frame->pts
-                     * av_q2d(m_formatContext->streams[m_mediaInfo.audioStreamIndex]->time_base);
-
-        // 只在非暂停状态下更新音频时钟
-        m_synchronizer->setClock(av::utils::ClockType::AUDIO, pts, 0);
-
-        // 同步音频样本数量
-        int originalSamples = frame->nb_samples;
-        int adjustedSamples = m_synchronizer->synchronizeAudio((short*) frame->data[0],
-                                                               frame->nb_samples,
-                                                               pts);
-
-        if (adjustedSamples != originalSamples) {
-            Logger::instance().debug("Audio samples adjusted from " + std::to_string(originalSamples)
-                                     + " to " + std::to_string(adjustedSamples) + " for sync");
-        }
-        if (m_paused) {
-            continue;
-        }
-        {
-            Logger::instance().debug("Writing audio frame to output device");
-            bool writeResult = m_audioOutput->writeFrame(framePtr);
-            Logger::instance().debug("Audio frame write result: " + std::to_string(writeResult));
-
-            // 如果写入失败,等待一段时间避免快速循环
-            if (!writeResult) {
-                Logger::instance().warning("Audio frame write failed, waiting before next frame");
-                std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            }
-        }
-
-        // framePtr 会自动释放内存,无需手动调用 av_frame_free
-    }
-
-    Logger::instance().info("Audio play thread finished, total frames processed: "
-                            + std::to_string(frameCount));
-}
-
-} // namespace player
-} // namespace av

+ 0 - 346
AV/code/player/player_core_v2.h

@@ -1,346 +0,0 @@
-#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 <memory>
-#include <atomic>
-#include <mutex>
-#include <string>
-#include <functional>
-#include <chrono>
-#include <thread>
-#include <condition_variable>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavcodec/avcodec.h>
-#include <libavutil/avutil.h>
-#include <libavutil/time.h>
-}
-
-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<PlayerState> 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<VideoDecoder> m_videoDecoder;
-    std::unique_ptr<AudioDecoder> m_audioDecoder;
-    
-    // 队列管理 - 分离视频和音频包队列以提高效率
-    std::unique_ptr<av::utils::PacketQueue> m_videoPacketQueue;
-    std::unique_ptr<av::utils::PacketQueue> m_audioPacketQueue;
-    std::unique_ptr<av::utils::FrameQueue> m_videoFrameQueue;
-    std::unique_ptr<av::utils::FrameQueue> m_audioFrameQueue;
-    
-    // 同步器
-    std::unique_ptr<SynchronizerV2> m_synchronizer;
-
-    // 音频输出
-    std::unique_ptr<AudioOutput> m_audioOutput;
-    
-    // 视频渲染(已移除直接依赖,改为使用回调)
-    // OpenGLVideoWidget* m_openGLVideoRenderer = nullptr;
-    
-    // 播放控制
-    std::atomic<double> m_volume{1.0};
-    std::atomic<double> m_playbackSpeed{1.0};
-    
-    // Seek控制
-    std::atomic<int64_t> m_seekTarget{-1};
-    std::atomic<int64_t> m_seekMinTime{INT64_MIN};
-    std::atomic<int64_t> m_seekMaxTime{INT64_MAX};
-    std::atomic<int> m_seekFlags{AVSEEK_FLAG_BACKWARD};
-    std::atomic<bool> m_seeking{false};
-    std::mutex m_seekMutex;
-    std::condition_variable m_seekCondition;
-    
-    // 流控制
-    std::atomic<bool> m_videoStreamEnabled{true};
-    std::atomic<bool> m_audioStreamEnabled{true};
-    
-    // 时间管理
-    std::chrono::steady_clock::time_point m_playStartTime;
-    std::atomic<int64_t> m_baseTime{0};
-    std::atomic<int64_t> 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<bool> m_threadsShouldStop{false};
-    std::atomic<bool> m_threadsRunning{false};
-    std::atomic<bool> m_paused{false};  // 暂停标志,类似ffplay.c中的paused
-    std::condition_variable m_pauseCondition;  // 暂停条件变量,类似ffplay.c中的continue_read_thread
-    std::mutex m_pauseMutex;  // 暂停互斥锁
-    
-    // 初始化标志
-    std::atomic<bool> m_initialized{false};
-    
-    // 帧计数
-    std::atomic<int64_t> m_frameCount{0};
-    std::atomic<int64_t> 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<int> m_errorCount{0};
-    std::chrono::steady_clock::time_point m_lastErrorTime;
-    
-    // 缓冲控制
-    std::atomic<bool> m_buffering{false};
-    std::atomic<double> m_bufferHealth{1.0};
-};
-
-} // namespace player
-} // namespace av
-
-#endif // AV_PLAYER_CORE_V2_H

+ 0 - 200
AV/code/recorder/recorder.cpp

@@ -1,200 +0,0 @@
-#include "recorder.h"
-#include "../base/logger.h"
-#include <filesystem>
-#include <algorithm>
-
-namespace av {
-namespace recorder {
-
-// 静态成员初始化
-bool RecorderModule::initialized_ = false;
-
-ErrorCode RecorderModule::initialize() {
-    if (initialized_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    AV_LOGGER_INFOF("Initializing Recorder Module v{}", getVersion());
-    
-    // TODO: 初始化FFmpeg库(如果需要)
-    // TODO: 检查硬件编码器支持
-    // TODO: 初始化音频设备枚举
-    
-    initialized_ = true;
-    
-    AV_LOGGER_INFO("Recorder Module initialized successfully");
-    return ErrorCode::SUCCESS;
-}
-
-void RecorderModule::cleanup() {
-    if (!initialized_) {
-        return;
-    }
-    
-    AV_LOGGER_INFO("Cleaning up Recorder Module");
-    
-    // TODO: 清理资源
-    
-    initialized_ = false;
-    
-    AV_LOGGER_INFO("Recorder Module cleaned up");
-}
-
-bool RecorderModule::isInitialized() {
-    return initialized_;
-}
-
-std::vector<std::string> RecorderModule::getSupportedFormats() {
-    return {
-        "mp4", "avi", "mkv", "mov", "flv", "webm",
-        "mp3", "wav", "aac", "ogg", "flac"
-    };
-}
-
-std::vector<std::string> RecorderModule::getSupportedAudioCodecs() {
-    return {
-        "aac", "mp3", "opus", "vorbis", "flac", "pcm_s16le"
-    };
-}
-
-std::vector<std::string> RecorderModule::getSupportedVideoCodecs() {
-    return {
-        "h264", "h265", "vp8", "vp9", "av1", "mpeg4"
-    };
-}
-
-namespace utils {
-
-AudioRecorderParams getDefaultAudioParams() {
-    AudioRecorderParams params;
-    params.capturerType = capture::CapturerType::AUDIO_MIC;
-    params.sampleRate = 44100;
-    params.channels = 2;
-    params.bitsPerSample = 16;
-    params.sampleFormat = AV_SAMPLE_FMT_S16;
-    params.codecName = "aac";
-    params.bitrate = 128000;
-    params.volumeScale = 1.0f;
-    params.enableMixing = false;
-    params.format = "mp4";
-    return params;
-}
-
-VideoRecorderParams getDefaultVideoParams() {
-    VideoRecorderParams params;
-    params.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
-    params.monitorIndex = 0;
-    params.width = 1920;
-    params.height = 1080;
-    params.frameRate = 30;
-    params.pixelFormat = AV_PIX_FMT_YUV420P;
-    params.codecName = "h264";
-    params.bitrate = 5000000; // 5 Mbps
-    params.keyFrameInterval = 30;
-    params.preset = "medium";
-    params.drawCursor = true;
-    params.captureAudio = false;
-    params.format = "mp4";
-    return params;
-}
-
-AVRecorderParams getDefaultAVParams() {
-    AVRecorderParams params;
-    params.audioParams = getDefaultAudioParams();
-    params.videoParams = getDefaultVideoParams();
-    params.enableAudio = true;
-    params.enableVideo = true;
-    params.enableSync = true;
-    params.syncThresholdMs = 40;
-    params.dropFrameOnSync = true;
-    params.format = "mp4";
-    return params;
-}
-
-bool isValidOutputPath(const std::string& path) {
-    if (path.empty()) {
-        return false;
-    }
-    
-    try {
-        std::filesystem::path fsPath(path);
-        
-        // 检查父目录是否存在或可创建
-        auto parentPath = fsPath.parent_path();
-        if (!parentPath.empty() && !std::filesystem::exists(parentPath)) {
-            // 尝试创建目录
-            std::error_code ec;
-            std::filesystem::create_directories(parentPath, ec);
-            if (ec) {
-                AV_LOGGER_ERRORF("Cannot create output directory: {}", ec.message());
-                return false;
-            }
-        }
-        
-        // 检查文件扩展名
-        auto extension = fsPath.extension().string();
-        if (extension.empty()) {
-            return false;
-        }
-        
-        // 转换为小写
-        std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
-        
-        // 检查是否为支持的格式
-        auto supportedFormats = RecorderModule::getSupportedFormats();
-        auto formatName = extension.substr(1); // 去掉点号
-        
-        return std::find(supportedFormats.begin(), supportedFormats.end(), formatName) != supportedFormats.end();
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Invalid output path: {}", e.what());
-        return false;
-    }
-}
-
-VideoRecorderParams getRecommendedVideoParams() {
-    VideoRecorderParams params = getDefaultVideoParams();
-    
-    // TODO: 根据系统性能调整参数
-    // 这里可以检查:
-    // - CPU性能
-    // - 可用内存
-    // - 硬件编码器支持
-    // - 显示器分辨率
-    
-    // 简单的性能检测示例
-    auto availableMemory = std::thread::hardware_concurrency(); // 简化的性能指标
-    
-    if (availableMemory <= 4) {
-        // 低性能设置
-        params.width = 1280;
-        params.height = 720;
-        params.frameRate = 24;
-        params.bitrate = 2000000; // 2 Mbps
-        params.preset = "fast";
-    } else if (availableMemory <= 8) {
-        // 中等性能设置
-        params.width = 1920;
-        params.height = 1080;
-        params.frameRate = 30;
-        params.bitrate = 5000000; // 5 Mbps
-        params.preset = "medium";
-    } else {
-        // 高性能设置
-        params.width = 1920;
-        params.height = 1080;
-        params.frameRate = 60;
-        params.bitrate = 8000000; // 8 Mbps
-        params.preset = "slow";
-    }
-    
-    AV_LOGGER_INFOF("Recommended video params: {}x{} @ {}fps, {} bps", 
-             params.width, params.height, params.frameRate, params.bitrate);
-    
-    return params;
-}
-
-} // namespace utils
-
-} // namespace recorder
-} // namespace av

+ 0 - 175
AV/code/recorder/recorder.h

@@ -1,175 +0,0 @@
-#ifndef AV_RECORDER_H
-#define AV_RECORDER_H
-
-/**
- * AV录制器模块
- * 
- * 这个模块提供了完整的音视频录制功能,基于AV模块的现有组件构建。
- * 主要特性:
- * - 音频录制:支持多设备采集、混音、实时编码
- * - 视频录制:支持屏幕录制、窗口采集、摄像头录制
- * - 音视频同步:提供精确的音视频同步机制
- * - 模块化设计:可独立使用音频或视频录制器
- * - 高性能:多线程处理,支持硬件加速
- * 
- * 使用示例:
- * 
- * // 音频录制
- * auto audioRecorder = RecorderFactoryImpl::createAudioRecorder();
- * AudioRecorderParams audioParams;
- * audioParams.outputPath = "output.mp4";
- * audioParams.sampleRate = 44100;
- * audioParams.channels = 2;
- * audioRecorder->initialize(audioParams);
- * audioRecorder->startRecording();
- * 
- * // 视频录制
- * auto videoRecorder = RecorderFactoryImpl::createVideoRecorder();
- * VideoRecorderParams videoParams;
- * videoParams.outputPath = "output.mp4";
- * videoParams.width = 1920;
- * videoParams.height = 1080;
- * videoParams.frameRate = 30;
- * videoRecorder->initialize(videoParams);
- * videoRecorder->startRecording();
- * 
- * // 音视频同步录制
- * auto avRecorder = RecorderFactoryImpl::createAVRecorder();
- * AVRecorderParams avParams;
- * avParams.outputPath = "output.mp4";
- * avParams.enableAudio = true;
- * avParams.enableVideo = true;
- * avParams.enableSync = true;
- * avRecorder->initialize(avParams);
- * avRecorder->startRecording();
- */
-
-// 核心接口
-#include "recorder_abstract_recorder.h"
-
-// 具体实现
-#include "recorder_audio_recorder.h"
-#include "recorder_video_recorder.h"
-#include "recorder_av_recorder.h"
-
-namespace av {
-namespace recorder {
-
-/**
- * 录制器模块版本信息
- */
-struct RecorderVersion {
-    static constexpr int MAJOR = 1;
-    static constexpr int MINOR = 0;
-    static constexpr int PATCH = 0;
-    
-    static std::string toString() {
-        return std::to_string(MAJOR) + "." + 
-               std::to_string(MINOR) + "." + 
-               std::to_string(PATCH);
-    }
-};
-
-/**
- * 录制器模块初始化
- */
-class RecorderModule {
-public:
-    /**
-     * 初始化录制器模块
-     */
-    static ErrorCode initialize();
-    
-    /**
-     * 清理录制器模块
-     */
-    static void cleanup();
-    
-    /**
-     * 获取模块版本
-     */
-    static std::string getVersion() {
-        return RecorderVersion::toString();
-    }
-    
-    /**
-     * 检查模块是否已初始化
-     */
-    static bool isInitialized();
-    
-    /**
-     * 获取支持的录制格式
-     */
-    static std::vector<std::string> getSupportedFormats();
-    
-    /**
-     * 获取支持的音频编码器
-     */
-    static std::vector<std::string> getSupportedAudioCodecs();
-    
-    /**
-     * 获取支持的视频编码器
-     */
-    static std::vector<std::string> getSupportedVideoCodecs();
-
-private:
-    static bool initialized_;
-};
-
-/**
- * 便利函数
- */
-namespace utils {
-
-/**
- * 创建音频录制器的便利函数
- */
-inline std::unique_ptr<AudioRecorder> createAudioRecorder() {
-    return RecorderFactoryImpl::createAudioRecorder();
-}
-
-/**
- * 创建视频录制器的便利函数
- */
-inline std::unique_ptr<VideoRecorder> createVideoRecorder() {
-    return RecorderFactoryImpl::createVideoRecorder();
-}
-
-/**
- * 创建音视频录制器的便利函数
- */
-inline std::unique_ptr<AVRecorder> createAVRecorder() {
-    return RecorderFactoryImpl::createAVRecorder();
-}
-
-/**
- * 获取默认音频参数
- */
-AudioRecorderParams getDefaultAudioParams();
-
-/**
- * 获取默认视频参数
- */
-VideoRecorderParams getDefaultVideoParams();
-
-/**
- * 获取默认音视频参数
- */
-AVRecorderParams getDefaultAVParams();
-
-/**
- * 检查输出路径是否有效
- */
-bool isValidOutputPath(const std::string& path);
-
-/**
- * 获取推荐的录制参数(基于系统性能)
- */
-VideoRecorderParams getRecommendedVideoParams();
-
-} // namespace utils
-
-} // namespace recorder
-} // namespace av
-
-#endif // AV_RECORDER_H

+ 0 - 41
AV/code/recorder/recorder.pri

@@ -1,41 +0,0 @@
-# AV录制器模块 - Qt项目包含文件
-# 用于将录制器模块集成到Qt项目中
-
-# 模块标识
-RECORDER_MODULE = 1
-
-# 包含路径
-INCLUDEPATH += $$PWD
-INCLUDEPATH += $$PWD/..
-
-# 依赖路径
-DEPENDPATH += $$PWD
-
-# 头文件
-HEADERS += \
-    $$PWD/recorder.h \
-    $$PWD/recorder_abstract_recorder.h \
-    $$PWD/recorder_audio_recorder.h \
-    $$PWD/recorder_video_recorder.h \
-    $$PWD/recorder_av_recorder.h
-
-# 源文件
-SOURCES += \
-    $$PWD/recorder.cpp \
-    $$PWD/recorder_abstract_recorder.cpp \
-    $$PWD/recorder_audio_recorder.cpp \
-    $$PWD/recorder_video_recorder.cpp \
-    $$PWD/recorder_av_recorder.cpp
-
-# 编译器定义
-DEFINES += AV_RECORDER_MODULE
-
-# C++标准
-CONFIG += c++17
-
-# Qt模块依赖
-QT += core multimedia
-
-
-# 包含录制器UI模块
-include($$PWD/ui/recorder_ui.pri)

+ 0 - 133
AV/code/recorder/recorder_abstract_recorder.cpp

@@ -1,133 +0,0 @@
-#include "recorder_abstract_recorder.h"
-#include "../base/logger.h"
-#include <chrono>
-
-namespace av {
-namespace recorder {
-
-AbstractRecorder::AbstractRecorder(MediaType mediaType)
-    : mediaType_(mediaType)
-    , state_(RecorderState::IDLE)
-    , frameCountForFps_(0) {
-    stats_.startTime = std::chrono::steady_clock::now();
-    lastFrameTime_ = std::chrono::steady_clock::now();
-    lastFpsCalcTime_ = std::chrono::steady_clock::now();
-}
-
-AbstractRecorder::~AbstractRecorder() {
-    close();
-}
-
-RecorderStats AbstractRecorder::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    auto stats = stats_;
-    
-    // 计算录制时长
-    if (state_.load() == RecorderState::RECORDING || 
-        state_.load() == RecorderState::PAUSED ||
-        state_.load() == RecorderState::STOPPED) {
-        auto now = std::chrono::steady_clock::now();
-        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - stats_.startTime);
-        stats.recordingTime = duration.count() / 1000.0;
-    }
-    
-    return stats;
-}
-
-void AbstractRecorder::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = RecorderStats{};
-    stats_.startTime = std::chrono::steady_clock::now();
-    frameCountForFps_ = 0;
-    lastFrameTime_ = std::chrono::steady_clock::now();
-    lastFpsCalcTime_ = std::chrono::steady_clock::now();
-}
-
-void AbstractRecorder::setState(RecorderState state) {
-    RecorderState oldState = state_.exchange(state);
-    
-    if (oldState != state) {
-        AV_LOGGER_INFOF("Recorder state changed: {} -> {}", 
-                static_cast<int>(oldState), static_cast<int>(state));
-        
-        if (stateCallback_) {
-            stateCallback_(state);
-        }
-        
-        // 状态变化时重置统计开始时间
-        if (state == RecorderState::RECORDING) {
-            std::lock_guard<std::mutex> lock(statsMutex_);
-            stats_.startTime = std::chrono::steady_clock::now();
-        }
-    }
-}
-
-void AbstractRecorder::reportError(ErrorCode error, const std::string& message) {
-    setState(RecorderState::ERROR);
-    
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.errorCount++;
-    }
-    
-    AV_LOGGER_ERRORF("Recorder error: {} - {}", static_cast<int>(error), message);
-    
-    if (errorCallback_) {
-        errorCallback_(error, message);
-    }
-}
-
-void AbstractRecorder::updateStats(bool success, uint64_t bytes) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (success) {
-        stats_.recordedFrames++;
-        stats_.totalBytes += bytes;
-        frameCountForFps_++;
-    } else {
-        stats_.droppedFrames++;
-    }
-    
-    // 定期计算帧率
-    auto now = std::chrono::steady_clock::now();
-    auto timeSinceLastCalc = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastFpsCalcTime_);
-    
-    if (timeSinceLastCalc.count() >= 1000) { // 每秒计算一次
-        calculateFrameRate();
-    }
-}
-
-void AbstractRecorder::calculateFrameRate() {
-    auto now = std::chrono::steady_clock::now();
-    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastFpsCalcTime_);
-    
-    if (duration.count() > 0) {
-        stats_.avgFrameRate = (frameCountForFps_ * 1000.0) / duration.count();
-        frameCountForFps_ = 0;
-        lastFpsCalcTime_ = now;
-    }
-}
-
-// RecorderFactory 实现
-std::unique_ptr<AbstractRecorder> RecorderFactory::createRecorder(MediaType mediaType) {
-    // 这里将在具体的录制器实现中完成
-    // 目前返回nullptr,待后续实现具体的录制器类
-    return nullptr;
-}
-
-bool RecorderFactory::isRecorderSupported(MediaType mediaType) {
-    switch (mediaType) {
-        case MediaType::AUDIO:
-        case MediaType::VIDEO:
-            return true;
-        default:
-            return false;
-    }
-}
-
-std::vector<MediaType> RecorderFactory::getSupportedMediaTypes() {
-    return {MediaType::AUDIO, MediaType::VIDEO};
-}
-
-} // namespace recorder
-} // namespace av

+ 0 - 193
AV/code/recorder/recorder_abstract_recorder.h

@@ -1,193 +0,0 @@
-#ifndef AV_RECORDER_ABSTRACT_RECORDER_H
-#define AV_RECORDER_ABSTRACT_RECORDER_H
-
-#include "../base/types.h"
-#include "../base/media_common.h"
-#include "../capture/capture_abstract_capturer.h"
-#include "../codec/codec_abstract_codec.h"
-#include "../muxer/muxer_abstract_muxer.h"
-#include <memory>
-#include <functional>
-#include <atomic>
-#include <mutex>
-#include <string>
-#include <vector>
-
-namespace av {
-namespace recorder {
-
-/**
- * 录制器状态
- */
-enum class RecorderState {
-    IDLE,           // 空闲
-    INITIALIZED,    // 已初始化
-    RECORDING,      // 录制中
-    PAUSED,         // 暂停
-    STOPPED,        // 已停止
-    ERROR           // 错误状态
-};
-
-/**
- * 录制器参数
- */
-struct RecorderParams {
-    MediaType mediaType;
-    std::string outputPath;         // 输出路径
-    std::string format;             // 输出格式
-    bool autoStart = false;         // 自动开始录制
-    
-    virtual ~RecorderParams() = default;
-};
-
-/**
- * 录制器统计信息
- */
-struct RecorderStats {
-    uint64_t recordedFrames = 0;    // 已录制帧数
-    uint64_t droppedFrames = 0;     // 丢弃帧数
-    uint64_t totalBytes = 0;        // 总字节数
-    uint64_t errorCount = 0;        // 错误次数
-    double recordingTime = 0.0;     // 录制时长(秒)
-    double avgFrameRate = 0.0;      // 平均帧率
-    std::chrono::steady_clock::time_point startTime; // 开始时间
-};
-
-/**
- * 抽象录制器基类
- * 整合采集器、编码器和复用器,提供完整的录制功能
- */
-class AbstractRecorder {
-public:
-    AbstractRecorder(MediaType mediaType);
-    virtual ~AbstractRecorder();
-
-    // 禁止拷贝
-    AbstractRecorder(const AbstractRecorder&) = delete;
-    AbstractRecorder& operator=(const AbstractRecorder&) = delete;
-
-    /**
-     * 初始化录制器
-     * @param params 录制参数
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode initialize(const RecorderParams& params) = 0;
-
-    /**
-     * 开始录制
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode startRecording() = 0;
-
-    /**
-     * 停止录制
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode stopRecording() = 0;
-
-    /**
-     * 暂停录制
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode pauseRecording() = 0;
-
-    /**
-     * 恢复录制
-     * @return 成功返回ErrorCode::SUCCESS
-     */
-    virtual ErrorCode resumeRecording() = 0;
-
-    /**
-     * 关闭录制器,释放资源
-     */
-    virtual void close() {}
-
-    // 状态查询
-    RecorderState getState() const { return state_.load(); }
-    bool isRecording() const { return state_.load() == RecorderState::RECORDING; }
-    bool isPaused() const { return state_.load() == RecorderState::PAUSED; }
-
-    // 统计信息
-    virtual RecorderStats getStats() const;
-    virtual void resetStats();
-
-    // 回调设置
-    using ErrorCallback = std::function<void(ErrorCode, const std::string&)>;
-    using StateCallback = std::function<void(RecorderState)>;
-    
-    void setErrorCallback(const ErrorCallback& callback) { errorCallback_ = callback; }
-    void setStateCallback(const StateCallback& callback) { stateCallback_ = callback; }
-
-protected:
-    /**
-     * 设置录制器状态
-     */
-    void setState(RecorderState state);
-
-    /**
-     * 报告错误
-     */
-    void reportError(ErrorCode error, const std::string& message = "");
-
-    /**
-     * 更新统计信息
-     */
-    void updateStats(bool success, uint64_t bytes = 0);
-
-    /**
-     * 计算帧率
-     */
-    void calculateFrameRate();
-
-    /**
-     * 验证参数
-     */
-    virtual bool validateParams(const RecorderParams& params) = 0;
-
-protected:
-    MediaType mediaType_;                   // 媒体类型
-    std::atomic<RecorderState> state_;      // 当前状态
-    RecorderParams params_;                 // 录制参数
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    RecorderStats stats_;
-    
-    // 回调函数
-    ErrorCallback errorCallback_;
-    StateCallback stateCallback_;
-    
-    // 帧率计算
-    std::chrono::steady_clock::time_point lastFrameTime_;
-    std::chrono::steady_clock::time_point lastFpsCalcTime_;
-    uint64_t frameCountForFps_ = 0;
-    
-    // 线程安全
-    mutable std::mutex recorderMutex_;
-};
-
-/**
- * 录制器工厂类
- */
-class RecorderFactory {
-public:
-    /**
-     * 创建录制器
-     */
-    static std::unique_ptr<AbstractRecorder> createRecorder(MediaType mediaType);
-    
-    /**
-     * 检查是否支持指定媒体类型的录制
-     */
-    static bool isRecorderSupported(MediaType mediaType);
-    
-    /**
-     * 获取支持的媒体类型列表
-     */
-    static std::vector<MediaType> getSupportedMediaTypes();
-};
-
-} // namespace recorder
-} // namespace av
-
-#endif // AV_RECORDER_ABSTRACT_RECORDER_H

+ 0 - 592
AV/code/recorder/recorder_audio_recorder.cpp

@@ -1,592 +0,0 @@
-#include "recorder_audio_recorder.h"
-#include "../base/logger.h"
-#include "../capture/capture_audio_capturer.h"
-#include "../codec/codec_audio_encoder.h"
-#include "../muxer/muxer_file_muxer.h"
-#include <algorithm>
-#include <cmath>
-
-extern "C" {
-#include <libavutil/channel_layout.h>
-}
-
-namespace av {
-namespace recorder {
-AudioRecorder::AudioRecorder()
-    : AbstractRecorder(MediaType::AUDIO)
-    , shouldStop_(false)
-    , volumeScale_(1.0f)
-    , currentAudioLevel_(0.0f)
-    , isPaused_(false)
-    , processedSamples_(0)
-{
-    threadPool_ = std::make_unique<utils::ThreadPool>(); // 2个工作线程
-    lastProcessTime_ = std::chrono::steady_clock::now();
-}
-
-AudioRecorder::~AudioRecorder() {
-    close();
-}
-
-ErrorCode AudioRecorder::initialize(const RecorderParams& params) {
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    audioParams_ = static_cast<const AudioRecorderParams&>(params);
-    params_ = params;
-    
-    // 初始化各个组件
-    ErrorCode result = initializeCapturers();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    result = initializeEncoder();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    result = initializeMuxer();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    setState(RecorderState::INITIALIZED);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::startRecording() {
-    if (getState() != RecorderState::INITIALIZED && getState() != RecorderState::STOPPED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStop_ = false;
-    isPaused_ = false;
-    
-    // 启动采集器
-    for (auto& capturer : capturers_) {
-        ErrorCode result = capturer->start();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to start audio capturer: {}", static_cast<int>(result));
-            return result;
-        }
-    }
-    
-    // 启动音频处理线程
-    processingThread_ = std::make_unique<std::thread>(&AudioRecorder::audioProcessingThread, this);
-    
-    setState(RecorderState::RECORDING);
-    resetStats();
-    
-    AV_LOGGER_INFO("Audio recording started");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::stopRecording() {
-    if (getState() != RecorderState::RECORDING && getState() != RecorderState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStop_ = true;
-    isPaused_ = false;
-    
-    // 通知处理线程停止
-    queueCondition_.notify_all();
-    
-    // 等待处理线程结束
-    if (processingThread_ && processingThread_->joinable()) {
-        processingThread_->join();
-        processingThread_.reset();
-    }
-    
-    // 停止采集器
-    for (auto& capturer : capturers_) {
-        capturer->stop();
-    }
-    
-    // 刷新编码器
-    if (encoder_) {
-        std::vector<AVPacketPtr> packets;
-        encoder_->finishEncode(packets);
-        
-        for (const auto& packet : packets) {
-            if (muxer_) {
-                muxer_->writePacket(packet.get());
-            }
-        }
-    }
-    
-    // 关闭复用器
-    if (muxer_) {
-        muxer_->close();
-    }
-    
-    setState(RecorderState::STOPPED);
-    
-    AV_LOGGER_INFO("Audio recording stopped");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::pauseRecording() {
-    if (getState() != RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    isPaused_ = true;
-    setState(RecorderState::PAUSED);
-    
-    AV_LOGGER_INFO("Audio recording paused");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::resumeRecording() {
-    if (getState() != RecorderState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    isPaused_ = false;
-    setState(RecorderState::RECORDING);
-    
-    AV_LOGGER_INFO("Audio recording resumed");
-    return ErrorCode::SUCCESS;
-}
-
-void AudioRecorder::close() {
-    if (getState() == RecorderState::RECORDING || getState() == RecorderState::PAUSED) {
-        stopRecording();
-    }
-    
-    cleanup();
-    setState(RecorderState::IDLE);
-}
-
-void AudioRecorder::setVolumeScale(float scale) {
-    volumeScale_ = std::max(0.0f, std::min(2.0f, scale)); // 限制在0-2之间
-}
-
-float AudioRecorder::getAudioLevel() const {
-    std::lock_guard<std::mutex> lock(audioLevelMutex_);
-    return currentAudioLevel_;
-}
-
-ErrorCode AudioRecorder::addAudioDevice(const std::string& deviceId, capture::CapturerType type) {
-    std::lock_guard<std::mutex> lock(capturerMutex_);
-    
-    // 创建新的采集器
-    auto capturer = std::make_unique<capture::AudioCapturer>();
-    
-    capture::AudioCaptureParams capturerParams(type);
-    capturerParams.deviceId = deviceId;
-    
-    ErrorCode result = capturer->initialize(capturerParams);
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 设置回调
-    size_t capturerIndex = capturers_.size();
-    capturer->setFrameCallback([this, capturerIndex](const AVFramePtr& frame) {
-        onAudioFrameCaptured(frame, capturerIndex);
-    });
-    
-    capturers_.push_back(std::move(capturer));
-    
-    AV_LOGGER_INFOF("Added audio device: {}", deviceId);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::removeAudioDevice(const std::string& deviceId) {
-    std::lock_guard<std::mutex> lock(capturerMutex_);
-    
-    auto it = std::find_if(capturers_.begin(), capturers_.end(),
-        [&deviceId](const std::unique_ptr<capture::AudioCapturer>& capturer) {
-            return capturer->getCurrentDevice() == deviceId;
-        });
-    
-    if (it != capturers_.end()) {
-        (*it)->stop();
-        (*it)->close();
-        capturers_.erase(it);
-        
-        AV_LOGGER_INFOF("Removed audio device: {}", deviceId);
-        return ErrorCode::SUCCESS;
-    }
-    
-    return ErrorCode::DEVICE_NOT_FOUND;
-}
-
-std::vector<std::string> AudioRecorder::getAvailableDevices(capture::CapturerType type) const {
-    (void)type; // 避免未使用参数警告
-    auto capturer = std::make_unique<capture::AudioCapturer>();
-    return capturer->getAvailableDevices();
-}
-
-bool AudioRecorder::validateParams(const RecorderParams& params) {
-    const auto& audioParams = static_cast<const AudioRecorderParams&>(params);
-    
-    if (audioParams.sampleRate == 0 || audioParams.channels == 0) {
-        AV_LOGGER_ERRORF("Invalid audio parameters: sampleRate={}, channels={}",
-                  audioParams.sampleRate, audioParams.channels);
-        return false;
-    }
-    
-    if (audioParams.outputPath.empty()) {
-        AV_LOGGER_ERROR("Output path is empty");
-        return false;
-    }
-    
-    return true;
-}
-
-void AudioRecorder::audioProcessingThread() {
-    AV_LOGGER_INFO("Audio processing thread started");
-    
-    try {
-        while (!shouldStop_) {
-            std::unique_lock<std::mutex> lock(queueMutex_);
-            
-            // 等待音频帧或停止信号
-            queueCondition_.wait(lock, [this] {
-                return !frameQueue_.empty() || shouldStop_;
-            });
-            
-            if (shouldStop_) {
-                break;
-            }
-            
-            // 处理队列中的音频帧
-            std::vector<AudioFrameData> framesToProcess;
-            while (!frameQueue_.empty()) {
-                framesToProcess.push_back(std::move(frameQueue_.front()));
-                frameQueue_.pop_front();
-            }
-            
-            lock.unlock();
-            
-            if (isPaused_) {
-                continue;
-            }
-            
-            // 按时间戳排序
-            std::sort(framesToProcess.begin(), framesToProcess.end(),
-                [](const AudioFrameData& a, const AudioFrameData& b) {
-                    return a.timestamp < b.timestamp;
-                });
-            
-            // 处理音频帧
-            for (auto& frameData : framesToProcess) {
-                if (shouldStop_ || isPaused_) {
-                    break;
-                }
-                
-                try {
-                    // 检查帧是否有效
-                    if (!frameData.frame) {
-                        AV_LOGGER_WARNING("Skipping null audio frame");
-                        continue;
-                    }
-                    
-                    // 验证音频帧数据
-                    if (frameData.frame->nb_samples <= 0 || !frameData.frame->data[0]) {
-                        AV_LOGGER_WARNING("Invalid audio frame data, skipping");
-                        continue;
-                    }
-                    
-                    // 在移动之前保存需要的值
-                    int nbSamples = frameData.frame->nb_samples;
-                    
-                    // 应用音量缩放
-                    AVFramePtr processedFrame = std::move(frameData.frame);
-                    if (volumeScale_ != 1.0f) {
-                        // TODO: 实现音量缩放
-                    }
-                    
-                    // 计算音频电平
-                    {
-                        std::lock_guard<std::mutex> levelLock(audioLevelMutex_);
-                        // TODO: 计算RMS音频电平
-                        currentAudioLevel_ = 0.5f; // 临时值
-                    }
-                    
-                    // 编码音频帧
-                    if (encoder_ && processedFrame) {
-                        // 在编码前进行帧有效性检查
-                        if (!processedFrame->data[0]) {
-                            AV_LOGGER_ERROR("严重错误:即将编码的音频帧数据指针为空");
-                            updateStats(false);
-                            continue;
-                        }
-                        
-                        AV_LOGGER_DEBUGF("准备编码音频帧: samples={}, format={}, data_ptr={}", 
-                                        processedFrame->nb_samples, processedFrame->format,
-                                        static_cast<void*>(processedFrame->data[0]));
-                        
-                        // 保存linesize用于统计(因为move后无法访问)
-                        int frameLinesize = processedFrame->linesize[0];
-                        
-                        std::vector<AVPacketPtr> packets;
-                        // 使用move语义明确转移所有权,避免潜在的双重释放
-                        ErrorCode result = encoder_->encode(std::move(processedFrame), packets);
-                        
-                        if (result == ErrorCode::SUCCESS) {
-                            for (const auto& packet : packets) {
-                                if (packet && packet->size > 0) {
-                                    onAudioPacketEncoded(packet);
-                                }
-                            }
-                            updateStats(true, frameLinesize);
-                        } else {
-                            updateStats(false);
-                            AV_LOGGER_ERRORF("Audio encoding failed: {}", static_cast<int>(result));
-                        }
-                    }
-
-                    // 使用之前保存的值,而不是已经被移动的 frameData.frame
-                    processedSamples_ += nbSamples;
-                    
-                } catch (const std::exception& e) {
-                    AV_LOGGER_ERRORF("Error processing audio frame: {}", e.what());
-                    updateStats(false);
-                }
-            }
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Audio processing thread crashed with exception: {}", e.what());
-    } catch (...) {
-        AV_LOGGER_ERROR("Audio processing thread crashed with unknown exception");
-    }
-    
-    AV_LOGGER_INFO("Audio processing thread stopped");
-}
-
-AVFramePtr AudioRecorder::mixAudioFrames(const std::vector<AVFramePtr>& frames) {
-    if (frames.empty()) {
-        return nullptr;
-    }
-    
-    if (frames.size() == 1) {
-        // 创建第一个帧的副本
-        AVFramePtr result = av::makeAVFrame();
-        if (result && frames[0] && av_frame_ref(result.get(), frames[0].get()) == 0) {
-            return result;
-        }
-        return nullptr;
-    }
-    
-    // TODO: 实现音频混音
-    // 目前返回第一个帧的副本
-    AVFramePtr result = av::makeAVFrame();
-    if (result && frames[0] && av_frame_ref(result.get(), frames[0].get()) == 0) {
-        return result;
-    }
-    return nullptr;
-}
-
-void AudioRecorder::onAudioFrameCaptured(const AVFramePtr& frame, size_t capturerIndex) {
-    if (shouldStop_ || !frame) {
-        return;
-    }
-    
-    // 创建frame的副本,因为参数是const引用
-    AVFramePtr frameCopy = av::makeAVFrame();
-    if (!frameCopy || av_frame_ref(frameCopy.get(), frame.get()) != 0) {
-        AV_LOGGER_ERROR("Failed to copy audio frame");
-        return;
-    }
-    
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        AudioFrameData frameData;
-        frameData.frame = std::move(frameCopy);
-        frameData.capturerIndex = capturerIndex;
-        frameData.timestamp = std::chrono::steady_clock::now();
-        frameQueue_.push_back(std::move(frameData));
-    }
-    
-    queueCondition_.notify_one();
-}
-
-void AudioRecorder::onAudioPacketEncoded(const AVPacketPtr& packet) {
-    if (muxer_ && packet) {
-        ErrorCode result = muxer_->writePacket(packet.get());
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to write audio packet: {}", static_cast<int>(result));
-        }
-    }
-}
-
-ErrorCode AudioRecorder::initializeCapturers() {
-    // 创建主采集器
-    auto mainCapturer = std::make_unique<capture::AudioCapturer>();
-    
-    // 设置采集器参数,确保与录制器参数一致
-    capture::AudioCaptureParams capturerParams(audioParams_.capturerType);
-    capturerParams.deviceId = audioParams_.deviceId;
-    capturerParams.sampleRate = audioParams_.sampleRate;
-    capturerParams.channels = audioParams_.channels;
-    capturerParams.sampleFormat = audioParams_.sampleFormat;
-    
-    AV_LOGGER_INFOF("初始化音频采集器: {}Hz, {}ch, {}", 
-                   capturerParams.sampleRate, capturerParams.channels,
-                   av_get_sample_fmt_name(capturerParams.sampleFormat));
-    
-    ErrorCode result = mainCapturer->initialize(capturerParams);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("Failed to initialize main audio capturer: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    // 获取采集器实际使用的参数,更新录制器参数
-    auto actualParams = mainCapturer->getCurrentParams();
-    audioParams_.sampleRate = actualParams.sampleRate;
-    audioParams_.channels = actualParams.channels;
-    audioParams_.sampleFormat = actualParams.sampleFormat;
-    
-    AV_LOGGER_INFOF("采集器实际参数: {}Hz, {}ch, {}", 
-                   audioParams_.sampleRate, audioParams_.channels,
-                   av_get_sample_fmt_name(audioParams_.sampleFormat));
-    
-    // 设置回调
-    mainCapturer->setFrameCallback([this](const AVFramePtr& frame) {
-        onAudioFrameCaptured(frame, 0);
-    });
-    
-    capturers_.push_back(std::move(mainCapturer));
-    
-    // 添加混音设备
-    for (const auto& deviceId : audioParams_.mixDevices) {
-        addAudioDevice(deviceId, audioParams_.capturerType);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::initializeEncoder() {
-    encoder_ = std::make_unique<codec::AudioEncoder>();
-    
-    // 使用正确的AudioEncoderParams而不是基础的CodecParams
-    codec::AudioEncoderParams encoderParams;
-    encoderParams.type = MediaType::AUDIO;
-    encoderParams.codecName = audioParams_.codecName;
-    encoderParams.bitRate = audioParams_.bitrate;
-    encoderParams.sampleRate = audioParams_.sampleRate;
-    encoderParams.channels = audioParams_.channels;
-    encoderParams.sampleFormat = audioParams_.sampleFormat;
-    
-    // 根据声道数设置声道布局
-    if (audioParams_.channels == 1) {
-        encoderParams.channelLayout = AV_CHANNEL_LAYOUT_MONO;
-    } else if (audioParams_.channels == 2) {
-        encoderParams.channelLayout = AV_CHANNEL_LAYOUT_STEREO;
-    } else {
-        av_channel_layout_default(&encoderParams.channelLayout, audioParams_.channels);
-    }
-    
-    AV_LOGGER_INFOF("初始化音频编码器: {}Hz, {}ch, {}, {}bps", 
-                   encoderParams.sampleRate, encoderParams.channels, 
-                   encoderParams.codecName, encoderParams.bitRate);
-    
-    ErrorCode result = encoder_->open(encoderParams);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("Failed to initialize audio encoder: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AudioRecorder::initializeMuxer() {
-    muxer_ = std::make_unique<muxer::FileMuxer>();
-    
-    // 创建音频流信息
-    muxer::StreamInfo audioStreamInfo;
-    audioStreamInfo.index = 0;
-    audioStreamInfo.type = muxer::StreamType::AUDIO;
-    audioStreamInfo.codecId = AV_CODEC_ID_AAC;  // 默认使用AAC
-    audioStreamInfo.codecName = audioParams_.codecName.empty() ? "aac" : audioParams_.codecName;
-    audioStreamInfo.sampleRate = audioParams_.sampleRate;
-    audioStreamInfo.channels = audioParams_.channels;
-    audioStreamInfo.sampleFormat = audioParams_.sampleFormat;
-    audioStreamInfo.bitrate = audioParams_.bitrate;
-    audioStreamInfo.timeBase = {1, static_cast<int>(audioParams_.sampleRate)};
-
-    // 设置声道布局
-    AVChannelLayout tempLayout;
-    if (audioParams_.channels == 1) {
-        tempLayout = AV_CHANNEL_LAYOUT_MONO;
-        av_channel_layout_copy(&audioStreamInfo.channelLayout, &tempLayout);
-    } else if (audioParams_.channels == 2) {
-        tempLayout = AV_CHANNEL_LAYOUT_STEREO;
-        av_channel_layout_copy(&audioStreamInfo.channelLayout, &tempLayout);
-    } else {
-        av_channel_layout_default(&audioStreamInfo.channelLayout, audioParams_.channels);
-    }
-    
-    // 创建复用器参数并添加流信息
-    muxer::FileMuxerParams muxerParams;
-    muxerParams.type = muxer::MuxerType::FILE_MUXER;
-    muxerParams.outputPath = audioParams_.outputPath;
-    muxerParams.outputFile = audioParams_.outputPath;  // FileMuxerParams 需要设置 outputFile
-    muxerParams.format = audioParams_.format;
-    muxerParams.overwrite = true;  // 允许覆盖已存在文件
-    muxerParams.streams.push_back(audioStreamInfo);  // 添加音频流
-    
-    AV_LOGGER_INFOF("添加音频流到复用器: {}Hz, {}ch, {}, {}bps", 
-                   audioStreamInfo.sampleRate, audioStreamInfo.channels, 
-                   audioStreamInfo.codecName, audioStreamInfo.bitrate);
-    
-    ErrorCode result = muxer_->initialize(muxerParams);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("Failed to initialize muxer: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-void AudioRecorder::cleanup() {
-    shouldStop_ = true;
-    
-    // 停止处理线程
-    if (processingThread_ && processingThread_->joinable()) {
-        queueCondition_.notify_all();
-        processingThread_->join();
-        processingThread_.reset();
-    }
-    
-    // 清理采集器
-    for (auto& capturer : capturers_) {
-        if (capturer) {
-            capturer->stop();
-            capturer->close();
-        }
-    }
-    capturers_.clear();
-    
-    // 清理编码器
-    if (encoder_) {
-        encoder_->close();
-        encoder_.reset();
-    }
-    
-    // 清理复用器
-    if (muxer_) {
-        muxer_->close();
-        muxer_.reset();
-    }
-    
-    // 清理线程池
-    if (threadPool_) {
-        threadPool_.reset();
-    }
-    
-    // 清理队列
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        frameQueue_.clear();
-    }
-}
-
-} // namespace recorder
-} // namespace av

+ 0 - 203
AV/code/recorder/recorder_audio_recorder.h

@@ -1,203 +0,0 @@
-#ifndef AV_RECORDER_AUDIO_RECORDER_H
-#define AV_RECORDER_AUDIO_RECORDER_H
-
-#include "recorder_abstract_recorder.h"
-#include "../capture/capture_audio_capturer.h"
-#include "../codec/codec_audio_encoder.h"
-#include "../muxer/muxer_abstract_muxer.h"
-#include "../utils/utils_thread_pool.h"
-#include <vector>
-#include <memory>
-#include <thread>
-#include <atomic>
-#include <deque>
-#include <condition_variable>
-
-namespace av {
-namespace recorder {
-
-/**
- * 音频录制器参数
- */
-struct AudioRecorderParams : public RecorderParams {
-    // 音频采集参数
-    capture::CapturerType capturerType = capture::CapturerType::AUDIO_MIC;
-    std::string deviceId;               // 音频设备ID
-    uint32_t sampleRate = 44100;        // 采样率
-    uint32_t channels = 2;              // 声道数
-    uint32_t bitsPerSample = 16;        // 位深度
-    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_S16;
-    
-    // 编码参数
-    std::string codecName = "aac";      // 编码器名称
-    uint32_t bitrate = 128000;          // 比特率
-    
-    // 混音参数
-    bool enableMixing = false;          // 是否启用混音
-    std::vector<std::string> mixDevices; // 混音设备列表
-    float volumeScale = 1.0f;           // 音量缩放
-    
-    AudioRecorderParams() {
-        mediaType = MediaType::AUDIO;
-        format = "mp4";
-    }
-};
-
-/**
- * 音频录制器
- * 支持多设备采集、混音、编码和输出
- */
-class AudioRecorder : public AbstractRecorder {
-public:
-    AudioRecorder();
-    virtual ~AudioRecorder();
-
-    // 实现基类接口
-    ErrorCode initialize(const RecorderParams& params) override;
-    ErrorCode startRecording() override;
-    ErrorCode stopRecording() override;
-    ErrorCode pauseRecording() override;
-    ErrorCode resumeRecording() override;
-    void close() override;
-
-    // 音频特定功能
-    /**
-     * 设置音量缩放
-     */
-    void setVolumeScale(float scale);
-    
-    /**
-     * 获取音频电平
-     */
-    float getAudioLevel() const;
-    
-    /**
-     * 添加音频设备
-     */
-    ErrorCode addAudioDevice(const std::string& deviceId, capture::CapturerType type);
-    
-    /**
-     * 移除音频设备
-     */
-    ErrorCode removeAudioDevice(const std::string& deviceId);
-    
-    /**
-     * 获取可用音频设备列表
-     */
-    std::vector<std::string> getAvailableDevices(capture::CapturerType type) const;
-
-protected:
-    bool validateParams(const RecorderParams& params) override;
-
-private:
-    /**
-     * 音频处理线程
-     */
-    void audioProcessingThread();
-    
-    /**
-     * 混音处理
-     */
-    AVFramePtr mixAudioFrames(const std::vector<AVFramePtr>& frames);
-    
-    /**
-     * 音频帧回调
-     */
-    void onAudioFrameCaptured(const AVFramePtr& frame, size_t capturerIndex);
-    
-    /**
-     * 编码完成回调
-     */
-    void onAudioPacketEncoded(const AVPacketPtr& packet);
-    
-    /**
-     * 初始化采集器
-     */
-    ErrorCode initializeCapturers();
-    
-    /**
-     * 初始化编码器
-     */
-    ErrorCode initializeEncoder();
-    
-    /**
-     * 初始化复用器
-     */
-    ErrorCode initializeMuxer();
-    
-    /**
-     * 清理资源
-     */
-    void cleanup();
-
-private:
-    AudioRecorderParams audioParams_;
-    
-    // 采集器
-    std::vector<std::unique_ptr<capture::AudioCapturer>> capturers_;
-    
-    // 编码器
-    std::unique_ptr<codec::AudioEncoder> encoder_;
-    
-    // 复用器
-    std::unique_ptr<muxer::AbstractMuxer> muxer_;
-    
-    // 线程池
-    std::unique_ptr<utils::ThreadPool> threadPool_;
-    
-    // 音频处理线程
-    std::unique_ptr<std::thread> processingThread_;
-    std::atomic<bool> shouldStop_;
-    
-    // 音频帧队列
-    struct AudioFrameData {
-        AVFramePtr frame;
-        size_t capturerIndex;
-        std::chrono::steady_clock::time_point timestamp;
-        
-        // 默认构造函数
-        AudioFrameData() = default;
-        
-        // 移动构造函数
-        AudioFrameData(AudioFrameData&& other) noexcept
-            : frame(std::move(other.frame))
-            , capturerIndex(other.capturerIndex)
-            , timestamp(other.timestamp) {}
-        
-        // 移动赋值运算符
-        AudioFrameData& operator=(AudioFrameData&& other) noexcept {
-            if (this != &other) {
-                frame = std::move(other.frame);
-                capturerIndex = other.capturerIndex;
-                timestamp = other.timestamp;
-            }
-            return *this;
-        }
-        
-        // 禁用拷贝构造函数和拷贝赋值运算符
-        AudioFrameData(const AudioFrameData&) = delete;
-        AudioFrameData& operator=(const AudioFrameData&) = delete;
-    };
-    
-    std::deque<AudioFrameData> frameQueue_;
-    std::mutex queueMutex_;
-    std::condition_variable queueCondition_;
-    
-    // 混音相关
-    float volumeScale_;
-    mutable std::mutex audioLevelMutex_;
-    float currentAudioLevel_;
-    
-    // 同步相关
-    std::mutex capturerMutex_;
-    std::atomic<bool> isPaused_;
-    
-    // 统计信息
-    std::atomic<uint64_t> processedSamples_;
-    std::chrono::steady_clock::time_point lastProcessTime_;
-};
-
-} // namespace recorder
-} // namespace av
-
-#endif // AV_RECORDER_AUDIO_RECORDER_H

+ 0 - 710
AV/code/recorder/recorder_av_recorder.cpp

@@ -1,710 +0,0 @@
-#include "recorder_av_recorder.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <chrono>
-
-namespace av {
-namespace recorder {
-
-AVRecorder::AVRecorder()
-    : AbstractRecorder(MediaType::UNKNOWN)
-    , shouldStopSync_(false)
-    , audioTimestamp_(0)
-    , videoTimestamp_(0)
-    , audioEnabled_(true)
-    , videoEnabled_(true)
-    , syncEnabled_(true)
-    , syncThreshold_(40)
-    , dropFrameOnSync_(true)
-    , audioPacketCount_(0)
-    , videoPacketCount_(0) {
-    
-    recordingStartTime_ = std::chrono::steady_clock::now();
-}
-
-AVRecorder::~AVRecorder() {
-    close();
-}
-
-ErrorCode AVRecorder::initialize(const RecorderParams& params) {
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    avParams_ = static_cast<const AVRecorderParams&>(params);
-    params_ = params;
-    
-    audioEnabled_ = avParams_.enableAudio;
-    videoEnabled_ = avParams_.enableVideo;
-    syncEnabled_ = avParams_.enableSync;
-    syncThreshold_ = avParams_.syncThresholdMs;
-    dropFrameOnSync_ = avParams_.dropFrameOnSync;
-    
-    // 初始化子录制器
-    ErrorCode result = initializeSubRecorders();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    // 初始化同步器
-    if (syncEnabled_ && audioEnabled_ && videoEnabled_) {
-        result = initializeSynchronizer();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_WARNING("Failed to initialize synchronizer, continuing without sync");
-            syncEnabled_ = false;
-        }
-    }
-    
-    setState(RecorderState::INITIALIZED);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AVRecorder::startRecording() {
-    if (getState() != RecorderState::INITIALIZED && getState() != RecorderState::STOPPED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStopSync_ = false;
-    recordingStartTime_ = std::chrono::steady_clock::now();
-    
-    // 重置统计信息
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        combinedStats_ = CombinedStats{};
-    }
-    
-    {
-        std::lock_guard<std::mutex> lock(syncMutex_);
-        syncStatus_ = SyncStatus{};
-    }
-    
-    audioTimestamp_ = 0;
-    videoTimestamp_ = 0;
-    audioPacketCount_ = 0;
-    videoPacketCount_ = 0;
-    
-    // 启动音频录制器
-    if (audioEnabled_ && audioRecorder_) {
-        ErrorCode result = audioRecorder_->startRecording();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to start audio recording: {}", static_cast<int>(result));
-            return result;
-        }
-    }
-    
-    // 启动视频录制器
-    if (videoEnabled_ && videoRecorder_) {
-        ErrorCode result = videoRecorder_->startRecording();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to start video recording: {}", static_cast<int>(result));
-            // 如果视频启动失败,停止音频
-            if (audioEnabled_ && audioRecorder_) {
-                audioRecorder_->stopRecording();
-            }
-            return result;
-        }
-    }
-    
-    // 启动同步线程
-    if (syncEnabled_ && audioEnabled_ && videoEnabled_) {
-        syncThread_ = std::make_unique<std::thread>(&AVRecorder::synchronizationThread, this);
-    }
-    
-    setState(RecorderState::RECORDING);
-    resetStats();
-    
-    AV_LOGGER_INFOF("AV recording started - Audio: {}, Video: {}, Sync: {}", 
-             audioEnabled_.load(), videoEnabled_.load(), syncEnabled_.load());
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AVRecorder::stopRecording() {
-    if (getState() != RecorderState::RECORDING && getState() != RecorderState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStopSync_ = true;
-    
-    // 等待同步线程结束
-    if (syncThread_ && syncThread_->joinable()) {
-        syncThread_->join();
-        syncThread_.reset();
-    }
-    
-    // 停止子录制器
-    ErrorCode audioResult = ErrorCode::SUCCESS;
-    ErrorCode videoResult = ErrorCode::SUCCESS;
-    
-    if (audioEnabled_ && audioRecorder_) {
-        audioResult = audioRecorder_->stopRecording();
-    }
-    
-    if (videoEnabled_ && videoRecorder_) {
-        videoResult = videoRecorder_->stopRecording();
-    }
-    
-    setState(RecorderState::STOPPED);
-    
-    // 更新最终统计信息
-    updateCombinedStats();
-    
-    AV_LOGGER_INFO("AV recording stopped");
-    
-    // 返回第一个错误(如果有)
-    if (audioResult != ErrorCode::SUCCESS) {
-        return audioResult;
-    }
-    return videoResult;
-}
-
-ErrorCode AVRecorder::pauseRecording() {
-    if (getState() != RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode audioResult = ErrorCode::SUCCESS;
-    ErrorCode videoResult = ErrorCode::SUCCESS;
-    
-    if (audioEnabled_ && audioRecorder_) {
-        audioResult = audioRecorder_->pauseRecording();
-    }
-    
-    if (videoEnabled_ && videoRecorder_) {
-        videoResult = videoRecorder_->pauseRecording();
-    }
-    
-    setState(RecorderState::PAUSED);
-    
-    AV_LOGGER_INFO("AV recording paused");
-    
-    if (audioResult != ErrorCode::SUCCESS) {
-        return audioResult;
-    }
-    return videoResult;
-}
-
-ErrorCode AVRecorder::resumeRecording() {
-    if (getState() != RecorderState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode audioResult = ErrorCode::SUCCESS;
-    ErrorCode videoResult = ErrorCode::SUCCESS;
-    
-    if (audioEnabled_ && audioRecorder_) {
-        audioResult = audioRecorder_->resumeRecording();
-    }
-    
-    if (videoEnabled_ && videoRecorder_) {
-        videoResult = videoRecorder_->resumeRecording();
-    }
-    
-    setState(RecorderState::RECORDING);
-    
-    AV_LOGGER_INFO("AV recording resumed");
-    
-    if (audioResult != ErrorCode::SUCCESS) {
-        return audioResult;
-    }
-    return videoResult;
-}
-
-void AVRecorder::close() {
-    if (getState() == RecorderState::RECORDING || getState() == RecorderState::PAUSED) {
-        stopRecording();
-    }
-    
-    cleanup();
-    setState(RecorderState::IDLE);
-}
-
-ErrorCode AVRecorder::setAudioEnabled(bool enabled) {
-    if (getState() == RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    audioEnabled_ = enabled;
-    avParams_.enableAudio = enabled;
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AVRecorder::setVideoEnabled(bool enabled) {
-    if (getState() == RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    videoEnabled_ = enabled;
-    avParams_.enableVideo = enabled;
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVRecorder::SyncStatus AVRecorder::getSyncStatus() const {
-    std::lock_guard<std::mutex> lock(syncMutex_);
-    return syncStatus_;
-}
-
-void AVRecorder::setSyncThreshold(int64_t thresholdMs) {
-    syncThreshold_ = thresholdMs;
-    avParams_.syncThresholdMs = thresholdMs;
-}
-
-void AVRecorder::setDropFrameOnSync(bool drop) {
-    dropFrameOnSync_ = drop;
-    avParams_.dropFrameOnSync = drop;
-}
-
-AVRecorder::CombinedStats AVRecorder::getCombinedStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    CombinedStats stats = combinedStats_;
-    
-    // 更新实时数据
-    if (audioRecorder_) {
-        stats.audioStats = audioRecorder_->getStats();
-    }
-    
-    if (videoRecorder_) {
-        stats.videoStats = videoRecorder_->getStats();
-    }
-    
-    stats.syncStatus = getSyncStatus();
-    
-    // 计算总录制时间
-    auto now = std::chrono::steady_clock::now();
-    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - recordingStartTime_);
-    stats.totalRecordingTime = duration.count() / 1000.0;
-    
-    // 计算总文件大小
-    stats.totalFileSize = stats.audioStats.totalBytes + stats.videoStats.totalBytes;
-    
-    return stats;
-}
-
-AVFramePtr AVRecorder::getCurrentVideoFrame() const {
-    if (videoRecorder_) {
-        return videoRecorder_->getCurrentFrame();
-    }
-    return nullptr;
-}
-
-float AVRecorder::getCurrentAudioLevel() const {
-    if (audioRecorder_) {
-        return audioRecorder_->getAudioLevel();
-    }
-    return 0.0f;
-}
-
-// 独立音频采集控制
-ErrorCode AVRecorder::startAudioCapture() {
-    if (!audioRecorder_) {
-        AV_LOGGER_ERROR("Audio recorder not initialized");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (audioRecorder_->getState() == RecorderState::RECORDING) {
-        AV_LOGGER_WARNING("Audio capture already started");
-        return ErrorCode::SUCCESS;
-    }
-    
-    ErrorCode result = audioRecorder_->startRecording();
-    if (result == ErrorCode::SUCCESS) {
-        audioEnabled_ = true;
-        AV_LOGGER_INFO("Audio capture started independently");
-    }
-    
-    return result;
-}
-
-ErrorCode AVRecorder::stopAudioCapture() {
-    if (!audioRecorder_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    if (audioRecorder_->getState() != RecorderState::RECORDING && 
-        audioRecorder_->getState() != RecorderState::PAUSED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    ErrorCode result = audioRecorder_->stopRecording();
-    if (result == ErrorCode::SUCCESS) {
-        AV_LOGGER_INFO("Audio capture stopped independently");
-    }
-    
-    return result;
-}
-
-ErrorCode AVRecorder::pauseAudioCapture() {
-    if (!audioRecorder_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = audioRecorder_->pauseRecording();
-    if (result == ErrorCode::SUCCESS) {
-        AV_LOGGER_INFO("Audio capture paused independently");
-    }
-    
-    return result;
-}
-
-ErrorCode AVRecorder::resumeAudioCapture() {
-    if (!audioRecorder_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = audioRecorder_->resumeRecording();
-    if (result == ErrorCode::SUCCESS) {
-        AV_LOGGER_INFO("Audio capture resumed independently");
-    }
-    
-    return result;
-}
-
-// 独立视频采集控制
-ErrorCode AVRecorder::startVideoCapture() {
-    if (!videoRecorder_) {
-        AV_LOGGER_ERROR("Video recorder not initialized");
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (videoRecorder_->getState() == RecorderState::RECORDING) {
-        AV_LOGGER_WARNING("Video capture already started");
-        return ErrorCode::SUCCESS;
-    }
-    
-    ErrorCode result = videoRecorder_->startRecording();
-    if (result == ErrorCode::SUCCESS) {
-        videoEnabled_ = true;
-        AV_LOGGER_INFO("Video capture started independently");
-    }
-    
-    return result;
-}
-
-ErrorCode AVRecorder::stopVideoCapture() {
-    if (!videoRecorder_) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    if (videoRecorder_->getState() != RecorderState::RECORDING && 
-        videoRecorder_->getState() != RecorderState::PAUSED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    ErrorCode result = videoRecorder_->stopRecording();
-    if (result == ErrorCode::SUCCESS) {
-        AV_LOGGER_INFO("Video capture stopped independently");
-    }
-    
-    return result;
-}
-
-ErrorCode AVRecorder::pauseVideoCapture() {
-    if (!videoRecorder_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = videoRecorder_->pauseRecording();
-    if (result == ErrorCode::SUCCESS) {
-        AV_LOGGER_INFO("Video capture paused independently");
-    }
-    
-    return result;
-}
-
-ErrorCode AVRecorder::resumeVideoCapture() {
-    if (!videoRecorder_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    ErrorCode result = videoRecorder_->resumeRecording();
-    if (result == ErrorCode::SUCCESS) {
-        AV_LOGGER_INFO("Video capture resumed independently");
-    }
-    
-    return result;
-}
-
-// 实时切换功能
-ErrorCode AVRecorder::toggleAudioRecording(bool enable) {
-    if (!audioRecorder_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (enable) {
-        if (!isAudioRecording()) {
-            return startAudioCapture();
-        }
-    } else {
-        if (isAudioRecording()) {
-            return pauseAudioCapture(); // 使用暂停而不是停止,保持状态
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AVRecorder::toggleVideoRecording(bool enable) {
-    if (!videoRecorder_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    if (enable) {
-        if (!isVideoRecording()) {
-            return startVideoCapture();
-        }
-    } else {
-        if (isVideoRecording()) {
-            return pauseVideoCapture(); // 使用暂停而不是停止,保持状态
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 状态查询
-bool AVRecorder::isAudioRecording() const {
-    return audioRecorder_ && 
-           audioRecorder_->getState() == RecorderState::RECORDING;
-}
-
-bool AVRecorder::isVideoRecording() const {
-    return videoRecorder_ && 
-           videoRecorder_->getState() == RecorderState::RECORDING;
-}
-
-bool AVRecorder::isAudioCapturing() const {
-    return audioRecorder_ && 
-           (audioRecorder_->getState() == RecorderState::RECORDING || 
-            audioRecorder_->getState() == RecorderState::PAUSED);
-}
-
-bool AVRecorder::isVideoCapturing() const {
-    return videoRecorder_ && 
-           (videoRecorder_->getState() == RecorderState::RECORDING || 
-            videoRecorder_->getState() == RecorderState::PAUSED);
-}
-
-bool AVRecorder::validateParams(const RecorderParams& params) {
-    const auto& avParams = static_cast<const AVRecorderParams&>(params);
-    
-    if (!avParams.enableAudio && !avParams.enableVideo) {
-        AV_LOGGER_ERROR("Both audio and video are disabled");
-        return false;
-    }
-    
-    if (avParams.outputPath.empty()) {
-        AV_LOGGER_ERROR("Output path is empty");
-        return false;
-    }
-    
-    // 验证音频参数
-    if (avParams.enableAudio) {
-        if (avParams.audioParams.sampleRate == 0 || avParams.audioParams.channels == 0) {
-            AV_LOGGER_ERROR("Invalid audio parameters");
-            return false;
-        }
-    }
-    
-    // 验证视频参数
-    if (avParams.enableVideo) {
-        if (avParams.videoParams.width == 0 || avParams.videoParams.height == 0) {
-            AV_LOGGER_ERROR("Invalid video parameters");
-            return false;
-        }
-    }
-    
-    return true;
-}
-
-void AVRecorder::synchronizationThread() {
-    AV_LOGGER_INFO("Synchronization thread started");
-    
-    const auto syncInterval = std::chrono::milliseconds(100); // 100ms检查间隔
-    
-    try {
-        while (!shouldStopSync_) {
-            std::this_thread::sleep_for(syncInterval);
-            
-            if (getState() != RecorderState::RECORDING) {
-                continue;
-            }
-            
-            try {
-                checkSyncStatus();
-                updateCombinedStats();
-            } catch (const std::exception& e) {
-                AV_LOGGER_ERRORF("Error in sync check: {}", e.what());
-                // 同步错误不应该终止整个录制过程,继续运行
-            }
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Synchronization thread crashed with exception: {}", e.what());
-    } catch (...) {
-        AV_LOGGER_ERROR("Synchronization thread crashed with unknown exception");
-    }
-    
-    AV_LOGGER_INFO("Synchronization thread stopped");
-}
-
-void AVRecorder::onAudioPacket(const AVPacketPtr& packet) {
-    if (packet) {
-        audioTimestamp_ = packet->pts;
-        audioPacketCount_++;
-    }
-}
-
-void AVRecorder::onVideoPacket(const AVPacketPtr& packet) {
-    if (packet) {
-        videoTimestamp_ = packet->pts;
-        videoPacketCount_++;
-    }
-}
-
-void AVRecorder::checkSyncStatus() {
-    if (!syncEnabled_ || !audioEnabled_ || !videoEnabled_) {
-        return;
-    }
-    
-    int64_t audioTs = audioTimestamp_.load();
-    int64_t videoTs = videoTimestamp_.load();
-    int64_t timeDiff = audioTs - videoTs;
-    
-    {
-        std::lock_guard<std::mutex> lock(syncMutex_);
-        syncStatus_.audioTimestamp = audioTs;
-        syncStatus_.videoTimestamp = videoTs;
-        syncStatus_.timeDiff = timeDiff;
-        syncStatus_.isInSync = std::abs(timeDiff) <= syncThreshold_;
-    }
-    
-    // 如果不同步,尝试调整
-    if (!syncStatus_.isInSync && dropFrameOnSync_) {
-        adjustSync(timeDiff);
-    }
-}
-
-void AVRecorder::adjustSync(int64_t timeDiff) {
-    // 简单的同步策略:丢弃超前的帧
-    if (timeDiff > syncThreshold_) {
-        // 音频超前,通知音频录制器丢帧
-        std::lock_guard<std::mutex> lock(syncMutex_);
-        syncStatus_.droppedAudioFrames++;
-    } else if (timeDiff < -syncThreshold_) {
-        // 视频超前,通知视频录制器丢帧
-        std::lock_guard<std::mutex> lock(syncMutex_);
-        syncStatus_.droppedVideoFrames++;
-    }
-}
-
-ErrorCode AVRecorder::initializeSubRecorders() {
-    // 初始化音频录制器
-    if (avParams_.enableAudio) {
-        audioRecorder_ = std::make_unique<AudioRecorder>();
-        
-        // 设置输出路径(音频部分)
-        auto audioParams = avParams_.audioParams;
-        audioParams.outputPath = avParams_.outputPath;
-        
-        ErrorCode result = audioRecorder_->initialize(audioParams);
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to initialize audio recorder: {}", static_cast<int>(result));
-            return result;
-        }
-    }
-    
-    // 初始化视频录制器
-    if (avParams_.enableVideo) {
-        videoRecorder_ = std::make_unique<VideoRecorder>();
-        
-        // 设置输出路径(视频部分)
-        auto videoParams = avParams_.videoParams;
-        videoParams.outputPath = avParams_.outputPath;
-        
-        ErrorCode result = videoRecorder_->initialize(videoParams);
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to initialize video recorder: {}", static_cast<int>(result));
-            return result;
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode AVRecorder::initializeSynchronizer() {
-    synchronizer_ = std::make_unique<utils::SynchronizerV2>();
-    
-    // TODO: 配置同步器参数
-    
-    return ErrorCode::SUCCESS;
-}
-
-void AVRecorder::cleanup() {
-    shouldStopSync_ = true;
-    
-    // 停止同步线程
-    if (syncThread_ && syncThread_->joinable()) {
-        syncThread_->join();
-        syncThread_.reset();
-    }
-    
-    // 清理子录制器
-    if (audioRecorder_) {
-        audioRecorder_->close();
-        audioRecorder_.reset();
-    }
-    
-    if (videoRecorder_) {
-        videoRecorder_->close();
-        videoRecorder_.reset();
-    }
-    
-    // 清理同步器
-    if (synchronizer_) {
-        synchronizer_.reset();
-    }
-}
-
-void AVRecorder::updateCombinedStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (audioRecorder_) {
-        combinedStats_.audioStats = audioRecorder_->getStats();
-    }
-    
-    if (videoRecorder_) {
-        combinedStats_.videoStats = videoRecorder_->getStats();
-    }
-    
-    combinedStats_.syncStatus = getSyncStatus();
-}
-
-// RecorderFactoryImpl 实现
-std::unique_ptr<AudioRecorder> RecorderFactoryImpl::createAudioRecorder() {
-    return std::make_unique<AudioRecorder>();
-}
-
-std::unique_ptr<VideoRecorder> RecorderFactoryImpl::createVideoRecorder() {
-    return std::make_unique<VideoRecorder>();
-}
-
-std::unique_ptr<AVRecorder> RecorderFactoryImpl::createAVRecorder() {
-    return std::make_unique<AVRecorder>();
-}
-
-std::unique_ptr<AbstractRecorder> RecorderFactoryImpl::createRecorder(MediaType mediaType) {
-    switch (mediaType) {
-        case MediaType::AUDIO:
-            return createAudioRecorder();
-        case MediaType::VIDEO:
-            return createVideoRecorder();
-        case MediaType::UNKNOWN: // 用于表示音视频混合
-            return createAVRecorder();
-        default:
-            return nullptr;
-    }
-}
-
-} // namespace recorder
-} // namespace av

+ 0 - 268
AV/code/recorder/recorder_av_recorder.h

@@ -1,268 +0,0 @@
-#ifndef AV_RECORDER_AV_RECORDER_H
-#define AV_RECORDER_AV_RECORDER_H
-
-#include "recorder_abstract_recorder.h"
-#include "recorder_audio_recorder.h"
-#include "recorder_video_recorder.h"
-#include "../utils/utils_synchronizer_v2.h"
-#include <memory>
-#include <atomic>
-#include <mutex>
-
-namespace av {
-namespace recorder {
-
-/**
- * 音视频录制器参数
- */
-struct AVRecorderParams : public RecorderParams {
-    // 音频参数
-    AudioRecorderParams audioParams;
-    bool enableAudio = true;
-    
-    // 视频参数
-    VideoRecorderParams videoParams;
-    bool enableVideo = true;
-    
-    // 同步参数
-    bool enableSync = true;             // 是否启用音视频同步
-    int64_t syncThresholdMs = 40;       // 同步阈值(毫秒)
-    bool dropFrameOnSync = true;        // 同步时是否丢帧
-    
-    AVRecorderParams() {
-        mediaType = MediaType::UNKNOWN; // 表示混合媒体类型
-        format = "mp4";
-    }
-};
-
-/**
- * 音视频录制器
- * 整合音频和视频录制功能,提供同步录制能力
- */
-class AVRecorder : public AbstractRecorder {
-public:
-    AVRecorder();
-    virtual ~AVRecorder();
-
-    // 实现基类接口
-    ErrorCode initialize(const RecorderParams& params) override;
-    ErrorCode startRecording() override;
-    ErrorCode stopRecording() override;
-    ErrorCode pauseRecording() override;
-    ErrorCode resumeRecording() override;
-    void close() override;
-
-    // 音视频特定功能
-    /**
-     * 获取音频录制器
-     */
-    AudioRecorder* getAudioRecorder() const { return audioRecorder_.get(); }
-    
-    /**
-     * 获取视频录制器
-     */
-    VideoRecorder* getVideoRecorder() const { return videoRecorder_.get(); }
-    
-    /**
-     * 设置音频启用状态
-     */
-    ErrorCode setAudioEnabled(bool enabled);
-    
-    /**
-     * 设置视频启用状态
-     */
-    ErrorCode setVideoEnabled(bool enabled);
-    
-    /**
-     * 独立控制音频采集
-     */
-    ErrorCode startAudioCapture();
-    ErrorCode stopAudioCapture();
-    ErrorCode pauseAudioCapture();
-    ErrorCode resumeAudioCapture();
-    
-    /**
-     * 独立控制视频采集
-     */
-    ErrorCode startVideoCapture();
-    ErrorCode stopVideoCapture();
-    ErrorCode pauseVideoCapture();
-    ErrorCode resumeVideoCapture();
-    
-    /**
-     * 实时切换音频/视频流
-     */
-    ErrorCode toggleAudioRecording(bool enable);
-    ErrorCode toggleVideoRecording(bool enable);
-    
-    /**
-     * 获取音频/视频录制状态
-     */
-    bool isAudioRecording() const;
-    bool isVideoRecording() const;
-    bool isAudioCapturing() const;
-    bool isVideoCapturing() const;
-    
-    /**
-     * 获取同步状态
-     */
-    struct SyncStatus {
-        bool isInSync = true;           // 是否同步
-        int64_t audioTimestamp = 0;     // 音频时间戳
-        int64_t videoTimestamp = 0;     // 视频时间戳
-        int64_t timeDiff = 0;           // 时间差(ms)
-        uint64_t droppedAudioFrames = 0; // 丢弃的音频帧
-        uint64_t droppedVideoFrames = 0; // 丢弃的视频帧
-    };
-    
-    SyncStatus getSyncStatus() const;
-    
-    /**
-     * 设置同步参数
-     */
-    void setSyncThreshold(int64_t thresholdMs);
-    void setDropFrameOnSync(bool drop);
-    
-    /**
-     * 获取综合统计信息
-     */
-    struct CombinedStats {
-        RecorderStats audioStats;
-        RecorderStats videoStats;
-        SyncStatus syncStatus;
-        double totalRecordingTime = 0.0;
-        uint64_t totalFileSize = 0;
-    };
-    
-    CombinedStats getCombinedStats() const;
-    
-    /**
-     * 获取当前预览帧
-     */
-    AVFramePtr getCurrentVideoFrame() const;
-    
-    /**
-     * 获取当前音频电平
-     */
-    float getCurrentAudioLevel() const;
-
-protected:
-    bool validateParams(const RecorderParams& params) override;
-
-private:
-    /**
-     * 同步线程
-     */
-    void synchronizationThread();
-    
-    /**
-     * 音频包回调
-     */
-    void onAudioPacket(const AVPacketPtr& packet);
-    
-    /**
-     * 视频包回调
-     */
-    void onVideoPacket(const AVPacketPtr& packet);
-    
-    /**
-     * 检查同步状态
-     */
-    void checkSyncStatus();
-    
-    /**
-     * 调整同步
-     */
-    void adjustSync(int64_t timeDiff);
-    
-    /**
-     * 初始化子录制器
-     */
-    ErrorCode initializeSubRecorders();
-    
-    /**
-     * 初始化同步器
-     */
-    ErrorCode initializeSynchronizer();
-    
-    /**
-     * 清理资源
-     */
-    void cleanup();
-    
-    /**
-     * 更新综合统计信息
-     */
-    void updateCombinedStats();
-
-private:
-    AVRecorderParams avParams_;
-    
-    // 子录制器
-    std::unique_ptr<AudioRecorder> audioRecorder_;
-    std::unique_ptr<VideoRecorder> videoRecorder_;
-    
-    // 同步器
-    std::unique_ptr<utils::SynchronizerV2> synchronizer_;
-    
-    // 同步线程
-    std::unique_ptr<std::thread> syncThread_;
-    std::atomic<bool> shouldStopSync_;
-    
-    // 同步状态
-    mutable std::mutex syncMutex_;
-    SyncStatus syncStatus_;
-    
-    // 时间戳管理
-    std::atomic<int64_t> audioTimestamp_;
-    std::atomic<int64_t> videoTimestamp_;
-    std::chrono::steady_clock::time_point recordingStartTime_;
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    CombinedStats combinedStats_;
-    
-    // 控制标志
-    std::atomic<bool> audioEnabled_;
-    std::atomic<bool> videoEnabled_;
-    std::atomic<bool> syncEnabled_;
-    
-    // 同步参数
-    std::atomic<int64_t> syncThreshold_;
-    std::atomic<bool> dropFrameOnSync_;
-    
-    // 包计数器
-    std::atomic<uint64_t> audioPacketCount_;
-    std::atomic<uint64_t> videoPacketCount_;
-};
-
-/**
- * 录制器工厂类的扩展实现
- */
-class RecorderFactoryImpl {
-public:
-    /**
-     * 创建音频录制器
-     */
-    static std::unique_ptr<AudioRecorder> createAudioRecorder();
-    
-    /**
-     * 创建视频录制器
-     */
-    static std::unique_ptr<VideoRecorder> createVideoRecorder();
-    
-    /**
-     * 创建音视频录制器
-     */
-    static std::unique_ptr<AVRecorder> createAVRecorder();
-    
-    /**
-     * 创建录制器(根据媒体类型)
-     */
-    static std::unique_ptr<AbstractRecorder> createRecorder(MediaType mediaType);
-};
-
-} // namespace recorder
-} // namespace av
-
-#endif // AV_RECORDER_AV_RECORDER_H

+ 0 - 817
AV/code/recorder/recorder_video_recorder.cpp

@@ -1,817 +0,0 @@
-#include "recorder_video_recorder.h"
-#include "../base/logger.h"
-#include "../capture/capture_video_capturer.h"
-#include "../codec/codec_video_encoder.h"
-#include "../muxer/muxer_file_muxer.h"
-#include <algorithm>
-#include <chrono>
-
-extern "C" {
-#include <libavcodec/avcodec.h>
-}
-
-namespace av {
-namespace recorder {
-
-VideoRecorder::VideoRecorder()
-    : AbstractRecorder(MediaType::VIDEO)
-    , shouldStop_(false)
-    , isPaused_(false)
-    , avgCaptureTime_(0.0)
-    , avgEncodeTime_(0.0)
-    , consecutiveDrops_(0) {
-    
-    threadPool_ = std::make_unique<utils::ThreadPool>(); // 3个工作线程
-    
-    // 配置帧队列参数
-    utils::FrameQueueConfig frameQueueConfig;
-    frameQueueConfig.maxSize = 30;
-    frameQueue_ = std::make_unique<utils::FrameQueue>(frameQueueConfig); // 30帧缓冲
-    
-    lastFrameTime_ = std::chrono::steady_clock::now();
-    lastCaptureTime_ = std::chrono::steady_clock::now();
-    lastEncodeTime_ = std::chrono::steady_clock::now();
-}
-
-VideoRecorder::~VideoRecorder() {
-    close();
-}
-
-ErrorCode VideoRecorder::initialize(const RecorderParams& params) {
-    if (!validateParams(params)) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    videoParams_ = static_cast<const VideoRecorderParams&>(params);
-    params_ = params;
-    
-    // 计算帧间隔
-    frameInterval_ = std::chrono::microseconds(1000000 / videoParams_.frameRate);
-    
-    // 初始化各个组件
-    ErrorCode result = initializeCapturer();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    result = initializeEncoder();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    result = initializeMuxer();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    setState(RecorderState::INITIALIZED);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::startRecording() {
-    if (getState() != RecorderState::INITIALIZED && getState() != RecorderState::STOPPED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStop_ = false;
-    isPaused_ = false;
-    consecutiveDrops_ = 0;
-    
-    // 重置统计信息
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        captureStats_ = CaptureStats{};
-    }
-    
-    // 启动采集器
-    if (capturer_) {
-        ErrorCode result = capturer_->start();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to start video capturer: {}", static_cast<int>(result));
-            return result;
-        }
-    }
-    
-    // 启动复用器
-    if (muxer_) {
-        ErrorCode result = muxer_->start();
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to start muxer: {}", static_cast<int>(result));
-            return result;
-        }
-        AV_LOGGER_INFO("Muxer started successfully");
-    }
-    
-    // 启动处理线程
-    processingThread_ = std::make_unique<std::thread>(&VideoRecorder::videoProcessingThread, this);
-    frameRateThread_ = std::make_unique<std::thread>(&VideoRecorder::frameRateControlThread, this);
-    
-    setState(RecorderState::RECORDING);
-    resetStats();
-    
-    AV_LOGGER_INFOF("Video recording started: {}x{} @ {}fps", 
-             videoParams_.width, videoParams_.height, videoParams_.frameRate);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::stopRecording() {
-    if (getState() != RecorderState::RECORDING && getState() != RecorderState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    shouldStop_ = true;
-    isPaused_ = false;
-    
-    // 通知所有等待的线程
-    frameCondition_.notify_all();
-    
-    // 等待处理线程结束
-    if (processingThread_ && processingThread_->joinable()) {
-        processingThread_->join();
-        processingThread_.reset();
-    }
-    
-    if (frameRateThread_ && frameRateThread_->joinable()) {
-        frameRateThread_->join();
-        frameRateThread_.reset();
-    }
-    
-    // 停止采集器
-    if (capturer_) {
-        capturer_->stop();
-    }
-    
-    // 刷新编码器
-    if (encoder_) {
-        std::vector<AVPacketPtr> packets;
-        encoder_->finishEncode(packets);
-        
-        for (const auto& packet : packets) {
-            if (muxer_) {
-                muxer_->writePacket(packet.get());
-            }
-        }
-    }
-    
-    // 关闭复用器
-    if (muxer_) {
-        muxer_->close();
-    }
-    
-    setState(RecorderState::STOPPED);
-    
-    AV_LOGGER_INFO("Video recording stopped");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::pauseRecording() {
-    if (getState() != RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    isPaused_ = true;
-    setState(RecorderState::PAUSED);
-    
-    AV_LOGGER_INFO("Video recording paused");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::resumeRecording() {
-    if (getState() != RecorderState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    isPaused_ = false;
-    setState(RecorderState::RECORDING);
-    frameCondition_.notify_all();
-    
-    AV_LOGGER_INFO("Video recording resumed");
-    return ErrorCode::SUCCESS;
-}
-
-void VideoRecorder::close() {
-    if (getState() == RecorderState::RECORDING || getState() == RecorderState::PAUSED) {
-        stopRecording();
-    }
-    
-    cleanup();
-    setState(RecorderState::IDLE);
-}
-
-ErrorCode VideoRecorder::setCaptureSource(VideoCaptureMethod method, const std::string& source) {
-    if (getState() == RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    videoParams_.captureMethod = method;
-    videoParams_.deviceId = source;
-    
-    // 重新初始化采集器
-    if (capturer_) {
-        capturer_->close();
-        return initializeCapturer();
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::setCaptureWindow(void* windowHandle) {
-    if (getState() == RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    videoParams_.captureMethod = VideoCaptureMethod::WINDOW_CAPTURE;
-    videoParams_.windowHandle = windowHandle;
-    
-    if (capturer_) {
-        capturer_->close();
-        return initializeCapturer();
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::setCaptureMonitor(int monitorIndex) {
-    if (getState() == RecorderState::RECORDING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    videoParams_.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
-    videoParams_.monitorIndex = monitorIndex;
-    
-    if (capturer_) {
-        capturer_->close();
-        return initializeCapturer();
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr VideoRecorder::getCurrentFrame() const {
-    std::lock_guard<std::mutex> lock(currentFrameMutex_);
-    if (!currentFrame_) {
-        return nullptr;
-    }
-    
-    // 创建新的frame并复制数据
-    AVFramePtr frame = makeAVFrame();
-    if (!frame) {
-        return nullptr;
-    }
-    
-    if (av_frame_ref(frame.get(), currentFrame_.get()) < 0) {
-        return nullptr;
-    }
-    
-    return frame;
-}
-
-void VideoRecorder::setDrawCursor(bool draw) {
-    videoParams_.drawCursor = draw;
-    // TODO: 通知采集器更新设置
-}
-
-VideoRecorder::CaptureStats VideoRecorder::getCaptureStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    return captureStats_;
-}
-
-std::vector<std::string> VideoRecorder::getAvailableDevices(VideoCaptureMethod method) const {
-    // TODO: 根据method参数返回对应类型的设备列表
-    (void)method; // 避免未使用参数警告
-    auto capturer = std::make_unique<capture::VideoCapturer>();
-    return capturer->getAvailableDevices();
-}
-
-std::vector<std::pair<uint32_t, uint32_t>> VideoRecorder::getSupportedResolutions() const {
-    // 返回常见的分辨率列表
-    return {
-        {1920, 1080}, {1680, 1050}, {1600, 900}, {1440, 900},
-        {1366, 768}, {1280, 1024}, {1280, 800}, {1280, 720},
-        {1024, 768}, {800, 600}, {640, 480}
-    };
-}
-
-bool VideoRecorder::validateParams(const RecorderParams& params) {
-    const auto& videoParams = static_cast<const VideoRecorderParams&>(params);
-    
-    if (videoParams.width == 0 || videoParams.height == 0) {
-        AV_LOGGER_ERRORF("Invalid video dimensions: {}x{}", videoParams.width, videoParams.height);
-        return false;
-    }
-    
-    if (videoParams.frameRate == 0 || videoParams.frameRate > 120) {
-        AV_LOGGER_ERRORF("Invalid frame rate: {}", videoParams.frameRate);
-        return false;
-    }
-    
-    if (videoParams.outputPath.empty()) {
-        AV_LOGGER_ERROR("Output path is empty");
-        return false;
-    }
-    
-    return true;
-}
-
-void VideoRecorder::videoProcessingThread() {
-    AV_LOGGER_INFO("Video processing thread started");
-    
-    try {
-        while (!shouldStop_) {
-            if (isPaused_) {
-                std::unique_lock<std::mutex> lock(frameMutex_);
-                frameCondition_.wait(lock, [this] { return !isPaused_ || shouldStop_; });
-                continue;
-            }
-            
-            // 从队列获取帧
-            AVFramePtr frame = frameQueue_->pop(100);
-            if (!frame) {
-                continue;
-            }
-            
-            // 验证帧的有效性
-            if (frame->width <= 0 || frame->height <= 0) {
-                AV_LOGGER_WARNING("Invalid frame dimensions, skipping");
-                continue;
-            }
-            auto encodeStart = std::chrono::steady_clock::now();
-            
-            // 处理视频帧
-            AVFramePtr processedFrame = processVideoFrame(std::move(frame));
-            if (!processedFrame) {
-                updateStats(false);
-                continue;
-            }
-            
-            // 在编码前创建预览副本(编码后processedFrame将被move走)
-            AVFramePtr previewFrame = nullptr;
-            try {
-                previewFrame = makeAVFrame();
-                if (previewFrame) {
-                    previewFrame->format = processedFrame->format;
-                    previewFrame->width = processedFrame->width;
-                    previewFrame->height = processedFrame->height;
-                    previewFrame->pts = processedFrame->pts;
-                    
-                    if (av_frame_get_buffer(previewFrame.get(), 32) >= 0 &&
-                        av_frame_copy(previewFrame.get(), processedFrame.get()) >= 0 &&
-                        av_frame_copy_props(previewFrame.get(), processedFrame.get()) >= 0) {
-                        // 预览副本创建成功
-                    } else {
-                        previewFrame.reset(); // 创建失败,清空指针
-                    }
-                }
-            } catch (const std::exception& e) {
-                AV_LOGGER_DEBUGF("Failed to create preview frame: {}", e.what());
-                previewFrame.reset();
-            }
-            
-            // 编码视频帧
-            if (encoder_) {
-                // 在编码前进行最后的帧有效性检查
-                if (!processedFrame->data[0]) {
-                    AV_LOGGER_ERROR("严重错误:即将编码的帧数据指针为空");
-                    updateStats(false);
-                    continue;
-                }
-                
-                AV_LOGGER_DEBUGF("准备编码帧: width={}, height={}, format={}, data_ptr={}", 
-                                processedFrame->width, processedFrame->height, 
-                                processedFrame->format, static_cast<void*>(processedFrame->data[0]));
-                
-                std::vector<AVPacketPtr> packets;
-                // 使用move语义明确转移所有权,避免潜在的双重释放
-                ErrorCode result = encoder_->encode(std::move(processedFrame), packets);
-                
-                auto encodeEnd = std::chrono::steady_clock::now();
-                auto encodeTime = std::chrono::duration_cast<std::chrono::microseconds>(encodeEnd - encodeStart).count() / 1000.0;
-                
-                if (result == ErrorCode::SUCCESS && !packets.empty()) {
-                    size_t totalSize = 0;
-                    for (const auto& packet : packets) {
-                        if (packet && packet->size > 0) {
-                            onVideoPacketEncoded(packet);
-                            totalSize += packet->size;
-                        }
-                    }
-                    updateStats(true, totalSize);
-                    
-                    // 更新编码时间统计
-                    avgEncodeTime_ = (avgEncodeTime_ * 0.9) + (encodeTime * 0.1);
-                } else {
-                    updateStats(false);
-                    consecutiveDrops_++;
-                    AV_LOGGER_ERRORF("Video encoding failed: {}", static_cast<int>(result));
-                }
-            }
-            
-            // 更新当前帧(用于预览)
-            if (previewFrame) {
-                try {
-                    std::lock_guard<std::mutex> lock(currentFrameMutex_);
-                    currentFrame_ = std::move(previewFrame);
-                } catch (const std::exception& e) {
-                    AV_LOGGER_ERRORF("Error updating current frame: {}", e.what());
-                }
-            }
-
-            
-            // 计算实际帧率
-            calculateActualFrameRate();
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Video processing thread crashed with exception: {}", e.what());
-    } catch (...) {
-        AV_LOGGER_ERROR("Video processing thread crashed with unknown exception");
-    }
-    
-    AV_LOGGER_INFO("Video processing thread stopped");
-}
-
-void VideoRecorder::frameRateControlThread() {
-    AV_LOGGER_INFO("Frame rate control thread started");
-    
-    auto nextFrameTime = std::chrono::steady_clock::now();
-    
-    while (!shouldStop_) {
-        if (isPaused_) {
-            std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            nextFrameTime = std::chrono::steady_clock::now();
-            continue;
-        }
-        
-        // 等待到下一帧时间
-        std::this_thread::sleep_until(nextFrameTime);
-        nextFrameTime += frameInterval_;
-        
-        // 检查是否过载
-        bool isOverloaded = checkOverload();
-        
-        {
-            std::lock_guard<std::mutex> lock(statsMutex_);
-            captureStats_.isOverloaded = isOverloaded;
-            captureStats_.captureOverhead = avgCaptureTime_;
-            captureStats_.encodeTime = avgEncodeTime_;
-        }
-        
-        if (isOverloaded) {
-            // 如果过载,跳过一些帧
-            nextFrameTime += frameInterval_;
-            consecutiveDrops_++;
-        }
-    }
-    
-    AV_LOGGER_INFO("Frame rate control thread stopped");
-}
-
-void VideoRecorder::onVideoFrameCaptured(const AVFramePtr& frame) {
-    if (shouldStop_ || isPaused_ || !frame) {
-        return;
-    }
-    
-    // 验证帧数据的有效性
-    if (frame->width <= 0 || frame->height <= 0 || !frame->data[0]) {
-        AV_LOGGER_WARNING("Invalid frame data, skipping");
-        return;
-    }
-    
-    auto captureEnd = std::chrono::steady_clock::now();
-    auto captureTime = std::chrono::duration_cast<std::chrono::microseconds>(captureEnd - lastCaptureTime_).count() / 1000.0;
-    lastCaptureTime_ = captureEnd;
-    
-    // 更新采集时间统计
-    avgCaptureTime_ = (avgCaptureTime_ * 0.9) + (captureTime * 0.1);
-    
-    try {
-        // 创建帧的副本以避免内存管理问题
-        AVFramePtr frameCopy = makeAVFrame();
-        if (!frameCopy) {
-            AV_LOGGER_ERROR("创建帧副本失败");
-            consecutiveDrops_++;
-            updateStats(false);
-            return;
-        }
-        
-        // 复制帧属性
-        frameCopy->format = frame->format;
-        frameCopy->width = frame->width;
-        frameCopy->height = frame->height;
-        frameCopy->pts = frame->pts;
-        
-        // 分配独立的缓冲区
-        if (av_frame_get_buffer(frameCopy.get(), 32) < 0) {
-            AV_LOGGER_ERROR("分配帧缓冲区失败");
-            consecutiveDrops_++;
-            updateStats(false);
-            return;
-        }
-        
-        // 复制帧数据(创建真正的副本,避免引用计数问题)
-        if (av_frame_copy(frameCopy.get(), frame.get()) < 0) {
-            AV_LOGGER_ERROR("复制帧数据失败");
-            consecutiveDrops_++;
-            updateStats(false);
-            return;
-        }
-        
-        // 复制帧属性
-        if (av_frame_copy_props(frameCopy.get(), frame.get()) < 0) {
-            AV_LOGGER_ERROR("复制帧属性失败");
-            consecutiveDrops_++;
-            updateStats(false);
-            return;
-        }
-        
-        // 使用新的安全接口将帧加入队列
-        if (frameQueue_->push(std::move(frameCopy)) != ErrorCode::SUCCESS) {
-            // 队列满,丢弃帧 - 智能指针自动清理
-            consecutiveDrops_++;
-            updateStats(false);
-            AV_LOGGER_DEBUG("Frame queue full, dropped frame");
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Error in onVideoFrameCaptured: {}", e.what());
-        consecutiveDrops_++;
-        updateStats(false);
-    }
-}
-
-void VideoRecorder::onVideoPacketEncoded(const AVPacketPtr& packet) {
-    if (muxer_ && packet) {
-        ErrorCode result = muxer_->writePacket(packet.get());
-        if (result != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERRORF("Failed to write video packet: {}", static_cast<int>(result));
-        }
-    }
-}
-
-ErrorCode VideoRecorder::initializeCapturer() {
-    capturer_ = std::make_unique<capture::VideoCapturer>();
-    
-    // 根据采集方法设置参数
-    capture::CapturerType capturerType;
-    std::string deviceId;
-    
-    switch (videoParams_.captureMethod) {
-        case VideoCaptureMethod::SCREEN_CAPTURE:
-            capturerType = capture::CapturerType::VIDEO_SCREEN;
-            deviceId = std::to_string(videoParams_.monitorIndex);
-            break;
-        case VideoCaptureMethod::WINDOW_CAPTURE:
-            capturerType = capture::CapturerType::VIDEO_WINDOW;
-            // TODO: 设置窗口句柄
-            break;
-        case VideoCaptureMethod::CAMERA_CAPTURE:
-            capturerType = capture::CapturerType::VIDEO_CAMERA;
-            deviceId = videoParams_.deviceId;
-            break;
-        default:
-            capturerType = capture::CapturerType::VIDEO_SCREEN;
-            break;
-    }
-    
-    capture::VideoCaptureParams capturerParams(capturerType);
-    capturerParams.deviceId = deviceId;
-    
-    // 设置视频参数
-    capturerParams.width = videoParams_.width;
-    capturerParams.height = videoParams_.height;
-    capturerParams.fps = videoParams_.frameRate;
-    capturerParams.pixelFormat = videoParams_.pixelFormat;
-    
-    // 调试信息:检查参数值
-    AV_LOGGER_INFOF("Setting capturer params: width={}, height={}, fps={}", 
-                   capturerParams.width, capturerParams.height, capturerParams.fps);
-    
-    // 确保参数有效
-    if (capturerParams.width <= 0 || capturerParams.height <= 0) {
-        AV_LOGGER_ERRORF("Invalid video dimensions from videoParams_: {}x{}", 
-                        videoParams_.width, videoParams_.height);
-        // 使用默认值
-        capturerParams.width = 1920;
-        capturerParams.height = 1080;
-        AV_LOGGER_INFOF("Using default dimensions: {}x{}", 
-                       capturerParams.width, capturerParams.height);
-    }
-    
-    // 根据采集方法设置特定参数
-    switch (videoParams_.captureMethod) {
-        case VideoCaptureMethod::SCREEN_CAPTURE:
-            capturerParams.screenIndex = videoParams_.monitorIndex;
-            capturerParams.captureCursor = videoParams_.drawCursor;
-            break;
-        case VideoCaptureMethod::WINDOW_CAPTURE:
-            capturerParams.windowHandle = videoParams_.windowHandle;
-            capturerParams.captureCursor = videoParams_.drawCursor;
-            break;
-        case VideoCaptureMethod::CAMERA_CAPTURE:
-            capturerParams.cameraIndex = 0; // 默认使用第一个摄像头,可以根据deviceId解析
-            break;
-    }
-    
-    ErrorCode result = capturer_->initialize(capturerParams);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("Failed to initialize video capturer: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    // 设置回调
-    capturer_->setFrameCallback([this](const AVFramePtr& frame) {
-        onVideoFrameCaptured(frame);
-    });
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::initializeEncoder() {
-    encoder_ = std::make_unique<codec::VideoEncoder>();
-    
-    // 创建视频编码器参数
-    codec::VideoEncoderParams encoderParams;
-    encoderParams.type = MediaType::VIDEO;
-    
-    // 如果指定的编码器名称无效,则自动选择最佳编码器
-    std::string codecName = videoParams_.codecName;
-    if (codecName.empty() || codecName == "h264") {
-        codecName = codec::VideoEncoder::getRecommendedEncoder();
-        if (codecName.empty()) {
-            codecName = "libx264";  // 最后的回退选项
-        }
-        AV_LOGGER_INFOF("Auto-selected encoder: {}", codecName);
-    }
-    
-    encoderParams.codecName = codecName;
-    encoderParams.width = videoParams_.width;
-    encoderParams.height = videoParams_.height;
-    encoderParams.fps = videoParams_.frameRate;
-    encoderParams.bitRate = videoParams_.bitrate;  // 注意字段名称差异
-    encoderParams.gopSize = videoParams_.keyFrameInterval;  // GOP大小对应关键帧间隔
-    encoderParams.maxBFrames = 0;  // 使用默认值,VideoRecorderParams中没有此字段
-    encoderParams.preset = videoParams_.preset;
-    encoderParams.tune = "";  // 使用默认值,VideoRecorderParams中没有此字段
-    encoderParams.lowLatency = false;  // 使用默认值,VideoRecorderParams中没有此字段
-    encoderParams.hardwareAccel = true;  // 使用默认值,VideoRecorderParams中没有此字段
-    encoderParams.pixelFormat = videoParams_.pixelFormat;
-    
-    AV_LOGGER_INFOF("Setting encoder params: codec={}, width={}, height={}, fps={}, bitRate={}", 
-                   encoderParams.codecName, encoderParams.width, encoderParams.height, 
-                   encoderParams.fps, encoderParams.bitRate);
-    
-    ErrorCode result = encoder_->open(encoderParams);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("Failed to initialize video encoder: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    // 更新实际使用的编码器名称
-    videoParams_.codecName = codecName;
-    AV_LOGGER_INFOF("Updated videoParams_.codecName to: {}", videoParams_.codecName);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode VideoRecorder::initializeMuxer() {
-    muxer_ = std::make_unique<muxer::FileMuxer>();
-    
-    // 创建 FileMuxerParams 而不是基类 MuxerParams
-    muxer::FileMuxerParams fileMuxerParams;
-    fileMuxerParams.outputPath = videoParams_.outputPath;
-    fileMuxerParams.outputFile = videoParams_.outputPath;  // FileMuxerParams 需要设置 outputFile
-    fileMuxerParams.format = videoParams_.format;
-    fileMuxerParams.overwrite = true;  // 允许覆盖已存在文件
-    fileMuxerParams.enableFastStart = true;  // 启用快速开始
-    
-    // 添加视频流信息
-    muxer::StreamInfo videoStream;
-    videoStream.index = 0;
-    videoStream.type = muxer::StreamType::VIDEO;
-    videoStream.codecName = videoParams_.codecName;
-    
-    // 从编码器获取 codecId
-    const AVCodec* codec = avcodec_find_encoder_by_name(videoParams_.codecName.c_str());
-    if (codec) {
-        videoStream.codecId = codec->id;
-        AV_LOGGER_INFOF("设置编解码器ID: {} ({})", static_cast<int>(codec->id), codec->name);
-    } else {
-        AV_LOGGER_ERRORF("无法找到编码器: {}", videoParams_.codecName);
-        return ErrorCode::CODEC_NOT_FOUND;
-    }
-    
-    videoStream.width = videoParams_.width;
-    videoStream.height = videoParams_.height;
-    videoStream.frameRate = {static_cast<int>(videoParams_.frameRate), 1};
-    videoStream.pixelFormat = videoParams_.pixelFormat;
-    videoStream.bitrate = videoParams_.bitrate;
-    videoStream.timeBase = {1, static_cast<int>(videoParams_.frameRate)};
-    
-    fileMuxerParams.streams.push_back(videoStream);
-    
-    AV_LOGGER_INFOF("Initializing muxer with outputFile: {}, format: {}, video stream: {}x{}@{}fps, codecId: {}", 
-                   fileMuxerParams.outputFile, fileMuxerParams.format, 
-                   videoStream.width, videoStream.height, videoParams_.frameRate, 
-                   static_cast<int>(videoStream.codecId));
-    
-    ErrorCode result = muxer_->initialize(fileMuxerParams);
-    if (result != ErrorCode::SUCCESS) {
-        AV_LOGGER_ERRORF("Failed to initialize muxer: {}", static_cast<int>(result));
-        return result;
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-AVFramePtr VideoRecorder::processVideoFrame(AVFramePtr frame) {
-    if (!frame) {
-        return nullptr;
-    }
-    
-    // TODO: 实现视频帧处理(缩放、格式转换等)
-    // 使用移动语义转移所有权,避免拷贝
-    // 如果将来需要修改帧数据,再考虑创建副本
-    return std::move(frame);
-}
-
-void VideoRecorder::calculateActualFrameRate() {
-    auto now = std::chrono::steady_clock::now();
-    frameTimestamps_.push_back(now);
-    
-    // 保持队列大小
-    while (frameTimestamps_.size() > MAX_FRAME_TIMESTAMPS) {
-        frameTimestamps_.pop_front();
-    }
-    
-    // 计算帧率
-    if (frameTimestamps_.size() >= 2) {
-        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
-            frameTimestamps_.back() - frameTimestamps_.front()).count();
-        
-        if (duration > 0) {
-            double fps = (frameTimestamps_.size() - 1) * 1000.0 / duration;
-            
-            std::lock_guard<std::mutex> lock(statsMutex_);
-            captureStats_.actualFrameRate = fps;
-        }
-    }
-}
-
-bool VideoRecorder::checkOverload() const {
-    // 检查编码时间是否超过帧间隔
-    double frameIntervalMs = 1000.0 / videoParams_.frameRate;
-    return (avgCaptureTime_ + avgEncodeTime_) > (frameIntervalMs * 0.8); // 80%阈值
-}
-
-void VideoRecorder::cleanup() {
-    shouldStop_ = true;
-    
-    // 停止处理线程
-    frameCondition_.notify_all();
-    
-    if (processingThread_ && processingThread_->joinable()) {
-        processingThread_->join();
-        processingThread_.reset();
-    }
-    
-    if (frameRateThread_ && frameRateThread_->joinable()) {
-        frameRateThread_->join();
-        frameRateThread_.reset();
-    }
-    
-    // 清理采集器
-    if (capturer_) {
-        capturer_->stop();
-        capturer_->close();
-        capturer_.reset();
-    }
-    
-    // 清理编码器
-    if (encoder_) {
-        encoder_->close();
-        encoder_.reset();
-    }
-    
-    // 清理复用器
-    if (muxer_) {
-        muxer_->close();
-        muxer_.reset();
-    }
-    
-    // 清理线程池
-    if (threadPool_) {
-        threadPool_.reset();
-    }
-    
-    // 清理帧队列
-    if (frameQueue_) {
-        frameQueue_->clear();
-    }
-    
-    // 清理当前帧
-    {
-        std::lock_guard<std::mutex> lock(currentFrameMutex_);
-        currentFrame_.reset();
-    }
-}
-
-} // namespace recorder
-} // namespace av

+ 0 - 245
AV/code/recorder/recorder_video_recorder.h

@@ -1,245 +0,0 @@
-#ifndef AV_RECORDER_VIDEO_RECORDER_H
-#define AV_RECORDER_VIDEO_RECORDER_H
-
-#include "recorder_abstract_recorder.h"
-#include "../capture/capture_video_capturer.h"
-#include "../codec/codec_video_encoder.h"
-#include "../muxer/muxer_abstract_muxer.h"
-#include "../muxer/muxer_file_muxer.h"
-#include "../utils/utils_thread_pool.h"
-#include "../utils/utils_frame_queue.h"
-#include <memory>
-#include <thread>
-#include <atomic>
-#include <mutex>
-#include <condition_variable>
-#include <deque>
-
-namespace av {
-namespace recorder {
-
-/**
- * 视频采集方法
- */
-enum class VideoCaptureMethod {
-    SCREEN_CAPTURE,     // 屏幕采集
-    WINDOW_CAPTURE,     // 窗口采集
-    CAMERA_CAPTURE      // 摄像头采集
-};
-
-/**
- * 视频录制器参数
- */
-struct VideoRecorderParams : public RecorderParams {
-    // 视频采集参数
-    VideoCaptureMethod captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
-    std::string deviceId;               // 设备ID(摄像头)或显示器索引
-    void* windowHandle = nullptr;       // 窗口句柄(窗口采集)
-    int monitorIndex = 0;               // 显示器索引(屏幕采集)
-    
-    // 视频参数
-    uint32_t width = 1920;              // 视频宽度
-    uint32_t height = 1080;             // 视频高度
-    uint32_t frameRate = 30;            // 帧率
-    AVPixelFormat pixelFormat = AV_PIX_FMT_YUV420P;
-    
-    // 编码参数
-    std::string codecName = "libx264";  // 编码器名称(使用libx264软件编码器)
-    uint32_t bitrate = 5000000;         // 比特率 (5Mbps)
-    uint32_t keyFrameInterval = 30;     // 关键帧间隔
-    std::string preset = "medium";      // 编码预设
-    
-    // 采集选项
-    bool drawCursor = true;             // 是否绘制鼠标光标
-    bool captureAudio = false;          // 是否同时采集音频
-    
-    VideoRecorderParams() {
-        mediaType = MediaType::VIDEO;
-        format = "mp4";
-    }
-};
-
-/**
- * 视频录制器
- * 支持屏幕录制、窗口采集、摄像头录制等功能
- */
-class VideoRecorder : public AbstractRecorder {
-public:
-    VideoRecorder();
-    virtual ~VideoRecorder();
-
-    // 实现基类接口
-    ErrorCode initialize(const RecorderParams& params) override;
-    ErrorCode startRecording() override;
-    ErrorCode stopRecording() override;
-    ErrorCode pauseRecording() override;
-    ErrorCode resumeRecording() override;
-    void close() override;
-
-    // 视频特定功能
-    /**
-     * 设置采集源
-     */
-    ErrorCode setCaptureSource(VideoCaptureMethod method, const std::string& source);
-    
-    /**
-     * 设置窗口采集源
-     */
-    ErrorCode setCaptureWindow(void* windowHandle);
-    
-    /**
-     * 设置显示器采集源
-     */
-    ErrorCode setCaptureMonitor(int monitorIndex);
-    
-    /**
-     * 获取当前帧(用于预览)
-     */
-    AVFramePtr getCurrentFrame() const;
-    
-    /**
-     * 设置是否绘制光标
-     */
-    void setDrawCursor(bool draw);
-    
-    /**
-     * 获取采集统计信息
-     */
-    struct CaptureStats {
-        double actualFrameRate = 0.0;      // 实际帧率
-        double captureOverhead = 0.0;      // 采集开销(ms)
-        double encodeTime = 0.0;            // 编码时间(ms)
-        uint64_t droppedFrames = 0;         // 丢帧数
-        bool isOverloaded = false;          // 是否过载
-    };
-    
-    CaptureStats getCaptureStats() const;
-    
-    /**
-     * 获取可用的采集设备
-     */
-    std::vector<std::string> getAvailableDevices(VideoCaptureMethod method) const;
-    
-    /**
-     * 获取支持的分辨率列表
-     */
-    std::vector<std::pair<uint32_t, uint32_t>> getSupportedResolutions() const;
-
-protected:
-    bool validateParams(const RecorderParams& params) override;
-
-private:
-    /**
-     * 视频处理线程
-     */
-    void videoProcessingThread();
-    
-    /**
-     * 帧率控制线程
-     */
-    void frameRateControlThread();
-    
-    /**
-     * 视频帧回调
-     */
-    void onVideoFrameCaptured(const AVFramePtr& frame);
-    
-    /**
-     * 编码完成回调
-     */
-    void onVideoPacketEncoded(const AVPacketPtr& packet);
-    
-    /**
-     * 初始化采集器
-     */
-    ErrorCode initializeCapturer();
-    
-    /**
-     * 初始化编码器
-     */
-    ErrorCode initializeEncoder();
-    
-    /**
-     * 初始化复用器
-     */
-    ErrorCode initializeMuxer();
-    
-    /**
-     * 处理视频帧
-     */
-    AVFramePtr processVideoFrame(AVFramePtr frame);
-    
-    /**
-     * 计算帧率
-     */
-    void calculateActualFrameRate();
-    
-    /**
-     * 检查是否过载
-     */
-    bool checkOverload() const;
-    
-    /**
-     * 清理资源
-     */
-    void cleanup();
-
-private:
-    VideoRecorderParams videoParams_;
-    
-    // 采集器
-    std::unique_ptr<capture::VideoCapturer> capturer_;
-    
-    // 编码器
-    std::unique_ptr<codec::VideoEncoder> encoder_;
-    
-    // 复用器
-    std::unique_ptr<muxer::AbstractMuxer> muxer_;
-    
-    // 线程池
-    std::unique_ptr<utils::ThreadPool> threadPool_;
-    
-    // 处理线程
-    std::unique_ptr<std::thread> processingThread_;
-    std::unique_ptr<std::thread> frameRateThread_;
-    std::atomic<bool> shouldStop_;
-    
-    // 帧队列
-    std::unique_ptr<utils::FrameQueue> frameQueue_;
-    
-    // 当前帧(用于预览)
-    mutable std::mutex currentFrameMutex_;
-    AVFramePtr currentFrame_;
-    
-    // 帧率控制
-    std::atomic<bool> isPaused_;
-    std::chrono::steady_clock::time_point lastFrameTime_;
-    std::chrono::microseconds frameInterval_;
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    CaptureStats captureStats_;
-    
-    // 帧率计算
-    std::deque<std::chrono::steady_clock::time_point> frameTimestamps_;
-    static constexpr size_t MAX_FRAME_TIMESTAMPS = 60; // 保留最近60帧的时间戳
-    
-    // 性能监控
-    std::chrono::steady_clock::time_point lastCaptureTime_;
-    std::chrono::steady_clock::time_point lastEncodeTime_;
-    double avgCaptureTime_;
-    double avgEncodeTime_;
-    
-    // 丢帧检测
-    static constexpr int OVERLOAD_THRESHOLD_MS = 50; // 50ms阈值
-    std::atomic<uint64_t> consecutiveDrops_;
-    
-    // 同步
-    std::condition_variable frameCondition_;
-    std::mutex frameMutex_;
-};
-
-} // namespace recorder
-} // namespace av
-
-#endif // AV_RECORDER_VIDEO_RECORDER_H

+ 0 - 669
AV/code/recorder/ui/recorder_audio_widget.cpp

@@ -1,669 +0,0 @@
-#include "recorder_audio_widget.h"
-#include <QComboBox>
-#include <QDateTime>
-#include <QDebug>
-#include <QPainterPath>
-#include <QLinearGradient>
-#include <QApplication>
-#include <QStyle>
-#include <cmath>
-
-// AudioLevelWidget 实现
-
-AudioLevelWidget::AudioLevelWidget(QWidget* parent)
-    : QWidget(parent)
-    , m_leftLevel(0.0)
-    , m_rightLevel(0.0)
-    , m_leftPeak(0.0)
-    , m_rightPeak(0.0)
-    , m_leftPeakTime(0)
-    , m_rightPeakTime(0)
-    , m_peakHoldTime(1500)
-    , m_overloadThreshold(0.95)
-    , m_showValues(true) {
-    
-    setMinimumSize(100, 40);
-    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
-    
-    // 创建峰值更新定时器
-    m_peakTimer = new QTimer(this);
-    connect(m_peakTimer, &QTimer::timeout, this, &AudioLevelWidget::updatePeaks);
-    m_peakTimer->start(50); // 20fps更新
-}
-
-AudioLevelWidget::~AudioLevelWidget() = default;
-
-void AudioLevelWidget::setLeftLevel(double level) {
-    QMutexLocker locker(&m_mutex);
-    
-    level = qBound(0.0, level, 1.0);
-    m_leftLevel = level;
-    
-    // 更新峰值
-    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
-    if (level > m_leftPeak) {
-        m_leftPeak = level;
-        m_leftPeakTime = currentTime;
-    }
-    
-    update();
-}
-
-void AudioLevelWidget::setRightLevel(double level) {
-    QMutexLocker locker(&m_mutex);
-    
-    level = qBound(0.0, level, 1.0);
-    m_rightLevel = level;
-    
-    // 更新峰值
-    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
-    if (level > m_rightPeak) {
-        m_rightPeak = level;
-        m_rightPeakTime = currentTime;
-    }
-    
-    update();
-}
-
-void AudioLevelWidget::setLevels(double left, double right) {
-    QMutexLocker locker(&m_mutex);
-    
-    left = qBound(0.0, left, 1.0);
-    right = qBound(0.0, right, 1.0);
-    
-    m_leftLevel = left;
-    m_rightLevel = right;
-    
-    // 更新峰值
-    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
-    
-    if (left > m_leftPeak) {
-        m_leftPeak = left;
-        m_leftPeakTime = currentTime;
-    }
-    
-    if (right > m_rightPeak) {
-        m_rightPeak = right;
-        m_rightPeakTime = currentTime;
-    }
-    
-    update();
-}
-
-void AudioLevelWidget::resetPeaks() {
-    QMutexLocker locker(&m_mutex);
-    
-    m_leftPeak = 0.0;
-    m_rightPeak = 0.0;
-    m_leftPeakTime = 0;
-    m_rightPeakTime = 0;
-    
-    update();
-}
-
-void AudioLevelWidget::paintEvent(QPaintEvent* event) {
-    Q_UNUSED(event)
-    
-    QPainter painter(this);
-    painter.setRenderHint(QPainter::Antialiasing);
-    
-    QMutexLocker locker(&m_mutex);
-    
-    // 计算绘制区域
-    QRect drawRect = rect().adjusted(2, 2, -2, -2);
-    int channelHeight = (drawRect.height() - 4) / 2;
-    
-    // 绘制左声道
-    QRect leftRect(drawRect.x(), drawRect.y(), drawRect.width(), channelHeight);
-    drawChannel(painter, leftRect, m_leftLevel, m_leftPeak, true);
-    
-    // 绘制右声道
-    QRect rightRect(drawRect.x(), drawRect.y() + channelHeight + 4, 
-                   drawRect.width(), channelHeight);
-    drawChannel(painter, rightRect, m_rightLevel, m_rightPeak, false);
-    
-    // 绘制标签
-    painter.setPen(Qt::white);
-    painter.setFont(QFont("Arial", 8));
-    
-    painter.drawText(leftRect.adjusted(2, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, "L");
-    painter.drawText(rightRect.adjusted(2, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, "R");
-    
-    // 绘制数值
-    if (m_showValues) {
-        QString leftText = QString("%1").arg(static_cast<int>(m_leftLevel * 100));
-        QString rightText = QString("%1").arg(static_cast<int>(m_rightLevel * 100));
-        
-        painter.drawText(leftRect.adjusted(0, 0, -2, 0), Qt::AlignRight | Qt::AlignVCenter, leftText);
-        painter.drawText(rightRect.adjusted(0, 0, -2, 0), Qt::AlignRight | Qt::AlignVCenter, rightText);
-    }
-}
-
-QSize AudioLevelWidget::sizeHint() const {
-    return QSize(180, 32);
-}
-
-QSize AudioLevelWidget::minimumSizeHint() const {
-    return QSize(120, 32);
-}
-
-void AudioLevelWidget::updatePeaks() {
-    QMutexLocker locker(&m_mutex);
-    
-    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
-    bool needUpdate = false;
-    
-    // 检查左声道峰值是否过期
-    if (m_leftPeakTime > 0 && (currentTime - m_leftPeakTime) > m_peakHoldTime) {
-        m_leftPeak = m_leftLevel;
-        m_leftPeakTime = currentTime;
-        needUpdate = true;
-    }
-    
-    // 检查右声道峰值是否过期
-    if (m_rightPeakTime > 0 && (currentTime - m_rightPeakTime) > m_peakHoldTime) {
-        m_rightPeak = m_rightLevel;
-        m_rightPeakTime = currentTime;
-        needUpdate = true;
-    }
-    
-    if (needUpdate) {
-        update();
-    }
-}
-
-void AudioLevelWidget::drawChannel(QPainter& painter, const QRect& rect, 
-                                  double level, double peak, bool isLeft) {
-    Q_UNUSED(isLeft)
-    
-    // 绘制背景
-    painter.fillRect(rect, QColor(40, 40, 40));
-    
-    // 绘制边框
-    painter.setPen(QColor(80, 80, 80));
-    painter.drawRect(rect);
-    
-    if (level <= 0.0) {
-        return;
-    }
-    
-    // 计算电平条宽度
-    int levelWidth = static_cast<int>(rect.width() * level);
-    QRect levelRect(rect.x(), rect.y(), levelWidth, rect.height());
-    
-    // 创建渐变
-    QLinearGradient gradient(levelRect.topLeft(), levelRect.topRight());
-    
-    if (level < 0.7) {
-        // 绿色区域
-        gradient.setColorAt(0.0, QColor(0, 255, 0));
-        gradient.setColorAt(1.0, QColor(100, 255, 0));
-    } else if (level < m_overloadThreshold) {
-        // 黄色区域
-        gradient.setColorAt(0.0, QColor(100, 255, 0));
-        gradient.setColorAt(0.5, QColor(255, 255, 0));
-        gradient.setColorAt(1.0, QColor(255, 200, 0));
-    } else {
-        // 红色区域(过载)
-        gradient.setColorAt(0.0, QColor(255, 200, 0));
-        gradient.setColorAt(1.0, QColor(255, 0, 0));
-    }
-    
-    painter.fillRect(levelRect, gradient);
-    
-    // 绘制峰值线
-    if (peak > level && peak > 0.0) {
-        int peakX = static_cast<int>(rect.x() + rect.width() * peak);
-        QColor peakColor = getLevelColor(peak);
-        
-        painter.setPen(QPen(peakColor, 2));
-        painter.drawLine(peakX, rect.y(), peakX, rect.y() + rect.height());
-    }
-}
-
-QColor AudioLevelWidget::getLevelColor(double level) const {
-    if (level < 0.7) {
-        return QColor(0, 255, 0); // 绿色
-    } else if (level < m_overloadThreshold) {
-        return QColor(255, 255, 0); // 黄色
-    } else {
-        return QColor(255, 0, 0); // 红色
-    }
-}
-
-// RecorderAudioWidget 实现
-
-RecorderAudioWidget::RecorderAudioWidget(QWidget* parent)
-    : QWidget(parent)
-    , m_mainLayout(nullptr)
-    , m_controlLayout(nullptr)
-    , m_deviceLayout(nullptr)
-    , m_infoLayout(nullptr)
-    , m_volumeLabel(nullptr)
-    , m_volumeSlider(nullptr)
-    , m_volumeValueLabel(nullptr)
-    , m_muteButton(nullptr)
-    , m_levelWidget(nullptr)
-    , m_deviceLabel(nullptr)
-    , m_deviceCombo(nullptr)
-    , m_settingsButton(nullptr)
-    , m_statusLabel(nullptr)
-    , m_volumeAnimation(nullptr)
-    , m_levelOpacityEffect(nullptr)
-    , m_showAdvancedControls(true)
-    , m_volumeChanging(false) {
-    
-    initializeUI();
-    connectSignals();
-    updateUI();
-}
-
-RecorderAudioWidget::~RecorderAudioWidget() = default;
-
-void RecorderAudioWidget::setAudioInfo(const AudioInfo& info) {
-    QMutexLocker locker(&m_mutex);
-    
-    m_audioInfo = info;
-    
-    // 更新UI(在主线程中)
-    QMetaObject::invokeMethod(this, "updateUI", Qt::QueuedConnection);
-}
-
-void RecorderAudioWidget::setVolume(double volume) {
-    QMutexLocker locker(&m_mutex);
-    
-    volume = qBound(0.0, volume, 1.0);
-    if (qAbs(m_audioInfo.volume - volume) < 0.001) {
-        return;
-    }
-    
-    m_audioInfo.volume = volume;
-    
-    // 更新滑块(避免循环信号)
-    if (!m_volumeChanging) {
-        QMetaObject::invokeMethod(this, "updateVolumeDisplay", Qt::QueuedConnection);
-    }
-    
-    emit volumeChanged(volume);
-}
-
-void RecorderAudioWidget::setMuted(bool muted) {
-    QMutexLocker locker(&m_mutex);
-    
-    if (m_audioInfo.isMuted == muted) {
-        return;
-    }
-    
-    m_audioInfo.isMuted = muted;
-    
-    QMetaObject::invokeMethod(this, "updateMuteButton", Qt::QueuedConnection);
-    
-    emit mutedChanged(muted);
-}
-
-void RecorderAudioWidget::setRecording(bool recording) {
-    QMutexLocker locker(&m_mutex);
-    
-    if (m_audioInfo.isRecording == recording) {
-        return;
-    }
-    
-    m_audioInfo.isRecording = recording;
-    
-    QMetaObject::invokeMethod(this, "updateUI", Qt::QueuedConnection);
-}
-
-void RecorderAudioWidget::updateAudioLevels(double left, double right) {
-    if (m_levelWidget) {
-        m_levelWidget->setLevels(left, right);
-    }
-}
-
-void RecorderAudioWidget::setAvailableDevices(const QStringList& devices) {
-    if (!m_deviceCombo) {
-        return;
-    }
-    
-    // 保存当前选择
-    QString currentDevice = m_deviceCombo->currentText();
-    
-    // 更新设备列表
-    m_deviceCombo->clear();
-    m_deviceCombo->addItems(devices);
-    
-    // 恢复选择
-    int index = m_deviceCombo->findText(currentDevice);
-    if (index >= 0) {
-        m_deviceCombo->setCurrentIndex(index);
-    }
-}
-
-void RecorderAudioWidget::setCurrentDevice(const QString& device) {
-    if (!m_deviceCombo) {
-        return;
-    }
-    
-    int index = m_deviceCombo->findText(device);
-    if (index >= 0) {
-        m_deviceCombo->setCurrentIndex(index);
-    }
-    
-    QMutexLocker locker(&m_mutex);
-    m_audioInfo.deviceName = device;
-    
-    QMetaObject::invokeMethod(this, "updateDeviceInfo", Qt::QueuedConnection);
-}
-
-QString RecorderAudioWidget::currentDevice() const {
-    if (!m_deviceCombo) {
-        return QString();
-    }
-    
-    return m_deviceCombo->currentText();
-}
-
-void RecorderAudioWidget::setShowAdvancedControls(bool show) {
-    m_showAdvancedControls = show;
-    
-    if (m_deviceLayout) {
-        m_deviceLabel->setVisible(show);
-        m_deviceCombo->setVisible(show);
-        m_settingsButton->setVisible(show);
-    }
-}
-
-void RecorderAudioWidget::resetAudioPeaks() {
-    if (m_levelWidget) {
-        m_levelWidget->resetPeaks();
-    }
-}
-
-void RecorderAudioWidget::paintEvent(QPaintEvent* event) {
-    // 绘制背景
-    QStyleOption opt;
-    opt.init(this);
-    QPainter painter(this);
-    style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
-    
-    QWidget::paintEvent(event);
-}
-
-void RecorderAudioWidget::onVolumeSliderChanged(int value) {
-    m_volumeChanging = true;
-    
-    double volume = value / 100.0;
-    setVolume(volume);
-    
-    // 更新数值标签
-    if (m_volumeValueLabel) {
-        m_volumeValueLabel->setText(QString("%1%").arg(value));
-    }
-    
-    m_volumeChanging = false;
-}
-
-void RecorderAudioWidget::onMuteButtonClicked() {
-    setMuted(!isMuted());
-}
-
-void RecorderAudioWidget::onDeviceComboChanged(const QString& device) {
-    QMutexLocker locker(&m_mutex);
-    m_audioInfo.deviceName = device;
-    locker.unlock();
-    
-    updateDeviceInfo();
-    emit deviceChanged(device);
-}
-
-void RecorderAudioWidget::onSettingsButtonClicked() {
-    emit audioSettingsRequested();
-}
-
-void RecorderAudioWidget::updateVolumeAnimation() {
-    // 音量变化动画效果
-    if (m_volumeAnimation && m_levelWidget) {
-        // 可以添加音量变化的视觉反馈
-    }
-}
-
-void RecorderAudioWidget::initializeUI() {
-    // 创建主布局
-    m_mainLayout = new QVBoxLayout(this);
-    m_mainLayout->setContentsMargins(6, 6, 6, 6);
-    m_mainLayout->setSpacing(4);
-    
-    // 音量控制布局
-    m_controlLayout = new QHBoxLayout();
-    m_controlLayout->setSpacing(6);
-    
-    m_volumeLabel = new QLabel("音量:");
-    m_volumeLabel->setMinimumWidth(35);
-    m_volumeLabel->setMaximumWidth(35);
-    
-    m_volumeSlider = new QSlider(Qt::Horizontal);
-    m_volumeSlider->setRange(0, 100);
-    m_volumeSlider->setValue(100);
-    m_volumeSlider->setMinimumWidth(80);
-    m_volumeSlider->setMaximumHeight(20);
-    
-    m_volumeValueLabel = new QLabel("100%");
-    m_volumeValueLabel->setMinimumWidth(30);
-    m_volumeValueLabel->setMaximumWidth(30);
-    m_volumeValueLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
-    
-    m_muteButton = new QPushButton();
-    m_muteButton->setCheckable(true);
-    m_muteButton->setFixedSize(20, 20);
-    m_muteButton->setToolTip("静音/取消静音");
-    
-    m_controlLayout->addWidget(m_volumeLabel);
-    m_controlLayout->addWidget(m_volumeSlider, 1);
-    m_controlLayout->addWidget(m_volumeValueLabel);
-    m_controlLayout->addWidget(m_muteButton);
-    
-    // 音频电平显示
-    m_levelWidget = new AudioLevelWidget();
-    m_levelWidget->setFixedHeight(32);  // 固定高度,避免被挤压
-    m_levelWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
-    
-    // 设备选择布局(简化版)
-    m_deviceLayout = new QHBoxLayout();
-    m_deviceLayout->setSpacing(4);
-    
-    m_deviceLabel = new QLabel("设备:");
-    m_deviceLabel->setMinimumWidth(35);
-    m_deviceLabel->setMaximumWidth(35);
-    
-    m_deviceCombo = new QComboBox();
-    m_deviceCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
-    m_deviceCombo->setMaximumHeight(22);
-    
-    m_settingsButton = new QPushButton("⚙");
-    m_settingsButton->setFixedSize(20, 20);
-    m_settingsButton->setToolTip("音频设置");
-    
-    m_deviceLayout->addWidget(m_deviceLabel);
-    m_deviceLayout->addWidget(m_deviceCombo, 1);
-    m_deviceLayout->addWidget(m_settingsButton);
-    
-    // 状态显示布局(简化版)
-    m_infoLayout = new QHBoxLayout();
-    m_infoLayout->setSpacing(4);
-    
-    m_statusLabel = new QLabel("待机");
-    m_statusLabel->setStyleSheet("font-size: 8pt; color: #888;");
-    m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
-
-    m_infoLayout->addStretch();
-    m_infoLayout->addWidget(m_statusLabel);
-    
-    // 添加到主布局
-    m_mainLayout->addLayout(m_controlLayout);
-    m_mainLayout->addWidget(m_levelWidget);
-    m_mainLayout->addLayout(m_deviceLayout);
-    m_mainLayout->addLayout(m_infoLayout);
-    
-    // 创建动画
-    m_volumeAnimation = new QPropertyAnimation(this, "volume");
-    m_volumeAnimation->setDuration(200);
-    m_volumeAnimation->setEasingCurve(QEasingCurve::OutCubic);
-    
-    // 设置样式
-    // setStyleSheet(R"(
-    //     RecorderAudioWidget {
-    //         background-color: #2b2b2b;
-    //         border: 1px solid #555;
-    //         border-radius: 4px;
-    //     }
-    //     QLabel {
-    //         color: #fff;
-    //     }
-    //     QSlider::groove:horizontal {
-    //         border: 1px solid #555;
-    //         height: 6px;
-    //         background: #333;
-    //         border-radius: 3px;
-    //     }
-    //     QSlider::handle:horizontal {
-    //         background: #0a84ff;
-    //         border: 1px solid #0a84ff;
-    //         width: 14px;
-    //         margin: -4px 0;
-    //         border-radius: 7px;
-    //     }
-    //     QSlider::sub-page:horizontal {
-    //         background: #0a84ff;
-    //         border-radius: 3px;
-    //     }
-    //     QPushButton {
-    //         background-color: #444;
-    //         border: 1px solid #666;
-    //         border-radius: 3px;
-    //         color: #fff;
-    //         padding: 4px 8px;
-    //     }
-    //     QPushButton:hover {
-    //         background-color: #555;
-    //     }
-    //     QPushButton:pressed {
-    //         background-color: #333;
-    //     }
-    //     QPushButton:checked {
-    //         background-color: #0a84ff;
-    //     }
-    //     QComboBox {
-    //         background-color: #444;
-    //         border: 1px solid #666;
-    //         border-radius: 3px;
-    //         color: #fff;
-    //         padding: 4px;
-    //     }
-    //     QComboBox::drop-down {
-    //         border: none;
-    //     }
-    //     QComboBox::down-arrow {
-    //         image: none;
-    //         border-left: 4px solid transparent;
-    //         border-right: 4px solid transparent;
-    //         border-top: 4px solid #fff;
-    //     }
-    // )");
-}
-
-void RecorderAudioWidget::connectSignals() {
-    // 音量控制信号
-    connect(m_volumeSlider, QOverload<int>::of(&QSlider::valueChanged),
-            this, &RecorderAudioWidget::onVolumeSliderChanged);
-    
-    connect(m_muteButton, &QPushButton::clicked,
-            this, &RecorderAudioWidget::onMuteButtonClicked);
-    
-    // 设备选择信号
-    connect(m_deviceCombo, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
-            this, &RecorderAudioWidget::onDeviceComboChanged);
-    
-    connect(m_settingsButton, &QPushButton::clicked,
-            this, &RecorderAudioWidget::onSettingsButtonClicked);
-    
-    // 动画信号
-    connect(m_volumeAnimation, &QPropertyAnimation::valueChanged,
-            this, &RecorderAudioWidget::updateVolumeAnimation);
-}
-
-void RecorderAudioWidget::updateUI() {
-    QMutexLocker locker(&m_mutex);
-    AudioInfo info = m_audioInfo;
-    locker.unlock();
-    
-    updateVolumeDisplay();
-    updateMuteButton();
-    updateDeviceInfo();
-    
-    // 更新状态标签
-    if (m_statusLabel) {
-        if (info.isRecording) {
-            m_statusLabel->setText("● 录制中");
-            m_statusLabel->setStyleSheet("color: #ff3b30; font-weight: bold;");
-        } else {
-            m_statusLabel->setText("待机");
-            m_statusLabel->setStyleSheet("color: #888; font-weight: normal;");
-        }
-    }
-}
-
-void RecorderAudioWidget::updateVolumeDisplay() {
-    if (!m_volumeSlider || !m_volumeValueLabel) {
-        return;
-    }
-    
-    QMutexLocker locker(&m_mutex);
-    int value = static_cast<int>(m_audioInfo.volume * 100);
-    locker.unlock();
-    
-    m_volumeChanging = true;
-    m_volumeSlider->setValue(value);
-    m_volumeValueLabel->setText(QString("%1%").arg(value));
-    m_volumeChanging = false;
-}
-
-void RecorderAudioWidget::updateMuteButton() {
-    if (!m_muteButton) {
-        return;
-    }
-    
-    QMutexLocker locker(&m_mutex);
-    bool muted = m_audioInfo.isMuted;
-    locker.unlock();
-    
-    m_muteButton->setChecked(muted);
-    m_muteButton->setText(muted ? "🔇" : "🔊");
-    m_muteButton->setToolTip(muted ? "取消静音" : "静音");
-    
-    // 更新音量滑块状态
-    if (m_volumeSlider) {
-        m_volumeSlider->setEnabled(!muted);
-    }
-}
-
-void RecorderAudioWidget::updateDeviceInfo() {
-    // 设备信息现在通过工具提示显示
-    QMutexLocker locker(&m_mutex);
-    QString infoText = formatAudioInfoText();
-    locker.unlock();
-    
-    if (m_deviceCombo) {
-        m_deviceCombo->setToolTip(infoText);
-    }
-}
-
-QString RecorderAudioWidget::formatAudioInfoText() const {
-    if (m_audioInfo.deviceName.isEmpty()) {
-        return "无音频设备";
-    }
-    
-    return QString("%1 | %2Hz %3ch %4bit")
-           .arg(m_audioInfo.deviceName)
-           .arg(m_audioInfo.sampleRate)
-           .arg(m_audioInfo.channels)
-           .arg(m_audioInfo.bitDepth);
-}

+ 0 - 320
AV/code/recorder/ui/recorder_audio_widget.h

@@ -1,320 +0,0 @@
-#ifndef AV_RECORDER_AUDIO_WIDGET_H
-#define AV_RECORDER_AUDIO_WIDGET_H
-
-#include <QWidget>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QProgressBar>
-#include <QLabel>
-#include <QPushButton>
-#include <QSlider>
-#include <QComboBox>
-#include <QTimer>
-#include <QMutex>
-#include <QPainter>
-#include <QStyleOption>
-#include <QPropertyAnimation>
-#include <QGraphicsOpacityEffect>
-#include <memory>
-
-/**
- * 音频电平显示组件
- * 
- * 显示实时音频电平,支持:
- * - 左右声道分别显示
- * - 峰值保持
- * - 过载指示
- * - 平滑动画
- */
-class AudioLevelWidget : public QWidget {
-    Q_OBJECT
-    Q_PROPERTY(double leftLevel READ leftLevel WRITE setLeftLevel)
-    Q_PROPERTY(double rightLevel READ rightLevel WRITE setRightLevel)
-
-public:
-    explicit AudioLevelWidget(QWidget* parent = nullptr);
-    ~AudioLevelWidget();
-
-    /**
-     * 设置音频电平 (0.0 - 1.0)
-     */
-    void setLeftLevel(double level);
-    void setRightLevel(double level);
-    void setLevels(double left, double right);
-    
-    /**
-     * 获取当前电平
-     */
-    double leftLevel() const { return m_leftLevel; }
-    double rightLevel() const { return m_rightLevel; }
-    
-    /**
-     * 设置峰值保持时间 (毫秒)
-     */
-    void setPeakHoldTime(int ms) { m_peakHoldTime = ms; }
-    
-    /**
-     * 设置过载阈值 (0.0 - 1.0)
-     */
-    void setOverloadThreshold(double threshold) { m_overloadThreshold = threshold; }
-    
-    /**
-     * 设置是否显示数值
-     */
-    void setShowValues(bool show) {
-        m_showValues = show;
-        update();
-    }
-    
-    /**
-     * 重置峰值
-     */
-    void resetPeaks();
-
-protected:
-    void paintEvent(QPaintEvent* event) override;
-    QSize sizeHint() const override;
-    QSize minimumSizeHint() const override;
-
-private slots:
-    void updatePeaks();
-
-private:
-    /**
-     * 绘制单个声道
-     */
-    void drawChannel(QPainter& painter, const QRect& rect, 
-                    double level, double peak, bool isLeft);
-    
-    /**
-     * 获取电平颜色
-     */
-    QColor getLevelColor(double level) const;
-
-private:
-    double m_leftLevel;
-    double m_rightLevel;
-    double m_leftPeak;
-    double m_rightPeak;
-    qint64 m_leftPeakTime;
-    qint64 m_rightPeakTime;
-    
-    int m_peakHoldTime;
-    double m_overloadThreshold;
-    bool m_showValues;
-    
-    QTimer* m_peakTimer;
-    mutable QMutex m_mutex;
-};
-
-/**
- * 录制器音频控制组件
- * 
- * 提供音频相关的控制界面,包括:
- * - 音量控制
- * - 静音开关
- * - 音频电平显示
- * - 音频设备选择
- * - 音频格式信息
- */
-class RecorderAudioWidget : public QWidget {
-    Q_OBJECT
-
-public:
-    /**
-     * 音频信息结构
-     */
-    struct AudioInfo {
-        QString deviceName;
-        int sampleRate = 44100;
-        int channels = 2;
-        int bitDepth = 16;
-        QString format;
-        bool isRecording = false;
-        bool isMuted = false;
-        double volume = 1.0;
-        
-        AudioInfo() = default;
-    };
-
-public:
-    explicit RecorderAudioWidget(QWidget* parent = nullptr);
-    ~RecorderAudioWidget();
-
-    /**
-     * 设置音频信息
-     */
-    void setAudioInfo(const AudioInfo& info);
-    
-    /**
-     * 获取音频信息
-     */
-    AudioInfo audioInfo() const { return m_audioInfo; }
-    
-    /**
-     * 设置音量 (0.0 - 1.0)
-     */
-    void setVolume(double volume);
-    
-    /**
-     * 获取音量
-     */
-    double volume() const { return m_audioInfo.volume; }
-    
-    /**
-     * 设置静音状态
-     */
-    void setMuted(bool muted);
-    
-    /**
-     * 获取静音状态
-     */
-    bool isMuted() const { return m_audioInfo.isMuted; }
-    
-    /**
-     * 设置录制状态
-     */
-    void setRecording(bool recording);
-    
-    /**
-     * 获取录制状态
-     */
-    bool isRecording() const { return m_audioInfo.isRecording; }
-    
-    /**
-     * 更新音频电平
-     */
-    void updateAudioLevels(double left, double right);
-    
-    /**
-     * 设置可用音频设备列表
-     */
-    void setAvailableDevices(const QStringList& devices);
-    
-    /**
-     * 设置当前音频设备
-     */
-    void setCurrentDevice(const QString& device);
-    
-    /**
-     * 获取当前音频设备
-     */
-    QString currentDevice() const;
-    
-    /**
-     * 设置是否显示高级控制
-     */
-    void setShowAdvancedControls(bool show);
-    
-    /**
-     * 重置音频电平峰值
-     */
-    void resetAudioPeaks();
-
-signals:
-    /**
-     * 音量改变信号
-     */
-    void volumeChanged(double volume);
-    
-    /**
-     * 静音状态改变信号
-     */
-    void mutedChanged(bool muted);
-    
-    /**
-     * 音频设备改变信号
-     */
-    void deviceChanged(const QString& device);
-    
-    /**
-     * 音频设置改变信号
-     */
-    void audioSettingsRequested();
-
-protected:
-    void paintEvent(QPaintEvent* event) override;
-
-private slots:
-    void onVolumeSliderChanged(int value);
-    void onMuteButtonClicked();
-    void onDeviceComboChanged(const QString& device);
-    void onSettingsButtonClicked();
-    void updateVolumeAnimation();
-
-private:
-    /**
-     * 初始化UI
-     */
-    void initializeUI();
-    
-    /**
-     * 连接信号槽
-     */
-    void connectSignals();
-    
-    /**
-     * 更新UI状态
-     */
-    void updateUI();
-    
-    /**
-     * 更新音量显示
-     */
-    void updateVolumeDisplay();
-    
-    /**
-     * 更新静音按钮
-     */
-    void updateMuteButton();
-    
-    /**
-     * 更新设备信息
-     */
-    void updateDeviceInfo();
-    
-    /**
-     * 格式化音频信息文本
-     */
-    QString formatAudioInfoText() const;
-
-private:
-    // UI组件
-    QVBoxLayout* m_mainLayout;
-    QHBoxLayout* m_controlLayout;
-    QHBoxLayout* m_deviceLayout;
-    QHBoxLayout* m_infoLayout;
-    
-    // 音量控制
-    QLabel* m_volumeLabel;
-    QSlider* m_volumeSlider;
-    QLabel* m_volumeValueLabel;
-    QPushButton* m_muteButton;
-    
-    // 音频电平
-    AudioLevelWidget* m_levelWidget;
-    
-    // 设备选择
-    QLabel* m_deviceLabel;
-    QComboBox* m_deviceCombo;
-    QPushButton* m_settingsButton;
-    
-    // 信息显示
-    QLabel* m_statusLabel;
-    
-    // 数据
-    AudioInfo m_audioInfo;
-    
-    // 动画
-    QPropertyAnimation* m_volumeAnimation;
-    QGraphicsOpacityEffect* m_levelOpacityEffect;
-    
-    // 状态
-    bool m_showAdvancedControls;
-    bool m_volumeChanging;
-    
-    // 线程安全
-    mutable QMutex m_mutex;
-};
-
-#endif // AV_RECORDER_AUDIO_WIDGET_H

+ 0 - 866
AV/code/recorder/ui/recorder_example_app.cpp

@@ -1,866 +0,0 @@
-#include "recorder_example_app.h"
-#include <QApplication>
-#include <QDesktopWidget>
-#include <QScreen>
-#include <QStandardPaths>
-#include <QDir>
-#include <QDateTime>
-#include <QKeySequence>
-#include <QShortcut>
-#include <QStorageInfo>
-#include <QDebug>
-
-RecorderExampleApp::RecorderExampleApp(QWidget* parent)
-    : QMainWindow(parent)
-    , m_recorderWidget(nullptr)
-    , m_centralWidget(nullptr)
-    , m_mainLayout(nullptr)
-    , m_mainSplitter(nullptr)
-    , m_menuBar(nullptr)
-    , m_fileMenu(nullptr)
-    , m_recordMenu(nullptr)
-    , m_viewMenu(nullptr)
-    , m_helpMenu(nullptr)
-    , m_mainToolBar(nullptr)
-    , m_recordToolBar(nullptr)
-    , m_statusBar(nullptr)
-    , m_statusLabel(nullptr)
-    , m_recordingTimeLabel(nullptr)
-    , m_fileSizeLabel(nullptr)
-    , m_bitrateLabel(nullptr)
-    , m_diskSpaceLabel(nullptr)
-    , m_recordingProgress(nullptr)
-    , m_trayIcon(nullptr)
-    , m_trayMenu(nullptr)
-    , m_showHideAction(nullptr)
-    , m_trayExitAction(nullptr)
-    , m_statusUpdateTimer(nullptr)
-    , m_recordingTimer(nullptr)
-    , m_diskSpaceTimer(nullptr)
-    , m_isRecording(false)
-    , m_isPaused(false)
-    , m_isPreviewActive(false)
-    , m_recordingStartTime(0)
-    , m_recordingDuration(0)
-    , m_settings(nullptr)
-    , m_minimizeToTray(true)
-    , m_closeToTray(true)
-    , m_autoStartPreview(false)
-    , m_showRecordingTime(true)
-    , m_showFileSize(true)
-    , m_showBitrate(true)
-    , m_showDiskSpace(true) {
-    
-    setWindowTitle("AV录制器示例应用");
-    setWindowIcon(QIcon(":/icons/recorder.png"));
-    resize(1200, 800);
-    
-    // 居中显示
-    QScreen* screen = QApplication::primaryScreen();
-    if (screen) {
-        QRect screenGeometry = screen->availableGeometry();
-        int x = (screenGeometry.width() - width()) / 2;
-        int y = (screenGeometry.height() - height()) / 2;
-        move(x, y);
-    }
-    
-    // 初始化设置
-    m_settings = new QSettings("AV", "RecorderExample", this);
-    
-    // RecorderModule已移除,现在使用RecorderMainWidget内部的录制器
-    
-    // 初始化UI
-    initializeUI();
-    connectSignals();
-    setupShortcuts();
-    
-    // 加载设置
-    loadSettings();
-    
-    // 初始化定时器
-    m_statusUpdateTimer = new QTimer(this);
-    m_statusUpdateTimer->setInterval(1000); // 每秒更新一次
-    connect(m_statusUpdateTimer, &QTimer::timeout, this, &RecorderExampleApp::updateStatusBar);
-    m_statusUpdateTimer->start();
-    
-    m_recordingTimer = new QTimer(this);
-    m_recordingTimer->setInterval(1000); // 每秒更新一次
-    connect(m_recordingTimer, &QTimer::timeout, this, &RecorderExampleApp::updateRecordingTime);
-    
-    m_diskSpaceTimer = new QTimer(this);
-    m_diskSpaceTimer->setInterval(30000); // 每30秒检查一次磁盘空间
-    connect(m_diskSpaceTimer, &QTimer::timeout, this, &RecorderExampleApp::checkDiskSpace);
-    m_diskSpaceTimer->start();
-    
-    // 创建系统托盘
-    if (QSystemTrayIcon::isSystemTrayAvailable()) {
-        createSystemTray();
-    }
-    
-    // 初始化UI状态
-    updateUI();
-    
-    // 自动开始预览
-    if (m_autoStartPreview) {
-        QTimer::singleShot(1000, this, &RecorderExampleApp::onStartPreview);
-    }
-}
-
-RecorderExampleApp::~RecorderExampleApp() {
-    saveSettings();
-    
-    // RecorderModule清理代码已移除
-}
-
-void RecorderExampleApp::closeEvent(QCloseEvent* event) {
-    if (m_closeToTray && m_trayIcon && m_trayIcon->isVisible()) {
-        hide();
-        showMessage("录制器", "应用程序已最小化到系统托盘", QSystemTrayIcon::Information);
-        event->ignore();
-    } else {
-        if (confirmExit()) {
-            saveSettings();
-            event->accept();
-        } else {
-            event->ignore();
-        }
-    }
-}
-
-void RecorderExampleApp::changeEvent(QEvent* event) {
-    QMainWindow::changeEvent(event);
-    
-    if (event->type() == QEvent::WindowStateChange) {
-        if (isMinimized() && m_minimizeToTray && m_trayIcon && m_trayIcon->isVisible()) {
-            hide();
-            event->ignore();
-        }
-    }
-}
-
-bool RecorderExampleApp::eventFilter(QObject* obj, QEvent* event) {
-    Q_UNUSED(obj)
-    Q_UNUSED(event)
-    return QMainWindow::eventFilter(obj, event);
-}
-
-void RecorderExampleApp::onNewRecording() {
-    if (m_isRecording) {
-        int ret = QMessageBox::question(this, "新建录制", 
-                                       "当前正在录制,是否停止当前录制并开始新的录制?",
-                                       QMessageBox::Yes | QMessageBox::No,
-                                       QMessageBox::No);
-        if (ret == QMessageBox::Yes) {
-            onStopRecording();
-        } else {
-            return;
-        }
-    }
-    
-    // 重置状态
-    m_currentRecordingFile.clear();
-    m_recordingDuration = 0;
-    updateWindowTitle();
-    updateUI();
-}
-
-void RecorderExampleApp::onOpenRecording() {
-    QString fileName = QFileDialog::getOpenFileName(this, "打开录制文件", 
-                                                   QStandardPaths::writableLocation(QStandardPaths::MoviesLocation),
-                                                   "视频文件 (*.mp4 *.avi *.mkv *.mov);;所有文件 (*.*)");
-    
-    if (!fileName.isEmpty()) {
-        // TODO: 实现播放录制文件的功能
-        QMessageBox::information(this, "打开录制文件", 
-                                 QString("将打开文件: %1\n\n此功能待实现").arg(fileName));
-    }
-}
-
-void RecorderExampleApp::onSaveRecording() {
-    if (m_currentRecordingFile.isEmpty()) {
-        QMessageBox::information(this, "保存录制", "当前没有录制文件");
-        return;
-    }
-    
-    QString fileName = QFileDialog::getSaveFileName(this, "保存录制文件", 
-                                                   m_currentRecordingFile,
-                                                   "视频文件 (*.mp4 *.avi *.mkv *.mov);;所有文件 (*.*)");
-    
-    if (!fileName.isEmpty() && fileName != m_currentRecordingFile) {
-        // TODO: 实现文件复制或移动
-        QMessageBox::information(this, "保存录制文件", 
-                                 QString("将保存到: %1\n\n此功能待实现").arg(fileName));
-    }
-}
-
-void RecorderExampleApp::onExportRecording() {
-    if (m_currentRecordingFile.isEmpty()) {
-        QMessageBox::information(this, "导出录制", "当前没有录制文件");
-        return;
-    }
-    
-    // TODO: 实现录制文件导出功能
-    QMessageBox::information(this, "导出录制文件", "导出功能待实现");
-}
-
-void RecorderExampleApp::onSettings() {
-    if (m_recorderWidget) {
-        m_recorderWidget->openSettings();
-    }
-}
-
-void RecorderExampleApp::onAbout() {
-    QMessageBox::about(this, "关于 AV录制器", 
-                      "<h3>AV录制器示例应用</h3>"
-                      "<p>版本: 1.0.0</p>"
-                      "<p>这是一个基于重构后的AV录制器模块的示例应用程序。</p>"
-                      "<p>功能特性:</p>"
-                      "<ul>"
-                      "<li>音频录制</li>"
-                      "<li>视频录制</li>"
-                      "<li>音视频同步录制</li>"
-                      "<li>实时预览</li>"
-                      "<li>硬件加速</li>"
-                      "<li>多种编码格式支持</li>"
-                      "</ul>"
-                      "<p>© 2024 AV录制器团队</p>");
-}
-
-void RecorderExampleApp::onExit() {
-    if (confirmExit()) {
-        QApplication::quit();
-    }
-}
-
-void RecorderExampleApp::onStartRecording() {
-    if (m_recorderWidget) {
-        m_recorderWidget->startRecording();
-    }
-}
-
-void RecorderExampleApp::onStopRecording() {
-    if (m_recorderWidget) {
-        m_recorderWidget->stopRecording();
-    }
-}
-
-void RecorderExampleApp::onPauseRecording() {
-    if (m_recorderWidget) {
-        m_recorderWidget->pauseRecording();
-    }
-}
-
-void RecorderExampleApp::onResumeRecording() {
-    if (m_recorderWidget) {
-        m_recorderWidget->resumeRecording();
-    }
-}
-
-void RecorderExampleApp::onStartPreview() {
-    if (m_recorderWidget) {
-        m_recorderWidget->startPreview();
-    }
-}
-
-void RecorderExampleApp::onStopPreview() {
-    if (m_recorderWidget) {
-        m_recorderWidget->stopPreview();
-    }
-}
-
-void RecorderExampleApp::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) {
-    switch (reason) {
-    case QSystemTrayIcon::Trigger:
-    case QSystemTrayIcon::DoubleClick:
-        onShowHide();
-        break;
-    default:
-        break;
-    }
-}
-
-void RecorderExampleApp::onShowHide() {
-    if (isVisible()) {
-        hide();
-    } else {
-        show();
-        raise();
-        activateWindow();
-    }
-}
-
-// 录制器状态变化处理函数已移除
-// 现在应该连接到RecorderMainWidget的相应信号
-
-// 录制器错误和统计信息处理函数已移除
-// 现在应该连接到RecorderMainWidget的相应信号
-
-void RecorderExampleApp::updateStatusBar() {
-    if (!m_statusBar) return;
-    
-    // 更新状态标签
-    if (m_statusLabel) {
-        QString status;
-        if (m_isRecording) {
-            status = m_isPaused ? "录制已暂停" : "正在录制";
-        } else if (m_isPreviewActive) {
-            status = "预览中";
-        } else {
-            status = "就绪";
-        }
-        m_statusLabel->setText(status);
-    }
-    
-    // 更新磁盘空间
-    if (m_diskSpaceLabel && m_showDiskSpace) {
-        checkDiskSpace();
-    }
-}
-
-void RecorderExampleApp::updateRecordingTime() {
-    if (!m_isRecording || m_isPaused) return;
-    
-    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
-    m_recordingDuration = (currentTime - m_recordingStartTime) / 1000;
-    
-    if (m_recordingTimeLabel && m_showRecordingTime) {
-        m_recordingTimeLabel->setText(QString("录制时间: %1").arg(formatTime(m_recordingDuration)));
-    }
-    
-    // 更新进度条(如果设置了最大录制时长)
-    if (m_recordingProgress) {
-        // TODO: 根据设置的最大录制时长更新进度
-    }
-}
-
-void RecorderExampleApp::checkDiskSpace() {
-    if (!m_diskSpaceLabel || !m_showDiskSpace) return;
-    
-    QString outputDir = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
-    QStorageInfo storage(outputDir);
-    
-    if (storage.isValid()) {
-        qint64 availableBytes = storage.bytesAvailable();
-        QString diskSpace = QString("可用空间: %1").arg(formatFileSize(availableBytes));
-        m_diskSpaceLabel->setText(diskSpace);
-        
-        // 检查磁盘空间是否不足(小于1GB)
-        if (availableBytes < 1024 * 1024 * 1024) {
-            m_diskSpaceLabel->setStyleSheet("color: red;");
-            if (m_isRecording) {
-                showMessage("磁盘空间不足", "可用磁盘空间不足1GB,建议停止录制", QSystemTrayIcon::Warning);
-            }
-        } else {
-            m_diskSpaceLabel->setStyleSheet("");
-        }
-    }
-}
-
-void RecorderExampleApp::initializeUI() {
-    // 创建中央部件
-    m_centralWidget = new QWidget();
-    setCentralWidget(m_centralWidget);
-    
-    // 创建主布局
-    m_mainLayout = new QVBoxLayout(m_centralWidget);
-    m_mainLayout->setContentsMargins(4, 4, 4, 4);
-    m_mainLayout->setSpacing(4);
-    
-    // 创建录制器主部件
-    m_recorderWidget = new RecorderMainWidget(this);
-    
-    // 初始化录制器主部件
-    if (!m_recorderWidget->initialize()) {
-        QMessageBox::critical(this, "错误", "初始化录制器失败");
-        // 可以选择退出应用或者禁用录制功能
-    }
-    
-    // 添加到布局
-    m_mainLayout->addWidget(m_recorderWidget);
-    
-    // 创建菜单栏
-    createMenuBar();
-    
-    // 创建工具栏
-    createToolBar();
-    
-    // 创建状态栏
-    createStatusBar();
-    
-    // 设置样式
-    // setStyleSheet(R"(
-    //     QMainWindow {
-    //         background-color: #2b2b2b;
-    //         color: #fff;
-    //     }
-    //     QMenuBar {
-    //         background-color: #333;
-    //         color: #fff;
-    //         border-bottom: 1px solid #555;
-    //     }
-    //     QMenuBar::item {
-    //         background-color: transparent;
-    //         padding: 4px 8px;
-    //     }
-    //     QMenuBar::item:selected {
-    //         background-color: #0a84ff;
-    //     }
-    //     QMenu {
-    //         background-color: #333;
-    //         color: #fff;
-    //         border: 1px solid #555;
-    //     }
-    //     QMenu::item {
-    //         padding: 4px 20px;
-    //     }
-    //     QMenu::item:selected {
-    //         background-color: #0a84ff;
-    //     }
-    //     QToolBar {
-    //         background-color: #333;
-    //         border: 1px solid #555;
-    //         spacing: 2px;
-    //     }
-    //     QToolButton {
-    //         background-color: #444;
-    //         border: 1px solid #666;
-    //         border-radius: 3px;
-    //         color: #fff;
-    //         padding: 4px;
-    //     }
-    //     QToolButton:hover {
-    //         background-color: #555;
-    //     }
-    //     QToolButton:pressed {
-    //         background-color: #333;
-    //     }
-    //     QStatusBar {
-    //         background-color: #333;
-    //         color: #fff;
-    //         border-top: 1px solid #555;
-    //     }
-    //     QLabel {
-    //         color: #fff;
-    //     }
-    //     QProgressBar {
-    //         border: 1px solid #555;
-    //         border-radius: 3px;
-    //         background-color: #444;
-    //         text-align: center;
-    //     }
-    //     QProgressBar::chunk {
-    //         background-color: #0a84ff;
-    //         border-radius: 2px;
-    //     }
-    // )");
-}
-
-void RecorderExampleApp::createMenuBar() {
-    m_menuBar = menuBar();
-    
-    // 文件菜单
-    m_fileMenu = m_menuBar->addMenu("文件(&F)");
-    
-    m_newAction = new QAction(QIcon(":/icons/new.png"), "新建录制(&N)", this);
-    m_newAction->setShortcut(QKeySequence::New);
-    m_newAction->setStatusTip("开始新的录制");
-    
-    m_openAction = new QAction(QIcon(":/icons/open.png"), "打开录制(&O)", this);
-    m_openAction->setShortcut(QKeySequence::Open);
-    m_openAction->setStatusTip("打开录制文件");
-    
-    m_saveAction = new QAction(QIcon(":/icons/save.png"), "保存录制(&S)", this);
-    m_saveAction->setShortcut(QKeySequence::Save);
-    m_saveAction->setStatusTip("保存当前录制");
-    
-    m_exportAction = new QAction(QIcon(":/icons/export.png"), "导出录制(&E)", this);
-    m_exportAction->setStatusTip("导出录制文件");
-    
-    m_fileMenu->addAction(m_newAction);
-    m_fileMenu->addSeparator();
-    m_fileMenu->addAction(m_openAction);
-    m_fileMenu->addAction(m_saveAction);
-    m_fileMenu->addAction(m_exportAction);
-    m_fileMenu->addSeparator();
-    
-    m_settingsAction = new QAction(QIcon(":/icons/settings.png"), "设置(&T)", this);
-    m_settingsAction->setShortcut(QKeySequence::Preferences);
-    m_settingsAction->setStatusTip("打开设置对话框");
-    m_fileMenu->addAction(m_settingsAction);
-    
-    m_fileMenu->addSeparator();
-    
-    m_exitAction = new QAction(QIcon(":/icons/exit.png"), "退出(&X)", this);
-    m_exitAction->setShortcut(QKeySequence::Quit);
-    m_exitAction->setStatusTip("退出应用程序");
-    m_fileMenu->addAction(m_exitAction);
-    
-    // 录制菜单
-    m_recordMenu = m_menuBar->addMenu("录制(&R)");
-    
-    m_startRecordingAction = new QAction(QIcon(":/icons/record.png"), "开始录制(&S)", this);
-    m_startRecordingAction->setShortcut(QKeySequence("F9"));
-    m_startRecordingAction->setStatusTip("开始录制");
-    
-    m_stopRecordingAction = new QAction(QIcon(":/icons/stop.png"), "停止录制(&T)", this);
-    m_stopRecordingAction->setShortcut(QKeySequence("F10"));
-    m_stopRecordingAction->setStatusTip("停止录制");
-    m_stopRecordingAction->setEnabled(false);
-    
-    m_pauseRecordingAction = new QAction(QIcon(":/icons/pause.png"), "暂停录制(&P)", this);
-    m_pauseRecordingAction->setShortcut(QKeySequence("F11"));
-    m_pauseRecordingAction->setStatusTip("暂停录制");
-    m_pauseRecordingAction->setEnabled(false);
-    
-    m_resumeRecordingAction = new QAction(QIcon(":/icons/resume.png"), "恢复录制(&R)", this);
-    m_resumeRecordingAction->setShortcut(QKeySequence("F12"));
-    m_resumeRecordingAction->setStatusTip("恢复录制");
-    m_resumeRecordingAction->setEnabled(false);
-    
-    m_recordMenu->addAction(m_startRecordingAction);
-    m_recordMenu->addAction(m_stopRecordingAction);
-    m_recordMenu->addSeparator();
-    m_recordMenu->addAction(m_pauseRecordingAction);
-    m_recordMenu->addAction(m_resumeRecordingAction);
-    m_recordMenu->addSeparator();
-    
-    m_startPreviewAction = new QAction(QIcon(":/icons/preview.png"), "开始预览(&V)", this);
-    m_startPreviewAction->setStatusTip("开始视频预览");
-    
-    m_stopPreviewAction = new QAction(QIcon(":/icons/stop_preview.png"), "停止预览(&W)", this);
-    m_stopPreviewAction->setStatusTip("停止视频预览");
-    m_stopPreviewAction->setEnabled(false);
-    
-    m_recordMenu->addAction(m_startPreviewAction);
-    m_recordMenu->addAction(m_stopPreviewAction);
-    
-    // 视图菜单
-    m_viewMenu = m_menuBar->addMenu("视图(&V)");
-    
-    // 自动启动预览选项
-    QAction* autoPreviewAction = new QAction("自动启动预览(&P)", this);
-    autoPreviewAction->setCheckable(true);
-    autoPreviewAction->setChecked(m_autoStartPreview);
-    connect(autoPreviewAction, &QAction::toggled, this, [this](bool checked) {
-        m_autoStartPreview = checked;
-        m_settings->setValue("autoStartPreview", m_autoStartPreview);
-    });
-    m_viewMenu->addAction(autoPreviewAction);
-    
-    // 帮助菜单
-    m_helpMenu = m_menuBar->addMenu("帮助(&H)");
-    
-    m_aboutAction = new QAction(QIcon(":/icons/about.png"), "关于(&A)", this);
-    m_aboutAction->setStatusTip("关于此应用程序");
-    
-    m_aboutQtAction = new QAction("关于Qt(&Q)", this);
-    m_aboutQtAction->setStatusTip("关于Qt框架");
-    
-    m_helpMenu->addAction(m_aboutAction);
-    m_helpMenu->addAction(m_aboutQtAction);
-}
-
-void RecorderExampleApp::createToolBar() {
-    // 主工具栏
-    m_mainToolBar = addToolBar("主工具栏");
-    m_mainToolBar->setObjectName("MainToolBar");
-    m_mainToolBar->addAction(m_newAction);
-    m_mainToolBar->addAction(m_openAction);
-    m_mainToolBar->addAction(m_saveAction);
-    m_mainToolBar->addSeparator();
-    m_mainToolBar->addAction(m_settingsAction);
-    
-    // 录制工具栏
-    m_recordToolBar = addToolBar("录制工具栏");
-    m_recordToolBar->setObjectName("RecordToolBar");
-    m_recordToolBar->addAction(m_startRecordingAction);
-    m_recordToolBar->addAction(m_stopRecordingAction);
-    m_recordToolBar->addAction(m_pauseRecordingAction);
-    m_recordToolBar->addAction(m_resumeRecordingAction);
-    m_recordToolBar->addSeparator();
-    m_recordToolBar->addAction(m_startPreviewAction);
-    m_recordToolBar->addAction(m_stopPreviewAction);
-}
-
-void RecorderExampleApp::createStatusBar() {
-    m_statusBar = statusBar();
-    
-    // 状态标签
-    m_statusLabel = new QLabel("就绪");
-    m_statusBar->addWidget(m_statusLabel);
-    
-    m_statusBar->addPermanentWidget(new QLabel("|"));
-    
-    // 录制时间
-    if (m_showRecordingTime) {
-        m_recordingTimeLabel = new QLabel("录制时间: 00:00:00");
-        m_statusBar->addPermanentWidget(m_recordingTimeLabel);
-        m_statusBar->addPermanentWidget(new QLabel("|"));
-    }
-    
-    // 文件大小
-    if (m_showFileSize) {
-        m_fileSizeLabel = new QLabel("文件大小: 0 MB");
-        m_statusBar->addPermanentWidget(m_fileSizeLabel);
-        m_statusBar->addPermanentWidget(new QLabel("|"));
-    }
-    
-    // 比特率
-    if (m_showBitrate) {
-        m_bitrateLabel = new QLabel("比特率: 0 kbps");
-        m_statusBar->addPermanentWidget(m_bitrateLabel);
-        m_statusBar->addPermanentWidget(new QLabel("|"));
-    }
-    
-    // 磁盘空间
-    if (m_showDiskSpace) {
-        m_diskSpaceLabel = new QLabel("可用空间: 检查中...");
-        m_statusBar->addPermanentWidget(m_diskSpaceLabel);
-    }
-    
-    // 录制进度条
-    m_recordingProgress = new QProgressBar();
-    m_recordingProgress->setVisible(false);
-    m_recordingProgress->setMaximumWidth(200);
-    m_statusBar->addPermanentWidget(m_recordingProgress);
-}
-
-void RecorderExampleApp::createSystemTray() {
-    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
-        return;
-    }
-    
-    // 创建托盘图标
-    m_trayIcon = new QSystemTrayIcon(this);
-    m_trayIcon->setIcon(QIcon(":/icons/recorder.png"));
-    m_trayIcon->setToolTip("AV录制器");
-    
-    // 创建托盘菜单
-    m_trayMenu = new QMenu(this);
-    
-    m_showHideAction = new QAction("显示/隐藏", this);
-    m_trayMenu->addAction(m_showHideAction);
-    m_trayMenu->addSeparator();
-    
-    m_trayMenu->addAction(m_startRecordingAction);
-    m_trayMenu->addAction(m_stopRecordingAction);
-    m_trayMenu->addSeparator();
-    
-    m_trayExitAction = new QAction("退出", this);
-    m_trayMenu->addAction(m_trayExitAction);
-    
-    m_trayIcon->setContextMenu(m_trayMenu);
-    m_trayIcon->show();
-}
-
-void RecorderExampleApp::setupShortcuts() {
-    // 全局快捷键
-    QShortcut* quickRecordShortcut = new QShortcut(QKeySequence("Ctrl+Shift+R"), this);
-    connect(quickRecordShortcut, &QShortcut::activated, [this]() {
-        if (m_isRecording) {
-            onStopRecording();
-        } else {
-            onStartRecording();
-        }
-    });
-    
-    QShortcut* quickPreviewShortcut = new QShortcut(QKeySequence("Ctrl+Shift+P"), this);
-    connect(quickPreviewShortcut, &QShortcut::activated, [this]() {
-        if (m_isPreviewActive) {
-            onStopPreview();
-        } else {
-            onStartPreview();
-        }
-    });
-}
-
-void RecorderExampleApp::connectSignals() {
-    // 菜单和工具栏信号
-    connect(m_newAction, &QAction::triggered, this, &RecorderExampleApp::onNewRecording);
-    connect(m_openAction, &QAction::triggered, this, &RecorderExampleApp::onOpenRecording);
-    connect(m_saveAction, &QAction::triggered, this, &RecorderExampleApp::onSaveRecording);
-    connect(m_exportAction, &QAction::triggered, this, &RecorderExampleApp::onExportRecording);
-    connect(m_settingsAction, &QAction::triggered, this, &RecorderExampleApp::onSettings);
-    connect(m_exitAction, &QAction::triggered, this, &RecorderExampleApp::onExit);
-    
-    connect(m_startRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onStartRecording);
-    connect(m_stopRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onStopRecording);
-    connect(m_pauseRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onPauseRecording);
-    connect(m_resumeRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onResumeRecording);
-    connect(m_startPreviewAction, &QAction::triggered, this, &RecorderExampleApp::onStartPreview);
-    connect(m_stopPreviewAction, &QAction::triggered, this, &RecorderExampleApp::onStopPreview);
-    
-    connect(m_aboutAction, &QAction::triggered, this, &RecorderExampleApp::onAbout);
-    connect(m_aboutQtAction, &QAction::triggered, qApp, &QApplication::aboutQt);
-    
-    // 系统托盘信号
-    if (m_trayIcon) {
-        connect(m_trayIcon, &QSystemTrayIcon::activated, this, &RecorderExampleApp::onTrayIconActivated);
-    }
-    if (m_showHideAction) {
-        connect(m_showHideAction, &QAction::triggered, this, &RecorderExampleApp::onShowHide);
-    }
-    if (m_trayExitAction) {
-        connect(m_trayExitAction, &QAction::triggered, this, &RecorderExampleApp::onExit);
-    }
-    
-    // 录制器主部件信号
-    if (m_recorderWidget) {
-        // TODO: 连接RecorderMainWidget的信号
-        // connect(m_recorderWidget, &RecorderMainWidget::someSignal, 
-        //         this, &RecorderExampleApp::someSlot);
-    }
-}
-
-void RecorderExampleApp::loadSettings() {
-    // 窗口设置
-    restoreGeometry(m_settings->value("geometry").toByteArray());
-    restoreState(m_settings->value("windowState").toByteArray());
-    
-    // 应用设置
-    m_minimizeToTray = m_settings->value("minimizeToTray", true).toBool();
-    m_closeToTray = m_settings->value("closeToTray", true).toBool();
-    m_autoStartPreview = m_settings->value("autoStartPreview", true).toBool();
-    
-    // 状态栏设置
-    m_showRecordingTime = m_settings->value("showRecordingTime", true).toBool();
-    m_showFileSize = m_settings->value("showFileSize", true).toBool();
-    m_showBitrate = m_settings->value("showBitrate", true).toBool();
-    m_showDiskSpace = m_settings->value("showDiskSpace", true).toBool();
-}
-
-void RecorderExampleApp::saveSettings() {
-    // 窗口设置
-    m_settings->setValue("geometry", saveGeometry());
-    m_settings->setValue("windowState", saveState());
-    
-    // 应用设置
-    m_settings->setValue("minimizeToTray", m_minimizeToTray);
-    m_settings->setValue("closeToTray", m_closeToTray);
-    m_settings->setValue("autoStartPreview", m_autoStartPreview);
-    
-    // 状态栏设置
-    m_settings->setValue("showRecordingTime", m_showRecordingTime);
-    m_settings->setValue("showFileSize", m_showFileSize);
-    m_settings->setValue("showBitrate", m_showBitrate);
-    m_settings->setValue("showDiskSpace", m_showDiskSpace);
-    
-    m_settings->sync();
-}
-
-void RecorderExampleApp::updateUI() {
-    // 更新动作状态
-    updateActions();
-    
-    // 更新窗口标题
-    updateWindowTitle();
-}
-
-void RecorderExampleApp::updateActions() {
-    // 录制相关动作
-    m_startRecordingAction->setEnabled(!m_isRecording);
-    m_stopRecordingAction->setEnabled(m_isRecording);
-    m_pauseRecordingAction->setEnabled(m_isRecording && !m_isPaused);
-    m_resumeRecordingAction->setEnabled(m_isRecording && m_isPaused);
-    
-    // 预览相关动作
-    m_startPreviewAction->setEnabled(!m_isPreviewActive);
-    m_stopPreviewAction->setEnabled(m_isPreviewActive);
-    
-    // 文件相关动作
-    m_saveAction->setEnabled(!m_currentRecordingFile.isEmpty());
-    m_exportAction->setEnabled(!m_currentRecordingFile.isEmpty());
-}
-
-void RecorderExampleApp::updateWindowTitle() {
-    QString title = "AV录制器示例应用";
-    
-    if (m_isRecording) {
-        if (m_isPaused) {
-            title += " - 录制已暂停";
-        } else {
-            title += " - 正在录制";
-        }
-        
-        if (m_recordingDuration > 0) {
-            title += QString(" (%1)").arg(formatTime(m_recordingDuration));
-        }
-    } else if (m_isPreviewActive) {
-        title += " - 预览中";
-    }
-    
-    if (!m_currentRecordingFile.isEmpty()) {
-        QFileInfo fileInfo(m_currentRecordingFile);
-        title += QString(" - %1").arg(fileInfo.fileName());
-    }
-    
-    setWindowTitle(title);
-}
-
-QString RecorderExampleApp::formatTime(qint64 seconds) const {
-    int hours = seconds / 3600;
-    int minutes = (seconds % 3600) / 60;
-    int secs = seconds % 60;
-    
-    return QString("%1:%2:%3")
-           .arg(hours, 2, 10, QChar('0'))
-           .arg(minutes, 2, 10, QChar('0'))
-           .arg(secs, 2, 10, QChar('0'));
-}
-
-QString RecorderExampleApp::formatFileSize(qint64 bytes) const {
-    const qint64 KB = 1024;
-    const qint64 MB = KB * 1024;
-    const qint64 GB = MB * 1024;
-    const qint64 TB = GB * 1024;
-    
-    if (bytes >= TB) {
-        return QString("%1 TB").arg(static_cast<double>(bytes) / TB, 0, 'f', 2);
-    } else if (bytes >= GB) {
-        return QString("%1 GB").arg(static_cast<double>(bytes) / GB, 0, 'f', 2);
-    } else if (bytes >= MB) {
-        return QString("%1 MB").arg(static_cast<double>(bytes) / MB, 0, 'f', 2);
-    } else if (bytes >= KB) {
-        return QString("%1 KB").arg(static_cast<double>(bytes) / KB, 0, 'f', 2);
-    } else {
-        return QString("%1 B").arg(bytes);
-    }
-}
-
-QString RecorderExampleApp::formatBitrate(qint64 bps) const {
-    const qint64 Kbps = 1000;
-    const qint64 Mbps = Kbps * 1000;
-    
-    if (bps >= Mbps) {
-        return QString("%1 Mbps").arg(static_cast<double>(bps) / Mbps, 0, 'f', 2);
-    } else if (bps >= Kbps) {
-        return QString("%1 kbps").arg(static_cast<double>(bps) / Kbps, 0, 'f', 1);
-    } else {
-        return QString("%1 bps").arg(bps);
-    }
-}
-
-bool RecorderExampleApp::confirmExit() {
-    if (m_isRecording) {
-        int ret = QMessageBox::question(this, "确认退出", 
-                                       "当前正在录制,确定要退出吗?\n录制将被停止。",
-                                       QMessageBox::Yes | QMessageBox::No,
-                                       QMessageBox::No);
-        
-        if (ret == QMessageBox::Yes) {
-            onStopRecording();
-            return true;
-        } else {
-            return false;
-        }
-    }
-    
-    return true;
-}
-
-void RecorderExampleApp::showMessage(const QString& title, const QString& message, 
-                                    QSystemTrayIcon::MessageIcon icon) {
-    if (m_trayIcon && m_trayIcon->isVisible()) {
-        m_trayIcon->showMessage(title, message, icon, 3000);
-    }
-}

+ 0 - 195
AV/code/recorder/ui/recorder_example_app.h

@@ -1,195 +0,0 @@
-#ifndef RECORDER_EXAMPLE_APP_H
-#define RECORDER_EXAMPLE_APP_H
-
-#include <QMainWindow>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QGridLayout>
-#include <QPushButton>
-#include <QLabel>
-#include <QComboBox>
-#include <QSlider>
-#include <QProgressBar>
-#include <QTextEdit>
-#include <QGroupBox>
-#include <QSplitter>
-#include <QTimer>
-#include <QStatusBar>
-#include <QMenuBar>
-#include <QToolBar>
-#include <QAction>
-#include <QFileDialog>
-#include <QMessageBox>
-#include <QSettings>
-#include <QCloseEvent>
-#include <QSystemTrayIcon>
-#include <QMenu>
-
-#include "recorder_main_widget.h"
-#include "../recorder.h"
-
-QT_BEGIN_NAMESPACE
-class QAction;
-class QMenu;
-class QSystemTrayIcon;
-QT_END_NAMESPACE
-
-/**
- * @brief 录制器示例应用程序
- * 
- * 这是一个完整的录制器应用程序示例,展示了如何使用重构后的录制器模块。
- * 提供了完整的用户界面和功能,包括:
- * - 录制控制(开始/停止/暂停/恢复)
- * - 实时预览
- * - 音频控制和电平显示
- * - 设置管理
- * - 状态监控
- * - 系统托盘支持
- * - 快捷键支持
- */
-class RecorderExampleApp : public QMainWindow {
-    Q_OBJECT
-
-public:
-    explicit RecorderExampleApp(QWidget* parent = nullptr);
-    ~RecorderExampleApp();
-
-protected:
-    void closeEvent(QCloseEvent* event) override;
-    void changeEvent(QEvent* event) override;
-    bool eventFilter(QObject* obj, QEvent* event) override;
-
-private slots:
-    // 菜单和工具栏操作
-    void onNewRecording();
-    void onOpenRecording();
-    void onSaveRecording();
-    void onExportRecording();
-    void onSettings();
-    void onAbout();
-    void onExit();
-    
-    // 录制控制
-    void onStartRecording();
-    void onStopRecording();
-    void onPauseRecording();
-    void onResumeRecording();
-    void onStartPreview();
-    void onStopPreview();
-    
-    // 系统托盘
-    void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason);
-    void onShowHide();
-    
-    // 录制器状态 (暂时保留,可能需要连接到RecorderMainWidget的信号)
-    // void onRecorderStateChanged(RecorderState state);
-    // void onRecorderError(const QString& error);
-    // void onRecorderStatisticsUpdated(const Statistics& stats);
-    
-    // 定时器
-    void updateStatusBar();
-    void updateRecordingTime();
-    void checkDiskSpace();
-    
-private:
-    void initializeUI();
-    void createMenuBar();
-    void createToolBar();
-    void createStatusBar();
-    void createSystemTray();
-    void setupShortcuts();
-    void connectSignals();
-    
-    void loadSettings();
-    void saveSettings();
-    
-    void updateUI();
-    void updateActions();
-    void updateWindowTitle();
-    
-    QString formatTime(qint64 seconds) const;
-    QString formatFileSize(qint64 bytes) const;
-    QString formatBitrate(qint64 bps) const;
-    
-    bool confirmExit();
-    void showMessage(const QString& title, const QString& message, 
-                    QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::Information);
-
-private:
-    // 核心组件
-    RecorderMainWidget* m_recorderWidget;
-    // RecorderModule已移除,现在使用RecorderMainWidget内部的录制器
-    
-    // UI组件
-    QWidget* m_centralWidget;
-    QVBoxLayout* m_mainLayout;
-    QSplitter* m_mainSplitter;
-    
-    // 菜单和工具栏
-    QMenuBar* m_menuBar;
-    QMenu* m_fileMenu;
-    QMenu* m_recordMenu;
-    QMenu* m_viewMenu;
-    QMenu* m_helpMenu;
-    
-    QToolBar* m_mainToolBar;
-    QToolBar* m_recordToolBar;
-    
-    // 动作
-    QAction* m_newAction;
-    QAction* m_openAction;
-    QAction* m_saveAction;
-    QAction* m_exportAction;
-    QAction* m_settingsAction;
-    QAction* m_exitAction;
-    
-    QAction* m_startRecordingAction;
-    QAction* m_stopRecordingAction;
-    QAction* m_pauseRecordingAction;
-    QAction* m_resumeRecordingAction;
-    QAction* m_startPreviewAction;
-    QAction* m_stopPreviewAction;
-    
-    QAction* m_aboutAction;
-    QAction* m_aboutQtAction;
-    
-    // 状态栏
-    QStatusBar* m_statusBar;
-    QLabel* m_statusLabel;
-    QLabel* m_recordingTimeLabel;
-    QLabel* m_fileSizeLabel;
-    QLabel* m_bitrateLabel;
-    QLabel* m_diskSpaceLabel;
-    QProgressBar* m_recordingProgress;
-    
-    // 系统托盘
-    QSystemTrayIcon* m_trayIcon;
-    QMenu* m_trayMenu;
-    QAction* m_showHideAction;
-    QAction* m_trayExitAction;
-    
-    // 定时器
-    QTimer* m_statusUpdateTimer;
-    QTimer* m_recordingTimer;
-    QTimer* m_diskSpaceTimer;
-    
-    // 状态
-    bool m_isRecording;
-    bool m_isPaused;
-    bool m_isPreviewActive;
-    qint64 m_recordingStartTime;
-    qint64 m_recordingDuration;
-    QString m_currentRecordingFile;
-    
-    // 设置
-    QSettings* m_settings;
-    bool m_minimizeToTray;
-    bool m_closeToTray;
-    bool m_autoStartPreview;
-    bool m_showRecordingTime;
-    bool m_showFileSize;
-    bool m_showBitrate;
-    bool m_showDiskSpace;
-};
-
-#endif // RECORDER_EXAMPLE_APP_H

+ 0 - 136
AV/code/recorder/ui/recorder_main.cpp

@@ -1,136 +0,0 @@
-#include <QApplication>
-#include <QDebug>
-#include <QDir>
-#include <QFontDatabase>
-#include <QPixmap>
-#include <QSplashScreen>
-#include <QStandardPaths>
-#include <QStyleFactory>
-#include <QTimer>
-#include "qthread.h"
-#include "recorder_example_app.h"
-
-int main(int argc, char *argv[])
-{ // 启用高DPI支持
-    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
-    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
-
-    QApplication app(argc, argv);
-    av::Logger::initialize("test_log.txt", av::LogLevel::DEBUG, false, true);
-    // 设置应用程序信息
-    app.setApplicationName("AV录制器示例应用");
-    app.setApplicationVersion("1.0.0");
-    app.setApplicationDisplayName("AV录制器");
-    app.setOrganizationName("AV");
-    app.setOrganizationDomain("av.com");
-    
-    // 设置应用程序图标
-    app.setWindowIcon(QIcon(":/icons/recorder.png"));
-
-    // 设置样式
-    // app.setStyle(QStyleFactory::create("Fusion"));
-
-    // 创建启动画面
-    QPixmap splashPixmap(400, 300);
-    splashPixmap.fill(QColor(43, 43, 43)); // 深色背景
-    
-    QPainter painter(&splashPixmap);
-    painter.setRenderHint(QPainter::Antialiasing);
-    
-    // 绘制标题
-    QFont titleFont("Arial", 24, QFont::Bold);
-    painter.setFont(titleFont);
-    painter.setPen(QColor(255, 255, 255));
-    painter.drawText(splashPixmap.rect(), Qt::AlignCenter, "AV录制器");
-    
-    // 绘制版本信息
-    QFont versionFont("Arial", 12);
-    painter.setFont(versionFont);
-    painter.setPen(QColor(200, 200, 200));
-    QRect versionRect = splashPixmap.rect();
-    versionRect.setTop(versionRect.center().y() + 30);
-    painter.drawText(versionRect, Qt::AlignCenter, "版本 1.0.0");
-    
-    // 绘制加载信息
-    QFont loadingFont("Arial", 10);
-    painter.setFont(loadingFont);
-    painter.setPen(QColor(150, 150, 150));
-    QRect loadingRect = splashPixmap.rect();
-    loadingRect.setTop(loadingRect.bottom() - 40);
-    painter.drawText(loadingRect, Qt::AlignCenter, "正在初始化...");
-    
-    QSplashScreen splash(splashPixmap);
-    splash.show();
-    
-    // 处理事件以显示启动画面
-    app.processEvents();
-    
-    // 模拟初始化过程
-    splash.showMessage("正在加载录制器模块...", Qt::AlignBottom | Qt::AlignCenter, Qt::white);
-    app.processEvents();
-    QThread::msleep(100);
-
-    splash.showMessage("正在初始化音频系统...", Qt::AlignBottom | Qt::AlignCenter, Qt::white);
-    app.processEvents();
-    QThread::msleep(100);
-
-    splash.showMessage("正在初始化视频系统...", Qt::AlignBottom | Qt::AlignCenter, Qt::white);
-    app.processEvents();
-    QThread::msleep(100);
-
-    splash.showMessage("正在加载用户界面...", Qt::AlignBottom | Qt::AlignCenter, Qt::white);
-    app.processEvents();
-    QThread::msleep(100);
-
-    // 创建并显示主窗口
-    RecorderExampleApp mainWindow;
-    
-    splash.showMessage("启动完成", Qt::AlignBottom | Qt::AlignCenter, Qt::white);
-    app.processEvents();
-    QThread::msleep(200);
-    
-    splash.finish(&mainWindow);
-    mainWindow.show();
-    
-    // 检查命令行参数
-    QStringList arguments = app.arguments();
-    for (int i = 1; i < arguments.size(); ++i) {
-        const QString& arg = arguments.at(i);
-        Q_UNUSED(arg); // 标记变量为未使用,避免编译警告
-
-        // if (arg == "--start-recording" || arg == "-r") {
-        //     // 自动开始录制
-        //     QTimer::singleShot(1000, &mainWindow, &RecorderExampleApp::onStartRecording);
-        // } else if (arg == "--start-preview" || arg == "-p") {
-        //     // 自动开始预览
-        //     QTimer::singleShot(1000, &mainWindow, &RecorderExampleApp::onStartPreview);
-        // } else if (arg == "--minimized" || arg == "-m") {
-        //     // 最小化启动
-        //     mainWindow.showMinimized();
-        // } else if (arg == "--help" || arg == "-h") {
-        //     // 显示帮助信息
-        //     qDebug() << "AV录制器示例应用 v1.0.0";
-        //     qDebug() << "";
-        //     qDebug() << "用法: recorder_example [选项]";
-        //     qDebug() << "";
-        //     qDebug() << "选项:";
-        //     qDebug() << "  -r, --start-recording    启动后自动开始录制";
-        //     qDebug() << "  -p, --start-preview      启动后自动开始预览";
-        //     qDebug() << "  -m, --minimized          最小化启动";
-        //     qDebug() << "  -h, --help               显示此帮助信息";
-        //     qDebug() << "";
-        //     qDebug() << "快捷键:";
-        //     qDebug() << "  F9                       开始录制";
-        //     qDebug() << "  F10                      停止录制";
-        //     qDebug() << "  F11                      暂停录制";
-        //     qDebug() << "  F12                      恢复录制";
-        //     qDebug() << "  Ctrl+Shift+R             快速录制开关";
-        //     qDebug() << "  Ctrl+Shift+P             快速预览开关";
-        //     qDebug() << "  Ctrl+T                   打开设置";
-        //     qDebug() << "  Ctrl+Q                   退出应用";
-        //     return 0;
-        // }
-    }
-    
-    return app.exec();
-}

+ 0 - 1297
AV/code/recorder/ui/recorder_main_widget.cpp

@@ -1,1297 +0,0 @@
-#include "recorder_main_widget.h"
-#include "../../base/logger.h"
-#include <QApplication>
-#include <QDesktopWidget>
-#include <QScreen>
-#include <QStandardPaths>
-#include <QDir>
-#include <QDateTime>
-#include <QScrollArea>
-#include <QTabWidget>
-
-extern "C" {
-#include <libavutil/pixfmt.h>
-}
-
-RecorderMainWidget::RecorderMainWidget(QWidget* parent)
-    : QWidget(parent)
-    , m_recorder(nullptr)
-    , m_isInitialized(false)
-    , m_isRecording(false)
-    , m_isPaused(false)
-    , m_isPreviewActive(false)
-    , m_recordDuration(0)
-    , m_settingsDialog(nullptr)
-    , m_independentControlGroup(nullptr)
-    , m_audioStartButton(nullptr)
-    , m_audioStopButton(nullptr)
-    , m_videoCaptureButton(nullptr)
-    , m_videoStopButton(nullptr)
-    , m_audioEnableCheck(nullptr)
-    , m_videoEnableCheck(nullptr) {
-    
-    setWindowTitle("AV录制器");
-    setMinimumSize(1050, 650);  // 调整尺寸适应音频控制的空间需求
-    resize(1250, 750);          // 调整默认尺寸
-    
-    initUI();
-    initConnections();
-    updateUIState();
-}
-
-RecorderMainWidget::~RecorderMainWidget() {
-    cleanup();
-}
-
-bool RecorderMainWidget::initialize() {
-    if (m_isInitialized) {
-        return true;
-    }
-
-    AV_LOGGER_INFO("Initializing RecorderMainWidget");
-
-    // 初始化录制器模块
-    auto result = RecorderModule::initialize();
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to initialize recorder module");
-        QMessageBox::critical(this, "错误", "初始化录制器模块失败");
-        return false;
-    }
-    
-    // 创建录制器
-    m_recorder = utils::createAVRecorder();
-    if (!m_recorder) {
-        AV_LOGGER_ERROR("Failed to create AV recorder");
-        QMessageBox::critical(this, "错误", "创建录制器失败");
-        return false;
-    }
-    
-    // 更新设备列表
-    updateCaptureDevices();
-    
-    // 设置默认输出路径
-    QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
-    if (defaultPath.isEmpty()) {
-        defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
-    }
-    QString fileName = QString("录制_%1.mp4").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
-    m_outputPathEdit->setText(QDir(defaultPath).filePath(fileName));
-    
-    m_isInitialized = true;
-    updateUIState();
-
-    AV_LOGGER_INFO("RecorderMainWidget initialized successfully");
-    return true;
-}
-
-void RecorderMainWidget::cleanup() {
-    if (!m_isInitialized) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Cleaning up RecorderMainWidget");
-
-    // 停止所有操作
-    if (m_isRecording) {
-        stopRecording();
-    }
-    if (m_isPreviewActive) {
-        stopPreview();
-    }
-    
-    // 停止定时器
-    if (m_updateTimer) {
-        m_updateTimer->stop();
-    }
-    if (m_previewTimer) {
-        m_previewTimer->stop();
-    }
-    if (m_audioLevelTimer) {
-        m_audioLevelTimer->stop();
-    }
-    
-    // 清理录制器
-    m_recorder.reset();
-    
-    // 清理模块
-    RecorderModule::cleanup();
-    
-    m_isInitialized = false;
-
-    AV_LOGGER_INFO("RecorderMainWidget cleaned up");
-}
-
-void RecorderMainWidget::startRecording() {
-    if (!m_isInitialized || m_isRecording) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Starting recording");
-
-    // 获取录制参数
-    auto params = getCurrentParams();
-    
-    // 验证输出路径
-    if (!utils::isValidOutputPath(params.outputPath)) {
-        QMessageBox::warning(this, "警告", "输出路径无效,请选择有效的输出文件");
-        return;
-    }
-    
-    // 初始化录制器
-    auto result = m_recorder->initialize(params);
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to initialize recorder");
-        QMessageBox::critical(this, "错误", "初始化录制器失败");
-        return;
-    }
-    
-    // 开始录制
-    result = m_recorder->startRecording();
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to start recording");
-        QMessageBox::critical(this, "错误", "开始录制失败");
-        return;
-    }
-    
-    m_isRecording = true;
-    m_isPaused = false;
-    m_recordStartTime = QTime::currentTime();
-    
-    // 启动更新定时器
-    if (!m_updateTimer->isActive()) {
-        m_updateTimer->start(UPDATE_INTERVAL_MS);
-    }
-    
-    updateUIState();
-    m_statusLabel->setText("录制中...");
-
-    AV_LOGGER_INFO("Recording started successfully");
-}
-
-void RecorderMainWidget::stopRecording() {
-    if (!m_isRecording) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Stopping recording");
-
-    auto result = m_recorder->stopRecording();
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to stop recording");
-        QMessageBox::warning(this, "警告", "停止录制时出现错误");
-    }
-    
-    m_isRecording = false;
-    m_isPaused = false;
-    m_recordDuration = 0;
-    
-    // 停止更新定时器
-    if (m_updateTimer && m_updateTimer->isActive()) {
-        m_updateTimer->stop();
-    }
-    
-    updateUIState();
-    m_statusLabel->setText("录制已停止");
-    
-    // 显示录制完成信息
-    auto combinedStats = m_recorder->getCombinedStats();
-    auto& videoStats = combinedStats.videoStats;
-    QString message = QString("录制完成\n文件: %1\n时长: %2\n帧数: %3")
-        .arg(QString::fromStdString(getCurrentParams().outputPath))
-        .arg(formatTime(static_cast<int64_t>(videoStats.recordingTime * 1000)))
-        .arg(videoStats.recordedFrames);
-    
-    QMessageBox::information(this, "录制完成", message);
-
-    // 重置录制器状态,以便可以重新启动
-    resetRecorderForRestart();
-
-    AV_LOGGER_INFO("Recording stopped successfully");
-}
-
-void RecorderMainWidget::pauseRecording() {
-    if (!m_isRecording || m_isPaused) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Pausing recording");
-
-    auto result = m_recorder->pauseRecording();
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to pause recording");
-        QMessageBox::warning(this, "警告", "暂停录制失败");
-        return;
-    }
-    
-    m_isPaused = true;
-    updateUIState();
-    m_statusLabel->setText("录制已暂停");
-
-    AV_LOGGER_INFO("Recording paused successfully");
-}
-
-void RecorderMainWidget::resumeRecording() {
-    if (!m_isRecording || !m_isPaused) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Resuming recording");
-
-    auto result = m_recorder->resumeRecording();
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to resume recording");
-        QMessageBox::warning(this, "警告", "恢复录制失败");
-        return;
-    }
-    
-    m_isPaused = false;
-    updateUIState();
-    m_statusLabel->setText("录制中...");
-
-    AV_LOGGER_INFO("Recording resumed successfully");
-}
-
-void RecorderMainWidget::startPreview() {
-    if (!m_isInitialized || m_isPreviewActive) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Starting preview");
-
-    // 获取预览参数(只需要视频参数)
-    auto params = getCurrentParams();
-    params.outputPath = "./preview_temp.mp4";   // 预览使用临时文件
-    params.enableAudio = false; // 预览通常不需要音频录制
-    
-    // 初始化录制器用于预览
-    auto result = m_recorder->initialize(params);
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to initialize recorder for preview");
-        QMessageBox::warning(this, "警告", "初始化预览失败");
-        return;
-    }
-    
-    // 开始预览(实际上是开始捕获但不录制到文件)
-    result = m_recorder->startRecording();
-    if (result != av::ErrorCode::SUCCESS) {
-        AV_LOGGER_ERROR("Failed to start preview");
-        QMessageBox::warning(this, "警告", "开始预览失败");
-        return;
-    }
-    
-    m_isPreviewActive = true;
-    
-    // 启动预览更新定时器
-    if (!m_previewTimer->isActive()) {
-        m_previewTimer->start(PREVIEW_INTERVAL_MS);
-    }
-    
-    updateUIState();
-    m_statusLabel->setText("预览中...");
-
-    AV_LOGGER_INFO("Preview started successfully");
-}
-
-void RecorderMainWidget::stopPreview() {
-    if (!m_isPreviewActive) {
-        return;
-    }
-
-    AV_LOGGER_INFO("Stopping preview");
-
-    m_recorder->stopRecording();
-    m_isPreviewActive = false;
-    
-    // 停止预览定时器
-    if (m_previewTimer->isActive()) {
-        m_previewTimer->stop();
-    }
-    
-    // 清空预览窗口
-    m_videoWidget->clearFrame();
-    
-    updateUIState();
-    m_statusLabel->setText("预览已停止");
-
-    // 重置录制器状态,以便可以重新启动
-    resetRecorderForRestart();
-
-    AV_LOGGER_INFO("Preview stopped successfully");
-}
-
-void RecorderMainWidget::openSettings() {
-    if (!m_settingsDialog) {
-        m_settingsDialog = new RecorderSettingsDialog(nullptr, this);
-    }
-    
-    // TODO: 设置当前参数
-    // m_settingsDialog->setSettings(getCurrentSettings());
-    
-    if (m_settingsDialog->exec() == QDialog::Accepted) {
-        // 应用新参数
-        auto settings = m_settingsDialog->getSettings();
-        // TODO: 将settings转换为AVRecorderParams
-        // applyRecorderParams(convertSettingsToParams(settings));
-
-        AV_LOGGER_INFO("Settings applied");
-        m_statusLabel->setText("设置已应用");
-    }
-}
-
-void RecorderMainWidget::selectOutputFile() {
-    QString currentPath = m_outputPathEdit->text();
-    QString dir = QFileInfo(currentPath).absolutePath();
-    
-    QString fileName = QFileDialog::getSaveFileName(
-        this,
-        "选择输出文件",
-        currentPath,
-        "视频文件 (*.mp4 *.avi *.mkv *.mov);;音频文件 (*.mp3 *.wav *.aac);;所有文件 (*.*)"
-    );
-    
-    if (!fileName.isEmpty()) {
-        m_outputPathEdit->setText(fileName);
-    }
-}
-
-void RecorderMainWidget::updateCaptureDevices() {
-    AV_LOGGER_INFO("Updating capture devices");
-
-    // 更新采集方法
-    m_captureMethodCombo->clear();
-    m_captureMethodCombo->addItem("屏幕录制", static_cast<int>(VideoCaptureMethod::SCREEN_CAPTURE));
-    m_captureMethodCombo->addItem("窗口录制", static_cast<int>(VideoCaptureMethod::WINDOW_CAPTURE));
-    m_captureMethodCombo->addItem("摄像头录制", static_cast<int>(VideoCaptureMethod::CAMERA_CAPTURE));
-    
-    // 更新采集源(这里简化处理,实际应该查询系统)
-    onCaptureMethodChanged();
-    
-    // 更新音频设备(这里简化处理,实际应该查询系统)
-    m_audioDeviceCombo->clear();
-    m_audioDeviceCombo->addItem("默认麦克风", 0);
-    m_audioDeviceCombo->addItem("默认扬声器", 1);
-
-    AV_LOGGER_INFO("Capture devices updated");
-}
-
-void RecorderMainWidget::onCaptureSourceChanged() {
-    // 采集源改变时的处理
-    updateUIState();
-}
-
-void RecorderMainWidget::onCaptureMethodChanged() {
-    // 根据采集方法更新采集源列表
-    m_captureSourceCombo->clear();
-    
-    int method = m_captureMethodCombo->currentData().toInt();
-    switch (static_cast<VideoCaptureMethod>(method)) {
-    case VideoCaptureMethod::SCREEN_CAPTURE:
-        // 添加屏幕列表(简化处理)
-        m_captureSourceCombo->addItem("主屏幕", 0);
-        m_captureSourceCombo->addItem("扩展屏幕", 1);
-        break;
-        
-    case VideoCaptureMethod::WINDOW_CAPTURE:
-        // 添加窗口列表(简化处理)
-        m_captureSourceCombo->addItem("当前窗口", 0);
-        break;
-        
-    case VideoCaptureMethod::CAMERA_CAPTURE:
-        // 添加摄像头列表(简化处理)
-        m_captureSourceCombo->addItem("默认摄像头", 0);
-        break;
-    }
-}
-
-void RecorderMainWidget::onAudioDeviceChanged() {
-    // 音频设备改变时的处理
-    updateUIState();
-}
-
-void RecorderMainWidget::onVolumeChanged(double volume) {
-    // 音量改变时的处理
-    AV_LOGGER_DEBUGF("Volume changed to {}", volume);
-}
-
-void RecorderMainWidget::onMuteChanged(bool muted) {
-    // 静音状态改变时的处理
-    AV_LOGGER_DEBUGF("Mute changed to {}", muted);
-}
-
-void RecorderMainWidget::updateRecordingStatus() {
-    if (!m_isRecording) {
-        m_recordTimeLabel->setText("00:00:00");
-        return;
-    }
-    
-    // 计算录制时间
-    int elapsed = m_recordStartTime.msecsTo(QTime::currentTime());
-    if (m_isPaused) {
-        elapsed = m_recordDuration;
-    } else {
-        m_recordDuration = elapsed;
-    }
-    
-    m_recordTimeLabel->setText(formatTime(elapsed));
-    
-    // 更新统计信息
-    if (m_recorder) {
-        auto combinedStats = m_recorder->getCombinedStats();
-        auto& videoStats = combinedStats.videoStats;
-        m_framesLabel->setText(QString("帧数: %1").arg(videoStats.recordedFrames));
-        m_droppedFramesLabel->setText(QString("丢帧: %1").arg(videoStats.droppedFrames));
-        
-        // 计算码率 (总字节数 / 录制时长 * 8)
-        double bitrate = videoStats.recordingTime > 0 ? (videoStats.totalBytes * 8.0 / videoStats.recordingTime) : 0;
-        m_bitrateLabel->setText(QString("码率: %1").arg(formatBitrate(static_cast<int64_t>(bitrate))));
-        
-        // 显示文件大小
-        m_fileSizeLabel->setText(QString("大小: %1").arg(formatFileSize(videoStats.totalBytes)));
-    }
-}
-
-void RecorderMainWidget::updatePreviewFrame() {
-    if (!m_isPreviewActive || !m_recorder) {
-        return;
-    }
-    
-    try {
-        // 获取当前预览帧
-        auto frame = m_recorder->getCurrentVideoFrame();
-        if (frame && frame->data[0]) {
-            AV_LOGGER_DEBUGF("更新预览帧: width={}, height={}, format={}, data_ptr={}", 
-                            frame->width, frame->height, frame->format, 
-                            static_cast<void*>(frame->data[0]));
-            bool updated = m_videoWidget->updateFrame(frame.get());
-            if (!updated) {
-                AV_LOGGER_WARNING("视频预览组件更新失败");
-            }
-        } else {
-            AV_LOGGER_DEBUG("未获取到有效的预览帧");
-        }
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("Error updating preview frame: {}", e.what());
-        // 预览错误不应该影响录制,继续运行
-    }
-}
-
-void RecorderMainWidget::updateAudioLevel() {
-    if (!m_recorder) {
-        return;
-    }
-    
-    // 获取音频电平(这里需要录制器提供音频电平接口)
-    // auto level = m_recorder->getCurrentAudioLevel();
-    // m_microphoneWidget->setLevel(level.micLevel);
-    // m_speakerWidget->setLevel(level.speakerLevel);
-}
-
-void RecorderMainWidget::onRecorderStateChanged(RecorderState state) {
-    AV_LOGGER_INFOF("Recorder state changed to {}", static_cast<int>(state));
-    updateUIState();
-}
-
-void RecorderMainWidget::onRecorderError(const QString& error) {
-    AV_LOGGER_ERRORF("Recorder error: {}", error.toStdString());
-    QMessageBox::critical(this, "录制器错误", error);
-    
-    // 停止当前操作
-    if (m_isRecording) {
-        stopRecording();
-    }
-    if (m_isPreviewActive) {
-        stopPreview();
-    }
-}
-
-void RecorderMainWidget::onStatisticsUpdated() {
-    // 统计信息更新时的处理
-    updateRecordingStatus();
-}
-
-void RecorderMainWidget::initUI() {
-    // 创建主分割器
-    m_mainSplitter = new QSplitter(Qt::Horizontal, this);
-    
-    // 创建左面板滚动区域
-    auto leftScrollArea = new QScrollArea();
-    leftScrollArea->setWidgetResizable(true);
-    leftScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
-    leftScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
-    leftScrollArea->setMinimumWidth(350);  // 增加最小宽度,给音频控件更多空间
-    leftScrollArea->setMaximumWidth(420);  // 增加最大宽度
-    
-    // 创建实际的左面板内容widget
-    m_leftPanel = new QWidget();
-    leftScrollArea->setWidget(m_leftPanel);
-    
-    // 创建右面板
-    m_rightPanel = new QWidget();
-    
-    m_mainSplitter->addWidget(leftScrollArea);
-    m_mainSplitter->addWidget(m_rightPanel);
-    m_mainSplitter->setStretchFactor(0, 0);  // 左面板固定大小
-    m_mainSplitter->setStretchFactor(1, 1);  // 右面板占用剩余空间
-    
-    // 初始化各个面板
-    initControlPanel();
-    initIndependentControlPanel();
-    initPreviewPanel();
-    initAudioPanel();
-    initSettingsPanel();
-    initStatusBar();
-    
-    // 设置左面板紧凑布局
-    auto leftLayout = new QVBoxLayout(m_leftPanel);
-    leftLayout->setContentsMargins(4, 4, 4, 4);
-    leftLayout->setSpacing(6);  // 稍微增加间距,让组件更清晰
-    
-    // 按重要性和空间需求设置各个组件
-    leftLayout->addWidget(m_controlGroup, 0);           // 录制控制 - 最重要,固定大小
-    leftLayout->addWidget(m_independentControlGroup, 0); // 独立控制面板,固定大小
-    leftLayout->addWidget(m_captureGroup, 0);           // 采集设置,固定大小
-    leftLayout->addWidget(m_outputGroup, 0);            // 输出设置,固定大小
-    leftLayout->addWidget(m_audioGroup, 1);             // 音频控制 - 给予优先扩展空间
-    leftLayout->addWidget(m_statsGroup, 0);             // 统计信息,固定大小
-    leftLayout->addStretch(0);                          // 底部填充空间
-    
-    // 设置右面板布局
-    auto rightLayout = new QVBoxLayout(m_rightPanel);
-    rightLayout->setContentsMargins(4, 4, 4, 4);
-    rightLayout->addWidget(m_previewGroup);
-    
-    // 设置主布局
-    auto mainLayout = new QVBoxLayout(this);
-    mainLayout->setContentsMargins(2, 2, 2, 0);  // 底部边距设为0,让状态栏贴底
-    mainLayout->setSpacing(0);  // 减少组件间距
-    mainLayout->addWidget(m_mainSplitter, 1);  // 主分割器占用主要空间
-    mainLayout->addWidget(m_statusBar, 0);     // 状态栏固定大小
-    
-    // 创建定时器
-    m_updateTimer = new QTimer(this);
-    m_previewTimer = new QTimer(this);
-    m_audioLevelTimer = new QTimer(this);
-}
-
-void RecorderMainWidget::initControlPanel() {
-    m_controlGroup = new QGroupBox("录制控制");
-    m_controlGroup->setMaximumHeight(140);
-    
-    // 创建按钮
-    m_recordButton = new QPushButton("开始录制");
-    m_pauseButton = new QPushButton("暂停");
-    m_stopButton = new QPushButton("停止");
-    m_previewButton = new QPushButton("预览");
-    m_settingsButton = new QPushButton("设置");
-    
-    // 设置按钮最小高度和样式
-    const int buttonHeight = 28;
-    m_recordButton->setMinimumHeight(buttonHeight);
-    m_pauseButton->setMinimumHeight(buttonHeight);
-    m_stopButton->setMinimumHeight(buttonHeight);
-    m_previewButton->setMinimumHeight(buttonHeight);
-    m_settingsButton->setMinimumHeight(buttonHeight);
-    
-    // 创建状态标签
-    m_recordTimeLabel = new QLabel("00:00:00");
-    m_recordTimeLabel->setStyleSheet("QLabel { font-weight: bold; color: #0066cc; }");
-    m_recordStatusLabel = new QLabel("就绪");
-    
-    // 紧凑布局
-    auto layout = new QGridLayout(m_controlGroup);
-    layout->setContentsMargins(6, 8, 6, 6);
-    layout->setSpacing(4);
-    layout->addWidget(m_recordButton, 0, 0);
-    layout->addWidget(m_pauseButton, 0, 1);
-    layout->addWidget(m_stopButton, 0, 2);
-    layout->addWidget(m_previewButton, 1, 0);
-    layout->addWidget(m_settingsButton, 1, 1, 1, 2);
-    
-    // 状态信息用更紧凑的布局
-    auto statusLayout = new QHBoxLayout();
-    statusLayout->setSpacing(8);
-    statusLayout->addWidget(new QLabel("时间:"));
-    statusLayout->addWidget(m_recordTimeLabel);
-    statusLayout->addWidget(new QLabel("状态:"));
-    statusLayout->addWidget(m_recordStatusLabel);
-    statusLayout->addStretch();
-    
-    layout->addLayout(statusLayout, 2, 0, 1, 3);
-}
-
-void RecorderMainWidget::initIndependentControlPanel() {
-    m_independentControlGroup = new QGroupBox("独立采集控制");
-    m_independentControlGroup->setMaximumHeight(120);
-    
-    // 创建控制按钮
-    m_audioStartButton = new QPushButton("启动音频");
-    m_audioStopButton = new QPushButton("停止音频");
-    m_videoCaptureButton = new QPushButton("启动视频");
-    m_videoStopButton = new QPushButton("停止视频");
-    
-    // 设置按钮高度
-    const int buttonHeight = 26;
-    m_audioStartButton->setMinimumHeight(buttonHeight);
-    m_audioStopButton->setMinimumHeight(buttonHeight);
-    m_videoCaptureButton->setMinimumHeight(buttonHeight);
-    m_videoStopButton->setMinimumHeight(buttonHeight);
-    
-    // 创建启用检查框
-    m_audioEnableCheck = new QCheckBox("启用音频录制");
-    m_videoEnableCheck = new QCheckBox("启用视频录制");
-    
-    // 设置默认状态
-    m_audioEnableCheck->setChecked(true);
-    m_videoEnableCheck->setChecked(true);
-    
-    // 设置按钮样式
-    m_audioStartButton->setStyleSheet("QPushButton { background-color: #34c759; color: white; }");
-    m_audioStopButton->setStyleSheet("QPushButton { background-color: #ff3b30; color: white; }");
-    m_videoCaptureButton->setStyleSheet("QPushButton { background-color: #007aff; color: white; }");
-    m_videoStopButton->setStyleSheet("QPushButton { background-color: #ff9500; color: white; }");
-    
-    // 紧凑布局
-    auto layout = new QGridLayout(m_independentControlGroup);
-    layout->setContentsMargins(6, 8, 6, 6);
-    layout->setSpacing(3);
-    
-    // 第一行:启用选项(水平布局)
-    auto enableLayout = new QHBoxLayout();
-    enableLayout->setSpacing(10);
-    enableLayout->addWidget(m_audioEnableCheck);
-    enableLayout->addWidget(m_videoEnableCheck);
-    layout->addLayout(enableLayout, 0, 0, 1, 4);
-    
-    // 第二行:音频控制
-    layout->addWidget(new QLabel("音频:"), 1, 0);
-    layout->addWidget(m_audioStartButton, 1, 1);
-    layout->addWidget(m_audioStopButton, 1, 2);
-    
-    // 第三行:视频控制
-    layout->addWidget(new QLabel("视频:"), 2, 0);
-    layout->addWidget(m_videoCaptureButton, 2, 1);
-    layout->addWidget(m_videoStopButton, 2, 2);
-}
-
-void RecorderMainWidget::initPreviewPanel() {
-    m_previewGroup = new QGroupBox("预览窗口");
-    
-    // 创建视频预览组件
-    m_videoWidget = new RecorderVideoWidget();
-    m_videoWidget->setMinimumSize(640, 480);
-    
-    // 初始化VideoWidget(默认参数:1920x1080, YUV420P)
-    if (!m_videoWidget->initialize(1920, 1080, AV_PIX_FMT_YUV420P)) {
-        AV_LOGGER_WARNING("Failed to initialize video widget with default parameters");
-        // 尝试RGB格式作为后备
-        if (!m_videoWidget->initialize(1920, 1080, AV_PIX_FMT_RGB24)) {
-            AV_LOGGER_ERROR("Failed to initialize video widget with RGB format");
-        }
-    }
-    
-    // 布局
-    auto layout = new QVBoxLayout(m_previewGroup);
-    layout->addWidget(m_videoWidget);
-}
-
-void RecorderMainWidget::initAudioPanel() {
-    m_audioGroup = new QGroupBox("音频控制");
-    m_audioGroup->setMinimumHeight(240);  // 给音频控制足够的最小高度
-    m_audioGroup->setMaximumHeight(280);  // 设置合理的最大高度
-    m_audioGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
-    
-    // 创建音频控制组件
-    m_microphoneWidget = new RecorderAudioWidget(this);
-    m_speakerWidget = new RecorderAudioWidget(this);
-    
-    // 设置widget标题和大小 - 给予充足空间
-    m_microphoneWidget->setObjectName("麦克风");
-    m_microphoneWidget->setMinimumHeight(100);  // 确保有足够高度显示所有控件
-    m_microphoneWidget->setMaximumHeight(120);
-    m_microphoneWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
-    
-    m_speakerWidget->setObjectName("扬声器");
-    m_speakerWidget->setMinimumHeight(100);  // 确保有足够高度显示所有控件
-    m_speakerWidget->setMaximumHeight(120);
-    m_speakerWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
-    
-    // 调整布局
-    auto layout = new QVBoxLayout(m_audioGroup);
-    layout->setContentsMargins(6, 10, 6, 6);  // 给顶部更多空间
-    layout->setSpacing(6);  // 增加适当间距
-    
-    // 添加标签来区分麦克风和扬声器
-    auto micLabel = new QLabel("麦克风");
-    micLabel->setStyleSheet("font-weight: bold; color: #0a84ff; font-size: 12px; margin-bottom: 2px;");
-    layout->addWidget(micLabel);
-    layout->addWidget(m_microphoneWidget);
-    
-    auto speakerLabel = new QLabel("扬声器");
-    speakerLabel->setStyleSheet("font-weight: bold; color: #34c759; font-size: 12px; margin-top: 6px; margin-bottom: 2px;");
-    layout->addWidget(speakerLabel);
-    layout->addWidget(m_speakerWidget);
-}
-
-void RecorderMainWidget::initSettingsPanel() {
-    // 采集设置组 - 紧凑布局
-    m_captureGroup = new QGroupBox("采集设置");
-    m_captureGroup->setMaximumHeight(160);
-    
-    m_captureMethodCombo = new QComboBox();
-    m_captureSourceCombo = new QComboBox();
-    m_audioDeviceCombo = new QComboBox();
-    m_refreshDevicesButton = new QPushButton("刷新设备");
-    m_drawCursorCheck = new QCheckBox("绘制光标");
-    m_captureAudioCheck = new QCheckBox("录制音频");
-    
-    // 设置控件高度
-    m_captureMethodCombo->setMaximumHeight(24);
-    m_captureSourceCombo->setMaximumHeight(24);
-    m_audioDeviceCombo->setMaximumHeight(24);
-    m_refreshDevicesButton->setMaximumHeight(26);
-    
-    m_drawCursorCheck->setChecked(true);
-    m_captureAudioCheck->setChecked(true);
-    
-    auto captureLayout = new QGridLayout(m_captureGroup);
-    captureLayout->setContentsMargins(6, 8, 6, 6);
-    captureLayout->setSpacing(3);
-    captureLayout->addWidget(new QLabel("采集方法:"), 0, 0);
-    captureLayout->addWidget(m_captureMethodCombo, 0, 1);
-    captureLayout->addWidget(new QLabel("采集源:"), 1, 0);
-    captureLayout->addWidget(m_captureSourceCombo, 1, 1);
-    captureLayout->addWidget(new QLabel("音频设备:"), 2, 0);
-    captureLayout->addWidget(m_audioDeviceCombo, 2, 1);
-    captureLayout->addWidget(m_refreshDevicesButton, 3, 0, 1, 2);
-    
-    // 选项水平布局
-    auto optionsLayout = new QHBoxLayout();
-    optionsLayout->setSpacing(10);
-    optionsLayout->addWidget(m_drawCursorCheck);
-    optionsLayout->addWidget(m_captureAudioCheck);
-    captureLayout->addLayout(optionsLayout, 4, 0, 1, 2);
-    
-    // 输出设置组 - 紧凑布局
-    m_outputGroup = new QGroupBox("输出设置");
-    m_outputGroup->setMaximumHeight(80);
-    
-    m_outputPathEdit = new QLineEdit();
-    m_browseOutputButton = new QPushButton("浏览...");
-    m_outputFormatCombo = new QComboBox();
-    
-    // 设置控件高度
-    m_outputPathEdit->setMaximumHeight(24);
-    m_browseOutputButton->setMaximumHeight(26);
-    m_outputFormatCombo->setMaximumHeight(24);
-    
-    m_outputFormatCombo->addItems({"MP4", "AVI", "MKV", "MOV"});
-    
-    auto outputLayout = new QGridLayout(m_outputGroup);
-    outputLayout->setContentsMargins(6, 8, 6, 6);
-    outputLayout->setSpacing(3);
-    outputLayout->addWidget(new QLabel("输出文件:"), 0, 0);
-    outputLayout->addWidget(m_outputPathEdit, 0, 1);
-    outputLayout->addWidget(m_browseOutputButton, 0, 2);
-    outputLayout->addWidget(new QLabel("格式:"), 1, 0);
-    outputLayout->addWidget(m_outputFormatCombo, 1, 1, 1, 2);
-    
-    // 统计信息组 - 紧凑布局
-    m_statsGroup = new QGroupBox("统计信息");
-    m_statsGroup->setMaximumHeight(120);
-    
-    m_fpsLabel = new QLabel("帧率: 0 fps");
-    m_bitrateLabel = new QLabel("码率: 0 bps");
-    m_framesLabel = new QLabel("帧数: 0");
-    m_droppedFramesLabel = new QLabel("丢帧: 0");
-    m_fileSizeLabel = new QLabel("大小: 0 B");
-    
-    // 设置标签样式
-    QString labelStyle = "QLabel { font-size: 11px; margin: 1px; }";
-    m_fpsLabel->setStyleSheet(labelStyle);
-    m_bitrateLabel->setStyleSheet(labelStyle);
-    m_framesLabel->setStyleSheet(labelStyle);
-    m_droppedFramesLabel->setStyleSheet(labelStyle);
-    m_fileSizeLabel->setStyleSheet(labelStyle);
-    
-    auto statsLayout = new QVBoxLayout(m_statsGroup);
-    statsLayout->setContentsMargins(6, 8, 6, 6);
-    statsLayout->setSpacing(2);
-    statsLayout->addWidget(m_fpsLabel);
-    statsLayout->addWidget(m_bitrateLabel);
-    statsLayout->addWidget(m_framesLabel);
-    statsLayout->addWidget(m_droppedFramesLabel);
-    statsLayout->addWidget(m_fileSizeLabel);
-}
-
-void RecorderMainWidget::initStatusBar() {
-    m_statusBar = new QStatusBar();
-    m_statusBar->setMaximumHeight(26);  // 限制状态栏最大高度
-    m_statusBar->setSizeGripEnabled(false);  // 禁用大小调整手柄
-    
-    m_statusLabel = new QLabel("就绪");
-    m_statusLabel->setStyleSheet("QLabel { padding: 2px 4px; margin: 0px; font-size: 12px; }");  // 减少内边距和字体大小
-    m_statusLabel->setMaximumHeight(22);  // 限制标签高度
-    
-    m_progressBar = new QProgressBar();
-    m_progressBar->setVisible(false);
-    m_progressBar->setMaximumHeight(18);  // 限制进度条高度
-    
-    m_statusBar->addWidget(m_statusLabel);
-    m_statusBar->addPermanentWidget(m_progressBar);
-}
-
-void RecorderMainWidget::initConnections() {
-    // 控制按钮连接
-    connect(m_recordButton, &QPushButton::clicked, this, &RecorderMainWidget::startRecording);
-    connect(m_pauseButton, &QPushButton::clicked, this, [this]() {
-        if (m_isPaused) {
-            resumeRecording();
-        } else {
-            pauseRecording();
-        }
-    });
-    connect(m_stopButton, &QPushButton::clicked, this, &RecorderMainWidget::stopRecording);
-    connect(m_previewButton, &QPushButton::clicked, this, [this]() {
-        if (m_isPreviewActive) {
-            stopPreview();
-        } else {
-            startPreview();
-        }
-    });
-    connect(m_settingsButton, &QPushButton::clicked, this, &RecorderMainWidget::openSettings);
-    
-    // 设置控件连接
-    connect(m_captureMethodCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
-            this, &RecorderMainWidget::onCaptureMethodChanged);
-    connect(m_captureSourceCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
-            this, &RecorderMainWidget::onCaptureSourceChanged);
-    connect(m_audioDeviceCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
-            this, &RecorderMainWidget::onAudioDeviceChanged);
-    connect(m_refreshDevicesButton, &QPushButton::clicked, this, &RecorderMainWidget::updateCaptureDevices);
-    connect(m_browseOutputButton, &QPushButton::clicked, this, &RecorderMainWidget::selectOutputFile);
-    
-    // 音频控件连接
-    connect(m_microphoneWidget, &RecorderAudioWidget::volumeChanged, this, &RecorderMainWidget::onVolumeChanged);
-    connect(m_microphoneWidget, &RecorderAudioWidget::mutedChanged, this, &RecorderMainWidget::onMuteChanged);
-    connect(m_speakerWidget, &RecorderAudioWidget::volumeChanged, this, &RecorderMainWidget::onVolumeChanged);
-    connect(m_speakerWidget, &RecorderAudioWidget::mutedChanged, this, &RecorderMainWidget::onMuteChanged);
-    
-    // 独立控制连接
-    connect(m_audioStartButton, &QPushButton::clicked, this, &RecorderMainWidget::onAudioStartClicked);
-    connect(m_audioStopButton, &QPushButton::clicked, this, &RecorderMainWidget::onAudioStopClicked);
-    connect(m_videoCaptureButton, &QPushButton::clicked, this, &RecorderMainWidget::onVideoCaptureClicked);
-    connect(m_videoStopButton, &QPushButton::clicked, this, &RecorderMainWidget::onVideoStopClicked);
-    connect(m_audioEnableCheck, &QCheckBox::toggled, this, &RecorderMainWidget::onAudioEnableChanged);
-    connect(m_videoEnableCheck, &QCheckBox::toggled, this, &RecorderMainWidget::onVideoEnableChanged);
-    
-    // 定时器连接
-    connect(m_updateTimer, &QTimer::timeout, this, &RecorderMainWidget::updateRecordingStatus);
-    connect(m_previewTimer, &QTimer::timeout, this, &RecorderMainWidget::updatePreviewFrame);
-    connect(m_audioLevelTimer, &QTimer::timeout, this, &RecorderMainWidget::updateAudioLevel);
-}
-
-void RecorderMainWidget::updateUIState() {
-    bool canRecord = m_isInitialized && !m_isRecording;
-    bool canStop = m_isRecording;
-    bool canPause = m_isRecording && !m_isPaused;
-    bool canResume = m_isRecording && m_isPaused;
-    bool canPreview = m_isInitialized && !m_isRecording;
-    
-    m_recordButton->setEnabled(canRecord);
-    m_stopButton->setEnabled(canStop);
-    m_pauseButton->setEnabled(canPause || canResume);
-    m_pauseButton->setText(m_isPaused ? "恢复" : "暂停");
-    m_previewButton->setEnabled(canPreview);
-    m_previewButton->setText(m_isPreviewActive ? "停止预览" : "开始预览");
-    
-    // 更新录制状态标签
-    if (m_isRecording) {
-        if (m_isPaused) {
-            m_recordStatusLabel->setText("已暂停");
-        } else {
-            m_recordStatusLabel->setText("录制中");
-        }
-    } else if (m_isPreviewActive) {
-        m_recordStatusLabel->setText("预览中");
-    } else {
-        m_recordStatusLabel->setText("就绪");
-    }
-    
-    // 禁用/启用设置控件
-    bool canChangeSettings = !m_isRecording && !m_isPreviewActive;
-    m_captureMethodCombo->setEnabled(canChangeSettings);
-    m_captureSourceCombo->setEnabled(canChangeSettings);
-    m_audioDeviceCombo->setEnabled(canChangeSettings);
-    m_outputPathEdit->setEnabled(canChangeSettings);
-    m_outputFormatCombo->setEnabled(canChangeSettings);
-    
-    // 控制音频/视频启用复选框的状态
-    bool canChangeEnableState = m_isInitialized && !m_isRecording && !m_isPreviewActive;
-    if (m_audioEnableCheck) {
-        m_audioEnableCheck->setEnabled(canChangeEnableState);
-    }
-    if (m_videoEnableCheck) {
-        m_videoEnableCheck->setEnabled(canChangeEnableState);
-    }
-    
-    // 更新独立控制按钮状态
-    updateIndependentControlButtons();
-}
-
-AVRecorderParams RecorderMainWidget::getCurrentParams() {
-    auto params = utils::getDefaultAVParams();
-    
-    // 设置输出路径
-    params.outputPath = m_outputPathEdit->text().toStdString();
-    
-    // 设置格式
-    QString format = m_outputFormatCombo->currentText().toLower();
-    params.format = format.toStdString();
-    params.audioParams.format = format.toStdString();
-    params.videoParams.format = format.toStdString();
-    
-    // 设置采集方法
-    int method = m_captureMethodCombo->currentData().toInt();
-    params.videoParams.captureMethod = static_cast<VideoCaptureMethod>(method);
-    
-    // 设置采集源
-    int source = m_captureSourceCombo->currentData().toInt();
-    if (params.videoParams.captureMethod == VideoCaptureMethod::SCREEN_CAPTURE) {
-        params.videoParams.monitorIndex = source;
-    }
-    
-    // 设置其他选项
-    params.videoParams.drawCursor = m_drawCursorCheck->isChecked();
-    params.enableAudio = m_captureAudioCheck->isChecked();
-    params.enableVideo = true;
-    params.enableSync = true;
-    
-    return params;
-}
-
-void RecorderMainWidget::applyRecorderParams(const AVRecorderParams& params) {
-    // 应用参数到UI控件
-    m_outputPathEdit->setText(QString::fromStdString(params.outputPath));
-    
-    // 设置格式
-    QString format = QString::fromStdString(params.format).toUpper();
-    int formatIndex = m_outputFormatCombo->findText(format);
-    if (formatIndex >= 0) {
-        m_outputFormatCombo->setCurrentIndex(formatIndex);
-    }
-    
-    // 设置采集方法
-    int methodIndex = m_captureMethodCombo->findData(static_cast<int>(params.videoParams.captureMethod));
-    if (methodIndex >= 0) {
-        m_captureMethodCombo->setCurrentIndex(methodIndex);
-        onCaptureMethodChanged();
-    }
-    
-    // 设置其他选项
-    m_drawCursorCheck->setChecked(params.videoParams.drawCursor);
-    m_captureAudioCheck->setChecked(params.enableAudio);
-}
-
-QString RecorderMainWidget::formatTime(int64_t ms) {
-    int seconds = ms / 1000;
-    int minutes = seconds / 60;
-    int hours = minutes / 60;
-    
-    seconds %= 60;
-    minutes %= 60;
-    
-    return QString("%1:%2:%3")
-        .arg(hours, 2, 10, QChar('0'))
-        .arg(minutes, 2, 10, QChar('0'))
-        .arg(seconds, 2, 10, QChar('0'));
-}
-
-QString RecorderMainWidget::formatFileSize(int64_t bytes) {
-    const char* units[] = {"B", "KB", "MB", "GB", "TB"};
-    int unitIndex = 0;
-    double size = bytes;
-    
-    while (size >= 1024 && unitIndex < 4) {
-        size /= 1024;
-        unitIndex++;
-    }
-    
-    return QString("%1 %2").arg(size, 0, 'f', 1).arg(units[unitIndex]);
-}
-
-QString RecorderMainWidget::formatBitrate(int64_t bps) {
-    if (bps < 1000) {
-        return QString("%1 bps").arg(bps);
-    } else if (bps < 1000000) {
-        return QString("%1 Kbps").arg(bps / 1000.0, 0, 'f', 1);
-    } else {
-        return QString("%1 Mbps").arg(bps / 1000000.0, 0, 'f', 1);
-    }
-}
-
-// 独立音频/视频控制实现
-void RecorderMainWidget::onAudioStartClicked() {
-    if (!m_recorder) {
-        QMessageBox::warning(this, "警告", "录制器未初始化");
-        return;
-    }
-    
-    auto result = m_recorder->startAudioCapture();
-    if (result == av::ErrorCode::SUCCESS) {
-        m_statusLabel->setText("音频采集已启动");
-        updateIndependentControlButtons();
-        AV_LOGGER_INFO("Audio capture started independently from UI");
-    } else {
-        QMessageBox::warning(this, "错误", "启动音频采集失败");
-        AV_LOGGER_ERRORF("Failed to start audio capture: {}", static_cast<int>(result));
-    }
-}
-
-void RecorderMainWidget::onAudioStopClicked() {
-    if (!m_recorder) {
-        return;
-    }
-    
-    auto result = m_recorder->stopAudioCapture();
-    if (result == av::ErrorCode::SUCCESS) {
-        m_statusLabel->setText("音频采集已停止");
-        updateIndependentControlButtons();
-        AV_LOGGER_INFO("Audio capture stopped independently from UI");
-    } else {
-        QMessageBox::warning(this, "错误", "停止音频采集失败");
-    }
-}
-
-void RecorderMainWidget::onVideoCaptureClicked() {
-    if (!m_recorder) {
-        QMessageBox::warning(this, "警告", "录制器未初始化");
-        return;
-    }
-    
-    auto result = m_recorder->startVideoCapture();
-    if (result == av::ErrorCode::SUCCESS) {
-        m_statusLabel->setText("视频采集已启动");
-        updateIndependentControlButtons();
-        AV_LOGGER_INFO("Video capture started independently from UI");
-    } else {
-        QMessageBox::warning(this, "错误", "启动视频采集失败");
-        AV_LOGGER_ERRORF("Failed to start video capture: {}", static_cast<int>(result));
-    }
-}
-
-void RecorderMainWidget::onVideoStopClicked() {
-    if (!m_recorder) {
-        return;
-    }
-    
-    auto result = m_recorder->stopVideoCapture();
-    if (result == av::ErrorCode::SUCCESS) {
-        m_statusLabel->setText("视频采集已停止");
-        updateIndependentControlButtons();
-        AV_LOGGER_INFO("Video capture stopped independently from UI");
-    } else {
-        QMessageBox::warning(this, "错误", "停止视频采集失败");
-    }
-}
-
-void RecorderMainWidget::onAudioEnableChanged(bool enabled) {
-    if (!m_recorder) {
-        AV_LOGGER_ERROR("Recorder not initialized when trying to change audio enable state");
-        // 阻止信号递归,安全地恢复checkbox状态
-        m_audioEnableCheck->blockSignals(true);
-        m_audioEnableCheck->setChecked(!enabled);
-        m_audioEnableCheck->blockSignals(false);
-        QMessageBox::warning(this, "错误", "录制器未初始化,无法更改音频设置");
-        return;
-    }
-    
-    // 检查录制器状态,如果正在录制则不允许更改
-    if (m_isRecording) {
-        AV_LOGGER_WARNING("Cannot change audio enable state while recording");
-        // 阻止信号递归,安全地恢复checkbox状态
-        m_audioEnableCheck->blockSignals(true);
-        m_audioEnableCheck->setChecked(!enabled);
-        m_audioEnableCheck->blockSignals(false);
-        QMessageBox::warning(this, "警告", "录制过程中无法更改音频启用状态");
-        return;
-    }
-    
-    auto result = m_recorder->setAudioEnabled(enabled);
-    if (result == av::ErrorCode::SUCCESS) {
-        updateIndependentControlButtons();
-        AV_LOGGER_INFOF("Audio recording {} from UI", enabled ? "enabled" : "disabled");
-        
-        if (enabled) {
-            m_statusLabel->setText("音频录制已启用");
-        } else {
-            m_statusLabel->setText("音频录制已禁用");
-        }
-    } else {
-        // 记录详细的错误信息
-        AV_LOGGER_ERRORF("Failed to {} audio recording: error code {}", 
-                        enabled ? "enable" : "disable", static_cast<int>(result));
-        
-        // 阻止信号递归,安全地恢复checkbox状态
-        m_audioEnableCheck->blockSignals(true);
-        m_audioEnableCheck->setChecked(!enabled);
-        m_audioEnableCheck->blockSignals(false);
-        
-        // 根据错误类型显示不同的错误信息
-        QString errorMsg;
-        switch (result) {
-            case av::ErrorCode::INVALID_STATE:
-                errorMsg = "录制器状态无效,无法更改音频设置";
-                break;
-            case av::ErrorCode::NOT_INITIALIZED:
-                errorMsg = "音频模块未初始化";
-                break;
-            case av::ErrorCode::DEVICE_NOT_FOUND:
-                errorMsg = "未找到音频设备";
-                break;
-            default:
-                errorMsg = enabled ? "启用音频录制失败" : "禁用音频录制失败";
-                errorMsg += QString("(错误代码:%1)").arg(static_cast<int>(result));
-                break;
-        }
-        
-        QMessageBox::warning(this, "错误", errorMsg);
-    }
-}
-
-void RecorderMainWidget::onVideoEnableChanged(bool enabled) {
-    if (!m_recorder) {
-        AV_LOGGER_ERROR("Recorder not initialized when trying to change video enable state");
-        // 阻止信号递归,安全地恢复checkbox状态
-        m_videoEnableCheck->blockSignals(true);
-        m_videoEnableCheck->setChecked(!enabled);
-        m_videoEnableCheck->blockSignals(false);
-        QMessageBox::warning(this, "错误", "录制器未初始化,无法更改视频设置");
-        return;
-    }
-    
-    // 检查录制器状态,如果正在录制则不允许更改
-    if (m_isRecording) {
-        AV_LOGGER_WARNING("Cannot change video enable state while recording");
-        // 阻止信号递归,安全地恢复checkbox状态
-        m_videoEnableCheck->blockSignals(true);
-        m_videoEnableCheck->setChecked(!enabled);
-        m_videoEnableCheck->blockSignals(false);
-        QMessageBox::warning(this, "警告", "录制过程中无法更改视频启用状态");
-        return;
-    }
-    
-    auto result = m_recorder->setVideoEnabled(enabled);
-    if (result == av::ErrorCode::SUCCESS) {
-        updateIndependentControlButtons();
-        AV_LOGGER_INFOF("Video recording {} from UI", enabled ? "enabled" : "disabled");
-        
-        if (enabled) {
-            m_statusLabel->setText("视频录制已启用");
-        } else {
-            m_statusLabel->setText("视频录制已禁用");
-        }
-    } else {
-        // 记录详细的错误信息
-        AV_LOGGER_ERRORF("Failed to {} video recording: error code {}", 
-                        enabled ? "enable" : "disable", static_cast<int>(result));
-        
-        // 阻止信号递归,安全地恢复checkbox状态
-        m_videoEnableCheck->blockSignals(true);
-        m_videoEnableCheck->setChecked(!enabled);
-        m_videoEnableCheck->blockSignals(false);
-        
-        // 根据错误类型显示不同的错误信息
-        QString errorMsg;
-        switch (result) {
-            case av::ErrorCode::INVALID_STATE:
-                errorMsg = "录制器状态无效,无法更改视频设置";
-                break;
-            case av::ErrorCode::NOT_INITIALIZED:
-                errorMsg = "视频模块未初始化";
-                break;
-            case av::ErrorCode::DEVICE_NOT_FOUND:
-                errorMsg = "未找到视频设备";
-                break;
-            default:
-                errorMsg = enabled ? "启用视频录制失败" : "禁用视频录制失败";
-                errorMsg += QString("(错误代码:%1)").arg(static_cast<int>(result));
-                break;
-        }
-        
-        QMessageBox::warning(this, "错误", errorMsg);
-    }
-}
-
-void RecorderMainWidget::updateIndependentControlButtons() {
-    if (!m_recorder) {
-        return;
-    }
-    
-    // 更新音频按钮状态
-    bool audioRecording = m_recorder->isAudioRecording();
-    bool audioCapturing = m_recorder->isAudioCapturing();
-    
-    m_audioStartButton->setEnabled(!audioRecording && m_audioEnableCheck->isChecked());
-    m_audioStopButton->setEnabled(audioCapturing);
-    
-    if (audioRecording) {
-        m_audioStartButton->setText("音频录制中");
-        m_audioStopButton->setText("停止音频");
-    } else if (audioCapturing) {
-        m_audioStartButton->setText("启动音频");
-        m_audioStopButton->setText("停止音频");
-    } else {
-        m_audioStartButton->setText("启动音频");
-        m_audioStopButton->setText("停止音频");
-    }
-    
-    // 更新视频按钮状态
-    bool videoRecording = m_recorder->isVideoRecording();
-    bool videoCapturing = m_recorder->isVideoCapturing();
-    
-    m_videoCaptureButton->setEnabled(!videoRecording && m_videoEnableCheck->isChecked());
-    m_videoStopButton->setEnabled(videoCapturing);
-    
-    if (videoRecording) {
-        m_videoCaptureButton->setText("视频录制中");
-        m_videoStopButton->setText("停止视频");
-    } else if (videoCapturing) {
-        m_videoCaptureButton->setText("启动视频");
-        m_videoStopButton->setText("停止视频");
-    } else {
-        m_videoCaptureButton->setText("启动视频");
-        m_videoStopButton->setText("停止视频");
-    }
-}
-
-void RecorderMainWidget::resetRecorderForRestart() {
-    AV_LOGGER_INFO("Resetting recorder for restart");
-    
-    // 确保录制器处于正确的状态
-    if (m_recorder) {
-        // 强制停止录制器(如果还在运行)
-        m_recorder->close();
-        
-        // 重新创建录制器实例
-        m_recorder = utils::createAVRecorder();
-        if (!m_recorder) {
-            AV_LOGGER_ERROR("Failed to recreate recorder");
-            QMessageBox::critical(this, "错误", "重新创建录制器失败");
-            return;
-        }
-    }
-    
-    // 重置UI状态
-    m_isRecording = false;
-    m_isPaused = false;
-    m_isPreviewActive = false;
-    m_recordDuration = 0;
-    
-    // 更新UI
-    updateUIState();
-    m_statusLabel->setText("就绪");
-    
-    AV_LOGGER_INFO("Recorder reset completed");
-}
-
-// #include "recorder_main_widget.moc"

+ 0 - 349
AV/code/recorder/ui/recorder_main_widget.h

@@ -1,349 +0,0 @@
-#ifndef AV_RECORDER_MAIN_WIDGET_H
-#define AV_RECORDER_MAIN_WIDGET_H
-
-#include <QWidget>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QGridLayout>
-#include <QPushButton>
-#include <QLabel>
-#include <QComboBox>
-#include <QCheckBox>
-#include <QSlider>
-#include <QSpinBox>
-#include <QDoubleSpinBox>
-#include <QLineEdit>
-#include <QProgressBar>
-#include <QTimer>
-#include <QTime>
-#include <QGroupBox>
-#include <QSplitter>
-#include <QStatusBar>
-#include <QFileDialog>
-#include <QMessageBox>
-#include <QApplication>
-#include <QDesktopWidget>
-#include <QScreen>
-#include <QScrollArea>
-#include <QTabWidget>
-#include <QMutex>
-#include <memory>
-
-#include "../recorder.h"
-#include "recorder_video_widget.h"
-#include "recorder_audio_widget.h"
-#include "recorder_settings_dialog.h"
-
-using namespace av::recorder;
-
-/**
- * 录制器主界面
- * 
- * 提供完整的音视频录制功能界面,包括:
- * - 录制控制(开始/停止/暂停/恢复)
- * - 实时预览窗口
- * - 音频控制和监控
- * - 录制设置
- * - 状态显示
- */
-class RecorderMainWidget : public QWidget {
-    Q_OBJECT
-
-public:
-    explicit RecorderMainWidget(QWidget* parent = nullptr);
-    ~RecorderMainWidget();
-
-    /**
-     * 初始化录制器
-     */
-    bool initialize();
-    
-    /**
-     * 清理资源
-     */
-    void cleanup();
-
-public slots:
-    /**
-     * 开始录制
-     */
-    void startRecording();
-    
-    /**
-     * 停止录制
-     */
-    void stopRecording();
-    
-    /**
-     * 暂停录制
-     */
-    void pauseRecording();
-    
-    /**
-     * 恢复录制
-     */
-    void resumeRecording();
-    
-    /**
-     * 开始预览
-     */
-    void startPreview();
-    
-    /**
-     * 停止预览
-     */
-    void stopPreview();
-    
-    /**
-     * 打开设置对话框
-     */
-    void openSettings();
-    
-    /**
-     * 选择输出文件
-     */
-    void selectOutputFile();
-    
-    /**
-     * 更新采集设备列表
-     */
-    void updateCaptureDevices();
-    
-    /**
-     * 采集源改变
-     */
-    void onCaptureSourceChanged();
-    
-    /**
-     * 采集方法改变
-     */
-    void onCaptureMethodChanged();
-    
-    /**
-     * 音频设备改变
-     */
-    void onAudioDeviceChanged();
-    
-    /**
-     * 音量改变
-     */
-    void onVolumeChanged(double volume);
-    
-    /**
-     * 静音状态改变
-     */
-    void onMuteChanged(bool muted);
-    
-    /**
-     * 更新录制状态
-     */
-    void updateRecordingStatus();
-    
-    /**
-     * 更新预览帧
-     */
-    void updatePreviewFrame();
-    
-    /**
-     * 更新音频电平
-     */
-    void updateAudioLevel();
-    
-    /**
-     * 独立音频/视频控制槽函数
-     */
-    void onAudioStartClicked();
-    void onAudioStopClicked();
-    void onVideoCaptureClicked();
-    void onVideoStopClicked();
-    void onAudioEnableChanged(bool enabled);
-    void onVideoEnableChanged(bool enabled);
-    
-    /**
-     * 更新独立控制按钮状态
-     */
-    void updateIndependentControlButtons();
-
-private slots:
-    /**
-     * 录制器状态改变
-     */
-    void onRecorderStateChanged(RecorderState state);
-    
-    /**
-     * 录制器错误
-     */
-    void onRecorderError(const QString& error);
-    
-    /**
-     * 统计信息更新
-     */
-    void onStatisticsUpdated();
-
-private:
-    /**
-     * 初始化UI
-     */
-    void initUI();
-    
-    /**
-     * 初始化控制面板
-     */
-    void initControlPanel();
-    
-    /**
-     * 初始化独立控制面板
-     */
-    void initIndependentControlPanel();
-    
-    /**
-     * 初始化预览面板
-     */
-    void initPreviewPanel();
-    
-    /**
-     * 初始化音频面板
-     */
-    void initAudioPanel();
-    
-    /**
-     * 初始化设置面板
-     */
-    void initSettingsPanel();
-    
-    /**
-     * 初始化状态栏
-     */
-    void initStatusBar();
-    
-    /**
-     * 重置录制器状态以便重新启动
-     */
-    void resetRecorderForRestart();
-    
-    /**
-     * 初始化连接
-     */
-    void initConnections();
-    
-    /**
-     * 更新UI状态
-     */
-    void updateUIState();
-    
-    /**
-     * 获取当前录制参数
-     */
-    AVRecorderParams getCurrentParams();
-    
-    /**
-     * 应用录制参数
-     */
-    void applyRecorderParams(const AVRecorderParams& params);
-    
-    /**
-     * 格式化时间
-     */
-    QString formatTime(int64_t ms);
-    
-    /**
-     * 格式化文件大小
-     */
-    QString formatFileSize(int64_t bytes);
-    
-    /**
-     * 格式化比特率
-     */
-    QString formatBitrate(int64_t bps);
-
-private:
-    // 录制器
-    std::unique_ptr<AVRecorder> m_recorder;
-    bool m_isInitialized;
-    bool m_isRecording;
-    bool m_isPaused;
-    bool m_isPreviewActive;
-    
-    // UI组件 - 主布局
-    QSplitter* m_mainSplitter;
-    QWidget* m_leftPanel;
-    QWidget* m_rightPanel;
-    
-    // UI组件 - 控制面板
-    QGroupBox* m_controlGroup;
-    QPushButton* m_recordButton;
-    QPushButton* m_pauseButton;
-    QPushButton* m_stopButton;
-    QPushButton* m_previewButton;
-    QPushButton* m_settingsButton;
-    QLabel* m_recordTimeLabel;
-    QLabel* m_recordStatusLabel;
-    
-    // 独立控制按钮
-    QGroupBox* m_independentControlGroup;
-    QPushButton* m_audioStartButton;
-    QPushButton* m_audioStopButton;
-    QPushButton* m_videoCaptureButton;
-    QPushButton* m_videoStopButton;
-    QCheckBox* m_audioEnableCheck;
-    QCheckBox* m_videoEnableCheck;
-    
-    // UI组件 - 采集设置
-    QGroupBox* m_captureGroup;
-    QComboBox* m_captureMethodCombo;
-    QComboBox* m_captureSourceCombo;
-    QComboBox* m_audioDeviceCombo;
-    QPushButton* m_refreshDevicesButton;
-    QCheckBox* m_drawCursorCheck;
-    QCheckBox* m_captureAudioCheck;
-    
-    // UI组件 - 输出设置
-    QGroupBox* m_outputGroup;
-    QLineEdit* m_outputPathEdit;
-    QPushButton* m_browseOutputButton;
-    QComboBox* m_outputFormatCombo;
-    
-    // UI组件 - 预览面板
-    QGroupBox* m_previewGroup;
-    RecorderVideoWidget* m_videoWidget;
-    
-    // UI组件 - 音频面板
-    QGroupBox* m_audioGroup;
-    RecorderAudioWidget* m_microphoneWidget;
-    RecorderAudioWidget* m_speakerWidget;
-    
-    // UI组件 - 统计信息
-    QGroupBox* m_statsGroup;
-    QLabel* m_fpsLabel;
-    QLabel* m_bitrateLabel;
-    QLabel* m_framesLabel;
-    QLabel* m_droppedFramesLabel;
-    QLabel* m_fileSizeLabel;
-    
-    // UI组件 - 状态栏
-    QStatusBar* m_statusBar;
-    QLabel* m_statusLabel;
-    QProgressBar* m_progressBar;
-    
-    // 定时器
-    QTimer* m_updateTimer;
-    QTimer* m_previewTimer;
-    QTimer* m_audioLevelTimer;
-    
-    // 录制状态
-    QTime m_recordStartTime;
-    int64_t m_recordDuration;
-    
-    // 设置对话框
-    RecorderSettingsDialog* m_settingsDialog;
-    
-    // 线程安全
-    QMutex m_mutex;
-    
-    // 常量
-    static constexpr int UPDATE_INTERVAL_MS = 100;
-    static constexpr int PREVIEW_INTERVAL_MS = 33; // ~30 FPS
-    static constexpr int AUDIO_LEVEL_INTERVAL_MS = 50;
-};
-
-#endif // AV_RECORDER_MAIN_WIDGET_H

+ 0 - 1461
AV/code/recorder/ui/recorder_settings_dialog.cpp

@@ -1,1461 +0,0 @@
-#include "recorder_settings_dialog.h"
-#include "../recorder.h"
-#include <QApplication>
-#include <QMessageBox>
-#include <QDir>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QDateTime>
-#include <QDebug>
-#include <QHeaderView>
-#include <QSplitter>
-#include <QFormLayout>
-#include <QButtonGroup>
-#include <QRadioButton>
-#include <QScrollArea>
-#include <QCloseEvent>
-
-RecorderSettingsDialog::RecorderSettingsDialog(av::recorder::RecorderModule* recorderModule, QWidget* parent)
-    : QDialog(parent)
-    , m_recorderModule(recorderModule)
-    , m_tabWidget(nullptr)
-    , m_mainLayout(nullptr)
-    , m_buttonLayout(nullptr)
-    , m_okButton(nullptr)
-    , m_cancelButton(nullptr)
-    , m_applyButton(nullptr)
-    , m_resetButton(nullptr)
-    , m_settingsChanged(false)
-    , m_updating(false) {
-    
-    setWindowTitle("录制器设置");
-    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
-    setModal(true);
-    resize(800, 600);
-    
-    // 初始化定时器
-    m_previewUpdateTimer = new QTimer(this);
-    m_previewUpdateTimer->setSingleShot(true);
-    m_previewUpdateTimer->setInterval(500);
-    connect(m_previewUpdateTimer, &QTimer::timeout, this, &RecorderSettingsDialog::updatePreview);
-    
-    m_deviceRefreshTimer = new QTimer(this);
-    m_deviceRefreshTimer->setInterval(5000); // 每5秒刷新一次设备列表
-    connect(m_deviceRefreshTimer, &QTimer::timeout, this, &RecorderSettingsDialog::refreshDevices);
-    
-    initializeUI();
-    connectSignals();
-    
-    // 加载默认设置
-    m_currentSettings = getDefaultSettings();
-    m_originalSettings = m_currentSettings;
-    
-    loadSettings();
-    writeSettingsToUI();
-    updateUI();
-}
-
-RecorderSettingsDialog::~RecorderSettingsDialog() = default;
-
-void RecorderSettingsDialog::setSettings(const Settings& settings) {
-    m_currentSettings = settings;
-    writeSettingsToUI();
-    updateUI();
-}
-
-RecorderSettingsDialog::Settings RecorderSettingsDialog::getSettings() const {
-    return m_currentSettings;
-}
-
-void RecorderSettingsDialog::showCategory(SettingsCategory category) {
-    if (m_tabWidget) {
-        m_tabWidget->setCurrentIndex(static_cast<int>(category));
-    }
-    show();
-    raise();
-    activateWindow();
-}
-
-void RecorderSettingsDialog::resetToDefaults() {
-    int ret = QMessageBox::question(this, "重置设置", 
-                                   "确定要重置所有设置为默认值吗?",
-                                   QMessageBox::Yes | QMessageBox::No,
-                                   QMessageBox::No);
-    
-    if (ret == QMessageBox::Yes) {
-        m_currentSettings = getDefaultSettings();
-        writeSettingsToUI();
-        updateUI();
-        m_settingsChanged = true;
-    }
-}
-
-void RecorderSettingsDialog::loadSettings() {
-    QSettings settings("AV", "Recorder");
-    
-    // 音频设置
-    settings.beginGroup("Audio");
-    m_currentSettings.audio.deviceName = settings.value("deviceName", "").toString();
-    m_currentSettings.audio.sampleRate = settings.value("sampleRate", 44100).toInt();
-    m_currentSettings.audio.channels = settings.value("channels", 2).toInt();
-    m_currentSettings.audio.bitDepth = settings.value("bitDepth", 16).toInt();
-    m_currentSettings.audio.codec = settings.value("codec", "aac").toString();
-    m_currentSettings.audio.bitrate = settings.value("bitrate", 128000).toInt();
-    m_currentSettings.audio.enableNoiseSuppression = settings.value("enableNoiseSuppression", false).toBool();
-    m_currentSettings.audio.enableEchoCancellation = settings.value("enableEchoCancellation", false).toBool();
-    m_currentSettings.audio.inputGain = settings.value("inputGain", 1.0).toDouble();
-    settings.endGroup();
-    
-    // 视频设置
-    settings.beginGroup("Video");
-    m_currentSettings.video.deviceName = settings.value("deviceName", "").toString();
-    m_currentSettings.video.width = settings.value("width", 1920).toInt();
-    m_currentSettings.video.height = settings.value("height", 1080).toInt();
-    m_currentSettings.video.frameRate = settings.value("frameRate", 30.0).toDouble();
-    m_currentSettings.video.codec = settings.value("codec", "h264").toString();
-    m_currentSettings.video.bitrate = settings.value("bitrate", 5000000).toInt();
-    m_currentSettings.video.preset = settings.value("preset", "medium").toString();
-    m_currentSettings.video.profile = settings.value("profile", "high").toString();
-    m_currentSettings.video.keyFrameInterval = settings.value("keyFrameInterval", 60).toInt();
-    m_currentSettings.video.enableHardwareAcceleration = settings.value("enableHardwareAcceleration", true).toBool();
-    settings.endGroup();
-    
-    // 输出设置
-    settings.beginGroup("Output");
-    m_currentSettings.output.outputDirectory = settings.value("outputDirectory", 
-        QStandardPaths::writableLocation(QStandardPaths::MoviesLocation)).toString();
-    m_currentSettings.output.fileNameTemplate = settings.value("fileNameTemplate", "recording_%Y%m%d_%H%M%S").toString();
-    m_currentSettings.output.containerFormat = settings.value("containerFormat", "mp4").toString();
-    m_currentSettings.output.autoCreateDirectory = settings.value("autoCreateDirectory", true).toBool();
-    m_currentSettings.output.overwriteExisting = settings.value("overwriteExisting", false).toBool();
-    m_currentSettings.output.maxFileSize = settings.value("maxFileSize", 0).toInt();
-    m_currentSettings.output.maxDuration = settings.value("maxDuration", 0).toInt();
-    settings.endGroup();
-    
-    // 高级设置
-    settings.beginGroup("Advanced");
-    m_currentSettings.advanced.bufferSize = settings.value("bufferSize", 4096).toInt();
-    m_currentSettings.advanced.threadCount = settings.value("threadCount", 0).toInt();
-    m_currentSettings.advanced.enableGPUAcceleration = settings.value("enableGPUAcceleration", true).toBool();
-    m_currentSettings.advanced.gpuDevice = settings.value("gpuDevice", "").toString();
-    m_currentSettings.advanced.enableLowLatency = settings.value("enableLowLatency", false).toBool();
-    m_currentSettings.advanced.enableRealTimeEncoding = settings.value("enableRealTimeEncoding", true).toBool();
-    m_currentSettings.advanced.encodingPriority = settings.value("encodingPriority", 0).toInt();
-    settings.endGroup();
-}
-
-void RecorderSettingsDialog::saveSettings() {
-    QSettings settings("AV", "Recorder");
-    
-    // 音频设置
-    settings.beginGroup("Audio");
-    settings.setValue("deviceName", m_currentSettings.audio.deviceName);
-    settings.setValue("sampleRate", m_currentSettings.audio.sampleRate);
-    settings.setValue("channels", m_currentSettings.audio.channels);
-    settings.setValue("bitDepth", m_currentSettings.audio.bitDepth);
-    settings.setValue("codec", m_currentSettings.audio.codec);
-    settings.setValue("bitrate", m_currentSettings.audio.bitrate);
-    settings.setValue("enableNoiseSuppression", m_currentSettings.audio.enableNoiseSuppression);
-    settings.setValue("enableEchoCancellation", m_currentSettings.audio.enableEchoCancellation);
-    settings.setValue("inputGain", m_currentSettings.audio.inputGain);
-    settings.endGroup();
-    
-    // 视频设置
-    settings.beginGroup("Video");
-    settings.setValue("deviceName", m_currentSettings.video.deviceName);
-    settings.setValue("width", m_currentSettings.video.width);
-    settings.setValue("height", m_currentSettings.video.height);
-    settings.setValue("frameRate", m_currentSettings.video.frameRate);
-    settings.setValue("codec", m_currentSettings.video.codec);
-    settings.setValue("bitrate", m_currentSettings.video.bitrate);
-    settings.setValue("preset", m_currentSettings.video.preset);
-    settings.setValue("profile", m_currentSettings.video.profile);
-    settings.setValue("keyFrameInterval", m_currentSettings.video.keyFrameInterval);
-    settings.setValue("enableHardwareAcceleration", m_currentSettings.video.enableHardwareAcceleration);
-    settings.endGroup();
-    
-    // 输出设置
-    settings.beginGroup("Output");
-    settings.setValue("outputDirectory", m_currentSettings.output.outputDirectory);
-    settings.setValue("fileNameTemplate", m_currentSettings.output.fileNameTemplate);
-    settings.setValue("containerFormat", m_currentSettings.output.containerFormat);
-    settings.setValue("autoCreateDirectory", m_currentSettings.output.autoCreateDirectory);
-    settings.setValue("overwriteExisting", m_currentSettings.output.overwriteExisting);
-    settings.setValue("maxFileSize", m_currentSettings.output.maxFileSize);
-    settings.setValue("maxDuration", m_currentSettings.output.maxDuration);
-    settings.endGroup();
-    
-    // 高级设置
-    settings.beginGroup("Advanced");
-    settings.setValue("bufferSize", m_currentSettings.advanced.bufferSize);
-    settings.setValue("threadCount", m_currentSettings.advanced.threadCount);
-    settings.setValue("enableGPUAcceleration", m_currentSettings.advanced.enableGPUAcceleration);
-    settings.setValue("gpuDevice", m_currentSettings.advanced.gpuDevice);
-    settings.setValue("enableLowLatency", m_currentSettings.advanced.enableLowLatency);
-    settings.setValue("enableRealTimeEncoding", m_currentSettings.advanced.enableRealTimeEncoding);
-    settings.setValue("encodingPriority", m_currentSettings.advanced.encodingPriority);
-    settings.endGroup();
-    
-    settings.sync();
-}
-
-bool RecorderSettingsDialog::validateSettings(QString* errorMessage) const {
-    // 验证音频设置
-    if (m_currentSettings.audio.sampleRate <= 0) {
-        if (errorMessage) *errorMessage = "无效的音频采样率";
-        return false;
-    }
-    
-    if (m_currentSettings.audio.channels <= 0 || m_currentSettings.audio.channels > 8) {
-        if (errorMessage) *errorMessage = "无效的音频声道数";
-        return false;
-    }
-    
-    if (m_currentSettings.audio.bitrate <= 0) {
-        if (errorMessage) *errorMessage = "无效的音频比特率";
-        return false;
-    }
-    
-    // 验证视频设置
-    if (m_currentSettings.video.width <= 0 || m_currentSettings.video.height <= 0) {
-        if (errorMessage) *errorMessage = "无效的视频分辨率";
-        return false;
-    }
-    
-    if (m_currentSettings.video.frameRate <= 0) {
-        if (errorMessage) *errorMessage = "无效的视频帧率";
-        return false;
-    }
-    
-    if (m_currentSettings.video.bitrate <= 0) {
-        if (errorMessage) *errorMessage = "无效的视频比特率";
-        return false;
-    }
-    
-    // 验证输出设置
-    if (!validateOutputDirectory(m_currentSettings.output.outputDirectory)) {
-        if (errorMessage) *errorMessage = "输出目录无效或无法访问";
-        return false;
-    }
-    
-    if (m_currentSettings.output.fileNameTemplate.isEmpty()) {
-        if (errorMessage) *errorMessage = "文件名模板不能为空";
-        return false;
-    }
-    
-    return true;
-}
-
-void RecorderSettingsDialog::showEvent(QShowEvent* event) {
-    QDialog::showEvent(event);
-    
-    // 刷新设备列表
-    updateAudioDevices();
-    updateVideoDevices();
-    updateCodecLists();
-    
-    // 启动设备刷新定时器
-    m_deviceRefreshTimer->start();
-}
-
-void RecorderSettingsDialog::closeEvent(QCloseEvent* event) {
-    // 停止定时器
-    m_deviceRefreshTimer->stop();
-    
-    if (m_settingsChanged) {
-        int ret = QMessageBox::question(this, "保存设置", 
-                                       "设置已修改,是否保存?",
-                                       QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,
-                                       QMessageBox::Save);
-        
-        if (ret == QMessageBox::Save) {
-            onApplySettings();
-        } else if (ret == QMessageBox::Cancel) {
-            event->ignore();
-            return;
-        }
-    }
-    
-    QDialog::closeEvent(event);
-}
-
-void RecorderSettingsDialog::onTabChanged(int index) {
-    Q_UNUSED(index)
-    updateUI();
-}
-
-void RecorderSettingsDialog::onAudioDeviceChanged(const QString& device) {
-    if (m_updating) return;
-    
-    m_currentSettings.audio.deviceName = device;
-    m_settingsChanged = true;
-    updateUI();
-}
-
-void RecorderSettingsDialog::onVideoDeviceChanged(const QString& device) {
-    if (m_updating) return;
-    
-    m_currentSettings.video.deviceName = device;
-    m_settingsChanged = true;
-    updateUI();
-}
-
-void RecorderSettingsDialog::onOutputDirectoryBrowse() {
-    QString dir = QFileDialog::getExistingDirectory(this, "选择输出目录", 
-                                                   m_currentSettings.output.outputDirectory);
-    if (!dir.isEmpty()) {
-        m_currentSettings.output.outputDirectory = dir;
-        if (m_outputDirectoryEdit) {
-            m_outputDirectoryEdit->setText(dir);
-        }
-        m_settingsChanged = true;
-        updateUI();
-    }
-}
-
-void RecorderSettingsDialog::onFileNameTemplateChanged() {
-    if (m_updating || !m_fileNameTemplateEdit) return;
-    
-    m_currentSettings.output.fileNameTemplate = m_fileNameTemplateEdit->text();
-    m_settingsChanged = true;
-    
-    // 延迟更新预览
-    m_previewUpdateTimer->start();
-}
-
-void RecorderSettingsDialog::onPresetSave() {
-    // TODO: 实现预设保存
-    QMessageBox::information(this, "预设管理", "预设保存功能待实现");
-}
-
-void RecorderSettingsDialog::onPresetLoad() {
-    // TODO: 实现预设加载
-    QMessageBox::information(this, "预设管理", "预设加载功能待实现");
-}
-
-void RecorderSettingsDialog::onPresetDelete() {
-    // TODO: 实现预设删除
-    QMessageBox::information(this, "预设管理", "预设删除功能待实现");
-}
-
-void RecorderSettingsDialog::onPresetExport() {
-    // TODO: 实现预设导出
-    QMessageBox::information(this, "预设管理", "预设导出功能待实现");
-}
-
-void RecorderSettingsDialog::onPresetImport() {
-    // TODO: 实现预设导入
-    QMessageBox::information(this, "预设管理", "预设导入功能待实现");
-}
-
-void RecorderSettingsDialog::onTestAudioDevice() {
-    // TODO: 实现音频设备测试
-    QMessageBox::information(this, "设备测试", "音频设备测试功能待实现");
-}
-
-void RecorderSettingsDialog::onTestVideoDevice() {
-    // TODO: 实现视频设备测试
-    QMessageBox::information(this, "设备测试", "视频设备测试功能待实现");
-}
-
-void RecorderSettingsDialog::onResetCategory() {
-    int currentTab = m_tabWidget ? m_tabWidget->currentIndex() : 0;
-    
-    int ret = QMessageBox::question(this, "重置设置", 
-                                   "确定要重置当前页面的设置为默认值吗?",
-                                   QMessageBox::Yes | QMessageBox::No,
-                                   QMessageBox::No);
-    
-    if (ret == QMessageBox::Yes) {
-        Settings defaultSettings = getDefaultSettings();
-        
-        switch (currentTab) {
-        case AudioCategory:
-            m_currentSettings.audio = defaultSettings.audio;
-            break;
-        case VideoCategory:
-            m_currentSettings.video = defaultSettings.video;
-            break;
-        case OutputCategory:
-            m_currentSettings.output = defaultSettings.output;
-            break;
-        case AdvancedCategory:
-            m_currentSettings.advanced = defaultSettings.advanced;
-            break;
-        default:
-            break;
-        }
-        
-        writeSettingsToUI();
-        updateUI();
-        m_settingsChanged = true;
-    }
-}
-
-void RecorderSettingsDialog::onApplySettings() {
-    readSettingsFromUI();
-    
-    QString errorMessage;
-    if (!validateSettings(&errorMessage)) {
-        QMessageBox::warning(this, "设置错误", errorMessage);
-        return;
-    }
-    
-    saveSettings();
-    emit settingsApplied(m_currentSettings);
-    
-    m_originalSettings = m_currentSettings;
-    m_settingsChanged = false;
-    
-    if (m_applyButton) {
-        m_applyButton->setEnabled(false);
-    }
-}
-
-void RecorderSettingsDialog::onOkClicked() {
-    onApplySettings();
-    accept();
-}
-
-void RecorderSettingsDialog::onCancelClicked() {
-    if (m_settingsChanged) {
-        int ret = QMessageBox::question(this, "取消设置", 
-                                       "设置已修改,确定要取消吗?",
-                                       QMessageBox::Yes | QMessageBox::No,
-                                       QMessageBox::No);
-        
-        if (ret == QMessageBox::No) {
-            return;
-        }
-    }
-    
-    // 恢复原始设置
-    m_currentSettings = m_originalSettings;
-    reject();
-}
-
-void RecorderSettingsDialog::updatePreview() {
-    if (m_fileNamePreviewLabel) {
-        m_fileNamePreviewLabel->setText(formatFileNamePreview());
-    }
-}
-
-void RecorderSettingsDialog::refreshDevices() {
-    updateAudioDevices();
-    updateVideoDevices();
-}
-
-void RecorderSettingsDialog::initializeUI() {
-    // 创建主布局
-    m_mainLayout = new QVBoxLayout(this);
-    m_mainLayout->setContentsMargins(8, 8, 8, 8);
-    m_mainLayout->setSpacing(8);
-    
-    // 创建选项卡
-    m_tabWidget = new QTabWidget();
-    m_tabWidget->addTab(createAudioSettingsPage(), "音频");
-    m_tabWidget->addTab(createVideoSettingsPage(), "视频");
-    m_tabWidget->addTab(createOutputSettingsPage(), "输出");
-    m_tabWidget->addTab(createAdvancedSettingsPage(), "高级");
-    m_tabWidget->addTab(createPresetSettingsPage(), "预设");
-    
-    // 创建按钮布局
-    m_buttonLayout = new QHBoxLayout();
-    
-    m_resetButton = new QPushButton("重置");
-    m_resetButton->setToolTip("重置当前页面设置为默认值");
-    
-    m_buttonLayout->addWidget(m_resetButton);
-    m_buttonLayout->addStretch();
-    
-    m_okButton = new QPushButton("确定");
-    m_okButton->setDefault(true);
-    
-    m_cancelButton = new QPushButton("取消");
-    
-    m_applyButton = new QPushButton("应用");
-    m_applyButton->setEnabled(false);
-    
-    m_buttonLayout->addWidget(m_okButton);
-    m_buttonLayout->addWidget(m_cancelButton);
-    m_buttonLayout->addWidget(m_applyButton);
-    
-    // 添加到主布局
-    m_mainLayout->addWidget(m_tabWidget);
-    m_mainLayout->addLayout(m_buttonLayout);
-    
-    // 设置样式
-    setStyleSheet(R"(
-        QDialog {
-            background-color: #2b2b2b;
-            color: #fff;
-        }
-        QTabWidget::pane {
-            border: 1px solid #555;
-            background-color: #333;
-        }
-        QTabBar::tab {
-            background-color: #444;
-            color: #fff;
-            padding: 8px 16px;
-            margin-right: 2px;
-        }
-        QTabBar::tab:selected {
-            background-color: #0a84ff;
-        }
-        QTabBar::tab:hover {
-            background-color: #555;
-        }
-        QGroupBox {
-            font-weight: bold;
-            border: 1px solid #555;
-            border-radius: 4px;
-            margin-top: 8px;
-            padding-top: 8px;
-        }
-        QGroupBox::title {
-            subcontrol-origin: margin;
-            left: 8px;
-            padding: 0 4px 0 4px;
-        }
-        QLabel {
-            color: #fff;
-        }
-        QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox {
-            background-color: #444;
-            border: 1px solid #666;
-            border-radius: 3px;
-            color: #fff;
-            padding: 4px;
-        }
-        QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QDoubleSpinBox:focus {
-            border-color: #0a84ff;
-        }
-        QPushButton {
-            background-color: #444;
-            border: 1px solid #666;
-            border-radius: 3px;
-            color: #fff;
-            padding: 6px 12px;
-        }
-        QPushButton:hover {
-            background-color: #555;
-        }
-        QPushButton:pressed {
-            background-color: #333;
-        }
-        QPushButton:default {
-            background-color: #0a84ff;
-        }
-        QCheckBox {
-            color: #fff;
-        }
-        QCheckBox::indicator {
-            width: 16px;
-            height: 16px;
-        }
-        QCheckBox::indicator:unchecked {
-            background-color: #444;
-            border: 1px solid #666;
-        }
-        QCheckBox::indicator:checked {
-            background-color: #0a84ff;
-            border: 1px solid #0a84ff;
-        }
-        QSlider::groove:horizontal {
-            border: 1px solid #555;
-            height: 6px;
-            background: #333;
-            border-radius: 3px;
-        }
-        QSlider::handle:horizontal {
-            background: #0a84ff;
-            border: 1px solid #0a84ff;
-            width: 14px;
-            margin: -4px 0;
-            border-radius: 7px;
-        }
-        QSlider::sub-page:horizontal {
-            background: #0a84ff;
-            border-radius: 3px;
-        }
-    )");
-}
-
-QWidget* RecorderSettingsDialog::createAudioSettingsPage() {
-    QWidget* page = new QWidget();
-    QVBoxLayout* layout = new QVBoxLayout(page);
-    layout->setContentsMargins(16, 16, 16, 16);
-    layout->setSpacing(12);
-    
-    // 音频设备组
-    QGroupBox* deviceGroup = new QGroupBox("音频设备");
-    QFormLayout* deviceLayout = new QFormLayout(deviceGroup);
-    
-    m_audioDeviceCombo = new QComboBox();
-    m_testAudioButton = new QPushButton("测试");
-    m_testAudioButton->setMaximumWidth(60);
-    
-    QHBoxLayout* deviceControlLayout = new QHBoxLayout();
-    deviceControlLayout->addWidget(m_audioDeviceCombo);
-    deviceControlLayout->addWidget(m_testAudioButton);
-    
-    deviceLayout->addRow("设备:", deviceControlLayout);
-    
-    // 音频格式组
-    QGroupBox* formatGroup = new QGroupBox("音频格式");
-    QFormLayout* formatLayout = new QFormLayout(formatGroup);
-    
-    m_audioSampleRateCombo = new QComboBox();
-    m_audioSampleRateCombo->addItems({"8000", "16000", "22050", "44100", "48000", "96000"});
-    m_audioSampleRateCombo->setCurrentText("44100");
-    
-    m_audioChannelsCombo = new QComboBox();
-    m_audioChannelsCombo->addItems({"1 (单声道)", "2 (立体声)", "6 (5.1)", "8 (7.1)"});
-    m_audioChannelsCombo->setCurrentIndex(1);
-    
-    m_audioBitDepthCombo = new QComboBox();
-    m_audioBitDepthCombo->addItems({"16", "24", "32"});
-    m_audioBitDepthCombo->setCurrentText("16");
-    
-    formatLayout->addRow("采样率:", m_audioSampleRateCombo);
-    formatLayout->addRow("声道:", m_audioChannelsCombo);
-    formatLayout->addRow("位深:", m_audioBitDepthCombo);
-    
-    // 音频编码组
-    QGroupBox* codecGroup = new QGroupBox("音频编码");
-    QFormLayout* codecLayout = new QFormLayout(codecGroup);
-    
-    m_audioCodecCombo = new QComboBox();
-    m_audioCodecCombo->addItems({"AAC", "MP3", "FLAC", "PCM"});
-    m_audioCodecCombo->setCurrentText("AAC");
-    
-    m_audioBitrateSpinBox = new QSpinBox();
-    m_audioBitrateSpinBox->setRange(64, 320);
-    m_audioBitrateSpinBox->setValue(128);
-    m_audioBitrateSpinBox->setSuffix(" kbps");
-    
-    codecLayout->addRow("编码器:", m_audioCodecCombo);
-    codecLayout->addRow("比特率:", m_audioBitrateSpinBox);
-    
-    // 音频处理组
-    QGroupBox* processingGroup = new QGroupBox("音频处理");
-    QFormLayout* processingLayout = new QFormLayout(processingGroup);
-    
-    m_audioNoiseSuppressionCheckBox = new QCheckBox("启用噪声抑制");
-    m_audioEchoCancellationCheckBox = new QCheckBox("启用回声消除");
-    
-    m_audioInputGainSpinBox = new QDoubleSpinBox();
-    m_audioInputGainSpinBox->setRange(0.1, 10.0);
-    m_audioInputGainSpinBox->setValue(1.0);
-    m_audioInputGainSpinBox->setSingleStep(0.1);
-    m_audioInputGainSpinBox->setDecimals(1);
-    
-    processingLayout->addRow(m_audioNoiseSuppressionCheckBox);
-    processingLayout->addRow(m_audioEchoCancellationCheckBox);
-    processingLayout->addRow("输入增益:", m_audioInputGainSpinBox);
-    
-    // 添加到页面布局
-    layout->addWidget(deviceGroup);
-    layout->addWidget(formatGroup);
-    layout->addWidget(codecGroup);
-    layout->addWidget(processingGroup);
-    layout->addStretch();
-    
-    return page;
-}
-
-QWidget* RecorderSettingsDialog::createVideoSettingsPage() {
-    QWidget* page = new QWidget();
-    QVBoxLayout* layout = new QVBoxLayout(page);
-    layout->setContentsMargins(16, 16, 16, 16);
-    layout->setSpacing(12);
-    
-    // 视频设备组
-    QGroupBox* deviceGroup = new QGroupBox("视频设备");
-    QFormLayout* deviceLayout = new QFormLayout(deviceGroup);
-    
-    m_videoDeviceCombo = new QComboBox();
-    m_testVideoButton = new QPushButton("测试");
-    m_testVideoButton->setMaximumWidth(60);
-    
-    QHBoxLayout* deviceControlLayout = new QHBoxLayout();
-    deviceControlLayout->addWidget(m_videoDeviceCombo);
-    deviceControlLayout->addWidget(m_testVideoButton);
-    
-    deviceLayout->addRow("设备:", deviceControlLayout);
-    
-    // 视频格式组
-    QGroupBox* formatGroup = new QGroupBox("视频格式");
-    QFormLayout* formatLayout = new QFormLayout(formatGroup);
-    
-    m_videoResolutionCombo = new QComboBox();
-    m_videoResolutionCombo->addItems({
-        "640x480", "800x600", "1024x768", "1280x720", 
-        "1920x1080", "2560x1440", "3840x2160"
-    });
-    m_videoResolutionCombo->setCurrentText("1920x1080");
-    
-    m_videoFrameRateSpinBox = new QDoubleSpinBox();
-    m_videoFrameRateSpinBox->setRange(1.0, 120.0);
-    m_videoFrameRateSpinBox->setValue(30.0);
-    m_videoFrameRateSpinBox->setSingleStep(1.0);
-    m_videoFrameRateSpinBox->setDecimals(1);
-    m_videoFrameRateSpinBox->setSuffix(" fps");
-    
-    formatLayout->addRow("分辨率:", m_videoResolutionCombo);
-    formatLayout->addRow("帧率:", m_videoFrameRateSpinBox);
-    
-    // 视频编码组
-    QGroupBox* codecGroup = new QGroupBox("视频编码");
-    QFormLayout* codecLayout = new QFormLayout(codecGroup);
-    
-    m_videoCodecCombo = new QComboBox();
-    m_videoCodecCombo->addItems({"H.264", "H.265", "VP9", "AV1"});
-    m_videoCodecCombo->setCurrentText("H.264");
-    
-    m_videoBitrateSpinBox = new QSpinBox();
-    m_videoBitrateSpinBox->setRange(500, 50000);
-    m_videoBitrateSpinBox->setValue(5000);
-    m_videoBitrateSpinBox->setSuffix(" kbps");
-    
-    m_videoPresetCombo = new QComboBox();
-    m_videoPresetCombo->addItems({"ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"});
-    m_videoPresetCombo->setCurrentText("medium");
-    
-    m_videoProfileCombo = new QComboBox();
-    m_videoProfileCombo->addItems({"baseline", "main", "high"});
-    m_videoProfileCombo->setCurrentText("high");
-    
-    m_videoKeyFrameSpinBox = new QSpinBox();
-    m_videoKeyFrameSpinBox->setRange(1, 300);
-    m_videoKeyFrameSpinBox->setValue(60);
-    
-    codecLayout->addRow("编码器:", m_videoCodecCombo);
-    codecLayout->addRow("比特率:", m_videoBitrateSpinBox);
-    codecLayout->addRow("预设:", m_videoPresetCombo);
-    codecLayout->addRow("配置:", m_videoProfileCombo);
-    codecLayout->addRow("关键帧间隔:", m_videoKeyFrameSpinBox);
-    
-    // 硬件加速组
-    QGroupBox* accelerationGroup = new QGroupBox("硬件加速");
-    QFormLayout* accelerationLayout = new QFormLayout(accelerationGroup);
-    
-    m_videoHardwareAccelCheckBox = new QCheckBox("启用硬件加速");
-    m_videoHardwareAccelCheckBox->setChecked(true);
-    
-    accelerationLayout->addRow(m_videoHardwareAccelCheckBox);
-    
-    // 添加到页面布局
-    layout->addWidget(deviceGroup);
-    layout->addWidget(formatGroup);
-    layout->addWidget(codecGroup);
-    layout->addWidget(accelerationGroup);
-    layout->addStretch();
-    
-    return page;
-}
-
-QWidget* RecorderSettingsDialog::createOutputSettingsPage() {
-    QWidget* page = new QWidget();
-    QVBoxLayout* layout = new QVBoxLayout(page);
-    layout->setContentsMargins(16, 16, 16, 16);
-    layout->setSpacing(12);
-    
-    // 输出路径组
-    QGroupBox* pathGroup = new QGroupBox("输出路径");
-    QFormLayout* pathLayout = new QFormLayout(pathGroup);
-    
-    m_outputDirectoryEdit = new QLineEdit();
-    m_outputDirectoryBrowseButton = new QPushButton("浏览");
-    m_outputDirectoryBrowseButton->setMaximumWidth(60);
-    
-    QHBoxLayout* pathControlLayout = new QHBoxLayout();
-    pathControlLayout->addWidget(m_outputDirectoryEdit);
-    pathControlLayout->addWidget(m_outputDirectoryBrowseButton);
-    
-    pathLayout->addRow("输出目录:", pathControlLayout);
-    
-    // 文件命名组
-    QGroupBox* namingGroup = new QGroupBox("文件命名");
-    QFormLayout* namingLayout = new QFormLayout(namingGroup);
-    
-    m_fileNameTemplateEdit = new QLineEdit();
-    m_fileNameTemplateEdit->setText("recording_%Y%m%d_%H%M%S");
-    
-    m_fileNamePreviewLabel = new QLabel();
-    m_fileNamePreviewLabel->setStyleSheet("color: #888; font-style: italic;");
-    
-    namingLayout->addRow("文件名模板:", m_fileNameTemplateEdit);
-    namingLayout->addRow("预览:", m_fileNamePreviewLabel);
-    
-    // 格式设置组
-    QGroupBox* formatGroup = new QGroupBox("格式设置");
-    QFormLayout* formatLayout = new QFormLayout(formatGroup);
-    
-    m_containerFormatCombo = new QComboBox();
-    m_containerFormatCombo->addItems({"MP4", "AVI", "MKV", "MOV", "FLV"});
-    m_containerFormatCombo->setCurrentText("MP4");
-    
-    formatLayout->addRow("容器格式:", m_containerFormatCombo);
-    
-    // 文件选项组
-    QGroupBox* optionsGroup = new QGroupBox("文件选项");
-    QFormLayout* optionsLayout = new QFormLayout(optionsGroup);
-    
-    m_autoCreateDirectoryCheckBox = new QCheckBox("自动创建目录");
-    m_autoCreateDirectoryCheckBox->setChecked(true);
-    
-    m_overwriteExistingCheckBox = new QCheckBox("覆盖已存在文件");
-    
-    m_maxFileSizeSpinBox = new QSpinBox();
-    m_maxFileSizeSpinBox->setRange(0, 10000);
-    m_maxFileSizeSpinBox->setValue(0);
-    m_maxFileSizeSpinBox->setSuffix(" MB (0=无限制)");
-    
-    m_maxDurationSpinBox = new QSpinBox();
-    m_maxDurationSpinBox->setRange(0, 10000);
-    m_maxDurationSpinBox->setValue(0);
-    m_maxDurationSpinBox->setSuffix(" 分钟 (0=无限制)");
-    
-    optionsLayout->addRow(m_autoCreateDirectoryCheckBox);
-    optionsLayout->addRow(m_overwriteExistingCheckBox);
-    optionsLayout->addRow("最大文件大小:", m_maxFileSizeSpinBox);
-    optionsLayout->addRow("最大录制时长:", m_maxDurationSpinBox);
-    
-    // 添加到页面布局
-    layout->addWidget(pathGroup);
-    layout->addWidget(namingGroup);
-    layout->addWidget(formatGroup);
-    layout->addWidget(optionsGroup);
-    layout->addStretch();
-    
-    return page;
-}
-
-QWidget* RecorderSettingsDialog::createAdvancedSettingsPage() {
-    QWidget* page = new QWidget();
-    QVBoxLayout* layout = new QVBoxLayout(page);
-    layout->setContentsMargins(16, 16, 16, 16);
-    layout->setSpacing(12);
-    
-    // 性能设置组
-    QGroupBox* performanceGroup = new QGroupBox("性能设置");
-    QFormLayout* performanceLayout = new QFormLayout(performanceGroup);
-    
-    m_bufferSizeSpinBox = new QSpinBox();
-    m_bufferSizeSpinBox->setRange(1024, 65536);
-    m_bufferSizeSpinBox->setValue(4096);
-    
-    m_threadCountSpinBox = new QSpinBox();
-    m_threadCountSpinBox->setRange(0, 16);
-    m_threadCountSpinBox->setValue(0);
-    m_threadCountSpinBox->setSuffix(" (0=自动)");
-    
-    performanceLayout->addRow("缓冲区大小:", m_bufferSizeSpinBox);
-    performanceLayout->addRow("线程数:", m_threadCountSpinBox);
-    
-    // GPU加速组
-    QGroupBox* gpuGroup = new QGroupBox("GPU加速");
-    QFormLayout* gpuLayout = new QFormLayout(gpuGroup);
-    
-    m_gpuAccelerationCheckBox = new QCheckBox("启用GPU加速");
-    m_gpuAccelerationCheckBox->setChecked(true);
-    
-    m_gpuDeviceCombo = new QComboBox();
-    m_gpuDeviceCombo->addItems({"自动选择", "NVIDIA CUDA", "Intel Quick Sync", "AMD VCE"});
-    
-    gpuLayout->addRow(m_gpuAccelerationCheckBox);
-    gpuLayout->addRow("GPU设备:", m_gpuDeviceCombo);
-    
-    // 编码设置组
-    QGroupBox* encodingGroup = new QGroupBox("编码设置");
-    QFormLayout* encodingLayout = new QFormLayout(encodingGroup);
-    
-    m_lowLatencyCheckBox = new QCheckBox("启用低延迟模式");
-    m_realTimeEncodingCheckBox = new QCheckBox("启用实时编码");
-    m_realTimeEncodingCheckBox->setChecked(true);
-    
-    m_encodingPrioritySlider = new QSlider(Qt::Horizontal);
-    m_encodingPrioritySlider->setRange(-2, 2);
-    m_encodingPrioritySlider->setValue(0);
-    m_encodingPrioritySlider->setTickPosition(QSlider::TicksBelow);
-    m_encodingPrioritySlider->setTickInterval(1);
-    
-    m_encodingPriorityLabel = new QLabel("正常");
-    
-    QHBoxLayout* priorityLayout = new QHBoxLayout();
-    priorityLayout->addWidget(m_encodingPrioritySlider);
-    priorityLayout->addWidget(m_encodingPriorityLabel);
-    
-    encodingLayout->addRow(m_lowLatencyCheckBox);
-    encodingLayout->addRow(m_realTimeEncodingCheckBox);
-    encodingLayout->addRow("编码优先级:", priorityLayout);
-    
-    // 添加到页面布局
-    layout->addWidget(performanceGroup);
-    layout->addWidget(gpuGroup);
-    layout->addWidget(encodingGroup);
-    layout->addStretch();
-    
-    return page;
-}
-
-QWidget* RecorderSettingsDialog::createPresetSettingsPage() {
-    QWidget* page = new QWidget();
-    QVBoxLayout* layout = new QVBoxLayout(page);
-    layout->setContentsMargins(16, 16, 16, 16);
-    layout->setSpacing(12);
-    
-    // 预设列表组
-    QGroupBox* listGroup = new QGroupBox("预设列表");
-    QVBoxLayout* listLayout = new QVBoxLayout(listGroup);
-    
-    m_presetListWidget = new QListWidget();
-    m_presetListWidget->setMinimumHeight(200);
-    
-    listLayout->addWidget(m_presetListWidget);
-    
-    // 预设操作组
-    QGroupBox* operationsGroup = new QGroupBox("预设操作");
-    QHBoxLayout* operationsLayout = new QHBoxLayout(operationsGroup);
-    
-    m_savePresetButton = new QPushButton("保存");
-    m_loadPresetButton = new QPushButton("加载");
-    m_deletePresetButton = new QPushButton("删除");
-    m_exportPresetButton = new QPushButton("导出");
-    m_importPresetButton = new QPushButton("导入");
-    
-    operationsLayout->addWidget(m_savePresetButton);
-    operationsLayout->addWidget(m_loadPresetButton);
-    operationsLayout->addWidget(m_deletePresetButton);
-    operationsLayout->addStretch();
-    operationsLayout->addWidget(m_exportPresetButton);
-    operationsLayout->addWidget(m_importPresetButton);
-    
-    // 预设描述组
-    QGroupBox* descriptionGroup = new QGroupBox("预设描述");
-    QVBoxLayout* descriptionLayout = new QVBoxLayout(descriptionGroup);
-    
-    m_presetDescriptionEdit = new QTextEdit();
-    m_presetDescriptionEdit->setMaximumHeight(100);
-    m_presetDescriptionEdit->setPlaceholderText("输入预设描述...");
-    
-    descriptionLayout->addWidget(m_presetDescriptionEdit);
-    
-    // 添加到页面布局
-    layout->addWidget(listGroup);
-    layout->addWidget(operationsGroup);
-    layout->addWidget(descriptionGroup);
-    
-    return page;
-}
-
-void RecorderSettingsDialog::connectSignals() {
-    // 选项卡信号
-    connect(m_tabWidget, QOverload<int>::of(&QTabWidget::currentChanged),
-            this, &RecorderSettingsDialog::onTabChanged);
-    
-    // 按钮信号
-    connect(m_okButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onOkClicked);
-    connect(m_cancelButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onCancelClicked);
-    connect(m_applyButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onApplySettings);
-    connect(m_resetButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onResetCategory);
-    
-    // 音频设置信号
-    if (m_audioDeviceCombo) {
-        connect(m_audioDeviceCombo, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
-                this, &RecorderSettingsDialog::onAudioDeviceChanged);
-    }
-    if (m_testAudioButton) {
-        connect(m_testAudioButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onTestAudioDevice);
-    }
-    
-    // 视频设置信号
-    if (m_videoDeviceCombo) {
-        connect(m_videoDeviceCombo, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
-                this, &RecorderSettingsDialog::onVideoDeviceChanged);
-    }
-    if (m_testVideoButton) {
-        connect(m_testVideoButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onTestVideoDevice);
-    }
-    
-    // 输出设置信号
-    if (m_outputDirectoryBrowseButton) {
-        connect(m_outputDirectoryBrowseButton, &QPushButton::clicked, 
-                this, &RecorderSettingsDialog::onOutputDirectoryBrowse);
-    }
-    if (m_fileNameTemplateEdit) {
-        connect(m_fileNameTemplateEdit, &QLineEdit::textChanged, 
-                this, &RecorderSettingsDialog::onFileNameTemplateChanged);
-    }
-    
-    // 预设管理信号
-    if (m_savePresetButton) {
-        connect(m_savePresetButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onPresetSave);
-    }
-    if (m_loadPresetButton) {
-        connect(m_loadPresetButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onPresetLoad);
-    }
-    if (m_deletePresetButton) {
-        connect(m_deletePresetButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onPresetDelete);
-    }
-    if (m_exportPresetButton) {
-        connect(m_exportPresetButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onPresetExport);
-    }
-    if (m_importPresetButton) {
-        connect(m_importPresetButton, &QPushButton::clicked, this, &RecorderSettingsDialog::onPresetImport);
-    }
-    
-    // 高级设置信号
-    if (m_encodingPrioritySlider) {
-        connect(m_encodingPrioritySlider, &QSlider::valueChanged, [this](int value) {
-            if (m_encodingPriorityLabel) {
-                QStringList labels = {"最低", "低", "正常", "高", "最高"};
-                m_encodingPriorityLabel->setText(labels[value + 2]);
-            }
-            m_settingsChanged = true;
-            if (m_applyButton) m_applyButton->setEnabled(true);
-        });
-    }
-    
-    // 通用设置改变信号
-    auto connectSettingsChanged = [this](QWidget* widget) {
-        if (auto* combo = qobject_cast<QComboBox*>(widget)) {
-            connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), [this]() {
-                if (!m_updating) {
-                    m_settingsChanged = true;
-                    if (m_applyButton) m_applyButton->setEnabled(true);
-                }
-            });
-        } else if (auto* spinBox = qobject_cast<QSpinBox*>(widget)) {
-            connect(spinBox, QOverload<int>::of(&QSpinBox::valueChanged), [this]() {
-                if (!m_updating) {
-                    m_settingsChanged = true;
-                    if (m_applyButton) m_applyButton->setEnabled(true);
-                }
-            });
-        } else if (auto* doubleSpinBox = qobject_cast<QDoubleSpinBox*>(widget)) {
-            connect(doubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), [this]() {
-                if (!m_updating) {
-                    m_settingsChanged = true;
-                    if (m_applyButton) m_applyButton->setEnabled(true);
-                }
-            });
-        } else if (auto* checkBox = qobject_cast<QCheckBox*>(widget)) {
-            connect(checkBox, &QCheckBox::toggled, [this]() {
-                if (!m_updating) {
-                    m_settingsChanged = true;
-                    if (m_applyButton) m_applyButton->setEnabled(true);
-                }
-            });
-        } else if (auto* lineEdit = qobject_cast<QLineEdit*>(widget)) {
-            connect(lineEdit, &QLineEdit::textChanged, [this]() {
-                if (!m_updating) {
-                    m_settingsChanged = true;
-                    if (m_applyButton) m_applyButton->setEnabled(true);
-                }
-            });
-        }
-    };
-    
-    // 连接所有设置控件
-    QList<QWidget*> settingsWidgets = {
-        m_audioSampleRateCombo, m_audioChannelsCombo, m_audioBitDepthCombo,
-        m_audioCodecCombo, m_audioBitrateSpinBox, m_audioNoiseSuppressionCheckBox,
-        m_audioEchoCancellationCheckBox, m_audioInputGainSpinBox,
-        m_videoResolutionCombo, m_videoFrameRateSpinBox, m_videoCodecCombo,
-        m_videoBitrateSpinBox, m_videoPresetCombo, m_videoProfileCombo,
-        m_videoKeyFrameSpinBox, m_videoHardwareAccelCheckBox,
-        m_outputDirectoryEdit, m_containerFormatCombo, m_autoCreateDirectoryCheckBox,
-        m_overwriteExistingCheckBox, m_maxFileSizeSpinBox, m_maxDurationSpinBox,
-        m_bufferSizeSpinBox, m_threadCountSpinBox, m_gpuAccelerationCheckBox,
-        m_gpuDeviceCombo, m_lowLatencyCheckBox, m_realTimeEncodingCheckBox
-    };
-    
-    for (QWidget* widget : settingsWidgets) {
-        if (widget) {
-            connectSettingsChanged(widget);
-        }
-    }
-}
-
-void RecorderSettingsDialog::updateUI() {
-    // 更新按钮状态
-    if (m_applyButton) {
-        m_applyButton->setEnabled(m_settingsChanged);
-    }
-    
-    // 更新预览
-    updatePreview();
-}
-
-void RecorderSettingsDialog::updateAudioDevices() {
-    if (!m_audioDeviceCombo || !m_recorderModule) {
-        return;
-    }
-    
-    // TODO: 从录制器模块获取音频设备列表
-    QStringList devices = {"默认音频设备", "麦克风 (内置)", "麦克风 (USB)"};
-    
-    QString currentDevice = m_audioDeviceCombo->currentText();
-    m_audioDeviceCombo->clear();
-    m_audioDeviceCombo->addItems(devices);
-    
-    int index = m_audioDeviceCombo->findText(currentDevice);
-    if (index >= 0) {
-        m_audioDeviceCombo->setCurrentIndex(index);
-    }
-}
-
-void RecorderSettingsDialog::updateVideoDevices() {
-    if (!m_videoDeviceCombo || !m_recorderModule) {
-        return;
-    }
-    
-    // TODO: 从录制器模块获取视频设备列表
-    QStringList devices = {"默认摄像头", "USB摄像头", "屏幕录制"};
-    
-    QString currentDevice = m_videoDeviceCombo->currentText();
-    m_videoDeviceCombo->clear();
-    m_videoDeviceCombo->addItems(devices);
-    
-    int index = m_videoDeviceCombo->findText(currentDevice);
-    if (index >= 0) {
-        m_videoDeviceCombo->setCurrentIndex(index);
-    }
-}
-
-void RecorderSettingsDialog::updateCodecLists() {
-    // TODO: 从录制器模块获取支持的编码器列表
-}
-
-void RecorderSettingsDialog::updatePresetList() {
-    if (!m_presetListWidget) {
-        return;
-    }
-    
-    // TODO: 加载预设列表
-    m_presetListWidget->clear();
-    m_presetListWidget->addItems({"默认设置", "高质量", "低延迟", "直播"});
-}
-
-void RecorderSettingsDialog::readSettingsFromUI() {
-    m_updating = true;
-    
-    // 读取音频设置
-    if (m_audioDeviceCombo) {
-        m_currentSettings.audio.deviceName = m_audioDeviceCombo->currentText();
-    }
-    if (m_audioSampleRateCombo) {
-        m_currentSettings.audio.sampleRate = m_audioSampleRateCombo->currentText().toInt();
-    }
-    if (m_audioChannelsCombo) {
-        m_currentSettings.audio.channels = m_audioChannelsCombo->currentIndex() == 0 ? 1 : 
-                                          (m_audioChannelsCombo->currentIndex() == 1 ? 2 : 
-                                          (m_audioChannelsCombo->currentIndex() == 2 ? 6 : 8));
-    }
-    if (m_audioBitDepthCombo) {
-        m_currentSettings.audio.bitDepth = m_audioBitDepthCombo->currentText().toInt();
-    }
-    if (m_audioCodecCombo) {
-        m_currentSettings.audio.codec = m_audioCodecCombo->currentText().toLower();
-    }
-    if (m_audioBitrateSpinBox) {
-        m_currentSettings.audio.bitrate = m_audioBitrateSpinBox->value() * 1000;
-    }
-    if (m_audioNoiseSuppressionCheckBox) {
-        m_currentSettings.audio.enableNoiseSuppression = m_audioNoiseSuppressionCheckBox->isChecked();
-    }
-    if (m_audioEchoCancellationCheckBox) {
-        m_currentSettings.audio.enableEchoCancellation = m_audioEchoCancellationCheckBox->isChecked();
-    }
-    if (m_audioInputGainSpinBox) {
-        m_currentSettings.audio.inputGain = m_audioInputGainSpinBox->value();
-    }
-    
-    // 读取视频设置
-    if (m_videoDeviceCombo) {
-        m_currentSettings.video.deviceName = m_videoDeviceCombo->currentText();
-    }
-    if (m_videoResolutionCombo) {
-        QStringList parts = m_videoResolutionCombo->currentText().split('x');
-        if (parts.size() == 2) {
-            m_currentSettings.video.width = parts[0].toInt();
-            m_currentSettings.video.height = parts[1].toInt();
-        }
-    }
-    if (m_videoFrameRateSpinBox) {
-        m_currentSettings.video.frameRate = m_videoFrameRateSpinBox->value();
-    }
-    if (m_videoCodecCombo) {
-        QString codec = m_videoCodecCombo->currentText().toLower();
-        if (codec == "h.264") codec = "h264";
-        else if (codec == "h.265") codec = "h265";
-        m_currentSettings.video.codec = codec;
-    }
-    if (m_videoBitrateSpinBox) {
-        m_currentSettings.video.bitrate = m_videoBitrateSpinBox->value() * 1000;
-    }
-    if (m_videoPresetCombo) {
-        m_currentSettings.video.preset = m_videoPresetCombo->currentText();
-    }
-    if (m_videoProfileCombo) {
-        m_currentSettings.video.profile = m_videoProfileCombo->currentText();
-    }
-    if (m_videoKeyFrameSpinBox) {
-        m_currentSettings.video.keyFrameInterval = m_videoKeyFrameSpinBox->value();
-    }
-    if (m_videoHardwareAccelCheckBox) {
-        m_currentSettings.video.enableHardwareAcceleration = m_videoHardwareAccelCheckBox->isChecked();
-    }
-    
-    // 读取输出设置
-    if (m_outputDirectoryEdit) {
-        m_currentSettings.output.outputDirectory = m_outputDirectoryEdit->text();
-    }
-    if (m_fileNameTemplateEdit) {
-        m_currentSettings.output.fileNameTemplate = m_fileNameTemplateEdit->text();
-    }
-    if (m_containerFormatCombo) {
-        m_currentSettings.output.containerFormat = m_containerFormatCombo->currentText().toLower();
-    }
-    if (m_autoCreateDirectoryCheckBox) {
-        m_currentSettings.output.autoCreateDirectory = m_autoCreateDirectoryCheckBox->isChecked();
-    }
-    if (m_overwriteExistingCheckBox) {
-        m_currentSettings.output.overwriteExisting = m_overwriteExistingCheckBox->isChecked();
-    }
-    if (m_maxFileSizeSpinBox) {
-        m_currentSettings.output.maxFileSize = m_maxFileSizeSpinBox->value();
-    }
-    if (m_maxDurationSpinBox) {
-        m_currentSettings.output.maxDuration = m_maxDurationSpinBox->value();
-    }
-    
-    // 读取高级设置
-    if (m_bufferSizeSpinBox) {
-        m_currentSettings.advanced.bufferSize = m_bufferSizeSpinBox->value();
-    }
-    if (m_threadCountSpinBox) {
-        m_currentSettings.advanced.threadCount = m_threadCountSpinBox->value();
-    }
-    if (m_gpuAccelerationCheckBox) {
-        m_currentSettings.advanced.enableGPUAcceleration = m_gpuAccelerationCheckBox->isChecked();
-    }
-    if (m_gpuDeviceCombo) {
-        m_currentSettings.advanced.gpuDevice = m_gpuDeviceCombo->currentText();
-    }
-    if (m_lowLatencyCheckBox) {
-        m_currentSettings.advanced.enableLowLatency = m_lowLatencyCheckBox->isChecked();
-    }
-    if (m_realTimeEncodingCheckBox) {
-        m_currentSettings.advanced.enableRealTimeEncoding = m_realTimeEncodingCheckBox->isChecked();
-    }
-    if (m_encodingPrioritySlider) {
-        m_currentSettings.advanced.encodingPriority = m_encodingPrioritySlider->value();
-    }
-    
-    m_updating = false;
-}
-
-void RecorderSettingsDialog::writeSettingsToUI() {
-    m_updating = true;
-    
-    // 写入音频设置
-    if (m_audioDeviceCombo) {
-        int index = m_audioDeviceCombo->findText(m_currentSettings.audio.deviceName);
-        if (index >= 0) m_audioDeviceCombo->setCurrentIndex(index);
-    }
-    if (m_audioSampleRateCombo) {
-        m_audioSampleRateCombo->setCurrentText(QString::number(m_currentSettings.audio.sampleRate));
-    }
-    if (m_audioChannelsCombo) {
-        int index = m_currentSettings.audio.channels == 1 ? 0 : 
-                   (m_currentSettings.audio.channels == 2 ? 1 : 
-                   (m_currentSettings.audio.channels == 6 ? 2 : 3));
-        m_audioChannelsCombo->setCurrentIndex(index);
-    }
-    if (m_audioBitDepthCombo) {
-        m_audioBitDepthCombo->setCurrentText(QString::number(m_currentSettings.audio.bitDepth));
-    }
-    if (m_audioCodecCombo) {
-        QString codec = m_currentSettings.audio.codec.toUpper();
-        int index = m_audioCodecCombo->findText(codec);
-        if (index >= 0) m_audioCodecCombo->setCurrentIndex(index);
-    }
-    if (m_audioBitrateSpinBox) {
-        m_audioBitrateSpinBox->setValue(m_currentSettings.audio.bitrate / 1000);
-    }
-    if (m_audioNoiseSuppressionCheckBox) {
-        m_audioNoiseSuppressionCheckBox->setChecked(m_currentSettings.audio.enableNoiseSuppression);
-    }
-    if (m_audioEchoCancellationCheckBox) {
-        m_audioEchoCancellationCheckBox->setChecked(m_currentSettings.audio.enableEchoCancellation);
-    }
-    if (m_audioInputGainSpinBox) {
-        m_audioInputGainSpinBox->setValue(m_currentSettings.audio.inputGain);
-    }
-    
-    // 写入视频设置
-    if (m_videoDeviceCombo) {
-        int index = m_videoDeviceCombo->findText(m_currentSettings.video.deviceName);
-        if (index >= 0) m_videoDeviceCombo->setCurrentIndex(index);
-    }
-    if (m_videoResolutionCombo) {
-        QString resolution = QString("%1x%2").arg(m_currentSettings.video.width).arg(m_currentSettings.video.height);
-        int index = m_videoResolutionCombo->findText(resolution);
-        if (index >= 0) m_videoResolutionCombo->setCurrentIndex(index);
-    }
-    if (m_videoFrameRateSpinBox) {
-        m_videoFrameRateSpinBox->setValue(m_currentSettings.video.frameRate);
-    }
-    if (m_videoCodecCombo) {
-        QString codec = m_currentSettings.video.codec;
-        if (codec == "h264") codec = "H.264";
-        else if (codec == "h265") codec = "H.265";
-        else codec = codec.toUpper();
-        int index = m_videoCodecCombo->findText(codec);
-        if (index >= 0) m_videoCodecCombo->setCurrentIndex(index);
-    }
-    if (m_videoBitrateSpinBox) {
-        m_videoBitrateSpinBox->setValue(m_currentSettings.video.bitrate / 1000);
-    }
-    if (m_videoPresetCombo) {
-        int index = m_videoPresetCombo->findText(m_currentSettings.video.preset);
-        if (index >= 0) m_videoPresetCombo->setCurrentIndex(index);
-    }
-    if (m_videoProfileCombo) {
-        int index = m_videoProfileCombo->findText(m_currentSettings.video.profile);
-        if (index >= 0) m_videoProfileCombo->setCurrentIndex(index);
-    }
-    if (m_videoKeyFrameSpinBox) {
-        m_videoKeyFrameSpinBox->setValue(m_currentSettings.video.keyFrameInterval);
-    }
-    if (m_videoHardwareAccelCheckBox) {
-        m_videoHardwareAccelCheckBox->setChecked(m_currentSettings.video.enableHardwareAcceleration);
-    }
-    
-    // 写入输出设置
-    if (m_outputDirectoryEdit) {
-        m_outputDirectoryEdit->setText(m_currentSettings.output.outputDirectory);
-    }
-    if (m_fileNameTemplateEdit) {
-        m_fileNameTemplateEdit->setText(m_currentSettings.output.fileNameTemplate);
-    }
-    if (m_containerFormatCombo) {
-        QString format = m_currentSettings.output.containerFormat.toUpper();
-        int index = m_containerFormatCombo->findText(format);
-        if (index >= 0) m_containerFormatCombo->setCurrentIndex(index);
-    }
-    if (m_autoCreateDirectoryCheckBox) {
-        m_autoCreateDirectoryCheckBox->setChecked(m_currentSettings.output.autoCreateDirectory);
-    }
-    if (m_overwriteExistingCheckBox) {
-        m_overwriteExistingCheckBox->setChecked(m_currentSettings.output.overwriteExisting);
-    }
-    if (m_maxFileSizeSpinBox) {
-        m_maxFileSizeSpinBox->setValue(m_currentSettings.output.maxFileSize);
-    }
-    if (m_maxDurationSpinBox) {
-        m_maxDurationSpinBox->setValue(m_currentSettings.output.maxDuration);
-    }
-    
-    // 写入高级设置
-    if (m_bufferSizeSpinBox) {
-        m_bufferSizeSpinBox->setValue(m_currentSettings.advanced.bufferSize);
-    }
-    if (m_threadCountSpinBox) {
-        m_threadCountSpinBox->setValue(m_currentSettings.advanced.threadCount);
-    }
-    if (m_gpuAccelerationCheckBox) {
-        m_gpuAccelerationCheckBox->setChecked(m_currentSettings.advanced.enableGPUAcceleration);
-    }
-    if (m_gpuDeviceCombo) {
-        int index = m_gpuDeviceCombo->findText(m_currentSettings.advanced.gpuDevice);
-        if (index >= 0) m_gpuDeviceCombo->setCurrentIndex(index);
-    }
-    if (m_lowLatencyCheckBox) {
-        m_lowLatencyCheckBox->setChecked(m_currentSettings.advanced.enableLowLatency);
-    }
-    if (m_realTimeEncodingCheckBox) {
-        m_realTimeEncodingCheckBox->setChecked(m_currentSettings.advanced.enableRealTimeEncoding);
-    }
-    if (m_encodingPrioritySlider) {
-        m_encodingPrioritySlider->setValue(m_currentSettings.advanced.encodingPriority);
-        if (m_encodingPriorityLabel) {
-            QStringList labels = {"最低", "低", "正常", "高", "最高"};
-            m_encodingPriorityLabel->setText(labels[m_currentSettings.advanced.encodingPriority + 2]);
-        }
-    }
-    
-    m_updating = false;
-}
-
-RecorderSettingsDialog::Settings RecorderSettingsDialog::getDefaultSettings() const {
-    Settings settings;
-    
-    // 默认音频设置
-    settings.audio.deviceName = "";
-    settings.audio.sampleRate = 44100;
-    settings.audio.channels = 2;
-    settings.audio.bitDepth = 16;
-    settings.audio.codec = "aac";
-    settings.audio.bitrate = 128000;
-    settings.audio.enableNoiseSuppression = false;
-    settings.audio.enableEchoCancellation = false;
-    settings.audio.inputGain = 1.0;
-    
-    // 默认视频设置
-    settings.video.deviceName = "";
-    settings.video.width = 1920;
-    settings.video.height = 1080;
-    settings.video.frameRate = 30.0;
-    settings.video.codec = "h264";
-    settings.video.bitrate = 5000000;
-    settings.video.preset = "medium";
-    settings.video.profile = "high";
-    settings.video.keyFrameInterval = 60;
-    settings.video.enableHardwareAcceleration = true;
-    
-    // 默认输出设置
-    settings.output.outputDirectory = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
-    settings.output.fileNameTemplate = "recording_%Y%m%d_%H%M%S";
-    settings.output.containerFormat = "mp4";
-    settings.output.autoCreateDirectory = true;
-    settings.output.overwriteExisting = false;
-    settings.output.maxFileSize = 0;
-    settings.output.maxDuration = 0;
-    
-    // 默认高级设置
-    settings.advanced.bufferSize = 4096;
-    settings.advanced.threadCount = 0;
-    settings.advanced.enableGPUAcceleration = true;
-    settings.advanced.gpuDevice = "自动选择";
-    settings.advanced.enableLowLatency = false;
-    settings.advanced.enableRealTimeEncoding = true;
-    settings.advanced.encodingPriority = 0;
-    
-    return settings;
-}
-
-QString RecorderSettingsDialog::formatFileNamePreview() const {
-    QString preview = m_currentSettings.output.fileNameTemplate;
-    QDateTime now = QDateTime::currentDateTime();
-    
-    preview.replace("%Y", now.toString("yyyy"));
-    preview.replace("%m", now.toString("MM"));
-    preview.replace("%d", now.toString("dd"));
-    preview.replace("%H", now.toString("hh"));
-    preview.replace("%M", now.toString("mm"));
-    preview.replace("%S", now.toString("ss"));
-    
-    preview += "." + m_currentSettings.output.containerFormat;
-    
-    return preview;
-}
-
-bool RecorderSettingsDialog::validateOutputDirectory(const QString& path) const {
-    QDir dir(path);
-    return dir.exists() || dir.mkpath(".");
-}

+ 0 - 413
AV/code/recorder/ui/recorder_settings_dialog.h

@@ -1,413 +0,0 @@
-#ifndef AV_RECORDER_SETTINGS_DIALOG_H
-#define AV_RECORDER_SETTINGS_DIALOG_H
-
-#include <QDialog>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QGridLayout>
-#include <QTabWidget>
-#include <QGroupBox>
-#include <QLabel>
-#include <QLineEdit>
-#include <QComboBox>
-#include <QSpinBox>
-#include <QDoubleSpinBox>
-#include <QSlider>
-#include <QCheckBox>
-#include <QPushButton>
-#include <QFileDialog>
-#include <QStandardPaths>
-#include <QSettings>
-#include <QTimer>
-#include <QProgressBar>
-#include <QTextEdit>
-#include <QSplitter>
-#include <QTreeWidget>
-#include <QListWidget>
-#include <memory>
-
-// 前向声明
-namespace av {
-namespace recorder {
-class RecorderModule;
-}
-}
-
-/**
- * 录制器设置对话框
- * 
- * 提供完整的录制参数配置界面,包括:
- * - 音频设置(设备、格式、质量)
- * - 视频设置(设备、分辨率、帧率、编码)
- * - 输出设置(路径、格式、文件名模板)
- * - 高级设置(编码器参数、性能优化)
- * - 预设管理(保存/加载配置预设)
- */
-class RecorderSettingsDialog : public QDialog {
-    Q_OBJECT
-
-public:
-    /**
-     * 设置类别
-     */
-    enum SettingsCategory {
-        AudioCategory,
-        VideoCategory,
-        OutputCategory,
-        AdvancedCategory,
-        PresetCategory
-    };
-    
-    /**
-     * 音频设置结构
-     */
-    struct AudioSettings {
-        QString deviceName;
-        int sampleRate = 44100;
-        int channels = 2;
-        int bitDepth = 16;
-        QString codec = "aac";
-        int bitrate = 128000;
-        bool enableNoiseSuppression = false;
-        bool enableEchoCancellation = false;
-        double inputGain = 1.0;
-        
-        AudioSettings() = default;
-    };
-    
-    /**
-     * 视频设置结构
-     */
-    struct VideoSettings {
-        QString deviceName;
-        int width = 1920;
-        int height = 1080;
-        double frameRate = 30.0;
-        QString codec = "h264";
-        int bitrate = 5000000;
-        QString preset = "medium";
-        QString profile = "high";
-        int keyFrameInterval = 60;
-        bool enableHardwareAcceleration = true;
-        
-        VideoSettings() = default;
-    };
-    
-    /**
-     * 输出设置结构
-     */
-    struct OutputSettings {
-        QString outputDirectory;
-        QString fileNameTemplate = "recording_%Y%m%d_%H%M%S";
-        QString containerFormat = "mp4";
-        bool autoCreateDirectory = true;
-        bool overwriteExisting = false;
-        int maxFileSize = 0; // 0 = unlimited
-        int maxDuration = 0; // 0 = unlimited
-        
-        OutputSettings() {
-            outputDirectory = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
-        }
-    };
-    
-    /**
-     * 高级设置结构
-     */
-    struct AdvancedSettings {
-        int bufferSize = 4096;
-        int threadCount = 0; // 0 = auto
-        bool enableGPUAcceleration = true;
-        QString gpuDevice;
-        bool enableLowLatency = false;
-        bool enableRealTimeEncoding = true;
-        int encodingPriority = 0; // -2 to 2
-        
-        AdvancedSettings() = default;
-    };
-    
-    /**
-     * 完整设置结构
-     */
-    struct Settings {
-        AudioSettings audio;
-        VideoSettings video;
-        OutputSettings output;
-        AdvancedSettings advanced;
-        
-        Settings() = default;
-    };
-
-public:
-    explicit RecorderSettingsDialog(av::recorder::RecorderModule* recorderModule, QWidget* parent = nullptr);
-    ~RecorderSettingsDialog();
-
-    /**
-     * 设置当前配置
-     */
-    void setSettings(const Settings& settings);
-    
-    /**
-     * 获取当前配置
-     */
-    Settings getSettings() const;
-    
-    /**
-     * 显示指定类别的设置
-     */
-    void showCategory(SettingsCategory category);
-    
-    /**
-     * 重置为默认设置
-     */
-    void resetToDefaults();
-    
-    /**
-     * 加载设置
-     */
-    void loadSettings();
-    
-    /**
-     * 保存设置
-     */
-    void saveSettings();
-    
-    /**
-     * 验证设置有效性
-     */
-    bool validateSettings(QString* errorMessage = nullptr) const;
-
-protected:
-    void showEvent(QShowEvent* event) override;
-    void closeEvent(QCloseEvent* event) override;
-
-private slots:
-    void onTabChanged(int index);
-    void onAudioDeviceChanged(const QString& device);
-    void onVideoDeviceChanged(const QString& device);
-    void onOutputDirectoryBrowse();
-    void onFileNameTemplateChanged();
-    void onPresetSave();
-    void onPresetLoad();
-    void onPresetDelete();
-    void onPresetExport();
-    void onPresetImport();
-    void onTestAudioDevice();
-    void onTestVideoDevice();
-    void onResetCategory();
-    void onApplySettings();
-    void onOkClicked();
-    void onCancelClicked();
-    void updatePreview();
-    void refreshDevices();
-
-signals:
-    /**
-     * 设置已应用信号
-     */
-    void settingsApplied(const Settings& settings);
-    
-    /**
-     * 设置已改变信号
-     */
-    void settingsChanged();
-
-private:
-    /**
-     * 初始化UI
-     */
-    void initializeUI();
-    
-    /**
-     * 创建音频设置页面
-     */
-    QWidget* createAudioSettingsPage();
-    
-    /**
-     * 创建视频设置页面
-     */
-    QWidget* createVideoSettingsPage();
-    
-    /**
-     * 创建输出设置页面
-     */
-    QWidget* createOutputSettingsPage();
-    
-    /**
-     * 创建高级设置页面
-     */
-    QWidget* createAdvancedSettingsPage();
-    
-    /**
-     * 创建预设管理页面
-     */
-    QWidget* createPresetSettingsPage();
-    
-    /**
-     * 连接信号槽
-     */
-    void connectSignals();
-    
-    /**
-     * 更新UI状态
-     */
-    void updateUI();
-    
-    /**
-     * 更新音频设备列表
-     */
-    void updateAudioDevices();
-    
-    /**
-     * 更新视频设备列表
-     */
-    void updateVideoDevices();
-    
-    /**
-     * 更新编码器列表
-     */
-    void updateCodecLists();
-    
-    /**
-     * 更新预设列表
-     */
-    void updatePresetList();
-    
-    /**
-     * 从UI读取设置
-     */
-    void readSettingsFromUI();
-    
-    /**
-     * 将设置写入UI
-     */
-    void writeSettingsToUI();
-    
-    /**
-     * 获取默认设置
-     */
-    Settings getDefaultSettings() const;
-    
-    /**
-     * 格式化文件名预览
-     */
-    QString formatFileNamePreview() const;
-    
-    /**
-     * 验证输出目录
-     */
-    bool validateOutputDirectory(const QString& path) const;
-    
-    /**
-     * 创建设置组
-     */
-    QGroupBox* createSettingsGroup(const QString& title, QWidget* content);
-    
-    /**
-     * 创建标签和控件的水平布局
-     */
-    QHBoxLayout* createLabeledControl(const QString& label, QWidget* control, 
-                                     const QString& tooltip = QString());
-    
-    /**
-     * 保存预设到文件
-     */
-    bool savePresetToFile(const QString& name, const Settings& settings);
-    
-    /**
-     * 从文件加载预设
-     */
-    bool loadPresetFromFile(const QString& name, Settings& settings);
-    
-    /**
-     * 获取预设文件路径
-     */
-    QString getPresetFilePath(const QString& name) const;
-    
-    /**
-     * 获取预设目录
-     */
-    QString getPresetDirectory() const;
-
-private:
-    // 核心组件
-    av::recorder::RecorderModule* m_recorderModule;
-    
-    // UI组件
-    QTabWidget* m_tabWidget;
-    QVBoxLayout* m_mainLayout;
-    QHBoxLayout* m_buttonLayout;
-    
-    // 按钮
-    QPushButton* m_okButton;
-    QPushButton* m_cancelButton;
-    QPushButton* m_applyButton;
-    QPushButton* m_resetButton;
-    
-    // 音频设置控件
-    QComboBox* m_audioDeviceCombo;
-    QComboBox* m_audioSampleRateCombo;
-    QComboBox* m_audioChannelsCombo;
-    QComboBox* m_audioBitDepthCombo;
-    QComboBox* m_audioCodecCombo;
-    QSpinBox* m_audioBitrateSpinBox;
-    QCheckBox* m_audioNoiseSuppressionCheckBox;
-    QCheckBox* m_audioEchoCancellationCheckBox;
-    QDoubleSpinBox* m_audioInputGainSpinBox;
-    QPushButton* m_testAudioButton;
-    
-    // 视频设置控件
-    QComboBox* m_videoDeviceCombo;
-    QComboBox* m_videoResolutionCombo;
-    QDoubleSpinBox* m_videoFrameRateSpinBox;
-    QComboBox* m_videoCodecCombo;
-    QSpinBox* m_videoBitrateSpinBox;
-    QComboBox* m_videoPresetCombo;
-    QComboBox* m_videoProfileCombo;
-    QSpinBox* m_videoKeyFrameSpinBox;
-    QCheckBox* m_videoHardwareAccelCheckBox;
-    QPushButton* m_testVideoButton;
-    
-    // 输出设置控件
-    QLineEdit* m_outputDirectoryEdit;
-    QPushButton* m_outputDirectoryBrowseButton;
-    QLineEdit* m_fileNameTemplateEdit;
-    QLabel* m_fileNamePreviewLabel;
-    QComboBox* m_containerFormatCombo;
-    QCheckBox* m_autoCreateDirectoryCheckBox;
-    QCheckBox* m_overwriteExistingCheckBox;
-    QSpinBox* m_maxFileSizeSpinBox;
-    QSpinBox* m_maxDurationSpinBox;
-    
-    // 高级设置控件
-    QSpinBox* m_bufferSizeSpinBox;
-    QSpinBox* m_threadCountSpinBox;
-    QCheckBox* m_gpuAccelerationCheckBox;
-    QComboBox* m_gpuDeviceCombo;
-    QCheckBox* m_lowLatencyCheckBox;
-    QCheckBox* m_realTimeEncodingCheckBox;
-    QSlider* m_encodingPrioritySlider;
-    QLabel* m_encodingPriorityLabel;
-    
-    // 预设管理控件
-    QListWidget* m_presetListWidget;
-    QPushButton* m_savePresetButton;
-    QPushButton* m_loadPresetButton;
-    QPushButton* m_deletePresetButton;
-    QPushButton* m_exportPresetButton;
-    QPushButton* m_importPresetButton;
-    QTextEdit* m_presetDescriptionEdit;
-    
-    // 数据
-    Settings m_currentSettings;
-    Settings m_originalSettings;
-    
-    // 状态
-    bool m_settingsChanged;
-    bool m_updating;
-    
-    // 定时器
-    QTimer* m_previewUpdateTimer;
-    QTimer* m_deviceRefreshTimer;
-};
-
-#endif // AV_RECORDER_SETTINGS_DIALOG_H

+ 0 - 36
AV/code/recorder/ui/recorder_ui.pri

@@ -1,36 +0,0 @@
-# UI模块头文件
-HEADERS += \
-    $$PWD/recorder_main_widget.h \
-    $$PWD/recorder_video_widget.h \
-    $$PWD/recorder_audio_widget.h \
-    $$PWD/recorder_settings_dialog.h \
-    $$PWD/recorder_example_app.h
-
-# UI模块源文件
-SOURCES += \
-    # $$PWD/recorder_main.cpp \
-    $$PWD/recorder_main_widget.cpp \
-    $$PWD/recorder_video_widget.cpp \
-    $$PWD/recorder_audio_widget.cpp \
-    $$PWD/recorder_settings_dialog.cpp \
-    $$PWD/recorder_example_app.cpp
-
-# Qt模块依赖
-QT += core widgets opengl multimedia
-
-# 编译器配置
-CONFIG += c++17
-
-# 包含路径
-INCLUDEPATH += $$PWD
-INCLUDEPATH += $$PWD/..
-INCLUDEPATH += $$PWD/../..
-INCLUDEPATH += $$PWD/../../..
-
-# 依赖路径
-DEPENDPATH += $$PWD
-DEPENDPATH += $$PWD/..
-
-
-# 资源文件
-RESOURCES += $$PWD/recorder_ui.qrc

+ 0 - 5
AV/code/recorder/ui/recorder_ui.qrc

@@ -1,5 +0,0 @@
-<RCC>
-    <qresource prefix="/">
-        <file>styles/recorder_ui.qss</file>
-    </qresource>
-</RCC>

+ 0 - 806
AV/code/recorder/ui/recorder_video_widget.cpp

@@ -1,806 +0,0 @@
-#include "recorder_video_widget.h"
-#include <QDebug>
-#include <QApplication>
-#include <QOpenGLContext>
-#include <QDateTime>
-#include <cstring>
-
-extern "C" {
-#include <libavutil/pixfmt.h>
-#include <libswscale/swscale.h>
-}
-
-// 顶点着色器源码
-static const char* vertexShaderSource = R"(
-#version 330 core
-layout (location = 0) in vec2 aPos;
-layout (location = 1) in vec2 aTexCoord;
-
-out vec2 TexCoord;
-
-uniform bool flipHorizontal;
-uniform bool flipVertical;
-
-void main() {
-    gl_Position = vec4(aPos, 0.0, 1.0);
-    
-    vec2 texCoord = aTexCoord;
-    if (flipHorizontal) {
-        texCoord.x = 1.0 - texCoord.x;
-    }
-    if (flipVertical) {
-        texCoord.y = 1.0 - texCoord.y;
-    }
-    
-    TexCoord = texCoord;
-}
-)";
-
-// YUV片段着色器源码
-static const char* yuvFragmentShaderSource = R"(
-#version 330 core
-out vec4 FragColor;
-
-in vec2 TexCoord;
-
-uniform sampler2D textureY;
-uniform sampler2D textureU;
-uniform sampler2D textureV;
-uniform bool grayscale;
-uniform float brightness;
-uniform float contrast;
-uniform float saturation;
-
-void main() {
-    float y = texture(textureY, TexCoord).r;
-    float u = texture(textureU, TexCoord).r - 0.5;
-    float v = texture(textureV, TexCoord).r - 0.5;
-    
-    // YUV to RGB conversion
-    float r = y + 1.402 * v;
-    float g = y - 0.344 * u - 0.714 * v;
-    float b = y + 1.772 * u;
-    
-    vec3 rgb = vec3(r, g, b);
-    
-    // Apply brightness
-    rgb += brightness;
-    
-    // Apply contrast
-    rgb = (rgb - 0.5) * contrast + 0.5;
-    
-    // Apply saturation
-    if (!grayscale) {
-        float gray = dot(rgb, vec3(0.299, 0.587, 0.114));
-        rgb = mix(vec3(gray), rgb, saturation);
-    } else {
-        float gray = dot(rgb, vec3(0.299, 0.587, 0.114));
-        rgb = vec3(gray);
-    }
-    
-    FragColor = vec4(clamp(rgb, 0.0, 1.0), 1.0);
-}
-)";
-
-// RGB片段着色器源码
-static const char* rgbFragmentShaderSource = R"(
-#version 330 core
-out vec4 FragColor;
-
-in vec2 TexCoord;
-
-uniform sampler2D textureRGB;
-uniform bool grayscale;
-uniform float brightness;
-uniform float contrast;
-uniform float saturation;
-
-void main() {
-    vec3 rgb = texture(textureRGB, TexCoord).rgb;
-    
-    // Apply brightness
-    rgb += brightness;
-    
-    // Apply contrast
-    rgb = (rgb - 0.5) * contrast + 0.5;
-    
-    // Apply saturation
-    if (!grayscale) {
-        float gray = dot(rgb, vec3(0.299, 0.587, 0.114));
-        rgb = mix(vec3(gray), rgb, saturation);
-    } else {
-        float gray = dot(rgb, vec3(0.299, 0.587, 0.114));
-        rgb = vec3(gray);
-    }
-    
-    FragColor = vec4(clamp(rgb, 0.0, 1.0), 1.0);
-}
-)";
-
-RecorderVideoWidget::RecorderVideoWidget(QWidget* parent)
-    : QOpenGLWidget(parent)
-    , m_textureY(0)
-    , m_textureU(0)
-    , m_textureV(0)
-    , m_textureRGB(0)
-    , m_VAO(0)
-    , m_VBO(0)
-    , m_frameWidth(0)
-    , m_frameHeight(0)
-    , m_frameFormat(AV_PIX_FMT_NONE)
-    , m_frameReady(false)
-    , m_keepAspectRatio(true)
-    , m_showFPS(true)
-    , m_noVideoText("No Video")
-    , m_backgroundColor(Qt::black)
-    , m_grayscale(false)
-    , m_flipHorizontal(false)
-    , m_flipVertical(false)
-    , m_brightness(0.0f)
-    , m_contrast(1.0f)
-    , m_saturation(1.0f)
-    , m_frameCount(0)
-    , m_currentFPS(0.0)
-    , m_lastFPSUpdate(0)
-    , m_initialized(false) {
-    
-    // 初始化帧数据
-    for (int i = 0; i < 4; ++i) {
-        m_frameData[i] = nullptr;
-        m_frameLinesize[i] = 0;
-    }
-    
-    // 创建FPS定时器
-    m_fpsTimer = new QTimer(this);
-    connect(m_fpsTimer, &QTimer::timeout, this, &RecorderVideoWidget::updateFPS);
-    m_fpsTimer->start(1000); // 每秒更新一次FPS
-    
-    // 设置OpenGL格式
-    QSurfaceFormat format;
-    format.setVersion(3, 3);
-    format.setProfile(QSurfaceFormat::CoreProfile);
-    setFormat(format);
-}
-
-RecorderVideoWidget::~RecorderVideoWidget() {
-    cleanup();
-}
-
-bool RecorderVideoWidget::initialize(int width, int height, int format) {
-    QMutexLocker locker(&m_mutex);
-    
-    if (width <= 0 || height <= 0) {
-        qWarning() << "Invalid video dimensions:" << width << "x" << height;
-        return false;
-    }
-    
-    // 分配帧缓冲区
-    if (!allocateFrameBuffer(width, height, format)) {
-        qWarning() << "Failed to allocate frame buffer";
-        return false;
-    }
-    
-    m_initialized = true;
-    
-    // 触发重绘
-    QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
-    
-    return true;
-}
-
-void RecorderVideoWidget::cleanup() {
-    QMutexLocker locker(&m_mutex);
-    
-    makeCurrent();
-    
-    // 释放OpenGL资源
-    if (m_textureY) {
-        glDeleteTextures(1, &m_textureY);
-        m_textureY = 0;
-    }
-    if (m_textureU) {
-        glDeleteTextures(1, &m_textureU);
-        m_textureU = 0;
-    }
-    if (m_textureV) {
-        glDeleteTextures(1, &m_textureV);
-        m_textureV = 0;
-    }
-    if (m_textureRGB) {
-        glDeleteTextures(1, &m_textureRGB);
-        m_textureRGB = 0;
-    }
-    if (m_VAO) {
-        glDeleteVertexArrays(1, &m_VAO);
-        m_VAO = 0;
-    }
-    if (m_VBO) {
-        glDeleteBuffers(1, &m_VBO);
-        m_VBO = 0;
-    }
-    
-    m_shaderProgram.reset();
-    
-    doneCurrent();
-    
-    // 释放帧缓冲区
-    freeFrameBuffer();
-    
-    m_frameReady = false;
-    m_initialized = false;
-}
-
-bool RecorderVideoWidget::updateFrame(AVFrame* frame) {
-    if (!frame || !m_initialized) {
-        qDebug() << "RecorderVideoWidget::updateFrame failed: frame=" << frame << ", initialized=" << m_initialized;
-        return false;
-    }
-    
-    // 验证帧数据的有效性
-    if (frame->width <= 0 || frame->height <= 0 || !frame->data[0]) {
-        qWarning() << "Invalid frame data received, skipping: width=" << frame->width 
-                   << ", height=" << frame->height << ", data[0]=" << frame->data[0];
-        return false;
-    }
-    
-    qDebug() << "RecorderVideoWidget::updateFrame: width=" << frame->width 
-             << ", height=" << frame->height << ", format=" << frame->format;
-    
-    QMutexLocker locker(&m_mutex);
-    
-    try {
-        // 检查帧格式是否匹配
-        if (frame->width != m_frameWidth || 
-            frame->height != m_frameHeight || 
-            frame->format != m_frameFormat) {
-            
-            // 重新分配缓冲区
-            if (!allocateFrameBuffer(frame->width, frame->height, frame->format)) {
-                qWarning() << "Failed to allocate frame buffer";
-                return false;
-            }
-            qDebug() << "Frame buffer reallocated:" << frame->width << "x" << frame->height;
-        }
-        
-        // 复制帧数据
-        if (!copyFromAVFrame(frame)) {
-            qWarning() << "Failed to copy frame data";
-            return false;
-        }
-        
-        m_frameReady = true;
-        m_frameCount++;
-        
-        // 限制触发重绘的频率,避免过度绘制
-        if (m_frameCount % 2 == 0) {  // 每2帧触发一次重绘
-            QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
-        }
-        
-        return true;
-    } catch (const std::exception& e) {
-        qWarning() << "Exception in updateFrame:" << e.what();
-        return false;
-    } catch (...) {
-        qWarning() << "Unknown exception in updateFrame";
-        return false;
-    }
-}
-
-bool RecorderVideoWidget::updateFrame(const VideoFrame& frame) {
-    if (!m_initialized) {
-        return false;
-    }
-    
-    QMutexLocker locker(&m_mutex);
-    
-    // 检查帧格式是否匹配
-    if (frame.width != m_frameWidth || 
-        frame.height != m_frameHeight || 
-        frame.format != m_frameFormat) {
-        
-        // 重新分配缓冲区
-        if (!allocateFrameBuffer(frame.width, frame.height, frame.format)) {
-            return false;
-        }
-    }
-    
-    // 复制帧数据
-    if (!copyFromVideoFrame(frame)) {
-        return false;
-    }
-    
-    m_frameReady = true;
-    m_frameCount++;
-    
-    // 触发重绘
-    QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
-    
-    return true;
-}
-
-void RecorderVideoWidget::clearFrame() {
-    QMutexLocker locker(&m_mutex);
-    
-    m_frameReady = false;
-    
-    // 触发重绘
-    QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
-}
-
-void RecorderVideoWidget::setGrayscale(bool enable) {
-    m_grayscale = enable;
-    update();
-}
-
-void RecorderVideoWidget::setFlipHorizontal(bool enable) {
-    m_flipHorizontal = enable;
-    update();
-}
-
-void RecorderVideoWidget::setFlipVertical(bool enable) {
-    m_flipVertical = enable;
-    update();
-}
-
-void RecorderVideoWidget::setBrightness(float brightness) {
-    m_brightness = qBound(-1.0f, brightness, 1.0f);
-    update();
-}
-
-void RecorderVideoWidget::setContrast(float contrast) {
-    m_contrast = qBound(0.0f, contrast, 2.0f);
-    update();
-}
-
-void RecorderVideoWidget::setSaturation(float saturation) {
-    m_saturation = qBound(0.0f, saturation, 2.0f);
-    update();
-}
-
-void RecorderVideoWidget::initializeGL() {
-    initializeOpenGLFunctions();
-    QOpenGLExtraFunctions::initializeOpenGLFunctions();
-    
-    // 设置背景色
-    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
-    
-    // 初始化着色器
-    if (!initShaders()) {
-        qWarning() << "Failed to initialize shaders";
-        return;
-    }
-    
-    // 创建纹理
-    createTextures();
-    
-    // 创建顶点数组对象
-    glGenVertexArrays(1, &m_VAO);
-    glGenBuffers(1, &m_VBO);
-    
-    glBindVertexArray(m_VAO);
-    
-    glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
-    glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES), VERTICES, GL_STATIC_DRAW);
-    
-    // 位置属性
-    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
-    glEnableVertexAttribArray(0);
-    
-    // 纹理坐标属性
-    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
-    glEnableVertexAttribArray(1);
-    
-    glBindBuffer(GL_ARRAY_BUFFER, 0);
-    glBindVertexArray(0);
-}
-
-void RecorderVideoWidget::paintGL() {
-    glClear(GL_COLOR_BUFFER_BIT);
-    
-    QMutexLocker locker(&m_mutex);
-    
-    if (!m_frameReady || !m_shaderProgram) {
-        // 绘制无视频提示
-        locker.unlock();
-        drawNoVideoHint();
-        return;
-    }
-    
-    // 使用着色器程序
-    m_shaderProgram->bind();
-    
-    // 设置uniform变量
-    m_shaderProgram->setUniformValue("grayscale", m_grayscale);
-    m_shaderProgram->setUniformValue("flipHorizontal", m_flipHorizontal);
-    m_shaderProgram->setUniformValue("flipVertical", m_flipVertical);
-    m_shaderProgram->setUniformValue("brightness", m_brightness);
-    m_shaderProgram->setUniformValue("contrast", m_contrast);
-    m_shaderProgram->setUniformValue("saturation", m_saturation);
-    
-    // 更新纹理数据
-    updateTextures();
-    
-    // 绑定纹理
-    if (m_frameFormat == AV_PIX_FMT_YUV420P) {
-        glActiveTexture(GL_TEXTURE0);
-        glBindTexture(GL_TEXTURE_2D, m_textureY);
-        m_shaderProgram->setUniformValue("textureY", 0);
-        
-        glActiveTexture(GL_TEXTURE1);
-        glBindTexture(GL_TEXTURE_2D, m_textureU);
-        m_shaderProgram->setUniformValue("textureU", 1);
-        
-        glActiveTexture(GL_TEXTURE2);
-        glBindTexture(GL_TEXTURE_2D, m_textureV);
-        m_shaderProgram->setUniformValue("textureV", 2);
-    } else {
-        glActiveTexture(GL_TEXTURE0);
-        glBindTexture(GL_TEXTURE_2D, m_textureRGB);
-        m_shaderProgram->setUniformValue("textureRGB", 0);
-    }
-    
-    // 绘制四边形
-    glBindVertexArray(m_VAO);
-    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
-    glBindVertexArray(0);
-    
-    m_shaderProgram->release();
-    
-    locker.unlock();
-    
-    // 绘制FPS信息
-    if (m_showFPS) {
-        drawFPSInfo();
-    }
-}
-
-void RecorderVideoWidget::resizeGL(int width, int height) {
-    glViewport(0, 0, width, height);
-}
-
-void RecorderVideoWidget::mousePressEvent(QMouseEvent* event) {
-    if (event->button() == Qt::LeftButton) {
-        emit clicked(event->pos());
-    }
-    QOpenGLWidget::mousePressEvent(event);
-}
-
-void RecorderVideoWidget::mouseDoubleClickEvent(QMouseEvent* event) {
-    if (event->button() == Qt::LeftButton) {
-        emit doubleClicked(event->pos());
-    }
-    QOpenGLWidget::mouseDoubleClickEvent(event);
-}
-
-void RecorderVideoWidget::updateFPS() {
-    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
-    
-    if (m_lastFPSUpdate > 0) {
-        qint64 elapsed = currentTime - m_lastFPSUpdate;
-        if (elapsed > 0) {
-            m_currentFPS = (m_frameCount * 1000.0) / elapsed;
-        }
-    }
-    
-    m_frameCount = 0;
-    m_lastFPSUpdate = currentTime;
-    
-    if (m_showFPS) {
-        update();
-    }
-}
-
-bool RecorderVideoWidget::initShaders() {
-    m_shaderProgram = std::make_unique<QOpenGLShaderProgram>();
-    
-    // 添加顶点着色器
-    if (!m_shaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource)) {
-        qWarning() << "Failed to compile vertex shader:" << m_shaderProgram->log();
-        return false;
-    }
-    
-    // 根据格式选择片段着色器
-    const char* fragmentSource = (m_frameFormat == AV_PIX_FMT_YUV420P) ? 
-                                  yuvFragmentShaderSource : rgbFragmentShaderSource;
-    
-    if (!m_shaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentSource)) {
-        qWarning() << "Failed to compile fragment shader:" << m_shaderProgram->log();
-        return false;
-    }
-    
-    // 链接着色器程序
-    if (!m_shaderProgram->link()) {
-        qWarning() << "Failed to link shader program:" << m_shaderProgram->log();
-        return false;
-    }
-    
-    return true;
-}
-
-void RecorderVideoWidget::createTextures() {
-    // 创建Y纹理
-    glGenTextures(1, &m_textureY);
-    glBindTexture(GL_TEXTURE_2D, m_textureY);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-    
-    // 创建U纹理
-    glGenTextures(1, &m_textureU);
-    glBindTexture(GL_TEXTURE_2D, m_textureU);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-    
-    // 创建V纹理
-    glGenTextures(1, &m_textureV);
-    glBindTexture(GL_TEXTURE_2D, m_textureV);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-    
-    // 创建RGB纹理
-    glGenTextures(1, &m_textureRGB);
-    glBindTexture(GL_TEXTURE_2D, m_textureRGB);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-}
-
-void RecorderVideoWidget::updateTextures() {
-    if (!m_frameReady) {
-        return;
-    }
-    
-    if (m_frameFormat == AV_PIX_FMT_YUV420P) {
-        // 更新Y纹理
-        glActiveTexture(GL_TEXTURE0);
-        glBindTexture(GL_TEXTURE_2D, m_textureY);
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, m_frameWidth, m_frameHeight, 
-                     0, GL_RED, GL_UNSIGNED_BYTE, m_frameData[0]);
-        
-        // 更新U纹理
-        glActiveTexture(GL_TEXTURE1);
-        glBindTexture(GL_TEXTURE_2D, m_textureU);
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, m_frameWidth/2, m_frameHeight/2, 
-                     0, GL_RED, GL_UNSIGNED_BYTE, m_frameData[1]);
-        
-        // 更新V纹理
-        glActiveTexture(GL_TEXTURE2);
-        glBindTexture(GL_TEXTURE_2D, m_textureV);
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, m_frameWidth/2, m_frameHeight/2, 
-                     0, GL_RED, GL_UNSIGNED_BYTE, m_frameData[2]);
-    } else {
-        // 更新RGB纹理
-        glActiveTexture(GL_TEXTURE0);
-        glBindTexture(GL_TEXTURE_2D, m_textureRGB);
-        
-        GLenum format = GL_RGB;
-        if (m_frameFormat == AV_PIX_FMT_RGBA || m_frameFormat == AV_PIX_FMT_BGRA) {
-            format = GL_RGBA;
-        }
-        
-        glTexImage2D(GL_TEXTURE_2D, 0, format, m_frameWidth, m_frameHeight, 
-                     0, format, GL_UNSIGNED_BYTE, m_frameData[0]);
-    }
-}
-
-QRectF RecorderVideoWidget::calculateDisplayRect() const {
-    if (!m_keepAspectRatio || m_frameWidth <= 0 || m_frameHeight <= 0) {
-        return QRectF(0, 0, width(), height());
-    }
-    
-    double widgetAspect = static_cast<double>(width()) / height();
-    double frameAspect = static_cast<double>(m_frameWidth) / m_frameHeight;
-    
-    QRectF displayRect;
-    
-    if (widgetAspect > frameAspect) {
-        // 控件更宽,以高度为准
-        int displayWidth = static_cast<int>(height() * frameAspect);
-        displayRect = QRectF((width() - displayWidth) / 2, 0, displayWidth, height());
-    } else {
-        // 控件更高,以宽度为准
-        int displayHeight = static_cast<int>(width() / frameAspect);
-        displayRect = QRectF(0, (height() - displayHeight) / 2, width(), displayHeight);
-    }
-    
-    return displayRect;
-}
-
-void RecorderVideoWidget::drawNoVideoHint() {
-    QPainter painter(this);
-    painter.setRenderHint(QPainter::Antialiasing);
-    
-    // 设置背景色
-    painter.fillRect(rect(), m_backgroundColor);
-    
-    // 绘制提示文本
-    painter.setPen(Qt::white);
-    painter.setFont(QFont("Arial", 16));
-    painter.drawText(rect(), Qt::AlignCenter, m_noVideoText);
-}
-
-void RecorderVideoWidget::drawFPSInfo() {
-    QPainter painter(this);
-    painter.setRenderHint(QPainter::Antialiasing);
-    
-    // 设置字体和颜色
-    painter.setPen(Qt::yellow);
-    painter.setFont(QFont("Arial", 12, QFont::Bold));
-    
-    // 绘制FPS信息
-    QString fpsText = QString("FPS: %1").arg(m_currentFPS, 0, 'f', 1);
-    QRect textRect = painter.fontMetrics().boundingRect(fpsText);
-    
-    // 绘制背景
-    QRect bgRect = textRect.adjusted(-5, -2, 5, 2);
-    bgRect.moveTopLeft(QPoint(10, 10));
-    painter.fillRect(bgRect, QColor(0, 0, 0, 128));
-    
-    // 绘制文本
-    painter.drawText(bgRect, Qt::AlignCenter, fpsText);
-}
-
-bool RecorderVideoWidget::copyFromAVFrame(AVFrame* frame) {
-    if (!frame || !frame->data[0]) {
-        return false;
-    }
-    
-    // 复制Y平面
-    if (m_frameData[0] && frame->data[0]) {
-        for (int y = 0; y < m_frameHeight; ++y) {
-            memcpy(m_frameData[0] + y * m_frameLinesize[0],
-                   frame->data[0] + y * frame->linesize[0],
-                   m_frameWidth);
-        }
-    }
-    
-    // 复制U平面
-    if (m_frameFormat == AV_PIX_FMT_YUV420P && m_frameData[1] && frame->data[1]) {
-        for (int y = 0; y < m_frameHeight / 2; ++y) {
-            memcpy(m_frameData[1] + y * m_frameLinesize[1],
-                   frame->data[1] + y * frame->linesize[1],
-                   m_frameWidth / 2);
-        }
-    }
-    
-    // 复制V平面
-    if (m_frameFormat == AV_PIX_FMT_YUV420P && m_frameData[2] && frame->data[2]) {
-        for (int y = 0; y < m_frameHeight / 2; ++y) {
-            memcpy(m_frameData[2] + y * m_frameLinesize[2],
-                   frame->data[2] + y * frame->linesize[2],
-                   m_frameWidth / 2);
-        }
-    }
-    
-    return true;
-}
-
-bool RecorderVideoWidget::copyFromVideoFrame(const VideoFrame& frame) {
-    if (!frame.data[0]) {
-        return false;
-    }
-    
-    // 复制Y平面或RGB数据
-    if (m_frameData[0] && frame.data[0]) {
-        for (int y = 0; y < m_frameHeight; ++y) {
-            int copySize = (m_frameFormat == AV_PIX_FMT_YUV420P) ? m_frameWidth : 
-                          (m_frameWidth * ((m_frameFormat == AV_PIX_FMT_RGB24) ? 3 : 4));
-            memcpy(m_frameData[0] + y * m_frameLinesize[0],
-                   frame.data[0] + y * frame.linesize[0],
-                   copySize);
-        }
-    }
-    
-    // 复制U平面
-    if (m_frameFormat == AV_PIX_FMT_YUV420P && m_frameData[1] && frame.data[1]) {
-        for (int y = 0; y < m_frameHeight / 2; ++y) {
-            memcpy(m_frameData[1] + y * m_frameLinesize[1],
-                   frame.data[1] + y * frame.linesize[1],
-                   m_frameWidth / 2);
-        }
-    }
-    
-    // 复制V平面
-    if (m_frameFormat == AV_PIX_FMT_YUV420P && m_frameData[2] && frame.data[2]) {
-        for (int y = 0; y < m_frameHeight / 2; ++y) {
-            memcpy(m_frameData[2] + y * m_frameLinesize[2],
-                   frame.data[2] + y * frame.linesize[2],
-                   m_frameWidth / 2);
-        }
-    }
-    
-    return true;
-}
-
-bool RecorderVideoWidget::allocateFrameBuffer(int width, int height, int format) {
-    // 验证参数
-    if (width <= 0 || height <= 0 || width > 8192 || height > 8192) {
-        qWarning() << "Invalid frame dimensions:" << width << "x" << height;
-        return false;
-    }
-    
-    // 释放旧缓冲区
-    freeFrameBuffer();
-    
-    m_frameWidth = width;
-    m_frameHeight = height;
-    m_frameFormat = format;
-    
-    try {
-        if (format == AV_PIX_FMT_YUV420P) {
-            // 分配Y平面
-            m_frameLinesize[0] = width;
-            size_t ySize = static_cast<size_t>(width) * height;
-            m_frameData[0] = static_cast<uint8_t*>(av_malloc(ySize));
-            
-            // 分配U平面
-            m_frameLinesize[1] = width / 2;
-            size_t uvSize = static_cast<size_t>(width) * height / 4;
-            m_frameData[1] = static_cast<uint8_t*>(av_malloc(uvSize));
-            
-            // 分配V平面
-            m_frameLinesize[2] = width / 2;
-            m_frameData[2] = static_cast<uint8_t*>(av_malloc(uvSize));
-            
-            bool success = m_frameData[0] && m_frameData[1] && m_frameData[2];
-            if (!success) {
-                qWarning() << "Failed to allocate YUV420P frame buffer";
-                freeFrameBuffer(); // 清理部分分配的内存
-                return false;
-            }
-            
-            qDebug() << "Allocated YUV420P buffer:" << width << "x" << height 
-                     << "Y:" << ySize << "U/V:" << uvSize;
-            return true;
-        } else {
-            // RGB格式
-            int bytesPerPixel = (format == AV_PIX_FMT_RGB24) ? 3 : 4;
-            m_frameLinesize[0] = width * bytesPerPixel;
-            size_t totalSize = static_cast<size_t>(width) * height * bytesPerPixel;
-            m_frameData[0] = static_cast<uint8_t*>(av_malloc(totalSize));
-            
-            bool success = (m_frameData[0] != nullptr);
-            if (!success) {
-                qWarning() << "Failed to allocate RGB frame buffer";
-                freeFrameBuffer();
-                return false;
-            }
-            
-            qDebug() << "Allocated RGB buffer:" << width << "x" << height 
-                     << "size:" << totalSize;
-            return true;
-        }
-    } catch (const std::exception& e) {
-        qWarning() << "Exception in allocateFrameBuffer:" << e.what();
-        freeFrameBuffer();
-        return false;
-    } catch (...) {
-        qWarning() << "Unknown exception in allocateFrameBuffer";
-        freeFrameBuffer();
-        return false;
-    }
-}
-
-void RecorderVideoWidget::freeFrameBuffer() {
-    for (int i = 0; i < 4; ++i) {
-        if (m_frameData[i]) {
-            av_free(m_frameData[i]);
-            m_frameData[i] = nullptr;
-        }
-        m_frameLinesize[i] = 0;
-    }
-    
-    m_frameWidth = 0;
-    m_frameHeight = 0;
-    m_frameFormat = AV_PIX_FMT_NONE;
-}
-
-// 静态成员定义
-constexpr float RecorderVideoWidget::VERTICES[];
-constexpr unsigned int RecorderVideoWidget::INDICES[];

+ 0 - 290
AV/code/recorder/ui/recorder_video_widget.h

@@ -1,290 +0,0 @@
-#ifndef AV_RECORDER_VIDEO_WIDGET_H
-#define AV_RECORDER_VIDEO_WIDGET_H
-
-#include <QOpenGLWidget>
-#include <QOpenGLFunctions>
-#include <QOpenGLExtraFunctions>
-#include <QOpenGLShaderProgram>
-#include <QOpenGLTexture>
-#include <QMutex>
-#include <QTimer>
-#include <QImage>
-#include <QPainter>
-#include <QResizeEvent>
-#include <QMouseEvent>
-#include <memory>
-
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/imgutils.h>
-}
-
-/**
- * 录制器视频预览组件
- * 
- * 基于OpenGL的高性能视频显示组件,支持:
- * - YUV和RGB格式显示
- * - 硬件加速渲染
- * - 保持宽高比
- * - 实时帧率显示
- * - 多种视觉效果
- */
-class RecorderVideoWidget : public QOpenGLWidget, protected QOpenGLExtraFunctions {
-    Q_OBJECT
-
-public:
-    /**
-     * 视频帧结构
-     */
-    struct VideoFrame {
-        uint8_t* data[4] = {nullptr};
-        int linesize[4] = {0};
-        int width = 0;
-        int height = 0;
-        int format = 0; // AVPixelFormat
-        int64_t pts = 0;
-        
-        VideoFrame() = default;
-        ~VideoFrame() {
-            for (int i = 0; i < 4; ++i) {
-                if (data[i]) {
-                    av_free(data[i]);
-                    data[i] = nullptr;
-                }
-            }
-        }
-        
-        // 禁用拷贝,只允许移动
-        VideoFrame(const VideoFrame&) = delete;
-        VideoFrame& operator=(const VideoFrame&) = delete;
-        VideoFrame(VideoFrame&& other) noexcept {
-            *this = std::move(other);
-        }
-        VideoFrame& operator=(VideoFrame&& other) noexcept {
-            if (this != &other) {
-                for (int i = 0; i < 4; ++i) {
-                    data[i] = other.data[i];
-                    linesize[i] = other.linesize[i];
-                    other.data[i] = nullptr;
-                    other.linesize[i] = 0;
-                }
-                width = other.width;
-                height = other.height;
-                format = other.format;
-                pts = other.pts;
-            }
-            return *this;
-        }
-    };
-
-public:
-    explicit RecorderVideoWidget(QWidget* parent = nullptr);
-    ~RecorderVideoWidget();
-
-    /**
-     * 初始化视频显示
-     */
-    bool initialize(int width, int height, int format);
-    
-    /**
-     * 清理资源
-     */
-    void cleanup();
-    
-    /**
-     * 更新视频帧
-     */
-    bool updateFrame(AVFrame* frame);
-    
-    /**
-     * 更新视频帧(自定义格式)
-     */
-    bool updateFrame(const VideoFrame& frame);
-    
-    /**
-     * 清空当前帧
-     */
-    void clearFrame();
-    
-    /**
-     * 设置保持宽高比
-     */
-    void setKeepAspectRatio(bool keep) {
-        m_keepAspectRatio = keep;
-        update();
-    }
-    
-    /**
-     * 获取是否保持宽高比
-     */
-    bool keepAspectRatio() const { return m_keepAspectRatio; }
-    
-    /**
-     * 设置显示FPS
-     */
-    void setShowFPS(bool show) {
-        m_showFPS = show;
-        update();
-    }
-    
-    /**
-     * 获取当前FPS
-     */
-    double getCurrentFPS() const { return m_currentFPS; }
-    
-    /**
-     * 设置无视频提示文本
-     */
-    void setNoVideoText(const QString& text) {
-        m_noVideoText = text;
-        update();
-    }
-    
-    /**
-     * 设置背景颜色
-     */
-    void setBackgroundColor(const QColor& color) {
-        m_backgroundColor = color;
-        update();
-    }
-    
-    // 视觉效果
-    void setGrayscale(bool enable);
-    void setFlipHorizontal(bool enable);
-    void setFlipVertical(bool enable);
-    void setBrightness(float brightness); // -1.0 to 1.0
-    void setContrast(float contrast);     // 0.0 to 2.0
-    void setSaturation(float saturation); // 0.0 to 2.0
-
-protected:
-    void initializeGL() override;
-    void paintGL() override;
-    void resizeGL(int width, int height) override;
-    void mousePressEvent(QMouseEvent* event) override;
-    void mouseDoubleClickEvent(QMouseEvent* event) override;
-
-private slots:
-    void updateFPS();
-
-signals:
-    /**
-     * 鼠标点击信号
-     */
-    void clicked(QPoint position);
-    
-    /**
-     * 双击信号
-     */
-    void doubleClicked(QPoint position);
-
-private:
-    /**
-     * 初始化着色器
-     */
-    bool initShaders();
-    
-    /**
-     * 创建纹理
-     */
-    void createTextures();
-    
-    /**
-     * 更新纹理数据
-     */
-    void updateTextures();
-    
-    /**
-     * 计算显示矩形
-     */
-    QRectF calculateDisplayRect() const;
-    
-    /**
-     * 绘制无视频提示
-     */
-    void drawNoVideoHint();
-    
-    /**
-     * 绘制FPS信息
-     */
-    void drawFPSInfo();
-    
-    /**
-     * 从AVFrame复制数据
-     */
-    bool copyFromAVFrame(AVFrame* frame);
-    
-    /**
-     * 从VideoFrame复制数据
-     */
-    bool copyFromVideoFrame(const VideoFrame& frame);
-    
-    /**
-     * 分配帧缓冲区
-     */
-    bool allocateFrameBuffer(int width, int height, int format);
-    
-    /**
-     * 释放帧缓冲区
-     */
-    void freeFrameBuffer();
-
-private:
-    // OpenGL资源
-    std::unique_ptr<QOpenGLShaderProgram> m_shaderProgram;
-    GLuint m_textureY;
-    GLuint m_textureU;
-    GLuint m_textureV;
-    GLuint m_textureRGB;
-    GLuint m_VAO;
-    GLuint m_VBO;
-    
-    // 帧数据
-    uint8_t* m_frameData[4];
-    int m_frameLinesize[4];
-    int m_frameWidth;
-    int m_frameHeight;
-    int m_frameFormat;
-    bool m_frameReady;
-    
-    // 显示设置
-    bool m_keepAspectRatio;
-    bool m_showFPS;
-    QString m_noVideoText;
-    QColor m_backgroundColor;
-    
-    // 视觉效果
-    bool m_grayscale;
-    bool m_flipHorizontal;
-    bool m_flipVertical;
-    float m_brightness;
-    float m_contrast;
-    float m_saturation;
-    
-    // FPS计算
-    QTimer* m_fpsTimer;
-    int m_frameCount;
-    double m_currentFPS;
-    qint64 m_lastFPSUpdate;
-    
-    // 线程安全
-    mutable QMutex m_mutex;
-    
-    // 初始化状态
-    bool m_initialized;
-    
-    // 顶点数据
-    static constexpr float VERTICES[] = {
-        // 位置        // 纹理坐标
-        -1.0f, -1.0f,  0.0f, 1.0f,
-         1.0f, -1.0f,  1.0f, 1.0f,
-         1.0f,  1.0f,  1.0f, 0.0f,
-        -1.0f,  1.0f,  0.0f, 0.0f
-    };
-    
-    static constexpr unsigned int INDICES[] = {
-        0, 1, 2,
-        2, 3, 0
-    };
-};
-
-#endif // AV_RECORDER_VIDEO_WIDGET_H

+ 0 - 611
AV/code/recorder/ui/styles/recorder_ui.qss

@@ -1,611 +0,0 @@
-/* AV录制器UI样式表 */
-/* 现代化深色主题 */
-
-/* 全局样式 */
-* {
-    font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
-    font-size: 9pt;
-}
-
-/* 主窗口 */
-QMainWindow {
-    background-color: #2b2b2b;
-    color: #ffffff;
-}
-
-/* 中央部件 */
-QWidget {
-    background-color: #2b2b2b;
-    color: #ffffff;
-    border: none;
-}
-
-/* 菜单栏 */
-QMenuBar {
-    background-color: #333333;
-    color: #ffffff;
-    border-bottom: 1px solid #555555;
-    padding: 2px;
-}
-
-QMenuBar::item {
-    background-color: transparent;
-    padding: 4px 8px;
-    border-radius: 3px;
-}
-
-QMenuBar::item:selected {
-    background-color: #0a84ff;
-}
-
-QMenuBar::item:pressed {
-    background-color: #0066cc;
-}
-
-/* 菜单 */
-QMenu {
-    background-color: #333333;
-    color: #ffffff;
-    border: 1px solid #555555;
-    border-radius: 4px;
-    padding: 4px;
-}
-
-QMenu::item {
-    background-color: transparent;
-    padding: 6px 20px;
-    border-radius: 3px;
-}
-
-QMenu::item:selected {
-    background-color: #0a84ff;
-}
-
-QMenu::separator {
-    height: 1px;
-    background-color: #555555;
-    margin: 4px 0px;
-}
-
-/* 工具栏 */
-QToolBar {
-    background-color: #333333;
-    border: 1px solid #555555;
-    border-radius: 4px;
-    spacing: 2px;
-    padding: 2px;
-}
-
-QToolBar::handle {
-    background-color: #555555;
-    width: 8px;
-    margin: 4px;
-    border-radius: 2px;
-}
-
-QToolBar::separator {
-    background-color: #555555;
-    width: 1px;
-    margin: 4px 2px;
-}
-
-/* 工具按钮 */
-QToolButton {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    color: #ffffff;
-    padding: 6px;
-    margin: 1px;
-}
-
-QToolButton:hover {
-    background-color: #555555;
-    border-color: #777777;
-}
-
-QToolButton:pressed {
-    background-color: #333333;
-    border-color: #555555;
-}
-
-QToolButton:checked {
-    background-color: #0a84ff;
-    border-color: #0066cc;
-}
-
-QToolButton:disabled {
-    background-color: #2b2b2b;
-    border-color: #444444;
-    color: #666666;
-}
-
-/* 按钮 */
-QPushButton {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    color: #ffffff;
-    padding: 6px 12px;
-    min-width: 60px;
-}
-
-QPushButton:hover {
-    background-color: #555555;
-    border-color: #777777;
-}
-
-QPushButton:pressed {
-    background-color: #333333;
-    border-color: #555555;
-}
-
-QPushButton:checked {
-    background-color: #0a84ff;
-    border-color: #0066cc;
-}
-
-QPushButton:disabled {
-    background-color: #2b2b2b;
-    border-color: #444444;
-    color: #666666;
-}
-
-/* 主要按钮 */
-QPushButton.primary {
-    background-color: #0a84ff;
-    border-color: #0066cc;
-}
-
-QPushButton.primary:hover {
-    background-color: #0066cc;
-    border-color: #004499;
-}
-
-QPushButton.primary:pressed {
-    background-color: #004499;
-    border-color: #003366;
-}
-
-/* 危险按钮 */
-QPushButton.danger {
-    background-color: #ff3b30;
-    border-color: #cc2e24;
-}
-
-QPushButton.danger:hover {
-    background-color: #cc2e24;
-    border-color: #99221b;
-}
-
-QPushButton.danger:pressed {
-    background-color: #99221b;
-    border-color: #661612;
-}
-
-/* 成功按钮 */
-QPushButton.success {
-    background-color: #34c759;
-    border-color: #2a9f47;
-}
-
-QPushButton.success:hover {
-    background-color: #2a9f47;
-    border-color: #1f7735;
-}
-
-QPushButton.success:pressed {
-    background-color: #1f7735;
-    border-color: #154f23;
-}
-
-/* 标签 */
-QLabel {
-    color: #ffffff;
-    background-color: transparent;
-}
-
-QLabel.title {
-    font-size: 12pt;
-    font-weight: bold;
-    color: #ffffff;
-}
-
-QLabel.subtitle {
-    font-size: 10pt;
-    color: #cccccc;
-}
-
-QLabel.caption {
-    font-size: 8pt;
-    color: #999999;
-}
-
-/* 输入框 */
-QLineEdit {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    color: #ffffff;
-    padding: 6px;
-    selection-background-color: #0a84ff;
-}
-
-QLineEdit:focus {
-    border-color: #0a84ff;
-}
-
-QLineEdit:disabled {
-    background-color: #2b2b2b;
-    border-color: #444444;
-    color: #666666;
-}
-
-/* 文本编辑器 */
-QTextEdit, QPlainTextEdit {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    color: #ffffff;
-    selection-background-color: #0a84ff;
-}
-
-QTextEdit:focus, QPlainTextEdit:focus {
-    border-color: #0a84ff;
-}
-
-/* 组合框 */
-QComboBox {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    color: #ffffff;
-    padding: 6px;
-    min-width: 100px;
-}
-
-QComboBox:hover {
-    border-color: #777777;
-}
-
-QComboBox:focus {
-    border-color: #0a84ff;
-}
-
-QComboBox::drop-down {
-    border: none;
-    width: 20px;
-}
-
-QComboBox::down-arrow {
-    image: url(:/icons/arrow_down.png);
-    width: 12px;
-    height: 12px;
-}
-
-QComboBox QAbstractItemView {
-    background-color: #333333;
-    border: 1px solid #555555;
-    border-radius: 4px;
-    color: #ffffff;
-    selection-background-color: #0a84ff;
-}
-
-/* 滑块 */
-QSlider::groove:horizontal {
-    background-color: #444444;
-    height: 6px;
-    border-radius: 3px;
-}
-
-QSlider::handle:horizontal {
-    background-color: #0a84ff;
-    border: 1px solid #0066cc;
-    width: 16px;
-    height: 16px;
-    border-radius: 8px;
-    margin: -5px 0;
-}
-
-QSlider::handle:horizontal:hover {
-    background-color: #0066cc;
-}
-
-QSlider::handle:horizontal:pressed {
-    background-color: #004499;
-}
-
-QSlider::sub-page:horizontal {
-    background-color: #0a84ff;
-    border-radius: 3px;
-}
-
-/* 进度条 */
-QProgressBar {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    text-align: center;
-    color: #ffffff;
-    height: 20px;
-}
-
-QProgressBar::chunk {
-    background-color: #0a84ff;
-    border-radius: 3px;
-}
-
-/* 复选框 */
-QCheckBox {
-    color: #ffffff;
-    spacing: 8px;
-}
-
-QCheckBox::indicator {
-    width: 16px;
-    height: 16px;
-    border: 1px solid #666666;
-    border-radius: 3px;
-    background-color: #444444;
-}
-
-QCheckBox::indicator:hover {
-    border-color: #777777;
-}
-
-QCheckBox::indicator:checked {
-    background-color: #0a84ff;
-    border-color: #0066cc;
-    image: url(:/icons/check.png);
-}
-
-/* 单选按钮 */
-QRadioButton {
-    color: #ffffff;
-    spacing: 8px;
-}
-
-QRadioButton::indicator {
-    width: 16px;
-    height: 16px;
-    border: 1px solid #666666;
-    border-radius: 8px;
-    background-color: #444444;
-}
-
-QRadioButton::indicator:hover {
-    border-color: #777777;
-}
-
-QRadioButton::indicator:checked {
-    background-color: #0a84ff;
-    border-color: #0066cc;
-}
-
-QRadioButton::indicator:checked::after {
-    content: "";
-    width: 6px;
-    height: 6px;
-    border-radius: 3px;
-    background-color: #ffffff;
-    margin: 4px;
-}
-
-/* 分组框 */
-QGroupBox {
-    color: #ffffff;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    margin-top: 10px;
-    padding-top: 10px;
-}
-
-QGroupBox::title {
-    subcontrol-origin: margin;
-    subcontrol-position: top left;
-    padding: 0 8px;
-    background-color: #2b2b2b;
-    color: #ffffff;
-    font-weight: bold;
-}
-
-/* 选项卡 */
-QTabWidget::pane {
-    border: 1px solid #666666;
-    border-radius: 4px;
-    background-color: #2b2b2b;
-}
-
-QTabBar::tab {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-bottom: none;
-    border-radius: 4px 4px 0 0;
-    color: #ffffff;
-    padding: 8px 16px;
-    margin-right: 2px;
-}
-
-QTabBar::tab:hover {
-    background-color: #555555;
-}
-
-QTabBar::tab:selected {
-    background-color: #0a84ff;
-    border-color: #0066cc;
-}
-
-/* 滚动条 */
-QScrollBar:vertical {
-    background-color: #333333;
-    width: 12px;
-    border-radius: 6px;
-}
-
-QScrollBar::handle:vertical {
-    background-color: #666666;
-    border-radius: 6px;
-    min-height: 20px;
-}
-
-QScrollBar::handle:vertical:hover {
-    background-color: #777777;
-}
-
-QScrollBar::add-line:vertical,
-QScrollBar::sub-line:vertical {
-    border: none;
-    background: none;
-}
-
-QScrollBar:horizontal {
-    background-color: #333333;
-    height: 12px;
-    border-radius: 6px;
-}
-
-QScrollBar::handle:horizontal {
-    background-color: #666666;
-    border-radius: 6px;
-    min-width: 20px;
-}
-
-QScrollBar::handle:horizontal:hover {
-    background-color: #777777;
-}
-
-QScrollBar::add-line:horizontal,
-QScrollBar::sub-line:horizontal {
-    border: none;
-    background: none;
-}
-
-/* 状态栏 */
-QStatusBar {
-    background-color: #333333;
-    color: #ffffff;
-    border-top: 1px solid #555555;
-    padding: 2px;
-}
-
-QStatusBar::item {
-    border: none;
-}
-
-/* 分割器 */
-QSplitter::handle {
-    background-color: #555555;
-}
-
-QSplitter::handle:horizontal {
-    width: 4px;
-}
-
-QSplitter::handle:vertical {
-    height: 4px;
-}
-
-QSplitter::handle:hover {
-    background-color: #777777;
-}
-
-/* 对话框 */
-QDialog {
-    background-color: #2b2b2b;
-    color: #ffffff;
-}
-
-/* 消息框 */
-QMessageBox {
-    background-color: #2b2b2b;
-    color: #ffffff;
-}
-
-QMessageBox QLabel {
-    color: #ffffff;
-}
-
-/* 文件对话框 */
-QFileDialog {
-    background-color: #2b2b2b;
-    color: #ffffff;
-}
-
-/* 工具提示 */
-QToolTip {
-    background-color: #333333;
-    color: #ffffff;
-    border: 1px solid #555555;
-    border-radius: 4px;
-    padding: 4px;
-}
-
-/* 录制器特定样式 */
-.RecorderMainWidget {
-    background-color: #2b2b2b;
-}
-
-.RecorderVideoWidget {
-    background-color: #000000;
-    border: 1px solid #666666;
-    border-radius: 4px;
-}
-
-.RecorderAudioWidget {
-    background-color: #333333;
-    border: 1px solid #666666;
-    border-radius: 4px;
-    padding: 8px;
-}
-
-.AudioLevelWidget {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 2px;
-}
-
-.RecorderSettingsDialog {
-    background-color: #2b2b2b;
-}
-
-/* 录制状态指示器 */
-.recording-indicator {
-    background-color: #ff3b30;
-    border-radius: 6px;
-    width: 12px;
-    height: 12px;
-}
-
-.paused-indicator {
-    background-color: #ff9500;
-    border-radius: 6px;
-    width: 12px;
-    height: 12px;
-}
-
-.stopped-indicator {
-    background-color: #666666;
-    border-radius: 6px;
-    width: 12px;
-    height: 12px;
-}
-
-/* 音频电平条 */
-.audio-level-bar {
-    background-color: #444444;
-    border: 1px solid #666666;
-    border-radius: 2px;
-}
-
-.audio-level-fill {
-    background-color: #34c759;
-    border-radius: 1px;
-}
-
-.audio-level-peak {
-    background-color: #ff9500;
-}
-
-.audio-level-overload {
-    background-color: #ff3b30;
-}

+ 0 - 726
AV/code/utils/utils_frame_queue.cpp

@@ -1,726 +0,0 @@
-#include "utils_frame_queue.h"
-#include "../base/logger.h"
-#include "../base/media_common.h"
-#include <algorithm>
-#include <deque>
-#include <shared_mutex>
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-FrameQueue::FrameQueue(const FrameQueueConfig& config)
-    : config_(config) {
-    Logger::instance().debugf("FrameQueue created with max size: {}", config_.maxSize);
-}
-
-FrameQueue::~FrameQueue() {
-    shutdown_ = true;
-    notEmpty_.notify_all();
-    notFull_.notify_all();
-    clear();
-    Logger::instance().debug("FrameQueue destroyed");
-}
-
-ErrorCode FrameQueue::enqueue(std::unique_ptr<FrameQueueItem> item) {
-    if (!item) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (shutdown_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    // 检查是否需要丢帧
-    if (shouldDropFrame(*item)) {
-        if (dropCallback_) {
-            dropCallback_(*item, "Smart frame drop");
-        }
-        
-        std::lock_guard<std::mutex> statsLock(statsMutex_);
-        stats_.totalDropped++;
-        
-        Logger::instance().debug("Frame dropped by smart drop policy");
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 等待队列有空间
-    if (blocking_ && queue_.size() >= config_.maxSize) {
-        if (config_.dropOnFull) {
-            if (config_.dropOldest) {
-                dropOldestFrame();
-            } else {
-                if (dropCallback_) {
-                    dropCallback_(*item, "Queue full - drop newest");
-                }
-                
-                std::lock_guard<std::mutex> statsLock(statsMutex_);
-                stats_.totalDropped++;
-                
-                Logger::instance().debug("Frame dropped - queue full");
-                return ErrorCode::SUCCESS;
-            }
-        } else {
-            // 等待队列有空间
-            if (!notFull_.wait_for(lock, std::chrono::milliseconds(config_.timeoutMs),
-                                  [this] { return queue_.size() < config_.maxSize || shutdown_; })) {
-                Logger::instance().warning("Enqueue timeout");
-                return ErrorCode::TIMEOUT;
-            }
-            
-            if (shutdown_) {
-                return ErrorCode::INVALID_STATE;
-            }
-        }
-    }
-    
-    // 添加到队列
-    queue_.push_back(std::move(item));
-    
-    // 更新统计信息
-    if (config_.enableStats) {
-        updateStats(*queue_.back(), true);
-    }
-    
-    // 通知等待的消费者
-    notEmpty_.notify_one();
-    
-    // 回调
-    if (enqueueCallback_) {
-        enqueueCallback_(*queue_.back());
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 预览方法实现
-const FrameQueueItem* FrameQueue::peek() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    if (queue_.empty()) {
-        return nullptr;
-    }
-    return queue_.front().get();
-}
-
-const FrameQueueItem* FrameQueue::peek(int index) const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    if (index < 0 || static_cast<size_t>(index) >= queue_.size()) {
-        return nullptr;
-    }
-    
-    // 使用deque的随机访问能力
-    return queue_[index].get();
-}
-
-const AVFramePtr& FrameQueue::peekFramePtr() const {
-    const FrameQueueItem* item = peek();
-    if (item) {
-        return item->frame;
-    }
-    static AVFramePtr nullFrame;
-    return nullFrame;
-}
-
-std::unique_ptr<FrameQueueItem> FrameQueue::dequeue() {
-    return dequeue(config_.timeoutMs);
-}
-
-std::unique_ptr<FrameQueueItem> FrameQueue::dequeue(int timeoutMs) {
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    // 等待队列有数据
-    if (blocking_ && queue_.empty()) {
-        if (!notEmpty_.wait_for(lock, std::chrono::milliseconds(timeoutMs),
-                               [this] { return !queue_.empty() || shutdown_; })) {
-            return nullptr; // 超时
-        }
-        
-        if (shutdown_ || queue_.empty()) {
-            return nullptr;
-        }
-    }
-    
-    if (queue_.empty()) {
-        return nullptr;
-    }
-    
-    // 取出队列头部元素
-    auto item = std::move(queue_.front());
-    queue_.pop_front();
-    
-    // 更新统计信息
-    if (config_.enableStats) {
-        updateStats(*item, false);
-    }
-    
-    // 通知等待的生产者
-    notFull_.notify_one();
-    
-    // 回调
-    if (dequeueCallback_) {
-        dequeueCallback_(*item);
-    }
-    
-    return item;
-}
-
-ErrorCode FrameQueue::enqueue(AVFramePtr frame, int streamIndex) {
-    if (!frame) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    auto item = std::make_unique<FrameQueueItem>(std::move(frame), streamIndex);
-    return enqueue(std::move(item));
-}
-
-AVFramePtr FrameQueue::dequeueFrame() {
-    auto item = dequeue();
-    if (item && item->frame) {
-        return std::move(item->frame);
-    }
-    return nullptr;
-}
-
-AVFramePtr FrameQueue::dequeueFrame(int timeoutMs) {
-    auto item = dequeue(timeoutMs);
-    if (item && item->frame) {
-        return std::move(item->frame);
-    }
-    return nullptr;
-}
-
-void FrameQueue::clear() {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    
-    while (!queue_.empty()) {
-        queue_.pop_front();
-    }
-    
-    Logger::instance().debug("Frame queue cleared");
-}
-
-void FrameQueue::flush() {
-    clear();
-    notEmpty_.notify_all();
-    notFull_.notify_all();
-}
-
-void FrameQueue::setMaxSize(size_t maxSize) {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    config_.maxSize = maxSize;
-    
-    // 如果当前队列大小超过新的最大值,丢弃多余的帧
-    while (queue_.size() > maxSize) {
-        if (config_.dropOldest) {
-            dropOldestFrame();
-        } else {
-            break; // 不丢弃,保持当前状态
-        }
-    }
-    
-    Logger::instance().debugf("Frame queue max size set to: {}", maxSize);
-}
-
-void FrameQueue::setDropPolicy(bool dropOnFull, bool dropOldest) {
-    config_.dropOnFull = dropOnFull;
-    config_.dropOldest = dropOldest;
-    Logger::instance().debugf("Drop policy set: dropOnFull={}, dropOldest={}", dropOnFull, dropOldest);
-}
-
-size_t FrameQueue::size() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    return queue_.size();
-}
-
-bool FrameQueue::empty() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    return queue_.empty();
-}
-
-bool FrameQueue::full() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    return queue_.size() >= config_.maxSize;
-}
-
-size_t FrameQueue::capacity() const {
-    return config_.maxSize;
-}
-
-FrameQueueStats FrameQueue::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    FrameQueueStats stats = stats_;
-    stats.currentSize = size();
-    return stats;
-}
-
-void FrameQueue::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = FrameQueueStats();
-    Logger::instance().debug("Frame queue stats reset");
-}
-
-void FrameQueue::enableFrameDrop(bool enable, double maxLatency, int dropRatio) {
-    config_.enableFrameDrop = enable;
-    config_.maxLatency = maxLatency;
-    config_.dropRatio = dropRatio;
-    
-    Logger::instance().debugf("Frame drop enabled: {}, maxLatency: {}ms, dropRatio: {}", 
-                 enable, maxLatency, dropRatio);
-}
-
-void FrameQueue::setFrameDropCallback(std::function<bool(const FrameQueueItem&)> callback) {
-    frameDropCallback_ = callback;
-}
-
-void FrameQueue::setBlocking(bool blocking) {
-    blocking_ = blocking;
-    if (!blocking) {
-        notEmpty_.notify_all();
-        notFull_.notify_all();
-    }
-    Logger::instance().debugf("Frame queue blocking mode: {}", blocking);
-}
-
-void FrameQueue::wakeup() {
-    notEmpty_.notify_all();
-    notFull_.notify_all();
-}
-
-// 内部方法实现
-bool FrameQueue::shouldDropFrame(const FrameQueueItem& item) const {
-    if (!config_.enableFrameDrop) {
-        return false;
-    }
-    
-    // 自定义丢帧回调
-    if (frameDropCallback_ && frameDropCallback_(item)) {
-        return true;
-    }
-    
-    // 基于延迟的丢帧
-    if (shouldDropByLatency(item)) {
-        return true;
-    }
-    
-    // 基于比例的丢帧
-    if (shouldDropByRatio()) {
-        return true;
-    }
-    
-    return false;
-}
-
-void FrameQueue::dropOldestFrame() {
-    if (!queue_.empty()) {
-        auto& oldestItem = queue_.front();
-        
-        if (dropCallback_) {
-            dropCallback_(*oldestItem, "Drop oldest frame");
-        }
-        
-        queue_.pop_front();
-        
-        std::lock_guard<std::mutex> statsLock(statsMutex_);
-        stats_.totalDropped++;
-        
-        Logger::instance().debug("Dropped oldest frame");
-    }
-}
-
-void FrameQueue::dropNewestFrame() {
-    // 这个方法在enqueue时调用,不需要实际操作队列
-    // 只需要更新统计信息
-}
-
-void FrameQueue::updateStats(const FrameQueueItem& item, bool isEnqueue) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (isEnqueue) {
-        stats_.totalEnqueued++;
-        stats_.maxSize = std::max(stats_.maxSize, queue_.size());
-    } else {
-        stats_.totalDequeued++;
-        
-        // 计算等待时间
-        double waitTime = calculateWaitTime(item);
-        if (waitTime > 0) {
-            // 更新平均等待时间
-            if (stats_.totalDequeued == 1) {
-                stats_.averageWaitTime = waitTime;
-            } else {
-                stats_.averageWaitTime = (stats_.averageWaitTime * (stats_.totalDequeued - 1) + waitTime) / stats_.totalDequeued;
-            }
-            
-            stats_.maxWaitTime = std::max(stats_.maxWaitTime, waitTime);
-        }
-    }
-    
-    stats_.currentSize = queue_.size();
-    stats_.lastUpdateTime = std::chrono::steady_clock::now();
-}
-
-double FrameQueue::calculateWaitTime(const FrameQueueItem& item) const {
-    auto now = std::chrono::steady_clock::now();
-    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now - item.enqueueTime);
-    return duration.count() / 1000.0; // 转换为毫秒
-}
-
-bool FrameQueue::shouldDropByLatency(const FrameQueueItem& item) const {
-    double waitTime = calculateWaitTime(item);
-    return waitTime > config_.maxLatency;
-}
-
-bool FrameQueue::shouldDropByRatio() const {
-    if (config_.dropRatio <= 1) {
-        return false;
-    }
-    
-    uint64_t count = frameCounter_.fetch_add(1);
-    return (count % config_.dropRatio) == 0;
-}
-
-// 多流帧队列实现
-MultiStreamFrameQueue::MultiStreamFrameQueue(const FrameQueueConfig& config)
-    : defaultConfig_(config) {
-    Logger::instance().debug("MultiStreamFrameQueue created");
-}
-
-MultiStreamFrameQueue::~MultiStreamFrameQueue() {
-    clear();
-    Logger::instance().debug("MultiStreamFrameQueue destroyed");
-}
-
-ErrorCode MultiStreamFrameQueue::addStream(int streamIndex, const FrameQueueConfig& config) {
-    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    if (streamQueues_.find(streamIndex) != streamQueues_.end()) {
-        Logger::instance().warningf("Stream {} already exists", streamIndex);
-        return ErrorCode::ALREADY_EXISTS;
-    }
-    
-    streamQueues_[streamIndex] = std::make_unique<FrameQueue>(config);
-    Logger::instance().debugf("Added stream: {}", streamIndex);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode MultiStreamFrameQueue::removeStream(int streamIndex) {
-    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        Logger::instance().warningf("Stream {} not found", streamIndex);
-        return ErrorCode::NOT_FOUND;
-    }
-    
-    streamQueues_.erase(it);
-    Logger::instance().debugf("Removed stream: {}", streamIndex);
-    
-    return ErrorCode::SUCCESS;
-}
-
-bool MultiStreamFrameQueue::hasStream(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    return streamQueues_.find(streamIndex) != streamQueues_.end();
-}
-
-std::vector<int> MultiStreamFrameQueue::getStreamIndices() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    std::vector<int> indices;
-    for (const auto& pair : streamQueues_) {
-        indices.push_back(pair.first);
-    }
-    
-    return indices;
-}
-
-ErrorCode MultiStreamFrameQueue::enqueue(AVFramePtr frame, int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        // 自动创建流队列
-        lock.unlock();
-        addStream(streamIndex, defaultConfig_);
-        lock.lock();
-        
-        it = streamQueues_.find(streamIndex);
-        if (it == streamQueues_.end()) {
-            return ErrorCode::NOT_FOUND;
-        }
-    }
-    
-    return it->second->enqueue(std::move(frame), streamIndex);
-}
-
-AVFramePtr MultiStreamFrameQueue::dequeue(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        return nullptr;
-    }
-    
-    return it->second->dequeueFrame();
-}
-
-AVFramePtr MultiStreamFrameQueue::dequeue(int streamIndex, int timeoutMs) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        return nullptr;
-    }
-    
-    return it->second->dequeueFrame(timeoutMs);
-}
-
-ErrorCode MultiStreamFrameQueue::enqueueToAll(AVFramePtr frame) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    if (!frame) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    ErrorCode result = ErrorCode::SUCCESS;
-    for (const auto& pair : streamQueues_) {
-        // 为每个流创建帧的副本
-        AVFramePtr frameCopy = makeAVFrame();
-        if (!frameCopy) {
-            result = ErrorCode::MEMORY_ALLOC_FAILED;
-            continue;
-        }
-        
-        if (av_frame_ref(frameCopy.get(), frame.get()) < 0) {
-            result = ErrorCode::COPY_FAILED;
-            continue;
-        }
-        
-        ErrorCode enqueueResult = pair.second->enqueue(std::move(frameCopy), pair.first);
-        if (enqueueResult != ErrorCode::SUCCESS) {
-            result = enqueueResult;
-        }
-    }
-    
-    return result;
-}
-
-std::vector<AVFramePtr> MultiStreamFrameQueue::dequeueFromAll() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    std::vector<AVFramePtr> frames;
-    for (const auto& pair : streamQueues_) {
-        AVFramePtr frame = pair.second->dequeueFrame();
-        frames.push_back(std::move(frame)); // 可能为nullptr
-    }
-    
-    return frames;
-}
-
-void MultiStreamFrameQueue::clear() {
-    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->clear();
-    }
-    
-    Logger::instance().debug("All stream queues cleared");
-}
-
-void MultiStreamFrameQueue::clearStream(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        it->second->clear();
-        Logger::instance().debugf("Stream {} queue cleared", streamIndex);
-    }
-}
-
-void MultiStreamFrameQueue::flush() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->flush();
-    }
-    
-    Logger::instance().debug("All stream queues flushed");
-}
-
-void MultiStreamFrameQueue::flushStream(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        it->second->flush();
-        Logger::instance().debugf("Stream {} queue flushed", streamIndex);
-    }
-}
-
-size_t MultiStreamFrameQueue::size() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    size_t totalSize = 0;
-    for (const auto& pair : streamQueues_) {
-        totalSize += pair.second->size();
-    }
-    
-    return totalSize;
-}
-
-size_t MultiStreamFrameQueue::size(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->size();
-    }
-    
-    return 0;
-}
-
-bool MultiStreamFrameQueue::empty() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (const auto& pair : streamQueues_) {
-        if (!pair.second->empty()) {
-            return false;
-        }
-    }
-    
-    return true;
-}
-
-bool MultiStreamFrameQueue::empty(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->empty();
-    }
-    
-    return true;
-}
-
-std::map<int, FrameQueueStats> MultiStreamFrameQueue::getAllStats() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    std::map<int, FrameQueueStats> allStats;
-    for (const auto& pair : streamQueues_) {
-        allStats[pair.first] = pair.second->getStats();
-    }
-    
-    return allStats;
-}
-
-FrameQueueStats MultiStreamFrameQueue::getStats(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->getStats();
-    }
-    
-    return FrameQueueStats();
-}
-
-void MultiStreamFrameQueue::resetStats() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->resetStats();
-    }
-    
-    Logger::instance().debug("All stream queue stats reset");
-}
-
-void MultiStreamFrameQueue::resetStats(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        it->second->resetStats();
-        Logger::instance().debugf("Stream {} queue stats reset", streamIndex);
-    }
-}
-
-void MultiStreamFrameQueue::setBlocking(bool blocking) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->setBlocking(blocking);
-    }
-    
-    Logger::instance().debugf("All stream queues blocking mode: {}", blocking);
-}
-
-void MultiStreamFrameQueue::wakeupAll() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->wakeup();
-    }
-}
-
-// 工厂类实现
-std::unique_ptr<FrameQueue> FrameQueueFactory::createStandardQueue(size_t maxSize) {
-    FrameQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 1000;
-    config.enableStats = true;
-    
-    return std::make_unique<FrameQueue>(config);
-}
-
-std::unique_ptr<FrameQueue> FrameQueueFactory::createLowLatencyQueue(size_t maxSize) {
-    FrameQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 100;
-    config.enableStats = true;
-    config.enableFrameDrop = true;
-    config.maxLatency = 50.0;
-    config.dropRatio = 3;
-    
-    return std::make_unique<FrameQueue>(config);
-}
-
-std::unique_ptr<FrameQueue> FrameQueueFactory::createHighCapacityQueue(size_t maxSize) {
-    FrameQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = false; // 不丢帧,等待
-    config.dropOldest = true;
-    config.timeoutMs = 5000;
-    config.enableStats = true;
-    config.enableFrameDrop = false;
-    
-    return std::make_unique<FrameQueue>(config);
-}
-
-std::unique_ptr<FrameQueue> FrameQueueFactory::createRealtimeQueue(size_t maxSize, double maxLatency) {
-    FrameQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 50;
-    config.enableStats = true;
-    config.enableFrameDrop = true;
-    config.maxLatency = maxLatency;
-    config.dropRatio = 2;
-    
-    return std::make_unique<FrameQueue>(config);
-}
-
-std::unique_ptr<MultiStreamFrameQueue> FrameQueueFactory::createMultiStreamQueue(const FrameQueueConfig& config) {
-    return std::make_unique<MultiStreamFrameQueue>(config);
-}
-
-} // namespace utils
-} // namespace av

+ 0 - 299
AV/code/utils/utils_frame_queue.h

@@ -1,299 +0,0 @@
-#ifndef AV_UTILS_FRAME_QUEUE_H
-#define AV_UTILS_FRAME_QUEUE_H
-
-#include "../base/types.h"
-#include <deque>
-#include <mutex>
-#include <condition_variable>
-#include <atomic>
-#include <chrono>
-#include <memory>
-#include <functional>
-#include <map>
-#include <shared_mutex>
-#include <vector>
-
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/avutil.h>
-}
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-// 帧队列项 - 使用智能指针统一管理内存
-struct FrameQueueItem {
-    AVFramePtr frame;                   // 帧数据 - 使用智能指针
-    int64_t pts = AV_NOPTS_VALUE;      // 显示时间戳
-    int64_t dts = AV_NOPTS_VALUE;      // 解码时间戳
-    double duration = 0.0;              // 帧持续时间
-    int streamIndex = -1;               // 流索引
-    bool isKeyFrame = false;            // 是否关键帧
-    std::chrono::steady_clock::time_point enqueueTime; // 入队时间
-    
-    FrameQueueItem() {
-        enqueueTime = std::chrono::steady_clock::now();
-    }
-    
-    // 从智能指针构造
-    FrameQueueItem(AVFramePtr f, int stream = -1) : frame(std::move(f)), streamIndex(stream) {
-        if (frame) {
-            pts = frame->pts;
-            dts = frame->pkt_dts;
-            isKeyFrame = (frame->key_frame == 1);
-        }
-        enqueueTime = std::chrono::steady_clock::now();
-    }
-    
-    // 从原生指针构造(为了兼容性,自动转换为智能指针)
-    FrameQueueItem(AVFrame* f, int stream = -1) : streamIndex(stream) {
-        if (f) {
-            frame = AVFramePtr(f);  // 转换为智能指针
-            pts = frame->pts;
-            dts = frame->pkt_dts;
-            isKeyFrame = (frame->key_frame == 1);
-        }
-        enqueueTime = std::chrono::steady_clock::now();
-    }
-    
-    // 智能指针自动管理内存,无需手动析构
-    ~FrameQueueItem() = default;
-    
-    // 移动构造函数
-    FrameQueueItem(FrameQueueItem&& other) noexcept
-        : frame(std::move(other.frame)), pts(other.pts), dts(other.dts),
-          duration(other.duration), streamIndex(other.streamIndex),
-          isKeyFrame(other.isKeyFrame), enqueueTime(other.enqueueTime) {
-        // frame 已经被移动,无需置空
-    }
-    
-    // 移动赋值操作符
-    FrameQueueItem& operator=(FrameQueueItem&& other) noexcept {
-        if (this != &other) {
-            frame = std::move(other.frame);
-            pts = other.pts;
-            dts = other.dts;
-            duration = other.duration;
-            streamIndex = other.streamIndex;
-            isKeyFrame = other.isKeyFrame;
-            enqueueTime = other.enqueueTime;
-            // other.frame 已经被移动,无需手动置空
-        }
-        return *this;
-    }
-    
-    // 禁用拷贝
-    FrameQueueItem(const FrameQueueItem&) = delete;
-    FrameQueueItem& operator=(const FrameQueueItem&) = delete;
-};
-
-// 帧队列统计信息
-struct FrameQueueStats {
-    size_t currentSize = 0;             // 当前队列大小
-    size_t maxSize = 0;                 // 最大队列大小
-    uint64_t totalEnqueued = 0;         // 总入队数量
-    uint64_t totalDequeued = 0;         // 总出队数量
-    uint64_t totalDropped = 0;          // 总丢弃数量
-    double averageWaitTime = 0.0;       // 平均等待时间(毫秒)
-    double maxWaitTime = 0.0;           // 最大等待时间(毫秒)
-    std::chrono::steady_clock::time_point lastUpdateTime;
-    
-    FrameQueueStats() {
-        lastUpdateTime = std::chrono::steady_clock::now();
-    }
-};
-
-// 帧队列配置
-struct FrameQueueConfig {
-    size_t maxSize = 100;               // 最大队列大小
-    bool dropOnFull = true;             // 队列满时是否丢弃新帧
-    bool dropOldest = true;             // 丢弃最旧的帧(false则丢弃最新的)
-    int timeoutMs = 1000;               // 超时时间(毫秒)
-    bool enableStats = true;            // 启用统计信息
-    
-    // 丢帧策略
-    bool enableFrameDrop = false;       // 启用智能丢帧
-    double maxLatency = 100.0;          // 最大延迟(毫秒)
-    int dropRatio = 2;                  // 丢帧比例(每N帧丢1帧)
-};
-
-// 帧队列类
-class FrameQueue {
-public:
-    explicit FrameQueue(const FrameQueueConfig& config = FrameQueueConfig());
-    ~FrameQueue();
-    
-    // 基本操作
-    ErrorCode enqueue(std::unique_ptr<FrameQueueItem> item);
-    std::unique_ptr<FrameQueueItem> dequeue();
-    std::unique_ptr<FrameQueueItem> dequeue(int timeoutMs);
-    
-    // 安全接口(使用智能指针)
-    ErrorCode enqueue(AVFramePtr frame, int streamIndex = -1);
-    
-    // 预览方法(不移除队列中的帧)
-    const FrameQueueItem* peek() const;
-    const FrameQueueItem* peek(int index) const;  // 预览第index个帧(0为队首)
-    const AVFramePtr& peekFramePtr() const;  // 预览队首帧
-    
-    // 帧操作接口
-    AVFramePtr dequeueFrame();
-    AVFramePtr dequeueFrame(int timeoutMs);
-    
-    // 便捷别名
-    ErrorCode push(AVFramePtr frame, int streamIndex = -1) {
-        return enqueue(std::move(frame), streamIndex);
-    }
-    AVFramePtr pop() {
-        return dequeueFrame();
-    }
-    AVFramePtr pop(int timeoutMs) {
-        return dequeueFrame(timeoutMs);
-    }
-    
-    // 队列控制
-    void clear();
-    void flush();
-    void setMaxSize(size_t maxSize);
-    void setDropPolicy(bool dropOnFull, bool dropOldest = true);
-    
-    // 状态查询
-    size_t size() const;
-    bool empty() const;
-    bool full() const;
-    size_t capacity() const;
-    
-    // 统计信息
-    FrameQueueStats getStats() const;
-    void resetStats();
-    
-    // 帧丢弃策略
-    void enableFrameDrop(bool enable, double maxLatency = 100.0, int dropRatio = 2);
-    void setFrameDropCallback(std::function<bool(const FrameQueueItem&)> callback);
-    
-    // 阻塞控制
-    void setBlocking(bool blocking);
-    void wakeup();
-    
-    // 回调设置
-    using EnqueueCallback = std::function<void(const FrameQueueItem&)>;
-    using DequeueCallback = std::function<void(const FrameQueueItem&)>;
-    using DropCallback = std::function<void(const FrameQueueItem&, const std::string&)>;
-    
-    void setEnqueueCallback(EnqueueCallback callback) { enqueueCallback_ = callback; }
-    void setDequeueCallback(DequeueCallback callback) { dequeueCallback_ = callback; }
-    void setDropCallback(DropCallback callback) { dropCallback_ = callback; }
-    
-protected:
-    // 内部方法
-    bool shouldDropFrame(const FrameQueueItem& item) const;
-    void dropOldestFrame();
-    void dropNewestFrame();
-    void updateStats(const FrameQueueItem& item, bool isEnqueue);
-    double calculateWaitTime(const FrameQueueItem& item) const;
-    
-    // 智能丢帧
-    bool shouldDropByLatency(const FrameQueueItem& item) const;
-    bool shouldDropByRatio() const;
-    
-private:
-    FrameQueueConfig config_;
-    
-    // 队列数据 - 使用deque以支持随机访问
-    std::deque<std::unique_ptr<FrameQueueItem>> queue_;
-    mutable std::mutex queueMutex_;
-    std::condition_variable notEmpty_;
-    std::condition_variable notFull_;
-    
-    // 状态控制
-    std::atomic<bool> blocking_{true};
-    std::atomic<bool> shutdown_{false};
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    FrameQueueStats stats_;
-    
-    // 丢帧控制
-    mutable std::atomic<uint64_t> frameCounter_{0};
-    std::function<bool(const FrameQueueItem&)> frameDropCallback_;
-    
-    // 回调函数
-    EnqueueCallback enqueueCallback_;
-    DequeueCallback dequeueCallback_;
-    DropCallback dropCallback_;
-};
-
-// 多流帧队列
-class MultiStreamFrameQueue {
-public:
-    explicit MultiStreamFrameQueue(const FrameQueueConfig& config = FrameQueueConfig());
-    ~MultiStreamFrameQueue();
-    
-    // 流管理
-    ErrorCode addStream(int streamIndex, const FrameQueueConfig& config = FrameQueueConfig());
-    ErrorCode removeStream(int streamIndex);
-    bool hasStream(int streamIndex) const;
-    std::vector<int> getStreamIndices() const;
-    
-    // 安全帧操作接口
-    ErrorCode enqueue(AVFramePtr frame, int streamIndex);
-    AVFramePtr dequeue(int streamIndex);
-    AVFramePtr dequeue(int streamIndex, int timeoutMs);
-    
-    // 安全批量操作接口
-    ErrorCode enqueueToAll(AVFramePtr frame);
-    std::vector<AVFramePtr> dequeueFromAll();
-    
-    // 队列控制
-    void clear();
-    void clearStream(int streamIndex);
-    void flush();
-    void flushStream(int streamIndex);
-    
-    // 状态查询
-    size_t size() const;
-    size_t size(int streamIndex) const;
-    bool empty() const;
-    bool empty(int streamIndex) const;
-    
-    // 统计信息
-    std::map<int, FrameQueueStats> getAllStats() const;
-    FrameQueueStats getStats(int streamIndex) const;
-    void resetStats();
-    void resetStats(int streamIndex);
-    
-    // 同步控制
-    void setBlocking(bool blocking);
-    void wakeupAll();
-    
-private:
-    FrameQueueConfig defaultConfig_;
-    std::map<int, std::unique_ptr<FrameQueue>> streamQueues_;
-    mutable std::shared_mutex streamsMutex_;
-};
-
-// 帧队列工厂
-class FrameQueueFactory {
-public:
-    // 创建标准帧队列
-    static std::unique_ptr<FrameQueue> createStandardQueue(size_t maxSize = 100);
-    
-    // 创建低延迟队列
-    static std::unique_ptr<FrameQueue> createLowLatencyQueue(size_t maxSize = 10);
-    
-    // 创建高容量队列
-    static std::unique_ptr<FrameQueue> createHighCapacityQueue(size_t maxSize = 1000);
-    
-    // 创建实时队列(启用智能丢帧)
-    static std::unique_ptr<FrameQueue> createRealtimeQueue(size_t maxSize = 50, double maxLatency = 50.0);
-    
-    // 创建多流队列
-    static std::unique_ptr<MultiStreamFrameQueue> createMultiStreamQueue(const FrameQueueConfig& config = FrameQueueConfig());
-};
-
-} // namespace utils
-} // namespace av
-
-#endif // AV_UTILS_FRAME_QUEUE_H

+ 0 - 1101
AV/code/utils/utils_packet_queue.cpp

@@ -1,1101 +0,0 @@
-#include "utils_packet_queue.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <shared_mutex>
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-PacketQueue::PacketQueue(const PacketQueueConfig& config)
-    : config_(config) {
-    Logger::instance().debugf("PacketQueue created with max size: {}, max bytes: {}", 
-                 config_.maxSize, config_.maxBytes);
-}
-
-PacketQueue::~PacketQueue() {
-    shutdown_ = true;
-    notEmpty_.notify_all();
-    notFull_.notify_all();
-    clear();
-    Logger::instance().debug("PacketQueue destroyed");
-}
-
-ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
-    if (!item) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    if (shutdown_) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    // 检查流过滤
-    if (!isStreamAllowed(item->streamIndex)) {
-        Logger::instance().debugf("Packet dropped - stream {} not allowed", item->streamIndex);
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    // 检查是否需要丢包
-    if (shouldDropPacket(*item)) {
-        if (dropCallback_) {
-            dropCallback_(*item, "Smart packet drop");
-        }
-        
-        std::lock_guard<std::mutex> statsLock(statsMutex_);
-        stats_.totalDropped++;
-        
-        Logger::instance().debug("Packet dropped by smart drop policy");
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 检查队列是否已满
-    size_t currentSize = config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
-    size_t currentBytes = totalBytes_.load();
-    
-    bool queueFull = (currentSize >= config_.maxSize) || (currentBytes >= config_.maxBytes);
-    
-    if (blocking_ && queueFull) {
-        if (config_.dropOnFull) {
-            // 根据策略丢弃包
-            if (config_.dropOldest) {
-                dropOldestPacket();
-            } else if (config_.dropNonKeyPackets && !item->isKeyPacket) {
-                dropNonKeyPackets();
-            } else {
-                if (dropCallback_) {
-                    dropCallback_(*item, "Queue full - drop newest");
-                }
-                
-                std::lock_guard<std::mutex> statsLock(statsMutex_);
-                stats_.totalDropped++;
-                
-                Logger::instance().debug("Packet dropped - queue full");
-                return ErrorCode::SUCCESS;
-            }
-        } else {
-            // 等待队列有空间
-            if (!notFull_.wait_for(lock, std::chrono::milliseconds(config_.timeoutMs), [this] {
-                    size_t newSize = config_.priorityQueue ? priorityQueue_.size()
-                                                           : normalQueue_.size();
-                    size_t newBytes = totalBytes_.load();
-                    return (newSize < config_.maxSize && newBytes < config_.maxBytes) || shutdown_;
-                })) {
-                Logger::instance().warning("Enqueue timeout");
-                return ErrorCode::TIMEOUT;
-            }
-
-            if (shutdown_) {
-                return ErrorCode::INVALID_STATE;
-            }
-        }
-    }
-    
-    // 更新字节计数
-    if (item->packet) {
-        totalBytes_ += item->packet->size;
-    }
-    
-    // 在move之前保存item的引用,用于后续的统计和回调
-    const PacketQueueItem& itemRef = *item;
-    
-    // 添加到队列
-    if (config_.priorityQueue) {
-        enqueueToPriorityQueue(std::move(item));
-    } else {
-        enqueueToNormalQueue(std::move(item));
-    }
-    
-    // 更新统计信息
-    if (config_.enableStats) {
-        updateStats(itemRef, true);
-    }
-    
-    // 通知等待的消费者
-    notEmpty_.notify_one();
-    
-    // 回调
-    if (enqueueCallback_) {
-        enqueueCallback_(itemRef);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-std::unique_ptr<PacketQueueItem> PacketQueue::dequeue() {
-    return dequeue(config_.timeoutMs);
-}
-
-std::unique_ptr<PacketQueueItem> PacketQueue::dequeue(int timeoutMs) {
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    // 等待队列有数据
-    if (blocking_) {
-        bool hasData = config_.priorityQueue ? !priorityQueue_.empty() : !normalQueue_.empty();
-        
-        if (!hasData) {
-            if (!notEmpty_.wait_for(lock, std::chrono::milliseconds(timeoutMs),
-                                   [this] { 
-                                       bool hasData = config_.priorityQueue ? !priorityQueue_.empty() : !normalQueue_.empty();
-                                       return hasData || shutdown_; 
-                                   })) {
-                return nullptr; // 超时
-            }
-            
-            if (shutdown_) {
-                return nullptr;
-            }
-        }
-    }
-    
-    // 检查队列是否为空
-    bool isEmpty = config_.priorityQueue ? priorityQueue_.empty() : normalQueue_.empty();
-    if (isEmpty) {
-        return nullptr;
-    }
-    
-    // 取出包
-    std::unique_ptr<PacketQueueItem> item;
-    if (config_.priorityQueue) {
-        item = dequeueFromPriorityQueue();
-    } else {
-        item = dequeueFromNormalQueue();
-    }
-    
-    if (!item) {
-        return nullptr;
-    }
-    
-    // 更新字节计数
-    if (item->packet) {
-        totalBytes_ -= item->packet->size;
-    }
-    
-    // 更新统计信息
-    if (config_.enableStats) {
-        updateStats(*item, false);
-    }
-    
-    // 通知等待的生产者
-    notFull_.notify_one();
-    
-    // 回调
-    if (dequeueCallback_) {
-        dequeueCallback_(*item);
-    }
-    
-    return item;
-}
-
-ErrorCode PacketQueue::enqueue(AVPacket* packet, int streamIndex, int priority) {
-    if (!packet) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    auto item = std::make_unique<PacketQueueItem>(packet, streamIndex, priority);
-    return enqueue(std::move(item));
-}
-
-AVPacket* PacketQueue::dequeuePacket() {
-    auto item = dequeue();
-    if (item) {
-        AVPacket* packet = item->packet;
-        item->packet = nullptr; // 转移所有权
-        return packet;
-    }
-    return nullptr;
-}
-
-AVPacket* PacketQueue::dequeuePacket(int timeoutMs) {
-    auto item = dequeue(timeoutMs);
-    if (item) {
-        AVPacket* packet = item->packet;
-        item->packet = nullptr; // 转移所有权
-        return packet;
-    }
-    return nullptr;
-}
-
-ErrorCode PacketQueue::enqueueWithPriority(AVPacket* packet, int priority, int streamIndex) {
-    if (!packet) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    auto item = std::make_unique<PacketQueueItem>(packet, streamIndex, priority);
-    return enqueue(std::move(item));
-}
-
-std::unique_ptr<PacketQueueItem> PacketQueue::dequeueHighestPriority() {
-    if (!config_.priorityQueue) {
-        Logger::instance().warning("Priority queue not enabled");
-        return dequeue();
-    }
-    
-    return dequeue();
-}
-
-void PacketQueue::clear() {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    
-    // 清空普通队列
-    while (!normalQueue_.empty()) {
-        normalQueue_.pop();
-    }
-    
-    // 清空优先级队列
-    while (!priorityQueue_.empty()) {
-        priorityQueue_.pop();
-    }
-    
-    totalBytes_ = 0;
-    Logger::instance().debug("Packet queue cleared");
-}
-
-void PacketQueue::flush() {
-    clear();
-    notEmpty_.notify_all();
-    notFull_.notify_all();
-}
-
-void PacketQueue::setMaxSize(size_t maxSize) {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    config_.maxSize = maxSize;
-    
-    // 如果当前队列大小超过新的最大值,丢弃多余的包
-    size_t currentSize = config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
-    while (currentSize > maxSize) {
-        if (config_.dropOldest) {
-            dropOldestPacket();
-        } else {
-            break;
-        }
-        currentSize = config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
-    }
-    
-    Logger::instance().debugf("Packet queue max size set to: {}", maxSize);
-}
-
-void PacketQueue::setMaxBytes(size_t maxBytes) {
-    config_.maxBytes = maxBytes;
-    Logger::instance().debugf("Packet queue max bytes set to: {}", maxBytes);
-}
-
-void PacketQueue::setDropPolicy(bool dropOnFull, bool dropOldest) {
-    config_.dropOnFull = dropOnFull;
-    config_.dropOldest = dropOldest;
-    Logger::instance().debugf("Drop policy set: dropOnFull={}, dropOldest={}", dropOnFull, dropOldest);
-}
-
-void PacketQueue::enablePriorityQueue(bool enable) {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    
-    if (config_.priorityQueue == enable) {
-        return;
-    }
-    
-    // 如果要切换队列类型,需要迁移数据
-    if (enable) {
-        // 从普通队列迁移到优先级队列
-        while (!normalQueue_.empty()) {
-            auto item = std::move(normalQueue_.front());
-            normalQueue_.pop();
-            priorityQueue_.push(std::move(item));
-        }
-    } else {
-        // 从优先级队列迁移到普通队列
-        std::vector<std::unique_ptr<PacketQueueItem>> tempItems;
-        while (!priorityQueue_.empty()) {
-            tempItems.push_back(std::move(const_cast<std::unique_ptr<PacketQueueItem>&>(priorityQueue_.top())));
-            priorityQueue_.pop();
-        }
-        
-        // 按时间戳排序后加入普通队列
-        std::sort(tempItems.begin(), tempItems.end(),
-                 [](const std::unique_ptr<PacketQueueItem>& a, const std::unique_ptr<PacketQueueItem>& b) {
-                     return a->dts < b->dts;
-                 });
-        
-        for (auto& item : tempItems) {
-            normalQueue_.push(std::move(item));
-        }
-    }
-    
-    config_.priorityQueue = enable;
-    Logger::instance().debugf("Priority queue {}", enable ? "enabled" : "disabled");
-}
-
-size_t PacketQueue::size() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    return config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
-}
-
-size_t PacketQueue::bytes() const {
-    return totalBytes_.load();
-}
-
-bool PacketQueue::empty() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    return config_.priorityQueue ? priorityQueue_.empty() : normalQueue_.empty();
-}
-
-bool PacketQueue::full() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    size_t currentSize = config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
-    return currentSize >= config_.maxSize;
-}
-
-bool PacketQueue::fullByBytes() const {
-    return totalBytes_.load() >= config_.maxBytes;
-}
-
-size_t PacketQueue::capacity() const {
-    return config_.maxSize;
-}
-
-size_t PacketQueue::capacityBytes() const {
-    return config_.maxBytes;
-}
-
-PacketQueueStats PacketQueue::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    PacketQueueStats stats = stats_;
-    stats.currentSize = size();
-    stats.totalBytes = bytes();
-    return stats;
-}
-
-void PacketQueue::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = PacketQueueStats();
-    Logger::instance().debug("Packet queue stats reset");
-}
-
-void PacketQueue::enablePacketDrop(bool enable, double maxLatency, int dropRatio) {
-    config_.enablePacketDrop = enable;
-    config_.maxLatency = maxLatency;
-    config_.dropRatio = dropRatio;
-    
-    Logger::instance().debugf("Packet drop enabled: {}, maxLatency: {}ms, dropRatio: {}", 
-                 enable, maxLatency, dropRatio);
-}
-
-void PacketQueue::setPacketDropCallback(std::function<bool(const PacketQueueItem&)> callback) {
-    packetDropCallback_ = callback;
-}
-
-void PacketQueue::setBlocking(bool blocking) {
-    blocking_ = blocking;
-    if (!blocking) {
-        notEmpty_.notify_all();
-        notFull_.notify_all();
-    }
-    Logger::instance().debugf("Packet queue blocking mode: {}", blocking);
-}
-
-void PacketQueue::wakeup() {
-    notEmpty_.notify_all();
-    notFull_.notify_all();
-}
-
-void PacketQueue::setStreamFilter(const std::vector<int>& allowedStreams) {
-    std::lock_guard<std::mutex> lock(streamFilterMutex_);
-    allowedStreams_ = allowedStreams;
-    hasStreamFilter_ = !allowedStreams.empty();
-    Logger::instance().debugf("Stream filter set with {} allowed streams", allowedStreams.size());
-}
-
-void PacketQueue::clearStreamFilter() {
-    std::lock_guard<std::mutex> lock(streamFilterMutex_);
-    allowedStreams_.clear();
-    hasStreamFilter_ = false;
-    Logger::instance().debug("Stream filter cleared");
-}
-
-// 内部方法实现
-bool PacketQueue::shouldDropPacket(const PacketQueueItem& item) const {
-    if (!config_.enablePacketDrop) {
-        return false;
-    }
-    
-    // 自定义丢包回调
-    if (packetDropCallback_ && packetDropCallback_(item)) {
-        return true;
-    }
-    
-    // 基于延迟的丢包
-    if (shouldDropByLatency(item)) {
-        return true;
-    }
-    
-    // 基于比例的丢包
-    if (shouldDropByRatio()) {
-        return true;
-    }
-    
-    // 基于大小的丢包
-    if (shouldDropBySize()) {
-        return true;
-    }
-    
-    return false;
-}
-
-void PacketQueue::dropOldestPacket() {
-    if (config_.priorityQueue) {
-        if (!priorityQueue_.empty()) {
-            auto& oldestItem = const_cast<std::unique_ptr<PacketQueueItem>&>(priorityQueue_.top());
-            
-            if (dropCallback_) {
-                dropCallback_(*oldestItem, "Drop oldest packet");
-            }
-            
-            if (oldestItem->packet) {
-                totalBytes_ -= oldestItem->packet->size;
-            }
-            
-            priorityQueue_.pop();
-            
-            std::lock_guard<std::mutex> statsLock(statsMutex_);
-            stats_.totalDropped++;
-            
-            Logger::instance().debug("Dropped oldest packet from priority queue");
-        }
-    } else {
-        if (!normalQueue_.empty()) {
-            auto& oldestItem = normalQueue_.front();
-            
-            if (dropCallback_) {
-                dropCallback_(*oldestItem, "Drop oldest packet");
-            }
-            
-            if (oldestItem->packet) {
-                totalBytes_ -= oldestItem->packet->size;
-            }
-            
-            normalQueue_.pop();
-            
-            std::lock_guard<std::mutex> statsLock(statsMutex_);
-            stats_.totalDropped++;
-            
-            Logger::instance().debug("Dropped oldest packet from normal queue");
-        }
-    }
-}
-
-void PacketQueue::dropNewestPacket() {
-    // 这个方法在enqueue时调用,不需要实际操作队列
-}
-
-void PacketQueue::dropLargestPacket() {
-    // 找到最大的包并丢弃
-    // 这里简化实现,直接丢弃最旧的包
-    dropOldestPacket();
-}
-
-void PacketQueue::dropNonKeyPackets() {
-    std::vector<std::unique_ptr<PacketQueueItem>> keyPackets;
-    
-    if (config_.priorityQueue) {
-        while (!priorityQueue_.empty()) {
-            auto item = std::move(const_cast<std::unique_ptr<PacketQueueItem>&>(priorityQueue_.top()));
-            priorityQueue_.pop();
-            
-            if (item->isKeyPacket) {
-                keyPackets.push_back(std::move(item));
-            } else {
-                if (dropCallback_) {
-                    dropCallback_(*item, "Drop non-key packet");
-                }
-                
-                if (item->packet) {
-                    totalBytes_ -= item->packet->size;
-                }
-                
-                std::lock_guard<std::mutex> statsLock(statsMutex_);
-                stats_.totalDropped++;
-            }
-        }
-        
-        // 重新加入关键包
-        for (auto& item : keyPackets) {
-            priorityQueue_.push(std::move(item));
-        }
-    } else {
-        while (!normalQueue_.empty()) {
-            auto item = std::move(normalQueue_.front());
-            normalQueue_.pop();
-            
-            if (item->isKeyPacket) {
-                keyPackets.push_back(std::move(item));
-            } else {
-                if (dropCallback_) {
-                    dropCallback_(*item, "Drop non-key packet");
-                }
-                
-                if (item->packet) {
-                    totalBytes_ -= item->packet->size;
-                }
-                
-                std::lock_guard<std::mutex> statsLock(statsMutex_);
-                stats_.totalDropped++;
-            }
-        }
-        
-        // 重新加入关键包
-        for (auto& item : keyPackets) {
-            normalQueue_.push(std::move(item));
-        }
-    }
-    
-    Logger::instance().debugf("Dropped non-key packets, kept {} key packets", keyPackets.size());
-}
-
-void PacketQueue::updateStats(const PacketQueueItem& item, bool isEnqueue) {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    if (isEnqueue) {
-        stats_.totalEnqueued++;
-        size_t currentSize = config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
-        stats_.maxSize = std::max(stats_.maxSize, currentSize);
-        
-        if (item.packet) {
-            stats_.totalBytes += item.packet->size;
-            
-            // 更新平均包大小
-            if (stats_.totalEnqueued == 1) {
-                stats_.averagePacketSize = item.packet->size;
-            } else {
-                stats_.averagePacketSize = (stats_.averagePacketSize * (stats_.totalEnqueued - 1) + item.packet->size) / stats_.totalEnqueued;
-            }
-        }
-    } else {
-        stats_.totalDequeued++;
-        
-        // 计算等待时间
-        double waitTime = calculateWaitTime(item);
-        if (waitTime > 0) {
-            // 更新平均等待时间
-            if (stats_.totalDequeued == 1) {
-                stats_.averageWaitTime = waitTime;
-            } else {
-                stats_.averageWaitTime = (stats_.averageWaitTime * (stats_.totalDequeued - 1) + waitTime) / stats_.totalDequeued;
-            }
-            
-            stats_.maxWaitTime = std::max(stats_.maxWaitTime, waitTime);
-        }
-    }
-    
-    stats_.lastUpdateTime = std::chrono::steady_clock::now();
-}
-
-double PacketQueue::calculateWaitTime(const PacketQueueItem& item) const {
-    auto now = std::chrono::steady_clock::now();
-    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now - item.enqueueTime);
-    return duration.count() / 1000.0; // 转换为毫秒
-}
-
-bool PacketQueue::isStreamAllowed(int streamIndex) const {
-    if (!hasStreamFilter_) {
-        return true;
-    }
-    
-    std::lock_guard<std::mutex> lock(streamFilterMutex_);
-    return std::find(allowedStreams_.begin(), allowedStreams_.end(), streamIndex) != allowedStreams_.end();
-}
-
-bool PacketQueue::shouldDropByLatency(const PacketQueueItem& item) const {
-    double waitTime = calculateWaitTime(item);
-    return waitTime > config_.maxLatency;
-}
-
-bool PacketQueue::shouldDropByRatio() const {
-    if (config_.dropRatio <= 1) {
-        return false;
-    }
-    
-    uint64_t count = packetCounter_.fetch_add(1);
-    return (count % config_.dropRatio) == 0;
-}
-
-bool PacketQueue::shouldDropBySize() const {
-    return totalBytes_.load() > config_.maxBytes;
-}
-
-void PacketQueue::enqueueToNormalQueue(std::unique_ptr<PacketQueueItem> item) {
-    normalQueue_.push(std::move(item));
-}
-
-void PacketQueue::enqueueToPriorityQueue(std::unique_ptr<PacketQueueItem> item) {
-    priorityQueue_.push(std::move(item));
-}
-
-std::unique_ptr<PacketQueueItem> PacketQueue::dequeueFromNormalQueue() {
-    if (normalQueue_.empty()) {
-        return nullptr;
-    }
-    
-    auto item = std::move(normalQueue_.front());
-    normalQueue_.pop();
-    return item;
-}
-
-std::unique_ptr<PacketQueueItem> PacketQueue::dequeueFromPriorityQueue() {
-    if (priorityQueue_.empty()) {
-        return nullptr;
-    }
-    
-    auto item = std::move(const_cast<std::unique_ptr<PacketQueueItem>&>(priorityQueue_.top()));
-    priorityQueue_.pop();
-    return item;
-}
-
-// 多流包队列实现
-MultiStreamPacketQueue::MultiStreamPacketQueue(const PacketQueueConfig& config)
-    : defaultConfig_(config) {
-    Logger::instance().debug("MultiStreamPacketQueue created");
-}
-
-MultiStreamPacketQueue::~MultiStreamPacketQueue() {
-    clear();
-    Logger::instance().debug("MultiStreamPacketQueue destroyed");
-}
-
-ErrorCode MultiStreamPacketQueue::addStream(int streamIndex, const PacketQueueConfig& config) {
-    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    if (streamQueues_.find(streamIndex) != streamQueues_.end()) {
-        Logger::instance().warningf("Stream {} already exists", streamIndex);
-        return ErrorCode::ALREADY_EXISTS;
-    }
-    
-    streamQueues_[streamIndex] = std::make_unique<PacketQueue>(config);
-    Logger::instance().debugf("Added stream: {}", streamIndex);
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode MultiStreamPacketQueue::removeStream(int streamIndex) {
-    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        Logger::instance().warningf("Stream {} not found", streamIndex);
-        return ErrorCode::NOT_FOUND;
-    }
-    
-    streamQueues_.erase(it);
-    Logger::instance().debugf("Removed stream: {}", streamIndex);
-    
-    return ErrorCode::SUCCESS;
-}
-
-bool MultiStreamPacketQueue::hasStream(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    return streamQueues_.find(streamIndex) != streamQueues_.end();
-}
-
-std::vector<int> MultiStreamPacketQueue::getStreamIndices() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    std::vector<int> indices;
-    for (const auto& pair : streamQueues_) {
-        indices.push_back(pair.first);
-    }
-    
-    return indices;
-}
-
-ErrorCode MultiStreamPacketQueue::enqueue(AVPacket* packet, int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        // 自动创建流队列
-        lock.unlock();
-        addStream(streamIndex, defaultConfig_);
-        lock.lock();
-        
-        it = streamQueues_.find(streamIndex);
-        if (it == streamQueues_.end()) {
-            return ErrorCode::NOT_FOUND;
-        }
-    }
-    
-    return it->second->enqueue(packet, streamIndex);
-}
-
-AVPacket* MultiStreamPacketQueue::dequeue(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        return nullptr;
-    }
-    
-    return it->second->dequeuePacket();
-}
-
-AVPacket* MultiStreamPacketQueue::dequeue(int streamIndex, int timeoutMs) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it == streamQueues_.end()) {
-        return nullptr;
-    }
-    
-    return it->second->dequeuePacket(timeoutMs);
-}
-
-ErrorCode MultiStreamPacketQueue::enqueueToAll(AVPacket* packet) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    ErrorCode result = ErrorCode::SUCCESS;
-    for (const auto& pair : streamQueues_) {
-        // 为每个流创建包的副本
-        AVPacket* packetCopy = av_packet_alloc();
-        if (!packetCopy) {
-            result = ErrorCode::MEMORY_ALLOC_FAILED;
-            continue;
-        }
-        
-        if (av_packet_ref(packetCopy, packet) < 0) {
-            av_packet_free(&packetCopy);
-            result = ErrorCode::COPY_FAILED;
-            continue;
-        }
-        
-        ErrorCode enqueueResult = pair.second->enqueue(packetCopy, pair.first);
-        if (enqueueResult != ErrorCode::SUCCESS) {
-            av_packet_free(&packetCopy);
-            result = enqueueResult;
-        }
-    }
-    
-    return result;
-}
-
-std::vector<AVPacket*> MultiStreamPacketQueue::dequeueFromAll() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    std::vector<AVPacket*> packets;
-    for (const auto& pair : streamQueues_) {
-        AVPacket* packet = pair.second->dequeuePacket();
-        packets.push_back(packet); // 可能为nullptr
-    }
-    
-    return packets;
-}
-
-AVPacket* MultiStreamPacketQueue::dequeueSynchronized() {
-    std::lock_guard<std::mutex> lock(syncMutex_);
-    
-    // 从同步队列中取出时间戳最小的包
-    if (!syncQueue_.empty()) {
-        SyncItem item = syncQueue_.top();
-        syncQueue_.pop();
-        return item.packet;
-    }
-    
-    // 如果同步队列为空,从各个流队列中取包并排序
-    std::vector<SyncItem> items;
-    
-    {
-        std::shared_lock<std::shared_mutex> streamLock(streamsMutex_);
-        for (const auto& pair : streamQueues_) {
-            AVPacket* packet = pair.second->dequeuePacket(10); // 短超时
-            if (packet) {
-                SyncItem item;
-                item.packet = packet;
-                item.streamIndex = pair.first;
-                item.timestamp = (packet->dts != AV_NOPTS_VALUE) ? packet->dts : packet->pts;
-                items.push_back(item);
-            }
-        }
-    }
-    
-    if (items.empty()) {
-        return nullptr;
-    }
-    
-    // 按时间戳排序
-    std::sort(items.begin(), items.end(), [](const SyncItem& a, const SyncItem& b) {
-        return a.timestamp < b.timestamp;
-    });
-    
-    // 返回时间戳最小的包
-    AVPacket* result = items[0].packet;
-    
-    // 将其余包放入同步队列
-    for (size_t i = 1; i < items.size(); ++i) {
-        syncQueue_.push(items[i]);
-    }
-    
-    return result;
-}
-
-std::vector<AVPacket*> MultiStreamPacketQueue::dequeueSynchronizedBatch(size_t maxCount) {
-    std::vector<AVPacket*> packets;
-    
-    for (size_t i = 0; i < maxCount; ++i) {
-        AVPacket* packet = dequeueSynchronized();
-        if (!packet) {
-            break;
-        }
-        packets.push_back(packet);
-    }
-    
-    return packets;
-}
-
-void MultiStreamPacketQueue::clear() {
-    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->clear();
-    }
-    
-    // 清空同步队列
-    std::lock_guard<std::mutex> syncLock(syncMutex_);
-    while (!syncQueue_.empty()) {
-        SyncItem item = syncQueue_.top();
-        syncQueue_.pop();
-        if (item.packet) {
-            av_packet_free(&item.packet);
-        }
-    }
-    
-    Logger::instance().debug("All stream queues cleared");
-}
-
-void MultiStreamPacketQueue::clearStream(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        it->second->clear();
-        Logger::instance().debugf("Stream {} queue cleared", streamIndex);
-    }
-}
-
-void MultiStreamPacketQueue::flush() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->flush();
-    }
-    
-    Logger::instance().debug("All stream queues flushed");
-}
-
-void MultiStreamPacketQueue::flushStream(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        it->second->flush();
-        Logger::instance().debugf("Stream {} queue flushed", streamIndex);
-    }
-}
-
-size_t MultiStreamPacketQueue::size() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    size_t totalSize = 0;
-    for (const auto& pair : streamQueues_) {
-        totalSize += pair.second->size();
-    }
-    
-    return totalSize;
-}
-
-size_t MultiStreamPacketQueue::size(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->size();
-    }
-    
-    return 0;
-}
-
-size_t MultiStreamPacketQueue::bytes() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    size_t totalBytes = 0;
-    for (const auto& pair : streamQueues_) {
-        totalBytes += pair.second->bytes();
-    }
-    
-    return totalBytes;
-}
-
-size_t MultiStreamPacketQueue::bytes(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->bytes();
-    }
-    
-    return 0;
-}
-
-bool MultiStreamPacketQueue::empty() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (const auto& pair : streamQueues_) {
-        if (!pair.second->empty()) {
-            return false;
-        }
-    }
-    
-    return true;
-}
-
-bool MultiStreamPacketQueue::empty(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->empty();
-    }
-    
-    return true;
-}
-
-std::map<int, PacketQueueStats> MultiStreamPacketQueue::getAllStats() const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    std::map<int, PacketQueueStats> allStats;
-    for (const auto& pair : streamQueues_) {
-        allStats[pair.first] = pair.second->getStats();
-    }
-    
-    return allStats;
-}
-
-PacketQueueStats MultiStreamPacketQueue::getStats(int streamIndex) const {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        return it->second->getStats();
-    }
-    
-    return PacketQueueStats();
-}
-
-void MultiStreamPacketQueue::resetStats() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->resetStats();
-    }
-    
-    Logger::instance().debug("All stream queue stats reset");
-}
-
-void MultiStreamPacketQueue::resetStats(int streamIndex) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    auto it = streamQueues_.find(streamIndex);
-    if (it != streamQueues_.end()) {
-        it->second->resetStats();
-        Logger::instance().debugf("Stream {} queue stats reset", streamIndex);
-    }
-}
-
-void MultiStreamPacketQueue::setBlocking(bool blocking) {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->setBlocking(blocking);
-    }
-    
-    Logger::instance().debugf("All stream queues blocking mode: {}", blocking);
-}
-
-void MultiStreamPacketQueue::wakeupAll() {
-    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
-    
-    for (auto& pair : streamQueues_) {
-        pair.second->wakeup();
-    }
-}
-
-// 工厂类实现
-std::unique_ptr<PacketQueue> PacketQueueFactory::createStandardQueue(size_t maxSize) {
-    PacketQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 1000;
-    config.enableStats = true;
-    
-    return std::make_unique<PacketQueue>(config);
-}
-
-std::unique_ptr<PacketQueue> PacketQueueFactory::createLowLatencyQueue(size_t maxSize) {
-    PacketQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 100;
-    config.enableStats = true;
-    config.enablePacketDrop = true;
-    config.maxLatency = 100.0;
-    config.dropRatio = 3;
-    
-    return std::make_unique<PacketQueue>(config);
-}
-
-std::unique_ptr<PacketQueue> PacketQueueFactory::createHighCapacityQueue(size_t maxSize) {
-    PacketQueueConfig config;
-    config.maxSize = maxSize;
-    config.maxBytes = 200 * 1024 * 1024; // 200MB
-    config.dropOnFull = false; // 不丢包,等待
-    config.dropOldest = true;
-    config.timeoutMs = 5000;
-    config.enableStats = true;
-    config.enablePacketDrop = false;
-    
-    return std::make_unique<PacketQueue>(config);
-}
-
-std::unique_ptr<PacketQueue> PacketQueueFactory::createRealtimeQueue(size_t maxSize, double maxLatency) {
-    PacketQueueConfig config;
-    config.maxSize = maxSize;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 50;
-    config.enableStats = true;
-    config.enablePacketDrop = true;
-    config.maxLatency = maxLatency;
-    config.dropRatio = 2;
-    config.dropNonKeyPackets = true;
-    
-    return std::make_unique<PacketQueue>(config);
-}
-
-std::unique_ptr<PacketQueue> PacketQueueFactory::createPriorityQueue(size_t maxSize) {
-    PacketQueueConfig config;
-    config.maxSize = maxSize;
-    config.priorityQueue = true;
-    config.dropOnFull = true;
-    config.dropOldest = true;
-    config.timeoutMs = 1000;
-    config.enableStats = true;
-    
-    return std::make_unique<PacketQueue>(config);
-}
-
-std::unique_ptr<MultiStreamPacketQueue> PacketQueueFactory::createMultiStreamQueue(const PacketQueueConfig& config) {
-    return std::make_unique<MultiStreamPacketQueue>(config);
-}
-
-} // namespace utils
-} // namespace av

+ 0 - 370
AV/code/utils/utils_packet_queue.h

@@ -1,370 +0,0 @@
-#ifndef AV_UTILS_PACKET_QUEUE_H
-#define AV_UTILS_PACKET_QUEUE_H
-
-#include "../base/types.h"
-#include <queue>
-#include <mutex>
-#include <shared_mutex>
-#include <condition_variable>
-#include <atomic>
-#include <chrono>
-#include <memory>
-#include <functional>
-#include <map>
-#include <vector>
-
-extern "C" {
-#include <libavcodec/packet.h>
-#include <libavutil/avutil.h>
-}
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-// 包队列项
-struct PacketQueueItem {
-    AVPacket* packet = nullptr;         // 包数据
-    int64_t pts = AV_NOPTS_VALUE;      // 显示时间戳
-    int64_t dts = AV_NOPTS_VALUE;      // 解码时间戳
-    double duration = 0.0;              // 包持续时间
-    int streamIndex = -1;               // 流索引
-    bool isKeyPacket = false;           // 是否关键包
-    int priority = 0;                   // 优先级(数值越大优先级越高)
-    std::chrono::steady_clock::time_point enqueueTime; // 入队时间
-    
-    PacketQueueItem() {
-        enqueueTime = std::chrono::steady_clock::now();
-    }
-    
-    PacketQueueItem(AVPacket* p, int stream = -1, int prio = 0) 
-        : packet(p), streamIndex(stream), priority(prio) {
-        if (packet) {
-            pts = packet->pts;
-            dts = packet->dts;
-            isKeyPacket = (packet->flags & AV_PKT_FLAG_KEY) != 0;
-        }
-        enqueueTime = std::chrono::steady_clock::now();
-    }
-    
-    ~PacketQueueItem() {
-        if (packet) {
-            av_packet_free(&packet);
-        }
-    }
-    
-    // 移动构造函数
-    PacketQueueItem(PacketQueueItem&& other) noexcept
-        : packet(other.packet), pts(other.pts), dts(other.dts),
-          duration(other.duration), streamIndex(other.streamIndex),
-          isKeyPacket(other.isKeyPacket), priority(other.priority),
-          enqueueTime(other.enqueueTime) {
-        other.packet = nullptr;
-    }
-    
-    // 移动赋值操作符
-    PacketQueueItem& operator=(PacketQueueItem&& other) noexcept {
-        if (this != &other) {
-            if (packet) {
-                av_packet_free(&packet);
-            }
-            packet = other.packet;
-            pts = other.pts;
-            dts = other.dts;
-            duration = other.duration;
-            streamIndex = other.streamIndex;
-            isKeyPacket = other.isKeyPacket;
-            priority = other.priority;
-            enqueueTime = other.enqueueTime;
-            other.packet = nullptr;
-        }
-        return *this;
-    }
-    
-    // 禁用拷贝
-    PacketQueueItem(const PacketQueueItem&) = delete;
-    PacketQueueItem& operator=(const PacketQueueItem&) = delete;
-};
-
-// 包队列统计信息
-struct PacketQueueStats {
-    size_t currentSize = 0;             // 当前队列大小
-    size_t maxSize = 0;                 // 最大队列大小
-    uint64_t totalEnqueued = 0;         // 总入队数量
-    uint64_t totalDequeued = 0;         // 总出队数量
-    uint64_t totalDropped = 0;          // 总丢弃数量
-    uint64_t totalBytes = 0;            // 总字节数
-    double averageWaitTime = 0.0;       // 平均等待时间(毫秒)
-    double maxWaitTime = 0.0;           // 最大等待时间(毫秒)
-    double averagePacketSize = 0.0;     // 平均包大小
-    std::chrono::steady_clock::time_point lastUpdateTime;
-    
-    PacketQueueStats() {
-        lastUpdateTime = std::chrono::steady_clock::now();
-    }
-};
-
-// 包队列配置
-struct PacketQueueConfig {
-    size_t maxSize = 200;               // 最大队列大小
-    size_t maxBytes = 50 * 1024 * 1024; // 最大字节数(50MB)
-    bool dropOnFull = true;             // 队列满时是否丢弃新包
-    bool dropOldest = true;             // 丢弃最旧的包(false则丢弃最新的)
-    bool priorityQueue = false;         // 是否启用优先级队列
-    int timeoutMs = 1000;               // 超时时间(毫秒)
-    bool enableStats = true;            // 启用统计信息
-    
-    // 丢包策略
-    bool enablePacketDrop = false;      // 启用智能丢包
-    double maxLatency = 200.0;          // 最大延迟(毫秒)
-    int dropRatio = 3;                  // 丢包比例(每N包丢1包)
-    bool dropNonKeyPackets = true;      // 优先丢弃非关键包
-};
-
-// 优先级比较器
-struct PacketPriorityCompare {
-    bool operator()(const std::unique_ptr<PacketQueueItem>& a,
-                   const std::unique_ptr<PacketQueueItem>& b) const {
-        // 优先级高的在前
-        if (a->priority != b->priority) {
-            return a->priority < b->priority;
-        }
-        
-        // 关键包优先
-        if (a->isKeyPacket != b->isKeyPacket) {
-            return !a->isKeyPacket && b->isKeyPacket;
-        }
-        
-        // 时间戳小的在前
-        return a->dts > b->dts;
-    }
-};
-
-// 包队列类
-class PacketQueue {
-public:
-    explicit PacketQueue(const PacketQueueConfig& config = PacketQueueConfig());
-    ~PacketQueue();
-    
-    // 基本操作
-    ErrorCode enqueue(std::unique_ptr<PacketQueueItem> item);
-    std::unique_ptr<PacketQueueItem> dequeue();
-    std::unique_ptr<PacketQueueItem> dequeue(int timeoutMs);
-    
-    // 便捷方法
-    ErrorCode enqueue(AVPacket* packet, int streamIndex = -1, int priority = 0);
-    AVPacket* dequeuePacket();
-    AVPacket* dequeuePacket(int timeoutMs);
-    
-    // 兼容性方法 (push/pop 别名)
-    ErrorCode push(AVPacket* packet, int streamIndex = -1, int priority = 0) {
-        return enqueue(packet, streamIndex, priority);
-    }
-    AVPacket* pop() {
-        return dequeuePacket();
-    }
-    AVPacket* pop(int timeoutMs) {
-        return dequeuePacket(timeoutMs);
-    }
-    
-    // 优先级队列操作
-    ErrorCode enqueueWithPriority(AVPacket* packet, int priority, int streamIndex = -1);
-    std::unique_ptr<PacketQueueItem> dequeueHighestPriority();
-    
-    // 队列控制
-    void clear();
-    void flush();
-    void setMaxSize(size_t maxSize);
-    void setMaxBytes(size_t maxBytes);
-    void setDropPolicy(bool dropOnFull, bool dropOldest = true);
-    void enablePriorityQueue(bool enable);
-    
-    // 状态查询
-    size_t size() const;
-    size_t bytes() const;
-    bool empty() const;
-    bool full() const;
-    bool fullByBytes() const;
-    size_t capacity() const;
-    size_t capacityBytes() const;
-    
-    // 统计信息
-    PacketQueueStats getStats() const;
-    void resetStats();
-    
-    // 包丢弃策略
-    void enablePacketDrop(bool enable, double maxLatency = 200.0, int dropRatio = 3);
-    void setPacketDropCallback(std::function<bool(const PacketQueueItem&)> callback);
-    
-    // 阻塞控制
-    void setBlocking(bool blocking);
-    void wakeup();
-    
-    // 流过滤
-    void setStreamFilter(const std::vector<int>& allowedStreams);
-    void clearStreamFilter();
-    
-    // 回调设置
-    using EnqueueCallback = std::function<void(const PacketQueueItem&)>;
-    using DequeueCallback = std::function<void(const PacketQueueItem&)>;
-    using DropCallback = std::function<void(const PacketQueueItem&, const std::string&)>;
-    
-    void setEnqueueCallback(EnqueueCallback callback) { enqueueCallback_ = callback; }
-    void setDequeueCallback(DequeueCallback callback) { dequeueCallback_ = callback; }
-    void setDropCallback(DropCallback callback) { dropCallback_ = callback; }
-    
-protected:
-    // 内部方法
-    bool shouldDropPacket(const PacketQueueItem& item) const;
-    void dropOldestPacket();
-    void dropNewestPacket();
-    void dropLargestPacket();
-    void dropNonKeyPackets();
-    void updateStats(const PacketQueueItem& item, bool isEnqueue);
-    double calculateWaitTime(const PacketQueueItem& item) const;
-    bool isStreamAllowed(int streamIndex) const;
-    
-    // 智能丢包
-    bool shouldDropByLatency(const PacketQueueItem& item) const;
-    bool shouldDropByRatio() const;
-    bool shouldDropBySize() const;
-    
-    // 队列操作
-    void enqueueToNormalQueue(std::unique_ptr<PacketQueueItem> item);
-    void enqueueToPriorityQueue(std::unique_ptr<PacketQueueItem> item);
-    std::unique_ptr<PacketQueueItem> dequeueFromNormalQueue();
-    std::unique_ptr<PacketQueueItem> dequeueFromPriorityQueue();
-    
-private:
-    PacketQueueConfig config_;
-    
-    // 队列数据
-    std::queue<std::unique_ptr<PacketQueueItem>> normalQueue_;
-    std::priority_queue<std::unique_ptr<PacketQueueItem>, 
-                       std::vector<std::unique_ptr<PacketQueueItem>>,
-                       PacketPriorityCompare> priorityQueue_;
-    
-    mutable std::mutex queueMutex_;
-    std::condition_variable notEmpty_;
-    std::condition_variable notFull_;
-    
-    // 状态控制
-    std::atomic<bool> blocking_{true};
-    std::atomic<bool> shutdown_{false};
-    std::atomic<size_t> totalBytes_{0};
-    
-    // 统计信息
-    mutable std::mutex statsMutex_;
-    PacketQueueStats stats_;
-    
-    // 丢包控制
-    mutable std::atomic<uint64_t> packetCounter_{0};
-    std::function<bool(const PacketQueueItem&)> packetDropCallback_;
-    
-    // 流过滤
-    std::vector<int> allowedStreams_;
-    bool hasStreamFilter_ = false;
-    mutable std::mutex streamFilterMutex_;
-    
-    // 回调函数
-    EnqueueCallback enqueueCallback_;
-    DequeueCallback dequeueCallback_;
-    DropCallback dropCallback_;
-};
-
-// 多流包队列
-class MultiStreamPacketQueue {
-public:
-    explicit MultiStreamPacketQueue(const PacketQueueConfig& config = PacketQueueConfig());
-    ~MultiStreamPacketQueue();
-    
-    // 流管理
-    ErrorCode addStream(int streamIndex, const PacketQueueConfig& config = PacketQueueConfig());
-    ErrorCode removeStream(int streamIndex);
-    bool hasStream(int streamIndex) const;
-    std::vector<int> getStreamIndices() const;
-    
-    // 包操作
-    ErrorCode enqueue(AVPacket* packet, int streamIndex);
-    AVPacket* dequeue(int streamIndex);
-    AVPacket* dequeue(int streamIndex, int timeoutMs);
-    
-    // 批量操作
-    ErrorCode enqueueToAll(AVPacket* packet);
-    std::vector<AVPacket*> dequeueFromAll();
-    
-    // 同步出队(按时间戳顺序)
-    AVPacket* dequeueSynchronized();
-    std::vector<AVPacket*> dequeueSynchronizedBatch(size_t maxCount = 10);
-    
-    // 队列控制
-    void clear();
-    void clearStream(int streamIndex);
-    void flush();
-    void flushStream(int streamIndex);
-    
-    // 状态查询
-    size_t size() const;
-    size_t size(int streamIndex) const;
-    size_t bytes() const;
-    size_t bytes(int streamIndex) const;
-    bool empty() const;
-    bool empty(int streamIndex) const;
-    
-    // 统计信息
-    std::map<int, PacketQueueStats> getAllStats() const;
-    PacketQueueStats getStats(int streamIndex) const;
-    void resetStats();
-    void resetStats(int streamIndex);
-    
-    // 同步控制
-    void setBlocking(bool blocking);
-    void wakeupAll();
-    
-private:
-    PacketQueueConfig defaultConfig_;
-    std::map<int, std::unique_ptr<PacketQueue>> streamQueues_;
-    mutable std::shared_mutex streamsMutex_;
-    
-    // 同步出队相关
-    struct SyncItem {
-        AVPacket* packet;
-        int streamIndex;
-        int64_t timestamp;
-        
-        bool operator>(const SyncItem& other) const {
-            return timestamp > other.timestamp;
-        }
-    };
-    
-    std::priority_queue<SyncItem, std::vector<SyncItem>, std::greater<SyncItem>> syncQueue_;
-    mutable std::mutex syncMutex_;
-};
-
-// 包队列工厂
-class PacketQueueFactory {
-public:
-    // 创建标准包队列
-    static std::unique_ptr<PacketQueue> createStandardQueue(size_t maxSize = 200);
-    
-    // 创建低延迟队列
-    static std::unique_ptr<PacketQueue> createLowLatencyQueue(size_t maxSize = 50);
-    
-    // 创建高容量队列
-    static std::unique_ptr<PacketQueue> createHighCapacityQueue(size_t maxSize = 2000);
-    
-    // 创建实时队列(启用智能丢包)
-    static std::unique_ptr<PacketQueue> createRealtimeQueue(size_t maxSize = 100, double maxLatency = 100.0);
-    
-    // 创建优先级队列
-    static std::unique_ptr<PacketQueue> createPriorityQueue(size_t maxSize = 200);
-    
-    // 创建多流队列
-    static std::unique_ptr<MultiStreamPacketQueue> createMultiStreamQueue(const PacketQueueConfig& config = PacketQueueConfig());
-};
-
-} // namespace utils
-} // namespace av
-
-#endif // AV_UTILS_PACKET_QUEUE_H

+ 0 - 836
AV/code/utils/utils_performance_monitor.cpp

@@ -1,836 +0,0 @@
-#include "utils_performance_monitor.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <sstream>
-#include <fstream>
-#include <iomanip>
-#include <thread>
-#include <cmath>
-#include <chrono>
-
-#ifdef _WIN32
-#include <windows.h>
-#include <psapi.h>
-#include <pdh.h>
-#pragma comment(lib, "pdh.lib")
-#pragma comment(lib, "psapi.lib")
-#else
-#include <sys/sysinfo.h>
-#include <sys/statvfs.h>
-#include <unistd.h>
-#endif
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-// PerformanceMonitor 实现
-PerformanceMonitor::PerformanceMonitor(const MonitorConfig& config)
-    : config_(config)
-    , initialized_(false)
-    , running_(false)
-    , monitoring_(false)
-    , startTime_(std::chrono::steady_clock::now())
-    , lastReportTime_(std::chrono::steady_clock::now()) {
-}
-
-PerformanceMonitor::~PerformanceMonitor() {
-    close();
-}
-
-ErrorCode PerformanceMonitor::initialize() {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    
-    if (initialized_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    try {
-        // 初始化基本指标
-        registerMetric("system.cpu_usage", MetricType::GAUGE, 90.0);
-        registerMetric("system.memory_usage", MetricType::GAUGE, 85.0);
-        registerMetric("system.disk_usage", MetricType::GAUGE, 90.0);
-        registerMetric("performance.frame_rate", MetricType::RATE, 0.0);
-        registerMetric("performance.latency", MetricType::HISTOGRAM, 100.0);
-        registerMetric("performance.throughput", MetricType::RATE, 0.0);
-        
-        startTime_ = std::chrono::steady_clock::now();
-        lastReportTime_ = startTime_;
-        
-        initialized_.store(true);
-        Logger::instance().info("Performance monitor initialized successfully");
-        
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        Logger::instance().errorf("Failed to initialize performance monitor: {}", e.what());
-        return ErrorCode::INITIALIZATION_FAILED;
-    }
-}
-
-ErrorCode PerformanceMonitor::start() {
-    if (!initialized_.load()) {
-        return ErrorCode::NOT_INITIALIZED;
-    }
-    
-    if (running_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    running_.store(true);
-    monitoring_.store(config_.enableMonitoring);
-    
-    Logger::instance().info("Performance monitor started");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::stop() {
-    if (!running_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    running_.store(false);
-    monitoring_.store(false);
-    
-    Logger::instance().info("Performance monitor stopped");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::reset() {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    resetAllStats();
-    clearAlerts();
-    
-    startTime_ = std::chrono::steady_clock::now();
-    lastReportTime_ = startTime_;
-    
-    Logger::instance().info("Performance monitor reset");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::close() {
-    stop();
-    
-    std::lock_guard<std::mutex> metricsLock(metricsMutex_);
-    std::lock_guard<std::mutex> alertsLock(alertsMutex_);
-    std::lock_guard<std::mutex> configLock(configMutex_);
-    
-    metrics_.clear();
-    metricTypes_.clear();
-    alertThresholds_.clear();
-    timerStarts_.clear();
-    historyData_.clear();
-    activeAlerts_.clear();
-    
-    initialized_.store(false);
-    
-    Logger::instance().info("Performance monitor closed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::registerMetric(const std::string& name, MetricType type, double alertThreshold) {
-    if (name.empty()) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    if (metrics_.find(name) != metrics_.end()) {
-        return ErrorCode::ALREADY_EXISTS;
-    }
-    
-    PerformanceStats stats;
-    stats.name = name;
-    stats.type = type;
-    stats.startTime = std::chrono::steady_clock::now();
-    stats.lastUpdateTime = stats.startTime;
-    
-    metrics_[name] = stats;
-    metricTypes_[name] = type;
-    
-    if (alertThreshold > 0.0) {
-        alertThresholds_[name] = alertThreshold;
-    }
-    
-    if (config_.enableLogging) {
-        Logger::instance().debugf("Registered metric: {} (type: {})", name, static_cast<int>(type));
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::unregisterMetric(const std::string& name) {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it == metrics_.end()) {
-        return ErrorCode::NOT_FOUND;
-    }
-    
-    metrics_.erase(it);
-    metricTypes_.erase(name);
-    alertThresholds_.erase(name);
-    timerStarts_.erase(name);
-    historyData_.erase(name);
-    
-    if (config_.enableLogging) {
-        Logger::instance().debugf("Unregistered metric: {}", name);
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-bool PerformanceMonitor::hasMetric(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    return metrics_.find(name) != metrics_.end();
-}
-
-std::vector<std::string> PerformanceMonitor::getMetricNames() const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    std::vector<std::string> names;
-    names.reserve(metrics_.size());
-    
-    for (const auto& pair : metrics_) {
-        names.push_back(pair.first);
-    }
-    
-    return names;
-}
-
-ErrorCode PerformanceMonitor::incrementCounter(const std::string& name, double value) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, value, true);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::decrementCounter(const std::string& name, double value) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, -value, true);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::setCounter(const std::string& name, double value) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, value, false);
-    return ErrorCode::SUCCESS;
-}
-
-double PerformanceMonitor::getCounter(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end() && it->second.type == MetricType::COUNTER) {
-        return it->second.value;
-    }
-    
-    return 0.0;
-}
-
-ErrorCode PerformanceMonitor::setGauge(const std::string& name, double value) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, value, false);
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::updateGauge(const std::string& name, double delta) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, delta, true);
-    return ErrorCode::SUCCESS;
-}
-
-double PerformanceMonitor::getGauge(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end() && it->second.type == MetricType::GAUGE) {
-        return it->second.value;
-    }
-    
-    return 0.0;
-}
-
-ErrorCode PerformanceMonitor::recordHistogram(const std::string& name, double value) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end() && it->second.type == MetricType::HISTOGRAM) {
-        updateHistogram(it->second, value);
-        checkAlerts(name, value);
-        
-        if (config_.enableLogging) {
-            logMetricUpdate(name, value);
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-PerformanceStats PerformanceMonitor::getHistogramStats(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end() && it->second.type == MetricType::HISTOGRAM) {
-        return it->second;
-    }
-    
-    return PerformanceStats();
-}
-
-ErrorCode PerformanceMonitor::startTimer(const std::string& name) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    timerStarts_[name] = std::chrono::steady_clock::now();
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::stopTimer(const std::string& name) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = timerStarts_.find(name);
-    if (it != timerStarts_.end()) {
-        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
-            std::chrono::steady_clock::now() - it->second).count() / 1000.0;
-        
-        timerStarts_.erase(it);
-        
-        auto metricIt = metrics_.find(name);
-        if (metricIt != metrics_.end() && metricIt->second.type == MetricType::TIMER) {
-            updateStatistics(metricIt->second, duration);
-            checkAlerts(name, duration);
-            
-            if (config_.enableLogging) {
-                logMetricUpdate(name, duration);
-            }
-        }
-    }
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::recordTimer(const std::string& name, double duration) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, duration, false);
-    return ErrorCode::SUCCESS;
-}
-
-double PerformanceMonitor::getTimerAverage(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end() && it->second.type == MetricType::TIMER) {
-        return it->second.avgValue;
-    }
-    
-    return 0.0;
-}
-
-ErrorCode PerformanceMonitor::recordRate(const std::string& name, double value) {
-    if (!monitoring_.load()) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    updateMetric(name, value, true);
-    return ErrorCode::SUCCESS;
-}
-
-double PerformanceMonitor::getRate(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end() && it->second.type == MetricType::RATE) {
-        return it->second.rate;
-    }
-    
-    return 0.0;
-}
-
-PerformanceStats PerformanceMonitor::getStats(const std::string& name) const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end()) {
-        return it->second;
-    }
-    
-    return PerformanceStats();
-}
-
-std::map<std::string, PerformanceStats> PerformanceMonitor::getAllStats() const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    return metrics_;
-}
-
-void PerformanceMonitor::resetStats(const std::string& name) {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end()) {
-        it->second.value = 0.0;
-        it->second.minValue = 0.0;
-        it->second.maxValue = 0.0;
-        it->second.avgValue = 0.0;
-        it->second.count = 0;
-        it->second.totalCount = 0;
-        it->second.rate = 0.0;
-        it->second.startTime = std::chrono::steady_clock::now();
-        it->second.lastUpdateTime = it->second.startTime;
-    }
-}
-
-void PerformanceMonitor::resetAllStats() {
-    for (const auto& pair : metrics_) {
-        resetStats(pair.first);
-    }
-}
-
-void PerformanceMonitor::setConfig(const MonitorConfig& config) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_ = config;
-    monitoring_.store(config_.enableMonitoring && running_.load());
-}
-
-MonitorConfig PerformanceMonitor::getConfig() const {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    return config_;
-}
-
-void PerformanceMonitor::enableMonitoring(bool enable) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.enableMonitoring = enable;
-    monitoring_.store(enable && running_.load());
-}
-
-void PerformanceMonitor::enableLogging(bool enable) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.enableLogging = enable;
-}
-
-void PerformanceMonitor::enableReporting(bool enable) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.enableReporting = enable;
-}
-
-void PerformanceMonitor::setReportInterval(double interval) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.reportInterval = interval;
-}
-
-void PerformanceMonitor::setReportCallback(PerformanceReportCallback callback) {
-    reportCallback_ = callback;
-}
-
-void PerformanceMonitor::setAlertCallback(PerformanceAlertCallback callback) {
-    alertCallback_ = callback;
-}
-
-std::string PerformanceMonitor::generateReport() const {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    std::ostringstream oss;
-    oss << "Performance Monitor Report\n";
-    oss << "========================\n";
-    oss << "Generated at: " << std::chrono::duration_cast<std::chrono::seconds>(
-        std::chrono::steady_clock::now().time_since_epoch()).count() << "\n";
-    oss << "Total metrics: " << metrics_.size() << "\n\n";
-    
-    for (const auto& pair : metrics_) {
-        const auto& stats = pair.second;
-        oss << "Metric: " << stats.name << "\n";
-        oss << "  Type: " << static_cast<int>(stats.type) << "\n";
-        oss << "  Current Value: " << std::fixed << std::setprecision(2) << stats.value << "\n";
-        oss << "  Min/Max/Avg: " << stats.minValue << "/" << stats.maxValue << "/" << stats.avgValue << "\n";
-        oss << "  Count: " << stats.count << "\n";
-        oss << "  Rate: " << stats.rate << "/sec\n";
-        oss << "\n";
-    }
-    
-    return oss.str();
-}
-
-ErrorCode PerformanceMonitor::exportToFile(const std::string& filename) const {
-    try {
-        std::ofstream file(filename);
-        if (!file.is_open()) {
-            return ErrorCode::FILE_OPERATION_FAILED;
-        }
-        
-        file << generateReport();
-        file.close();
-        
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        Logger::instance().errorf("Failed to export performance report: {}", e.what());
-        return ErrorCode::FILE_OPERATION_FAILED;
-    }
-}
-
-ErrorCode PerformanceMonitor::exportToJson(const std::string& filename) const {
-    // JSON导出实现
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode PerformanceMonitor::exportToCsv(const std::string& filename) const {
-    // CSV导出实现
-    return ErrorCode::SUCCESS;
-}
-
-void PerformanceMonitor::setAlertThreshold(const std::string& name, double threshold) {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    alertThresholds_[name] = threshold;
-}
-
-std::vector<PerformanceAlert> PerformanceMonitor::getActiveAlerts() const {
-    std::lock_guard<std::mutex> lock(alertsMutex_);
-    return activeAlerts_;
-}
-
-void PerformanceMonitor::clearAlerts() {
-    std::lock_guard<std::mutex> lock(alertsMutex_);
-    activeAlerts_.clear();
-}
-
-// 私有方法实现
-void PerformanceMonitor::updateMetric(const std::string& name, double value, bool isIncrement) {
-    std::lock_guard<std::mutex> lock(metricsMutex_);
-    
-    auto it = metrics_.find(name);
-    if (it != metrics_.end()) {
-        if (isIncrement) {
-            it->second.value += value;
-        } else {
-            it->second.value = value;
-        }
-        
-        updateStatistics(it->second, value);
-        checkAlerts(name, it->second.value);
-        
-        if (config_.enableLogging) {
-            logMetricUpdate(name, it->second.value);
-        }
-    }
-}
-
-void PerformanceMonitor::checkAlerts(const std::string& name, double value) {
-    if (!config_.enableAlerts) {
-        return;
-    }
-    
-    auto thresholdIt = alertThresholds_.find(name);
-    if (thresholdIt != alertThresholds_.end() && value > thresholdIt->second) {
-        PerformanceAlert alert;
-        alert.metricName = name;
-        alert.currentValue = value;
-        alert.threshold = thresholdIt->second;
-        alert.message = "Metric " + name + " exceeded threshold";
-        alert.timestamp = std::chrono::steady_clock::now();
-        
-        {
-            std::lock_guard<std::mutex> alertLock(alertsMutex_);
-            activeAlerts_.push_back(alert);
-        }
-        
-        if (alertCallback_) {
-            alertCallback_(alert);
-        }
-    }
-}
-
-void PerformanceMonitor::logMetricUpdate(const std::string& name, double value) {
-    Logger::instance().debugf("Metric updated: {} = {}", name, value);
-}
-
-void PerformanceMonitor::updateStatistics(PerformanceStats& stats, double value) {
-    stats.count++;
-    stats.totalCount++;
-    stats.lastUpdateTime = std::chrono::steady_clock::now();
-    
-    if (stats.count == 1) {
-        stats.minValue = value;
-        stats.maxValue = value;
-        stats.avgValue = value;
-    } else {
-        stats.minValue = (std::min)(stats.minValue, value);
-        stats.maxValue = (std::max)(stats.maxValue, value);
-        stats.avgValue = (stats.avgValue * (stats.count - 1) + value) / stats.count;
-    }
-    
-    // 计算速率
-    if (stats.type == MetricType::RATE) {
-        auto duration = std::chrono::duration_cast<std::chrono::seconds>(
-            stats.lastUpdateTime - stats.startTime).count();
-        if (duration > 0) {
-            stats.rate = stats.totalCount / static_cast<double>(duration);
-        }
-    }
-}
-
-void PerformanceMonitor::updateHistogram(PerformanceStats& stats, double value) {
-    updateStatistics(stats, value);
-    
-    // 保存历史数据
-    auto& history = historyData_[stats.name];
-    history.push_back(value);
-    
-    if (history.size() > config_.maxHistorySize) {
-        history.erase(history.begin());
-    }
-}
-
-// ScopedTimer 实现
-ScopedTimer::ScopedTimer(PerformanceMonitor* monitor, const std::string& name)
-    : monitor_(monitor)
-    , name_(name)
-    , startTime_(std::chrono::steady_clock::now()) {
-}
-
-ScopedTimer::~ScopedTimer() {
-    if (monitor_) {
-        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
-            std::chrono::steady_clock::now() - startTime_).count() / 1000.0;
-        monitor_->recordTimer(name_, duration);
-    }
-}
-
-// SystemPerformanceMonitor 实现
-SystemPerformanceMonitor::SystemPerformanceMonitor()
-    : cpuUsage_(0.0)
-    , memoryUsage_(0.0)
-    , diskUsage_(0.0)
-    , networkUsage_(0.0)
-    , gpuUsage_(0.0)
-    , lastUpdateTime_(std::chrono::steady_clock::now()) {
-}
-
-SystemPerformanceMonitor::~SystemPerformanceMonitor() {
-}
-
-ErrorCode SystemPerformanceMonitor::collectCpuUsage() {
-#ifdef _WIN32
-    // Windows CPU使用率收集实现
-    static PDH_HQUERY cpuQuery;
-    static PDH_HCOUNTER cpuTotal;
-    static bool initialized = false;
-    
-    if (!initialized) {
-        PdhOpenQuery(NULL, NULL, &cpuQuery);
-        PdhAddEnglishCounterA(cpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
-        PdhCollectQueryData(cpuQuery);
-        initialized = true;
-    }
-    
-    PDH_FMT_COUNTERVALUE counterVal;
-    PdhCollectQueryData(cpuQuery);
-    PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
-    cpuUsage_.store(counterVal.doubleValue);
-#else
-    // Linux CPU使用率收集实现
-    cpuUsage_.store(0.0); // 简化实现
-#endif
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SystemPerformanceMonitor::collectMemoryUsage() {
-#ifdef _WIN32
-    MEMORYSTATUSEX memInfo;
-    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
-    GlobalMemoryStatusEx(&memInfo);
-    
-    double totalMem = static_cast<double>(memInfo.ullTotalPhys);
-    double availMem = static_cast<double>(memInfo.ullAvailPhys);
-    double usedMem = totalMem - availMem;
-    
-    memoryUsage_.store((usedMem / totalMem) * 100.0);
-#else
-    struct sysinfo memInfo;
-    sysinfo(&memInfo);
-    
-    double totalMem = static_cast<double>(memInfo.totalram * memInfo.mem_unit);
-    double freeMem = static_cast<double>(memInfo.freeram * memInfo.mem_unit);
-    double usedMem = totalMem - freeMem;
-    
-    memoryUsage_.store((usedMem / totalMem) * 100.0);
-#endif
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SystemPerformanceMonitor::collectDiskUsage() {
-    // 磁盘使用率收集实现
-    diskUsage_.store(0.0); // 简化实现
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SystemPerformanceMonitor::collectNetworkUsage() {
-    // 网络使用率收集实现
-    networkUsage_.store(0.0); // 简化实现
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SystemPerformanceMonitor::collectGpuUsage() {
-    // GPU使用率收集实现
-    gpuUsage_.store(0.0); // 简化实现
-    return ErrorCode::SUCCESS;
-}
-
-double SystemPerformanceMonitor::getCpuUsage() const {
-    return cpuUsage_.load();
-}
-
-double SystemPerformanceMonitor::getMemoryUsage() const {
-    return memoryUsage_.load();
-}
-
-double SystemPerformanceMonitor::getDiskUsage() const {
-    return diskUsage_.load();
-}
-
-double SystemPerformanceMonitor::getNetworkUsage() const {
-    return networkUsage_.load();
-}
-
-double SystemPerformanceMonitor::getGpuUsage() const {
-    return gpuUsage_.load();
-}
-
-std::string SystemPerformanceMonitor::getSystemInfo() const {
-    std::ostringstream oss;
-    oss << "System Performance:\n";
-    oss << "CPU Usage: " << std::fixed << std::setprecision(1) << getCpuUsage() << "%\n";
-    oss << "Memory Usage: " << getMemoryUsage() << "%\n";
-    oss << "Disk Usage: " << getDiskUsage() << "%\n";
-    oss << "Network Usage: " << getNetworkUsage() << "%\n";
-    oss << "GPU Usage: " << getGpuUsage() << "%\n";
-    return oss.str();
-}
-
-std::string SystemPerformanceMonitor::getCpuInfo() const {
-    return "CPU Information"; // 简化实现
-}
-
-std::string SystemPerformanceMonitor::getMemoryInfo() const {
-    return "Memory Information"; // 简化实现
-}
-
-std::string SystemPerformanceMonitor::getGpuInfo() const {
-    return "GPU Information"; // 简化实现
-}
-
-ErrorCode SystemPerformanceMonitor::integrateWithMonitor(PerformanceMonitor* monitor) {
-    if (!monitor) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    // 定期更新系统指标到性能监控器
-    collectCpuUsage();
-    collectMemoryUsage();
-    collectDiskUsage();
-    collectNetworkUsage();
-    collectGpuUsage();
-    
-    monitor->setGauge("system.cpu_usage", getCpuUsage());
-    monitor->setGauge("system.memory_usage", getMemoryUsage());
-    monitor->setGauge("system.disk_usage", getDiskUsage());
-    monitor->setGauge("system.network_usage", getNetworkUsage());
-    monitor->setGauge("system.gpu_usage", getGpuUsage());
-    
-    return ErrorCode::SUCCESS;
-}
-
-void SystemPerformanceMonitor::updateSystemMetrics() {
-    collectCpuUsage();
-    collectMemoryUsage();
-    collectDiskUsage();
-    collectNetworkUsage();
-    collectGpuUsage();
-    
-    lastUpdateTime_ = std::chrono::steady_clock::now();
-}
-
-// PerformanceMonitorFactory 实现
-std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createStandardMonitor() {
-    MonitorConfig config;
-    config.enableMonitoring = true;
-    config.enableLogging = true;
-    config.enableReporting = true;
-    config.reportInterval = 10.0;
-    config.maxHistorySize = 1000;
-    config.enableAlerts = true;
-    
-    return std::make_unique<PerformanceMonitor>(config);
-}
-
-std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createLightweightMonitor() {
-    MonitorConfig config;
-    config.enableMonitoring = true;
-    config.enableLogging = false;
-    config.enableReporting = false;
-    config.reportInterval = 60.0;
-    config.maxHistorySize = 100;
-    config.enableAlerts = false;
-    
-    return std::make_unique<PerformanceMonitor>(config);
-}
-
-std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createDetailedMonitor() {
-    MonitorConfig config;
-    config.enableMonitoring = true;
-    config.enableLogging = true;
-    config.enableReporting = true;
-    config.reportInterval = 5.0;
-    config.maxHistorySize = 5000;
-    config.enableAlerts = true;
-    
-    return std::make_unique<PerformanceMonitor>(config);
-}
-
-std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createRealtimeMonitor() {
-    MonitorConfig config;
-    config.enableMonitoring = true;
-    config.enableLogging = false;
-    config.enableReporting = true;
-    config.reportInterval = 1.0;
-    config.maxHistorySize = 500;
-    config.enableAlerts = true;
-    
-    return std::make_unique<PerformanceMonitor>(config);
-}
-
-std::unique_ptr<SystemPerformanceMonitor> PerformanceMonitorFactory::createSystemMonitor() {
-    return std::make_unique<SystemPerformanceMonitor>();
-}
-
-} // namespace utils
-} // namespace av

+ 0 - 289
AV/code/utils/utils_performance_monitor.h

@@ -1,289 +0,0 @@
-#pragma once
-
-#include "../base/types.h"
-#include <memory>
-#include <chrono>
-#include <string>
-#include <map>
-#include <vector>
-#include <atomic>
-#include <mutex>
-#include <functional>
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-// 性能指标类型
-enum class MetricType {
-    COUNTER,        // 计数器
-    GAUGE,          // 仪表盘(当前值)
-    HISTOGRAM,      // 直方图
-    TIMER,          // 计时器
-    RATE            // 速率
-};
-
-// 性能统计信息
-struct PerformanceStats {
-    std::string name;                    // 指标名称
-    MetricType type;                     // 指标类型
-    double value = 0.0;                  // 当前值
-    double minValue = 0.0;               // 最小值
-    double maxValue = 0.0;               // 最大值
-    double avgValue = 0.0;               // 平均值
-    uint64_t count = 0;                  // 计数
-    uint64_t totalCount = 0;             // 总计数
-    double rate = 0.0;                   // 速率(每秒)
-    std::chrono::steady_clock::time_point lastUpdateTime; // 最后更新时间
-    std::chrono::steady_clock::time_point startTime;      // 开始时间
-};
-
-// 性能监控配置
-struct MonitorConfig {
-    bool enableMonitoring = true;       // 启用监控
-    bool enableLogging = true;           // 启用日志记录
-    bool enableReporting = true;         // 启用报告
-    double reportInterval = 10.0;        // 报告间隔(秒)
-    size_t maxHistorySize = 1000;        // 最大历史记录数
-    bool enableAlerts = false;           // 启用告警
-    double alertThreshold = 0.0;         // 告警阈值
-};
-
-// 性能告警信息
-struct PerformanceAlert {
-    std::string metricName;              // 指标名称
-    MetricType type;                     // 指标类型
-    double currentValue;                 // 当前值
-    double threshold;                    // 阈值
-    std::string message;                 // 告警消息
-    std::chrono::steady_clock::time_point timestamp; // 时间戳
-};
-
-// 性能报告回调
-using PerformanceReportCallback = std::function<void(const std::map<std::string, PerformanceStats>&)>;
-using PerformanceAlertCallback = std::function<void(const PerformanceAlert&)>;
-
-// 性能监控器
-class PerformanceMonitor {
-public:
-    explicit PerformanceMonitor(const MonitorConfig& config = MonitorConfig());
-    virtual ~PerformanceMonitor();
-
-    // 基本控制
-    ErrorCode initialize();
-    ErrorCode start();
-    ErrorCode stop();
-    ErrorCode reset();
-    ErrorCode close();
-
-    // 指标管理
-    ErrorCode registerMetric(const std::string& name, MetricType type, double alertThreshold = 0.0);
-    ErrorCode unregisterMetric(const std::string& name);
-    bool hasMetric(const std::string& name) const;
-    std::vector<std::string> getMetricNames() const;
-
-    // 计数器操作
-    ErrorCode incrementCounter(const std::string& name, double value = 1.0);
-    ErrorCode decrementCounter(const std::string& name, double value = 1.0);
-    ErrorCode setCounter(const std::string& name, double value);
-    double getCounter(const std::string& name) const;
-
-    // 仪表盘操作
-    ErrorCode setGauge(const std::string& name, double value);
-    ErrorCode updateGauge(const std::string& name, double delta);
-    double getGauge(const std::string& name) const;
-
-    // 直方图操作
-    ErrorCode recordHistogram(const std::string& name, double value);
-    PerformanceStats getHistogramStats(const std::string& name) const;
-
-    // 计时器操作
-    ErrorCode startTimer(const std::string& name);
-    ErrorCode stopTimer(const std::string& name);
-    ErrorCode recordTimer(const std::string& name, double duration);
-    double getTimerAverage(const std::string& name) const;
-
-    // 速率操作
-    ErrorCode recordRate(const std::string& name, double value = 1.0);
-    double getRate(const std::string& name) const;
-
-    // 统计信息
-    PerformanceStats getStats(const std::string& name) const;
-    std::map<std::string, PerformanceStats> getAllStats() const;
-    void resetStats(const std::string& name);
-    void resetAllStats();
-
-    // 配置管理
-    void setConfig(const MonitorConfig& config);
-    MonitorConfig getConfig() const;
-    void enableMonitoring(bool enable);
-    void enableLogging(bool enable);
-    void enableReporting(bool enable);
-    void setReportInterval(double interval);
-
-    // 回调设置
-    void setReportCallback(PerformanceReportCallback callback);
-    void setAlertCallback(PerformanceAlertCallback callback);
-
-    // 报告和导出
-    std::string generateReport() const;
-    ErrorCode exportToFile(const std::string& filename) const;
-    ErrorCode exportToJson(const std::string& filename) const;
-    ErrorCode exportToCsv(const std::string& filename) const;
-
-    // 告警管理
-    void setAlertThreshold(const std::string& name, double threshold);
-    std::vector<PerformanceAlert> getActiveAlerts() const;
-    void clearAlerts();
-
-private:
-    // 内部方法
-    void updateMetric(const std::string& name, double value, bool isIncrement = false);
-    void checkAlerts(const std::string& name, double value);
-    void generatePeriodicReport();
-    void logMetricUpdate(const std::string& name, double value);
-    bool isMetricValid(const std::string& name) const;
-    void cleanupOldData();
-    void updateRates();
-    
-    // 统计计算
-    void updateStatistics(PerformanceStats& stats, double value);
-    double calculateRate(const PerformanceStats& stats) const;
-    void updateHistogram(PerformanceStats& stats, double value);
-    
-private:
-    MonitorConfig config_;
-    
-    // 指标存储
-    std::map<std::string, PerformanceStats> metrics_;
-    std::map<std::string, MetricType> metricTypes_;
-    std::map<std::string, double> alertThresholds_;
-    
-    // 计时器状态
-    std::map<std::string, std::chrono::steady_clock::time_point> timerStarts_;
-    
-    // 历史数据
-    std::map<std::string, std::vector<double>> historyData_;
-    
-    // 告警信息
-    std::vector<PerformanceAlert> activeAlerts_;
-    
-    // 回调函数
-    PerformanceReportCallback reportCallback_;
-    PerformanceAlertCallback alertCallback_;
-    
-    // 状态管理
-    std::atomic<bool> initialized_;
-    std::atomic<bool> running_;
-    std::atomic<bool> monitoring_;
-    
-    // 线程同步
-    mutable std::mutex metricsMutex_;
-    mutable std::mutex alertsMutex_;
-    mutable std::mutex configMutex_;
-    
-    // 时间管理
-    std::chrono::steady_clock::time_point startTime_;
-    std::chrono::steady_clock::time_point lastReportTime_;
-};
-
-// 性能监控作用域计时器
-class ScopedTimer {
-public:
-    ScopedTimer(PerformanceMonitor* monitor, const std::string& name);
-    ~ScopedTimer();
-    
-    // 禁止拷贝
-    ScopedTimer(const ScopedTimer&) = delete;
-    ScopedTimer& operator=(const ScopedTimer&) = delete;
-    
-private:
-    PerformanceMonitor* monitor_;
-    std::string name_;
-    std::chrono::steady_clock::time_point startTime_;
-};
-
-// 性能监控宏
-#define PERF_MONITOR_COUNTER_INC(monitor, name) \
-    do { if (monitor) monitor->incrementCounter(name); } while(0)
-
-#define PERF_MONITOR_COUNTER_DEC(monitor, name) \
-    do { if (monitor) monitor->decrementCounter(name); } while(0)
-
-#define PERF_MONITOR_GAUGE_SET(monitor, name, value) \
-    do { if (monitor) monitor->setGauge(name, value); } while(0)
-
-#define PERF_MONITOR_HISTOGRAM_RECORD(monitor, name, value) \
-    do { if (monitor) monitor->recordHistogram(name, value); } while(0)
-
-#define PERF_MONITOR_RATE_RECORD(monitor, name) \
-    do { if (monitor) monitor->recordRate(name); } while(0)
-
-#define PERF_MONITOR_TIMER_SCOPE(monitor, name) \
-    av::utils::ScopedTimer _timer(monitor, name)
-
-// 系统性能监控器
-class SystemPerformanceMonitor {
-public:
-    SystemPerformanceMonitor();
-    virtual ~SystemPerformanceMonitor();
-
-    // 系统指标收集
-    ErrorCode collectCpuUsage();
-    ErrorCode collectMemoryUsage();
-    ErrorCode collectDiskUsage();
-    ErrorCode collectNetworkUsage();
-    ErrorCode collectGpuUsage();
-    
-    // 获取系统指标
-    double getCpuUsage() const;
-    double getMemoryUsage() const;
-    double getDiskUsage() const;
-    double getNetworkUsage() const;
-    double getGpuUsage() const;
-    
-    // 系统信息
-    std::string getSystemInfo() const;
-    std::string getCpuInfo() const;
-    std::string getMemoryInfo() const;
-    std::string getGpuInfo() const;
-    
-    // 集成到性能监控器
-    ErrorCode integrateWithMonitor(PerformanceMonitor* monitor);
-    
-private:
-    void updateSystemMetrics();
-    
-private:
-    std::atomic<double> cpuUsage_;
-    std::atomic<double> memoryUsage_;
-    std::atomic<double> diskUsage_;
-    std::atomic<double> networkUsage_;
-    std::atomic<double> gpuUsage_;
-    
-    mutable std::mutex systemMutex_;
-    std::chrono::steady_clock::time_point lastUpdateTime_;
-};
-
-// 性能监控工厂
-class PerformanceMonitorFactory {
-public:
-    // 创建标准性能监控器
-    static std::unique_ptr<PerformanceMonitor> createStandardMonitor();
-    
-    // 创建轻量级监控器
-    static std::unique_ptr<PerformanceMonitor> createLightweightMonitor();
-    
-    // 创建详细监控器
-    static std::unique_ptr<PerformanceMonitor> createDetailedMonitor();
-    
-    // 创建实时监控器
-    static std::unique_ptr<PerformanceMonitor> createRealtimeMonitor();
-    
-    // 创建系统监控器
-    static std::unique_ptr<SystemPerformanceMonitor> createSystemMonitor();
-};
-
-} // namespace utils
-} // namespace av

+ 0 - 762
AV/code/utils/utils_synchronizer_v2.cpp

@@ -1,762 +0,0 @@
-#include "utils_synchronizer_v2.h"
-#include "qdebug.h"
-#include "qglobal.h"
-#include <algorithm>
-#include <cmath>
-#include <iostream>
-#include <sstream>
-
-namespace av {
-namespace utils {
-
-// 构造函数
-SynchronizerV2::SynchronizerV2(const SyncConfigV2& config)
-    : m_config(config)
-    , m_syncStrategy(config.strategy)
-    , m_playbackSpeed(1.0)
-{
-    // 初始化时钟
-    initClock(m_audioClock, 0);
-    initClock(m_videoClock, 0);
-    initClock(m_externalClock, 0);
-    
-    // 初始化帧计时器
-    m_frameTimer = getCurrentTime();
-}
-
-// 析构函数
-SynchronizerV2::~SynchronizerV2() {
-    close();
-}
-
-// 初始化
-ErrorCode SynchronizerV2::initialize() {
-    if (m_initialized) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 重置状态
-    m_initialized = true;
-    m_running = false;
-    m_paused = false;
-    
-    // 重置时钟
-    initClock(m_audioClock, 0);
-    initClock(m_videoClock, 0);
-    initClock(m_externalClock, 0);
-    
-    // 重置帧计时器
-    m_frameTimer = getCurrentTime();
-    
-    // 重置统计信息
-    std::lock_guard<std::mutex> lock(m_statsMutex);
-    m_stats = SyncStatsV2();
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 关闭
-void SynchronizerV2::close() {
-    if (!m_initialized) {
-        return;
-    }
-    
-    stop();
-    m_initialized = false;
-}
-
-// 启动
-ErrorCode SynchronizerV2::start() {
-    if (!m_initialized) {
-        return ErrorCode::NOT_INITIALIZED;
-    }
-    
-    if (m_running) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    // 重置帧计时器
-    m_frameTimer = getCurrentTime();
-    
-    // 更新外部时钟
-    updateExternalClock();
-    
-    m_running = true;
-    m_paused = false;
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 停止
-ErrorCode SynchronizerV2::stop() {
-    if (!m_initialized || !m_running) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    m_running = false;
-    m_paused = false;
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 暂停
-ErrorCode SynchronizerV2::pause() {
-    if (!m_initialized || !m_running) {
-        return ErrorCode::NOT_STARTED;
-    }
-    
-    if (m_paused) {
-        return ErrorCode::SUCCESS;
-    }
-    {
-        // 设置时钟暂停状态
-        std::lock_guard<std::mutex> lock(m_clockMutex);
-        m_audioClock.paused = true;
-        m_videoClock.paused = true;
-        m_externalClock.paused = true;
-    }
-    m_paused = true;
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 恢复
-ErrorCode SynchronizerV2::resume() {
-    if (!m_initialized || !m_running) {
-        return ErrorCode::NOT_STARTED;
-    }
-    
-    if (!m_paused) {
-        return ErrorCode::SUCCESS;
-    }
-    // 防止互斥死锁
-    {
-        // 恢复时钟暂停状态
-        std::lock_guard<std::mutex> lock(m_clockMutex);
-        m_audioClock.paused = false;
-        m_videoClock.paused = false;
-        m_externalClock.paused = false;
-    }
-    // 更新外部时钟
-    updateExternalClock();
-    
-    m_paused = false;
-    
-    return ErrorCode::SUCCESS;
-}
-
-// 重置
-ErrorCode SynchronizerV2::reset() {
-    if (!m_initialized) {
-        return ErrorCode::NOT_INITIALIZED;
-    }
-    
-    // 重置时钟
-    std::lock_guard<std::mutex> lock(m_clockMutex);
-    initClock(m_audioClock, m_audioSerial);
-    initClock(m_videoClock, m_videoSerial);
-    initClock(m_externalClock, m_externalSerial);
-    
-    // 重置帧计时器
-    m_frameTimer = getCurrentTime();
-    
-    // 重置音频同步状态
-    m_audioDiffCum = 0.0;
-    m_audioDiffAvgCount = 0;
-    
-    // 重置统计信息
-    {
-        std::lock_guard<std::mutex> statsLock(m_statsMutex);
-        m_stats = SyncStatsV2();
-        m_stats.playbackSpeed = m_playbackSpeed;
-    }
-    return ErrorCode::SUCCESS;
-}
-
-// 设置流信息
-void SynchronizerV2::setStreamInfo(bool hasAudio, bool hasVideo) {
-    m_hasAudio = hasAudio;
-    m_hasVideo = hasVideo;
-
-    // // 如果没有音频,但同步策略是音频主时钟,则切换到视频主时钟
-    // if (!hasAudio && m_syncStrategy == SyncStrategy::AUDIO_MASTER) {
-    //     if (hasVideo) {
-    //         setSyncStrategy(SyncStrategy::VIDEO_MASTER);
-    //     } else {
-    //         setSyncStrategy(SyncStrategy::EXTERNAL_MASTER);
-    //     }
-    // }
-
-    // // 如果没有视频,但同步策略是视频主时钟,则切换到音频主时钟
-    // if (!hasVideo && m_syncStrategy == SyncStrategy::VIDEO_MASTER) {
-    //     if (hasAudio) {
-    //         setSyncStrategy(SyncStrategy::AUDIO_MASTER);
-    //     } else {
-    //         setSyncStrategy(SyncStrategy::EXTERNAL_MASTER);
-    //     }
-    // }
-
-    // 根据可用流调整同步策略
-    if (hasAudio && hasVideo) {
-        // 两种流都有,使用音频优先
-        setSyncStrategy(SyncStrategy::AUDIO_MASTER);
-    } else if (hasVideo && !hasAudio) {
-        // 只有视频,强制使用视频主时钟
-        setSyncStrategy(SyncStrategy::VIDEO_MASTER);
-    } else if (hasAudio && !hasVideo) {
-        // 只有音频,强制使用音频主时钟
-        setSyncStrategy(SyncStrategy::AUDIO_MASTER);
-    } else {
-        // 两种流都没有,使用外部时钟
-        setSyncStrategy(SyncStrategy::EXTERNAL_MASTER);
-    }
-}
-
-// 获取时钟值
-double SynchronizerV2::getClock(ClockType type) const {
-    std::lock_guard<std::mutex> lock(m_clockMutex);
-    
-    const Clock* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &m_audioClock;
-            break;
-        case ClockType::VIDEO:
-            clock = &m_videoClock;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &m_externalClock;
-            break;
-    }
-    
-    if (!clock) {
-        return 0.0;
-    }
-    
-    // 如果时钟暂停,直接返回pts
-    if (clock->paused) {
-        return clock->pts;
-    }
-    
-    double time = getCurrentTime();
-    // 计算当前时钟时间 = pts + (当前时间 - 上次更新时间) * 速度
-    // return clock->ptsDrift + (time - clock->lastUpdated) * clock->speed;
-
-    return clock->ptsDrift + time + (time - clock->lastUpdated) * (1.0 - clock->speed);
-}
-
-// 设置时钟
-void SynchronizerV2::setClock(ClockType type, double pts, int serial) {
-    setClockAt(type, pts, serial, getCurrentTime());
-}
-
-// 在指定时间设置时钟
-void SynchronizerV2::setClockAt(ClockType type, double pts, int serial, double time) {
-    std::lock_guard<std::mutex> lock(m_clockMutex);
-    if (m_paused) {
-        qDebug() << "setClockAt-->:" << (int) type << pts << serial << time;
-    }
-    Clock* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &m_audioClock;
-            break;
-        case ClockType::VIDEO:
-            clock = &m_videoClock;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &m_externalClock;
-            break;
-    }
-    
-    if (!clock) {
-        return;
-    }
-    
-    // 更新时钟
-    clock->pts = pts;
-    clock->lastUpdated = time;
-    clock->ptsDrift = clock->pts - time;
-    clock->serial = serial;
-    
-    // 更新统计信息
-    //updateStats();
-}
-
-// 设置时钟速度
-void SynchronizerV2::setClockSpeed(ClockType type, double speed) {
-    //std::lock_guard<std::mutex> lock(m_clockMutex);
-
-    Clock* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &m_audioClock;
-            break;
-        case ClockType::VIDEO:
-            clock = &m_videoClock;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &m_externalClock;
-            break;
-    }
-    
-    if (!clock) {
-        return;
-    }
-    
-    // 设置时钟速度前先更新当前pts
-    double pts = getClock(type);
-    clock->pts = pts;
-    clock->lastUpdated = getCurrentTime();
-    clock->ptsDrift = clock->pts - clock->lastUpdated;
-    clock->speed = speed;
-}
-
-// 获取主时钟类型
-ClockType SynchronizerV2::getMasterClockType() const {
-    // 根据同步策略和流信息确定主时钟类型
-    switch (m_syncStrategy) {
-        case SyncStrategy::AUDIO_MASTER:
-            if (m_hasAudio) {
-                return ClockType::AUDIO;
-            }
-            break;
-        case SyncStrategy::VIDEO_MASTER:
-            if (m_hasVideo) {
-                return ClockType::VIDEO;
-            }
-            break;
-        case SyncStrategy::EXTERNAL_MASTER:
-            return ClockType::EXTERNAL;
-    }
-    
-    // 如果首选的主时钟不可用,则按优先级选择
-    if (m_hasAudio) {
-        return ClockType::AUDIO;
-    } else if (m_hasVideo) {
-        return ClockType::VIDEO;
-    } else {
-        return ClockType::EXTERNAL;
-    }
-}
-
-// 获取主时钟值
-double SynchronizerV2::getMasterClock() const {
-    ClockType masterType = getMasterClockType();
-    return getClock(masterType);
-}
-
-// 计算视频帧目标延迟
-double SynchronizerV2::computeTargetDelay(double frameDuration, double videoPts) const {
-    double delay = 0.0;
-    
-    // 如果不是视频主时钟,则需要与主时钟同步
-    if (getMasterClockType() != ClockType::VIDEO) {
-        // 计算视频时钟与主时钟的差异
-        double diff = videoPts - getMasterClock();
-        
-        // 如果差异太大(超过noSyncThreshold),则不进行同步
-        if (std::fabs(diff) < m_config.noSyncThreshold) {
-            // 如果视频落后于主时钟或超前太多,则调整延迟
-            if (diff <= -m_config.syncThresholdMin) {  // 视频落后,减少延迟
-                delay = std::max(0.0, delay + diff);
-            } else if (diff >= m_config.syncThresholdMax) {  // 视频超前太多,增加延迟
-                delay = delay + diff;
-            } else if (diff >= m_config.syncThresholdMin) {  // 视频略微超前,平滑调整
-                delay = (delay + diff) * 2.0 / 3.0;
-            }
-        }
-    }
-    
-    // 添加帧持续时间
-    delay += frameDuration;
-    
-    return delay;
-}
-
-// 同步视频帧
-FrameDecision SynchronizerV2::synchronizeVideo(double pts, int serial, double duration) const {
-    FrameDecision decision;
-    
-    // 如果没有视频流,直接显示
-    if (!m_hasVideo) {
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = 0.0;
-        decision.reason = "No video stream";
-        return decision;
-    }
-    
-    // 如果暂停,直接显示
-    if (m_paused) {
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = 0.0;
-        decision.reason = "Playback paused";
-        return decision;
-    }
-    
-    // 计算目标延迟
-    double delay = computeTargetDelay(duration, pts);
-    
-    // 获取当前时间
-    double time = getCurrentTime();
-    
-    // 计算实际延迟(相对于上一帧的显示时间)
-    double actualDelay = time - m_frameTimer;
-    
-    // 计算同步误差
-    double syncError = 0.0;
-    if (getMasterClockType() != ClockType::VIDEO) {
-        syncError = pts - getMasterClock();
-    }
-    
-    // 更新帧计时器
-    m_frameTimer += delay;
-    
-    // 如果实际延迟大于两倍目标延迟,说明系统可能卡顿,重置帧计时器
-    if (actualDelay > 2.0 * delay) {
-        m_frameTimer = time;
-    }
-    
-    // 决定帧处理动作
-    if (time < m_frameTimer) {
-        // 当前时间小于下一帧显示时间,需要等待
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = m_frameTimer - time;  // 需要等待的时间
-        decision.syncError = syncError;
-        decision.reason = "Wait for next frame time";
-    } else {
-        // 当前时间已经超过下一帧显示时间
-        
-        // 如果延迟太大,可能需要丢帧
-        if (time > m_frameTimer + m_config.frameDropThreshold && getMasterClockType() != ClockType::VIDEO) {
-            decision.action = FrameAction::DROP;
-            decision.delay = 0.0;
-            decision.syncError = syncError;
-            decision.reason = "Frame too late, dropping";
-            
-            // 通知帧丢弃
-            notifyFrameDrop(ClockType::VIDEO, static_cast<int64_t>(pts * 1000));
-        } else {
-            // 正常显示
-            decision.action = FrameAction::DISPLAY;
-            decision.delay = 0.0;  // 立即显示
-            decision.syncError = syncError;
-            decision.reason = "Display immediately";
-        }
-    }
-    
-    // 通知同步误差
-    if (std::fabs(syncError) > m_config.syncThresholdMin) {
-        notifySyncError(syncError, decision.reason);
-    }
-    
-    return decision;
-}
-
-// 同步音频
-int SynchronizerV2::synchronizeAudio(short* samples, int samplesSize, double pts) {
-    // 如果没有音频流或者音频是主时钟,则不需要同步
-    if (!m_hasAudio || getMasterClockType() == ClockType::AUDIO || m_paused) {
-        return samplesSize;
-    }
-    
-    // 计算音频与主时钟的差异
-    double diff = getClock(ClockType::AUDIO) - getMasterClock();
-    
-    // 如果差异太大,则不进行同步
-    if (std::fabs(diff) > m_config.noSyncThreshold) {
-        // 重置音频差异累积
-        m_audioDiffCum = 0.0;
-        m_audioDiffAvgCount = 0;
-        return samplesSize;
-    }
-    
-    // 更新音频差异平均值
-    m_audioDiffCum = diff + m_audioDiffCum * (1.0 - m_config.audioDiffAvgCoef);
-    if (m_audioDiffAvgCount < m_config.audioDiffAvgCount) {
-        m_audioDiffAvgCount++;
-    } else {
-        double avgDiff = m_audioDiffCum / m_audioDiffAvgCount;
-        
-        // 根据差异调整音频样本数量
-        if (std::fabs(avgDiff) >= m_config.audioDiffThreshold) {
-            int wantedSamples = samplesSize;
-            int minSamples = samplesSize * (1.0 - m_config.audioDiffThreshold);
-            int maxSamples = samplesSize * (1.0 + m_config.audioDiffThreshold);
-            
-            // 计算调整后的样本数量
-            wantedSamples += static_cast<int>(diff * samplesSize);
-            wantedSamples = std::max(minSamples, std::min(wantedSamples, maxSamples));
-            
-            return wantedSamples;
-        }
-    }
-    
-    return samplesSize;
-}
-
-// 设置配置
-void SynchronizerV2::setConfig(const SyncConfigV2& config) {
-    m_config = config;
-    m_syncStrategy = config.strategy;
-}
-
-// 获取配置
-SyncConfigV2 SynchronizerV2::getConfig() const {
-    return m_config;
-}
-
-// 设置同步策略
-void SynchronizerV2::setSyncStrategy(SyncStrategy strategy) {
-    // 检查策略是否可用
-    if (strategy == SyncStrategy::AUDIO_MASTER && !m_hasAudio) {
-        if (m_hasVideo) {
-            strategy = SyncStrategy::VIDEO_MASTER;
-        } else {
-            strategy = SyncStrategy::EXTERNAL_MASTER;
-        }
-    } else if (strategy == SyncStrategy::VIDEO_MASTER && !m_hasVideo) {
-        if (m_hasAudio) {
-            strategy = SyncStrategy::AUDIO_MASTER;
-        } else {
-            strategy = SyncStrategy::EXTERNAL_MASTER;
-        }
-    }
-    
-    m_syncStrategy = strategy;
-    m_config.strategy = strategy;
-}
-
-// 获取同步策略
-SyncStrategy SynchronizerV2::getSyncStrategy() const {
-    return m_syncStrategy;
-}
-
-// 设置播放速度
-void SynchronizerV2::setPlaybackSpeed(double speed) {
-    // 限制速度范围
-    speed = std::max(m_config.clockSpeedMin, std::min(speed, m_config.clockSpeedMax));
-    
-    // 如果速度没有变化,则不需要更新
-    if (std::fabs(speed - m_playbackSpeed) < 0.01) {
-        return;
-    }
-    
-    // 更新播放速度
-    m_playbackSpeed = speed;
-    
-    // 更新所有时钟的速度
-    setClockSpeed(ClockType::AUDIO, speed);
-    setClockSpeed(ClockType::VIDEO, speed);
-    setClockSpeed(ClockType::EXTERNAL, speed);
-    
-    // 更新统计信息
-    std::lock_guard<std::mutex> lock(m_statsMutex);
-    m_stats.playbackSpeed = speed;
-}
-
-// 获取播放速度
-double SynchronizerV2::getPlaybackSpeed() const {
-    return m_playbackSpeed;
-}
-
-// 获取统计信息
-SyncStatsV2 SynchronizerV2::getStats() const {
-    std::lock_guard<std::mutex> lock(m_statsMutex);
-    return m_stats;
-}
-
-// 设置同步错误回调
-void SynchronizerV2::setSyncErrorCallback(const SyncErrorCallback& callback) {
-    std::lock_guard<std::mutex> lock(m_callbackMutex);
-    m_syncErrorCallback = callback;
-}
-
-// 设置帧丢弃回调
-void SynchronizerV2::setFrameDropCallback(const FrameDropCallback& callback) {
-    std::lock_guard<std::mutex> lock(m_callbackMutex);
-    m_frameDropCallback = callback;
-}
-
-// 获取调试信息
-std::string SynchronizerV2::getDebugInfo() const {
-    std::stringstream ss;
-    ss.precision(4);
-    // 获取当前状态
-    bool initialized = m_initialized;
-    bool running = m_running;
-    bool paused = m_paused;
-    
-    // 获取时钟值
-    double audioClock = getClock(ClockType::AUDIO);
-    double videoClock = getClock(ClockType::VIDEO);
-    double externalClock = getClock(ClockType::EXTERNAL);
-    double masterClock = getMasterClock();
-    
-    // 获取同步策略
-    SyncStrategy strategy = getSyncStrategy();
-    std::string strategyStr;
-    switch (strategy) {
-        case SyncStrategy::AUDIO_MASTER:
-            strategyStr = "AUDIO_MASTER";
-            break;
-        case SyncStrategy::VIDEO_MASTER:
-            strategyStr = "VIDEO_MASTER";
-            break;
-        case SyncStrategy::EXTERNAL_MASTER:
-            strategyStr = "EXTERNAL_MASTER";
-            break;
-    }
-    
-    // 获取主时钟类型
-    ClockType masterType = getMasterClockType();
-    std::string masterTypeStr;
-    switch (masterType) {
-        case ClockType::AUDIO:
-            masterTypeStr = "AUDIO";
-            break;
-        case ClockType::VIDEO:
-            masterTypeStr = "VIDEO";
-            break;
-        case ClockType::EXTERNAL:
-            masterTypeStr = "EXTERNAL";
-            break;
-    }
-    
-    // 获取统计信息
-    SyncStatsV2 stats = getStats();
-    
-    // 构建调试信息
-    ss << "SynchronizerV2 Debug Info:\n";
-    ss << "  State: " << (initialized ? "Initialized" : "Not Initialized")
-       << ", " << (running ? "Running" : "Stopped")
-       << ", " << (paused ? "Paused" : "Playing") << "\n";
-    ss << "  Streams: " << (m_hasAudio ? "Audio" : "No Audio")
-       << ", " << (m_hasVideo ? "Video" : "No Video") << "\n";
-    ss << "  Sync Strategy: " << strategyStr << "\n";
-    ss << "  CurrentTime: " << getCurrentTime() << "\n";
-    ss << "  Master Clock Type: " << masterTypeStr << "\n";
-    ss << "  Clocks (seconds):\n";
-    ss << "    Audio: " << audioClock << "\n";
-    ss << "    Video: " << videoClock << "\n";
-    ss << "    External: " << externalClock << "\n";
-    ss << "    Master: " << masterClock << "\n";
-    ss << "  Playback Speed: " << m_playbackSpeed << "\n";
-    ss << "  Stats:\n";
-    ss << "    Audio-Video Sync Error: " << stats.audioVideoSyncError << " seconds\n";
-    ss << "    Avg Sync Error: " << stats.avgSyncError << " seconds\n";
-    ss << "    Max Sync Error: " << stats.maxSyncError << " seconds\n";
-    ss << "    Dropped Frames: " << stats.droppedFrames << "\n";
-    ss << "    Duplicated Frames: " << stats.duplicatedFrames << "\n";
-    
-    return ss.str();
-}
-
-// 初始化时钟
-void SynchronizerV2::initClock(Clock& clock, int serial) {
-    clock.pts = 0.0;
-    clock.ptsDrift = 0.0;
-    clock.lastUpdated = getCurrentTime();
-    clock.speed = m_playbackSpeed;
-    clock.serial = serial;
-    clock.paused = false;
-    clock.queueSerial = serial;
-}
-
-// 将时钟同步到从属时钟
-void SynchronizerV2::syncClockToSlave(Clock& c, const Clock& slave) {
-    double clockDiff = getClock(ClockType::EXTERNAL) - getClock(ClockType::AUDIO);
-    double correction = 0.0;
-    
-    // 根据差异调整时钟速度
-    if (std::fabs(clockDiff) < m_config.noSyncThreshold) {
-        if (clockDiff <= -m_config.syncThresholdMin) {
-            // 外部时钟落后,加速
-            correction = -m_config.clockSpeedStep;
-        } else if (clockDiff >= m_config.syncThresholdMin) {
-            // 外部时钟超前,减速
-            correction = m_config.clockSpeedStep;
-        }
-        
-        // 应用速度调整
-        c.speed = m_playbackSpeed + correction;
-        c.speed = std::max(m_config.clockSpeedMin, std::min(c.speed, m_config.clockSpeedMax));
-    }
-}
-
-// 更新外部时钟
-void SynchronizerV2::updateExternalClock() {
-    // 更新外部时钟,使其与主时钟同步
-    if (getMasterClockType() != ClockType::EXTERNAL) {
-        double masterClock = getMasterClock();
-        setClock(ClockType::EXTERNAL, masterClock, m_externalSerial);
-    }
-}
-
-// 检查外部时钟速度
-void SynchronizerV2::checkExternalClockSpeed() {
-    if (m_hasAudio && getMasterClockType() == ClockType::EXTERNAL) {
-        // 将外部时钟同步到音频时钟
-        syncClockToSlave(m_externalClock, m_audioClock);
-    } else if (m_hasVideo && getMasterClockType() == ClockType::EXTERNAL) {
-        // 将外部时钟同步到视频时钟
-        syncClockToSlave(m_externalClock, m_videoClock);
-    }
-}
-
-// 获取当前时间(秒)
-double SynchronizerV2::getCurrentTime() const
-{
-    return av_gettime_relative() / 1000000.0;
-}
-
-// 更新统计信息
-void SynchronizerV2::updateStats() {
-    std::lock_guard<std::mutex> lock(m_statsMutex);
-    
-    // 更新时钟值
-    m_stats.audioClock = getClock(ClockType::AUDIO);
-    m_stats.videoClock = getClock(ClockType::VIDEO);
-    m_stats.externalClock = getClock(ClockType::EXTERNAL);
-    m_stats.masterClock = getMasterClock();
-    
-    // 计算音视频同步误差
-    if (m_hasAudio && m_hasVideo) {
-        m_stats.audioVideoSyncError = m_stats.audioClock - m_stats.videoClock;
-        
-        // 更新平均同步误差
-        double absError = std::fabs(m_stats.audioVideoSyncError);
-        m_stats.avgSyncError = (m_stats.avgSyncError * 0.9) + (absError * 0.1);
-        
-        // 更新最大同步误差
-        if (absError > m_stats.maxSyncError) {
-            m_stats.maxSyncError = absError;
-        }
-    }
-    
-    // 更新播放速度
-    m_stats.playbackSpeed = m_playbackSpeed;
-}
-
-// 通知同步错误
-void SynchronizerV2::notifySyncError(double error, const std::string& reason) const {
-    std::lock_guard<std::mutex> lock(m_callbackMutex);
-    if (m_syncErrorCallback) {
-        m_syncErrorCallback(error, reason);
-    }
-}
-
-// 通知帧丢弃
-void SynchronizerV2::notifyFrameDrop(ClockType type, int64_t pts) const {
-    std::lock_guard<std::mutex> lock(m_callbackMutex);
-    if (m_frameDropCallback) {
-        m_frameDropCallback(type, pts);
-    }
-    
-    // 更新统计信息
-    std::lock_guard<std::mutex> statsLock(m_statsMutex);
-    m_stats.droppedFrames++;
-}
-
-} // namespace utils
-} // namespace av

+ 0 - 239
AV/code/utils/utils_synchronizer_v2.h

@@ -1,239 +0,0 @@
-#ifndef AV_UTILS_SYNCHRONIZER_V2_H
-#define AV_UTILS_SYNCHRONIZER_V2_H
-
-#pragma once
-
-#include "../base/types.h"
-#include <atomic>
-#include <chrono>
-#include <deque>
-#include <functional>
-#include <limits>
-#include <memory>
-#include <mutex>
-#include <string>
-
-extern "C" {
-#include <libavutil/avutil.h>
-#include <libavutil/time.h>
-}
-
-namespace av {
-namespace utils {
-
-// 同步策略枚举
-enum class SyncStrategy {
-    AUDIO_MASTER,    // 音频作为主时钟源
-    VIDEO_MASTER,    // 视频作为主时钟源
-    EXTERNAL_MASTER  // 外部时钟作为主时钟源
-};
-
-// 时钟类型枚举
-enum class ClockType {
-    AUDIO,      // 音频时钟
-    VIDEO,      // 视频时钟
-    EXTERNAL    // 外部时钟
-};
-
-// 帧处理决策枚举
-enum class FrameAction {
-    DISPLAY,    // 显示帧
-    DROP,       // 丢弃帧
-    DUPLICATE,  // 重复帧
-    WAIT        // 等待
-};
-
-// 帧决策结构体
-struct FrameDecision {
-    FrameAction action = FrameAction::DISPLAY;
-    double delay = 0.0;        // 延迟时间(秒)
-    double syncError = 0.0;    // 同步误差(秒)
-    std::string reason;        // 决策原因
-};
-
-// 同步器配置结构体
-struct SyncConfigV2 {
-    SyncStrategy strategy = SyncStrategy::AUDIO_MASTER;  // 同步策略
-    
-    // 同步阈值(秒)
-    double syncThresholdMin = 0.04;  // 最小同步阈值
-    double syncThresholdMax = 0.1;   // 最大同步阈值
-    
-    // 帧处理阈值
-    double frameDropThreshold = 0.1;  // 丢帧阈值
-    double frameDupThreshold = 0.1;   // 重复帧阈值
-    
-    // 音频同步参数
-    double audioDiffThreshold = 0.1;  // 音频差异阈值
-    double audioDiffAvgCoef = 0.01;   // 音频差异平均系数
-    int audioDiffAvgCount = 20;       // 音频差异平均计数
-    
-    // 时钟速度调整参数
-    double clockSpeedMin = 0.9;       // 最小时钟速度
-    double clockSpeedMax = 1.1;       // 最大时钟速度
-    double clockSpeedStep = 0.001;    // 时钟速度调整步长
-    
-    // 缓冲区控制参数
-    int minFramesForSync = 2;         // 同步所需最小帧数
-    int maxFramesForSync = 10;        // 同步所需最大帧数
-    
-    // 无同步阈值(秒)
-    double noSyncThreshold = 10.0;    // 超过此阈值不进行同步
-};
-
-// 同步器统计信息结构体
-struct SyncStatsV2 {
-    double audioClock = 0.0;           // 音频时钟(秒)
-    double videoClock = 0.0;           // 视频时钟(秒)
-    double externalClock = 0.0;        // 外部时钟(秒)
-    double masterClock = 0.0;          // 主时钟(秒)
-    
-    double audioVideoSyncError = 0.0;  // 音视频同步误差(秒)
-    double avgSyncError = 0.0;         // 平均同步误差(秒)
-    double maxSyncError = 0.0;         // 最大同步误差(秒)
-    
-    int64_t droppedFrames = 0;         // 丢弃的帧数
-    int64_t duplicatedFrames = 0;       // 重复的帧数
-    
-    double playbackSpeed = 1.0;        // 播放速度
-};
-
-// 时钟结构体(基于ffplay.c中的Clock结构体)
-struct Clock {
-    double pts = 0.0;           // 时钟基准
-    double ptsDrift = 0.0;       // 时钟基准减去更新时间
-    double lastUpdated = 0.0;    // 最后更新时间
-    double speed = 1.0;          // 时钟速度
-    int serial = -1;             // 时钟基于此序列号的包
-    bool paused = false;         // 是否暂停
-    int queueSerial = -1;        // 当前包队列序列号,用于检测过时的时钟
-};
-
-// 前向声明
-namespace av {
-namespace player {
-class PlayerCoreV2;
-}
-}
-
-// 同步器类(基于ffplay.c实现)
-class SynchronizerV2 {
-    friend class av::player::PlayerCoreV2; // 声明PlayerCoreV2为友元类
-public:
-    // 构造函数和析构函数
-    explicit SynchronizerV2(const SyncConfigV2& config = SyncConfigV2());
-    ~SynchronizerV2();
-    
-    // 初始化和清理
-    ErrorCode initialize();
-    void close();
-    
-    // 控制接口
-    ErrorCode start();
-    ErrorCode stop();
-    ErrorCode pause();
-    ErrorCode resume();
-    ErrorCode reset();
-    
-    // 流信息设置
-    void setStreamInfo(bool hasAudio, bool hasVideo);
-    
-    // 时钟操作
-    double getClock(ClockType type) const;
-    void setClock(ClockType type, double pts, int serial);
-    void setClockAt(ClockType type, double pts, int serial, double time);
-    void setClockSpeed(ClockType type, double speed);
-    
-    // 主时钟操作
-    ClockType getMasterClockType() const;
-    double getMasterClock() const;
-    
-    // 同步操作
-    double computeTargetDelay(double frameDuration, double videoPts) const;
-    FrameDecision synchronizeVideo(double pts, int serial, double duration) const;
-    int synchronizeAudio(short* samples, int samplesSize, double pts);
-    
-    // 配置操作
-    void setConfig(const SyncConfigV2& config);
-    SyncConfigV2 getConfig() const;
-    void setSyncStrategy(SyncStrategy strategy);
-    SyncStrategy getSyncStrategy() const;
-    
-    // 播放速度控制
-    void setPlaybackSpeed(double speed);
-    double getPlaybackSpeed() const;
-    
-    // 统计信息
-    SyncStatsV2 getStats() const;
-    
-    // 回调设置
-    using SyncErrorCallback = std::function<void(double error, const std::string& reason)>;
-    using FrameDropCallback = std::function<void(ClockType type, int64_t pts)>;
-    
-    void setSyncErrorCallback(const SyncErrorCallback& callback);
-    void setFrameDropCallback(const FrameDropCallback& callback);
-    
-    // 调试信息
-    std::string getDebugInfo() const;
-    
-private:
-    // 内部时钟操作
-    void initClock(Clock& clock, int serial);
-    void syncClockToSlave(Clock& c, const Clock& slave);
-    void updateExternalClock();
-    void checkExternalClockSpeed();
-    
-    // 内部状态
-    std::atomic<bool> m_initialized{false};
-    std::atomic<bool> m_running{false};
-    std::atomic<bool> m_paused{false};
-    
-    // 配置
-    SyncConfigV2 m_config;
-    std::atomic<SyncStrategy> m_syncStrategy{SyncStrategy::AUDIO_MASTER};
-    
-    // 时钟
-    mutable std::mutex m_clockMutex;
-    Clock m_audioClock;
-    Clock m_videoClock;
-    Clock m_externalClock;
-    
-    // 流信息
-    std::atomic<bool> m_hasAudio{false};
-    std::atomic<bool> m_hasVideo{false};
-    
-    // 序列号
-    std::atomic<int> m_audioSerial{0};
-    std::atomic<int> m_videoSerial{0};
-    std::atomic<int> m_externalSerial{0};
-    
-    // 音频同步
-    double m_audioDiffCum{0.0};       // 用于音视频差异平均计算
-    int m_audioDiffAvgCount{0};
-    
-    // 播放控制
-    std::atomic<double> m_playbackSpeed{1.0};
-    
-    // 统计信息
-    mutable std::mutex m_statsMutex;
-    mutable SyncStatsV2 m_stats;
-    
-    // 回调
-    mutable std::mutex m_callbackMutex;
-    SyncErrorCallback m_syncErrorCallback;
-    FrameDropCallback m_frameDropCallback;
-    
-    // 帧计时器
-    mutable double m_frameTimer{0.0};
-    
-    // 辅助函数
-    double getCurrentTime() const;
-    void updateStats();
-    void notifySyncError(double error, const std::string& reason) const;
-    void notifyFrameDrop(ClockType type, int64_t pts) const;
-};
-
-} // namespace utils
-} // namespace av
-
-#endif // AV_UTILS_SYNCHRONIZER_V2_H

+ 0 - 849
AV/code/utils/utils_thread_pool.cpp

@@ -1,849 +0,0 @@
-#include "utils_thread_pool.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <sstream>
-#include <thread>
-#include <chrono>
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <pthread.h>
-#include <sys/prctl.h>
-#endif
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-// ThreadPool 实现
-ThreadPool::ThreadPool(const ThreadPoolConfig& config)
-    : config_(config)
-    , state_(ThreadPoolState::STOPPED)
-    , shutdown_(false)
-    , activeThreads_(0)
-    , idleThreads_(0)
-    , totalSubmittedTasks_(0)
-    , totalCompletedTasks_(0)
-    , totalFailedTasks_(0)
-    , totalCancelledTasks_(0)
-    , startTime_(std::chrono::steady_clock::now()) {
-    
-    // 验证配置
-    if (config_.minThreads > config_.maxThreads) {
-        config_.minThreads = config_.maxThreads;
-    }
-    
-    if (config_.minThreads == 0) {
-        config_.minThreads = 1;
-    }
-    
-    stats_.startTime = startTime_;
-}
-
-ThreadPool::~ThreadPool() {
-    shutdown(std::chrono::milliseconds(1000));
-}
-
-ErrorCode ThreadPool::initialize() {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    
-    if (state_.load() != ThreadPoolState::STOPPED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    try {
-        // 预分配线程容器
-        workers_.reserve(config_.maxThreads);
-        
-        Logger::instance().infof("Thread pool initialized with {} min threads, {} max threads", 
-                config_.minThreads, config_.maxThreads);
-        
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        Logger::instance().errorf("Failed to initialize thread pool: %s", e.what());
-        return ErrorCode::INITIALIZATION_FAILED;
-    }
-}
-
-ErrorCode ThreadPool::start() {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    
-    if (state_.load() == ThreadPoolState::RUNNING) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    if (state_.load() != ThreadPoolState::STOPPED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    state_.store(ThreadPoolState::STARTING);
-    shutdown_.store(false);
-    
-    try {
-        // 创建最小数量的工作线程
-        for (size_t i = 0; i < config_.minThreads; ++i) {
-            workers_.emplace_back(&ThreadPool::workerThread, this, i);
-        }
-        
-        activeThreads_.store(config_.minThreads);
-        idleThreads_.store(config_.minThreads);
-        
-        state_.store(ThreadPoolState::RUNNING);
-        startTime_ = std::chrono::steady_clock::now();
-        stats_.startTime = startTime_;
-        
-        Logger::instance().infof("Thread pool started with {} threads", config_.minThreads);
-        
-        return ErrorCode::SUCCESS;
-    } catch (const std::exception& e) {
-        Logger::instance().errorf("Failed to start thread pool: %s", e.what());
-        state_.store(ThreadPoolState::STOPPED);
-        return ErrorCode::OPERATION_FAILED;
-    }
-}
-
-ErrorCode ThreadPool::stop(bool waitForCompletion) {
-    if (state_.load() == ThreadPoolState::STOPPED) {
-        return ErrorCode::SUCCESS;
-    }
-    
-    state_.store(ThreadPoolState::STOPPING);
-    
-    if (waitForCompletion) {
-        waitForAllTasks();
-    } else {
-        clearPendingTasks();
-    }
-    
-    // 通知所有工作线程停止
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        shutdown_.store(true);
-    }
-    queueCondition_.notify_all();
-    
-    // 等待所有线程结束
-    for (auto& worker : workers_) {
-        if (worker.joinable()) {
-            worker.join();
-        }
-    }
-    
-    workers_.clear();
-    activeThreads_.store(0);
-    idleThreads_.store(0);
-    state_.store(ThreadPoolState::STOPPED);
-    
-    Logger::instance().info("Thread pool stopped");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode ThreadPool::pause() {
-    if (state_.load() != ThreadPoolState::RUNNING) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    state_.store(ThreadPoolState::PAUSED);
-    Logger::instance().info("Thread pool paused");
-    
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode ThreadPool::resume() {
-    if (state_.load() != ThreadPoolState::PAUSED) {
-        return ErrorCode::INVALID_STATE;
-    }
-    
-    state_.store(ThreadPoolState::RUNNING);
-    pauseCondition_.notify_all();
-    
-    Logger::instance().info("Thread pool resumed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode ThreadPool::shutdown(std::chrono::milliseconds timeout) {
-    auto startTime = std::chrono::steady_clock::now();
-    
-    // 首先尝试正常停止
-    ErrorCode result = stop(false);
-    
-    // 等待指定时间
-    while (state_.load() != ThreadPoolState::STOPPED && 
-           std::chrono::steady_clock::now() - startTime < timeout) {
-        std::this_thread::sleep_for(std::chrono::milliseconds(10));
-    }
-    
-    if (state_.load() != ThreadPoolState::STOPPED) {
-        Logger::instance().info("Thread pool shutdown timeout, forcing termination");
-        // 强制终止(在实际实现中可能需要更复杂的逻辑)
-        state_.store(ThreadPoolState::STOPPED);
-    }
-    
-    return result;
-}
-
-void ThreadPool::submitTask(std::shared_ptr<Task> task) {
-    if (!task || state_.load() == ThreadPoolState::STOPPED) {
-        return;
-    }
-    
-    {
-        std::lock_guard<std::mutex> lock(queueMutex_);
-        
-        if (config_.enablePriority) {
-            taskQueue_.push(task);
-        } else {
-            normalQueue_.push(task);
-        }
-        
-        // 记录任务
-        {
-            std::lock_guard<std::mutex> tasksLock(tasksMutex_);
-            activeTasks_[task->getId()] = task;
-        }
-        
-        totalSubmittedTasks_++;
-    }
-    
-    // 检查是否需要创建新线程
-    if (shouldCreateNewThread()) {
-        adjustThreadPoolSize();
-    }
-    
-    queueCondition_.notify_one();
-}
-
-bool ThreadPool::cancelTask(uint64_t taskId) {
-    std::lock_guard<std::mutex> lock(tasksMutex_);
-    
-    auto it = activeTasks_.find(taskId);
-    if (it != activeTasks_.end()) {
-        it->second->cancel();
-        activeTasks_.erase(it);
-        totalCancelledTasks_++;
-        return true;
-    }
-    
-    return false;
-}
-
-bool ThreadPool::isTaskCompleted(uint64_t taskId) const {
-    std::lock_guard<std::mutex> lock(tasksMutex_);
-    
-    auto it = completedTasks_.find(taskId);
-    return it != completedTasks_.end();
-}
-
-TaskStatus ThreadPool::getTaskStatus(uint64_t taskId) const {
-    std::lock_guard<std::mutex> lock(tasksMutex_);
-    
-    // 检查活跃任务
-    auto activeIt = activeTasks_.find(taskId);
-    if (activeIt != activeTasks_.end()) {
-        return activeIt->second->getStatus();
-    }
-    
-    // 检查已完成任务
-    auto completedIt = completedTasks_.find(taskId);
-    if (completedIt != completedTasks_.end()) {
-        return completedIt->second->status;
-    }
-    
-    return TaskStatus::PENDING;
-}
-
-std::shared_ptr<TaskInfo> ThreadPool::getTaskInfo(uint64_t taskId) const {
-    std::lock_guard<std::mutex> lock(tasksMutex_);
-    
-    // 检查活跃任务
-    auto activeIt = activeTasks_.find(taskId);
-    if (activeIt != activeTasks_.end()) {
-        return activeIt->second->getInfo();
-    }
-    
-    // 检查已完成任务
-    auto completedIt = completedTasks_.find(taskId);
-    if (completedIt != completedTasks_.end()) {
-        return completedIt->second;
-    }
-    
-    return nullptr;
-}
-
-std::vector<std::shared_ptr<TaskInfo>> ThreadPool::getAllTaskInfo() const {
-    std::lock_guard<std::mutex> lock(tasksMutex_);
-    
-    std::vector<std::shared_ptr<TaskInfo>> result;
-    
-    // 添加活跃任务
-    for (const auto& pair : activeTasks_) {
-        result.push_back(pair.second->getInfo());
-    }
-    
-    // 添加已完成任务
-    for (const auto& pair : completedTasks_) {
-        result.push_back(pair.second);
-    }
-    
-    return result;
-}
-
-ThreadPoolState ThreadPool::getState() const {
-    return state_.load();
-}
-
-bool ThreadPool::isRunning() const {
-    return state_.load() == ThreadPoolState::RUNNING;
-}
-
-bool ThreadPool::isPaused() const {
-    return state_.load() == ThreadPoolState::PAUSED;
-}
-
-bool ThreadPool::isStopped() const {
-    return state_.load() == ThreadPoolState::STOPPED;
-}
-
-ThreadPoolStats ThreadPool::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    ThreadPoolStats currentStats = stats_;
-    currentStats.totalThreads = workers_.size();
-    currentStats.activeThreads = activeThreads_.load();
-    currentStats.idleThreads = idleThreads_.load();
-    
-    {
-        std::lock_guard<std::mutex> queueLock(queueMutex_);
-        if (config_.enablePriority) {
-            currentStats.pendingTasks = taskQueue_.size();
-        } else {
-            currentStats.pendingTasks = normalQueue_.size();
-        }
-    }
-    
-    {
-        std::lock_guard<std::mutex> tasksLock(tasksMutex_);
-        currentStats.runningTasks = activeTasks_.size();
-    }
-    
-    currentStats.completedTasks = totalCompletedTasks_.load();
-    currentStats.failedTasks = totalFailedTasks_.load();
-    currentStats.cancelledTasks = totalCancelledTasks_.load();
-    
-    return currentStats;
-}
-
-size_t ThreadPool::getActiveThreadCount() const {
-    return activeThreads_.load();
-}
-
-size_t ThreadPool::getIdleThreadCount() const {
-    return idleThreads_.load();
-}
-
-size_t ThreadPool::getPendingTaskCount() const {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    
-    if (config_.enablePriority) {
-        return taskQueue_.size();
-    } else {
-        return normalQueue_.size();
-    }
-}
-
-size_t ThreadPool::getCompletedTaskCount() const {
-    return totalCompletedTasks_.load();
-}
-
-void ThreadPool::setConfig(const ThreadPoolConfig& config) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_ = config;
-    
-    // 验证配置
-    if (config_.minThreads > config_.maxThreads) {
-        config_.minThreads = config_.maxThreads;
-    }
-    
-    if (config_.minThreads == 0) {
-        config_.minThreads = 1;
-    }
-}
-
-ThreadPoolConfig ThreadPool::getConfig() const {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    return config_;
-}
-
-ErrorCode ThreadPool::resizeThreadPool(size_t newSize) {
-    if (newSize == 0) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    std::lock_guard<std::mutex> lock(configMutex_);
-    
-    if (newSize < config_.minThreads) {
-        config_.minThreads = newSize;
-    }
-    
-    if (newSize > config_.maxThreads) {
-        config_.maxThreads = newSize;
-    }
-    
-    adjustThreadPoolSize();
-    
-    Logger::instance().infof("Thread pool resized to {} threads", newSize);
-    return ErrorCode::SUCCESS;
-}
-
-void ThreadPool::setThreadNamePrefix(const std::string& prefix) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.threadNamePrefix = prefix;
-}
-
-void ThreadPool::waitForAllTasks() {
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    completionCondition_.wait(lock, [this] {
-        bool queueEmpty = config_.enablePriority ? taskQueue_.empty() : normalQueue_.empty();
-        bool noActiveTasks;
-        {
-            std::lock_guard<std::mutex> tasksLock(tasksMutex_);
-            noActiveTasks = activeTasks_.empty();
-        }
-        return queueEmpty && noActiveTasks;
-    });
-}
-
-bool ThreadPool::waitForAllTasks(std::chrono::milliseconds timeout) {
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    return completionCondition_.wait_for(lock, timeout, [this] {
-        bool queueEmpty = config_.enablePriority ? taskQueue_.empty() : normalQueue_.empty();
-        bool noActiveTasks;
-        {
-            std::lock_guard<std::mutex> tasksLock(tasksMutex_);
-            noActiveTasks = activeTasks_.empty();
-        }
-        return queueEmpty && noActiveTasks;
-    });
-}
-
-void ThreadPool::clearPendingTasks() {
-    std::lock_guard<std::mutex> lock(queueMutex_);
-    
-    size_t cancelledCount = 0;
-    
-    if (config_.enablePriority) {
-        while (!taskQueue_.empty()) {
-            auto task = taskQueue_.top();
-            taskQueue_.pop();
-            task->cancel();
-            cancelledCount++;
-        }
-    } else {
-        while (!normalQueue_.empty()) {
-            auto task = normalQueue_.front();
-            normalQueue_.pop();
-            task->cancel();
-            cancelledCount++;
-        }
-    }
-    
-    totalCancelledTasks_ += cancelledCount;
-    
-    Logger::instance().infof("Cleared {} pending tasks", cancelledCount);
-}
-
-// 私有方法实现
-void ThreadPool::workerThread(size_t threadIndex) {
-    // 设置线程名称
-    std::ostringstream oss;
-    oss << config_.threadNamePrefix << "-" << threadIndex;
-    setThreadName(oss.str());
-    
-    Logger::instance().debugf("Worker thread %zu started", threadIndex);
-    
-    while (!shutdown_.load()) {
-        // 处理暂停状态
-        if (state_.load() == ThreadPoolState::PAUSED) {
-            std::unique_lock<std::mutex> pauseLock(queueMutex_);
-            pauseCondition_.wait(pauseLock, [this] {
-                return state_.load() != ThreadPoolState::PAUSED || shutdown_.load();
-            });
-            continue;
-        }
-        
-        // 获取任务
-        auto task = getNextTask();
-        if (!task) {
-            continue;
-        }
-        
-        // 更新线程状态
-        idleThreads_--;
-        
-        // 执行任务
-        try {
-            task->execute();
-            totalCompletedTasks_++;
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("Task execution failed: %s", e.what());
-            totalFailedTasks_++;
-        } catch (...) {
-            Logger::instance().error("Task execution failed with unknown exception");
-            totalFailedTasks_++;
-        }
-        
-        // 移动任务到已完成列表
-        {
-            std::lock_guard<std::mutex> tasksLock(tasksMutex_);
-            auto it = activeTasks_.find(task->getId());
-            if (it != activeTasks_.end()) {
-                completedTasks_[task->getId()] = task->getInfo();
-                activeTasks_.erase(it);
-            }
-        }
-        
-        // 更新线程状态
-        idleThreads_++;
-        
-        // 通知等待的线程
-        completionCondition_.notify_all();
-        
-        // 清理旧的已完成任务
-        cleanupCompletedTasks();
-    }
-    
-    Logger::instance().debugf("Worker thread %zu stopped", threadIndex);
-}
-
-std::shared_ptr<Task> ThreadPool::getNextTask() {
-    std::unique_lock<std::mutex> lock(queueMutex_);
-    
-    // 等待任务或停止信号
-    queueCondition_.wait_for(lock, config_.keepAliveTime, [this] {
-        bool hasTask = config_.enablePriority ? !taskQueue_.empty() : !normalQueue_.empty();
-        return hasTask || shutdown_.load();
-    });
-    
-    if (shutdown_.load()) {
-        return nullptr;
-    }
-    
-    std::shared_ptr<Task> task;
-    
-    if (config_.enablePriority && !taskQueue_.empty()) {
-        task = taskQueue_.top();
-        taskQueue_.pop();
-    } else if (!config_.enablePriority && !normalQueue_.empty()) {
-        task = normalQueue_.front();
-        normalQueue_.pop();
-    }
-    
-    return task;
-}
-
-void ThreadPool::adjustThreadPoolSize() {
-    size_t currentThreads = workers_.size();
-    size_t pendingTasks = getPendingTaskCount();
-    size_t idleThreads = idleThreads_.load();
-    
-    // 决定是否需要创建新线程
-    if (shouldCreateNewThread() && currentThreads < config_.maxThreads) {
-        try {
-            workers_.emplace_back(&ThreadPool::workerThread, this, currentThreads);
-            activeThreads_++;
-            idleThreads_++;
-            
-            Logger::instance().debugf("Created new worker thread, total: %zu", workers_.size());
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("Failed to create new worker thread: %s", e.what());
-        }
-    }
-    
-    // 注意:线程销毁通常在线程自然退出时处理,这里不实现动态销毁
-}
-
-void ThreadPool::updateStatistics() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    
-    // 更新统计信息
-    auto now = std::chrono::steady_clock::now();
-    auto totalTime = std::chrono::duration_cast<std::chrono::milliseconds>(now - stats_.startTime).count();
-    
-    if (totalCompletedTasks_.load() > 0) {
-        stats_.averageExecutionTime = static_cast<double>(totalTime) / totalCompletedTasks_.load();
-    }
-}
-
-void ThreadPool::cleanupCompletedTasks() {
-    std::lock_guard<std::mutex> lock(tasksMutex_);
-    
-    // 保持最近的1000个已完成任务
-    const size_t maxCompletedTasks = 1000;
-    
-    if (completedTasks_.size() > maxCompletedTasks) {
-        auto it = completedTasks_.begin();
-        std::advance(it, completedTasks_.size() - maxCompletedTasks);
-        completedTasks_.erase(completedTasks_.begin(), it);
-    }
-}
-
-bool ThreadPool::shouldCreateNewThread() const {
-    size_t currentThreads = workers_.size();
-    size_t pendingTasks = getPendingTaskCount();
-    size_t idleThreads = idleThreads_.load();
-    
-    return currentThreads < config_.maxThreads && 
-           pendingTasks > idleThreads && 
-           pendingTasks > 0;
-}
-
-bool ThreadPool::shouldDestroyThread() const {
-    size_t currentThreads = workers_.size();
-    size_t pendingTasks = getPendingTaskCount();
-    size_t idleThreads = idleThreads_.load();
-    
-    return currentThreads > config_.minThreads && 
-           idleThreads > pendingTasks + 1;
-}
-
-void ThreadPool::setThreadName(const std::string& name) {
-#ifdef _WIN32
-    // Windows 线程命名
-    std::wstring wname(name.begin(), name.end());
-    SetThreadDescription(GetCurrentThread(), wname.c_str());
-#elif defined(__linux__)
-    // Linux 线程命名
-    prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
-#else
-    // 其他平台暂不支持
-#endif
-}
-
-// WorkerThread 实现
-WorkerThread::WorkerThread(ThreadPool* pool, size_t index)
-    : pool_(pool)
-    , index_(index)
-    , running_(false)
-    , shouldStop_(false) {
-}
-
-WorkerThread::~WorkerThread() {
-    stop();
-    join();
-}
-
-void WorkerThread::start() {
-    if (running_.load()) {
-        return;
-    }
-    
-    shouldStop_.store(false);
-    thread_ = std::thread(&WorkerThread::run, this);
-    running_.store(true);
-}
-
-void WorkerThread::stop() {
-    shouldStop_.store(true);
-}
-
-void WorkerThread::join() {
-    if (thread_.joinable()) {
-        thread_.join();
-    }
-    running_.store(false);
-}
-
-bool WorkerThread::isRunning() const {
-    return running_.load();
-}
-
-std::thread::id WorkerThread::getId() const {
-    return thread_.get_id();
-}
-
-size_t WorkerThread::getIndex() const {
-    return index_;
-}
-
-void WorkerThread::run() {
-    // 工作线程的主循环由ThreadPool管理
-    // 这里可以添加额外的线程特定逻辑
-}
-
-// ThreadPoolFactory 实现
-std::unique_ptr<ThreadPool> ThreadPoolFactory::createStandardPool() {
-    ThreadPoolConfig config;
-    config.minThreads = 2;
-    config.maxThreads = std::thread::hardware_concurrency();
-    config.queueCapacity = 1000;
-    config.keepAliveTime = std::chrono::milliseconds(60000);
-    config.enablePriority = true;
-    config.enableStatistics = true;
-    config.threadNamePrefix = "StandardPool";
-    
-    return std::make_unique<ThreadPool>(config);
-}
-
-std::unique_ptr<ThreadPool> ThreadPoolFactory::createHighPerformancePool() {
-    ThreadPoolConfig config;
-    config.minThreads = std::thread::hardware_concurrency();
-    config.maxThreads = std::thread::hardware_concurrency() * 2;
-    config.queueCapacity = 5000;
-    config.keepAliveTime = std::chrono::milliseconds(30000);
-    config.enablePriority = true;
-    config.enableStatistics = true;
-    config.threadNamePrefix = "HighPerfPool";
-    
-    return std::make_unique<ThreadPool>(config);
-}
-
-std::unique_ptr<ThreadPool> ThreadPoolFactory::createLightweightPool() {
-    ThreadPoolConfig config;
-    config.minThreads = 1;
-    config.maxThreads = 4;
-    config.queueCapacity = 100;
-    config.keepAliveTime = std::chrono::milliseconds(120000);
-    config.enablePriority = false;
-    config.enableStatistics = false;
-    config.threadNamePrefix = "LightPool";
-    
-    return std::make_unique<ThreadPool>(config);
-}
-
-std::unique_ptr<ThreadPool> ThreadPoolFactory::createRealtimePool() {
-    ThreadPoolConfig config;
-    config.minThreads = std::thread::hardware_concurrency();
-    config.maxThreads = std::thread::hardware_concurrency();
-    config.queueCapacity = 500;
-    config.keepAliveTime = std::chrono::milliseconds(10000);
-    config.enablePriority = true;
-    config.enableStatistics = true;
-    config.threadNamePrefix = "RealtimePool";
-    
-    return std::make_unique<ThreadPool>(config);
-}
-
-std::unique_ptr<ThreadPool> ThreadPoolFactory::createCustomPool(const ThreadPoolConfig& config) {
-    return std::make_unique<ThreadPool>(config);
-}
-
-size_t ThreadPoolFactory::getRecommendedThreadCount() {
-    return (std::max)(2u, std::thread::hardware_concurrency());
-}
-
-size_t ThreadPoolFactory::getCpuCoreCount() {
-    return std::thread::hardware_concurrency();
-}
-
-// ThreadPoolManager 实现
-ThreadPoolManager& ThreadPoolManager::getInstance() {
-    static ThreadPoolManager instance;
-    return instance;
-}
-
-ThreadPoolManager::ThreadPoolManager() {
-    // 创建默认线程池
-    defaultPool_ = ThreadPoolFactory::createStandardPool();
-    defaultPool_->initialize();
-    defaultPool_->start();
-}
-
-ThreadPoolManager::~ThreadPoolManager() {
-    shutdownAll();
-}
-
-ThreadPool* ThreadPoolManager::getDefaultPool() {
-    return defaultPool_.get();
-}
-
-ErrorCode ThreadPoolManager::createPool(const std::string& name, const ThreadPoolConfig& config) {
-    if (name.empty()) {
-        return ErrorCode::INVALID_PARAMS;
-    }
-    
-    std::lock_guard<std::mutex> lock(poolsMutex_);
-    
-    if (namedPools_.find(name) != namedPools_.end()) {
-        return ErrorCode::ALREADY_EXISTS;
-    }
-    
-    auto pool = std::make_unique<ThreadPool>(config);
-    ErrorCode result = pool->initialize();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    result = pool->start();
-    if (result != ErrorCode::SUCCESS) {
-        return result;
-    }
-    
-    namedPools_[name] = std::move(pool);
-    
-    Logger::instance().infof("Created thread pool: {}", name);
-    return ErrorCode::SUCCESS;
-}
-
-ThreadPool* ThreadPoolManager::getPool(const std::string& name) {
-    std::lock_guard<std::mutex> lock(poolsMutex_);
-    
-    auto it = namedPools_.find(name);
-    if (it != namedPools_.end()) {
-        return it->second.get();
-    }
-    
-    return nullptr;
-}
-
-ErrorCode ThreadPoolManager::destroyPool(const std::string& name) {
-    std::lock_guard<std::mutex> lock(poolsMutex_);
-    
-    auto it = namedPools_.find(name);
-    if (it == namedPools_.end()) {
-        return ErrorCode::NOT_FOUND;
-    }
-    
-    it->second->shutdown();
-    namedPools_.erase(it);
-    
-    Logger::instance().infof("Destroyed thread pool: {}", name);
-    return ErrorCode::SUCCESS;
-}
-
-std::vector<std::string> ThreadPoolManager::getPoolNames() const {
-    std::lock_guard<std::mutex> lock(poolsMutex_);
-    
-    std::vector<std::string> names;
-    names.reserve(namedPools_.size());
-    
-    for (const auto& pair : namedPools_) {
-        names.push_back(pair.first);
-    }
-    
-    return names;
-}
-
-void ThreadPoolManager::shutdownAll() {
-    std::lock_guard<std::mutex> lock(poolsMutex_);
-    
-    // 关闭所有命名线程池
-    for (auto& pair : namedPools_) {
-        pair.second->shutdown();
-    }
-    namedPools_.clear();
-    
-    // 关闭默认线程池
-    if (defaultPool_) {
-        defaultPool_->shutdown();
-        defaultPool_.reset();
-    }
-    
-    Logger::instance().info("All thread pools shutdown");
-}
-
-} // namespace utils
-} // namespace av

+ 0 - 390
AV/code/utils/utils_thread_pool.h

@@ -1,390 +0,0 @@
-#pragma once
-
-#include "../base/types.h"
-#include <memory>
-#include <thread>
-#include <vector>
-#include <queue>
-#include <functional>
-#include <mutex>
-#include <condition_variable>
-#include <atomic>
-#include <future>
-#include <chrono>
-#include <string>
-#include <map>
-
-namespace av {
-namespace utils {
-
-using namespace av;
-
-// 任务优先级
-enum class TaskPriority {
-    LOW = 0,
-    NORMAL = 1,
-    HIGH = 2,
-    CRITICAL = 3
-};
-
-// 任务状态
-enum class TaskStatus {
-    PENDING,        // 等待执行
-    RUNNING,        // 正在执行
-    COMPLETED,      // 已完成
-    FAILED,         // 执行失败
-    CANCELLED       // 已取消
-};
-
-// 线程池状态
-enum class ThreadPoolState {
-    STOPPED,        // 已停止
-    STARTING,       // 启动中
-    RUNNING,        // 运行中
-    STOPPING,       // 停止中
-    PAUSED          // 已暂停
-};
-
-// 任务信息
-struct TaskInfo {
-    uint64_t id = 0;                     // 任务ID
-    std::string name;                    // 任务名称
-    TaskPriority priority = TaskPriority::NORMAL; // 优先级
-    TaskStatus status = TaskStatus::PENDING;       // 状态
-    std::chrono::steady_clock::time_point submitTime;  // 提交时间
-    std::chrono::steady_clock::time_point startTime;   // 开始时间
-    std::chrono::steady_clock::time_point endTime;     // 结束时间
-    std::thread::id threadId;            // 执行线程ID
-    std::string errorMessage;            // 错误信息
-};
-
-// 线程池统计信息
-struct ThreadPoolStats {
-    size_t totalThreads = 0;             // 总线程数
-    size_t activeThreads = 0;           // 活跃线程数
-    size_t idleThreads = 0;              // 空闲线程数
-    size_t pendingTasks = 0;             // 等待任务数
-    size_t runningTasks = 0;             // 运行任务数
-    size_t completedTasks = 0;           // 完成任务数
-    size_t failedTasks = 0;              // 失败任务数
-    size_t cancelledTasks = 0;           // 取消任务数
-    double averageExecutionTime = 0.0;   // 平均执行时间(毫秒)
-    double averageWaitTime = 0.0;        // 平均等待时间(毫秒)
-    std::chrono::steady_clock::time_point startTime; // 启动时间
-};
-
-// 线程池配置
-struct ThreadPoolConfig {
-    size_t minThreads = 2;               // 最小线程数
-    size_t maxThreads = 8;               // 最大线程数
-    size_t queueCapacity = 1000;         // 队列容量
-    std::chrono::milliseconds keepAliveTime{60000}; // 线程保活时间
-    bool allowCoreThreadTimeout = false; // 允许核心线程超时
-    bool enablePriority = true;          // 启用优先级
-    bool enableStatistics = true;        // 启用统计
-    std::string threadNamePrefix = "ThreadPool"; // 线程名称前缀
-};
-
-// 任务包装器
-class Task {
-public:
-    Task() = default;
-    virtual ~Task() = default;
-    
-    template<typename F, typename... Args>
-    Task(F&& f, Args&&... args)
-        : function_(std::bind(std::forward<F>(f), std::forward<Args>(args)...))
-        , info_(std::make_shared<TaskInfo>()) {
-        info_->id = generateTaskId();
-        info_->submitTime = std::chrono::steady_clock::now();
-    }
-    
-    void execute() {
-        if (function_) {
-            info_->status = TaskStatus::RUNNING;
-            info_->startTime = std::chrono::steady_clock::now();
-            info_->threadId = std::this_thread::get_id();
-            
-            try {
-                function_();
-                info_->status = TaskStatus::COMPLETED;
-            } catch (const std::exception& e) {
-                info_->status = TaskStatus::FAILED;
-                info_->errorMessage = e.what();
-            } catch (...) {
-                info_->status = TaskStatus::FAILED;
-                info_->errorMessage = "Unknown exception";
-            }
-            
-            info_->endTime = std::chrono::steady_clock::now();
-        }
-    }
-    
-    void cancel() {
-        info_->status = TaskStatus::CANCELLED;
-    }
-    
-    uint64_t getId() const { return info_->id; }
-    std::shared_ptr<TaskInfo> getInfo() const { return info_; }
-    
-    void setName(const std::string& name) { info_->name = name; }
-    void setPriority(TaskPriority priority) { info_->priority = priority; }
-    
-    TaskPriority getPriority() const { return info_->priority; }
-    TaskStatus getStatus() const { return info_->status; }
-    
-private:
-    static uint64_t generateTaskId() {
-        static std::atomic<uint64_t> counter{0};
-        return ++counter;
-    }
-    
-private:
-    std::function<void()> function_;
-    std::shared_ptr<TaskInfo> info_;
-};
-
-// 任务比较器(用于优先级队列)
-struct TaskComparator {
-    bool operator()(const std::shared_ptr<Task>& a, const std::shared_ptr<Task>& b) const {
-        return a->getPriority() < b->getPriority();
-    }
-};
-
-// 线程池
-class ThreadPool {
-public:
-    explicit ThreadPool(const ThreadPoolConfig& config = ThreadPoolConfig());
-    virtual ~ThreadPool();
-    
-    // 禁止拷贝和移动
-    ThreadPool(const ThreadPool&) = delete;
-    ThreadPool& operator=(const ThreadPool&) = delete;
-    ThreadPool(ThreadPool&&) = delete;
-    ThreadPool& operator=(ThreadPool&&) = delete;
-    
-    // 基本控制
-    ErrorCode initialize();
-    ErrorCode start();
-    ErrorCode stop(bool waitForCompletion = true);
-    ErrorCode pause();
-    ErrorCode resume();
-    ErrorCode shutdown(std::chrono::milliseconds timeout = std::chrono::milliseconds(5000));
-    
-    // 任务提交
-    template<typename F, typename... Args>
-    auto submit(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
-        using ReturnType = typename std::result_of<F(Args...)>::type;
-        
-        auto task = std::make_shared<std::packaged_task<ReturnType()>>(
-            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
-        );
-        
-        auto future = task->get_future();
-        auto taskWrapper = std::make_shared<Task>([task]() { (*task)(); });
-        
-        submitTask(taskWrapper);
-        return future;
-    }
-    
-    template<typename F, typename... Args>
-    uint64_t submitWithPriority(TaskPriority priority, F&& f, Args&&... args) {
-        auto task = std::make_shared<Task>(std::forward<F>(f), std::forward<Args>(args)...);
-        task->setPriority(priority);
-        submitTask(task);
-        return task->getId();
-    }
-    
-    template<typename F, typename... Args>
-    uint64_t submitNamed(const std::string& name, F&& f, Args&&... args) {
-        auto task = std::make_shared<Task>(std::forward<F>(f), std::forward<Args>(args)...);
-        task->setName(name);
-        submitTask(task);
-        return task->getId();
-    }
-    
-    // 任务管理
-    bool cancelTask(uint64_t taskId);
-    bool isTaskCompleted(uint64_t taskId) const;
-    TaskStatus getTaskStatus(uint64_t taskId) const;
-    std::shared_ptr<TaskInfo> getTaskInfo(uint64_t taskId) const;
-    std::vector<std::shared_ptr<TaskInfo>> getAllTaskInfo() const;
-    
-    // 状态查询
-    ThreadPoolState getState() const;
-    bool isRunning() const;
-    bool isPaused() const;
-    bool isStopped() const;
-    
-    // 统计信息
-    ThreadPoolStats getStats() const;
-    size_t getActiveThreadCount() const;
-    size_t getIdleThreadCount() const;
-    size_t getPendingTaskCount() const;
-    size_t getCompletedTaskCount() const;
-    
-    // 配置管理
-    void setConfig(const ThreadPoolConfig& config);
-    ThreadPoolConfig getConfig() const;
-    ErrorCode resizeThreadPool(size_t newSize);
-    void setThreadNamePrefix(const std::string& prefix);
-    
-    // 等待和同步
-    void waitForAllTasks();
-    bool waitForAllTasks(std::chrono::milliseconds timeout);
-    void clearPendingTasks();
-    
-private:
-    // 内部方法
-    void submitTask(std::shared_ptr<Task> task);
-    void workerThread(size_t threadIndex);
-    std::shared_ptr<Task> getNextTask();
-    void adjustThreadPoolSize();
-    void updateStatistics();
-    void cleanupCompletedTasks();
-    bool shouldCreateNewThread() const;
-    bool shouldDestroyThread() const;
-    void setThreadName(const std::string& name);
-    
-private:
-    ThreadPoolConfig config_;
-    
-    // 状态管理
-    std::atomic<ThreadPoolState> state_;
-    std::atomic<bool> shutdown_;
-    
-    // 线程管理
-    std::vector<std::thread> workers_;
-    std::atomic<size_t> activeThreads_;
-    std::atomic<size_t> idleThreads_;
-    
-    // 任务队列
-    std::priority_queue<std::shared_ptr<Task>, std::vector<std::shared_ptr<Task>>, TaskComparator> taskQueue_;
-    std::queue<std::shared_ptr<Task>> normalQueue_; // 非优先级队列
-    
-    // 任务管理
-    std::map<uint64_t, std::shared_ptr<Task>> activeTasks_;
-    std::map<uint64_t, std::shared_ptr<TaskInfo>> completedTasks_;
-    
-    // 统计信息
-    ThreadPoolStats stats_;
-    std::atomic<size_t> totalSubmittedTasks_;
-    std::atomic<size_t> totalCompletedTasks_;
-    std::atomic<size_t> totalFailedTasks_;
-    std::atomic<size_t> totalCancelledTasks_;
-    
-    // 同步控制
-    mutable std::mutex queueMutex_;
-    mutable std::mutex tasksMutex_;
-    mutable std::mutex statsMutex_;
-    mutable std::mutex configMutex_;
-    
-    std::condition_variable queueCondition_;
-    std::condition_variable pauseCondition_;
-    std::condition_variable completionCondition_;
-    
-    // 时间管理
-    std::chrono::steady_clock::time_point startTime_;
-};
-
-// 工作线程
-class WorkerThread {
-public:
-    WorkerThread(ThreadPool* pool, size_t index);
-    ~WorkerThread();
-    
-    void start();
-    void stop();
-    void join();
-    
-    bool isRunning() const;
-    std::thread::id getId() const;
-    size_t getIndex() const;
-    
-private:
-    void run();
-    
-private:
-    ThreadPool* pool_;
-    size_t index_;
-    std::thread thread_;
-    std::atomic<bool> running_;
-    std::atomic<bool> shouldStop_;
-};
-
-// 线程池工厂
-class ThreadPoolFactory {
-public:
-    // 创建标准线程池
-    static std::unique_ptr<ThreadPool> createStandardPool();
-    
-    // 创建高性能线程池
-    static std::unique_ptr<ThreadPool> createHighPerformancePool();
-    
-    // 创建轻量级线程池
-    static std::unique_ptr<ThreadPool> createLightweightPool();
-    
-    // 创建实时线程池
-    static std::unique_ptr<ThreadPool> createRealtimePool();
-    
-    // 创建自定义线程池
-    static std::unique_ptr<ThreadPool> createCustomPool(const ThreadPoolConfig& config);
-    
-    // 获取系统推荐的线程数
-    static size_t getRecommendedThreadCount();
-    
-    // 获取CPU核心数
-    static size_t getCpuCoreCount();
-};
-
-// 线程池管理器(单例)
-class ThreadPoolManager {
-public:
-    static ThreadPoolManager& getInstance();
-    
-    // 获取默认线程池
-    ThreadPool* getDefaultPool();
-    
-    // 创建命名线程池
-    ErrorCode createPool(const std::string& name, const ThreadPoolConfig& config);
-    
-    // 获取命名线程池
-    ThreadPool* getPool(const std::string& name);
-    
-    // 销毁线程池
-    ErrorCode destroyPool(const std::string& name);
-    
-    // 获取所有线程池名称
-    std::vector<std::string> getPoolNames() const;
-    
-    // 关闭所有线程池
-    void shutdownAll();
-    
-private:
-    ThreadPoolManager();
-    ~ThreadPoolManager();
-    
-    ThreadPoolManager(const ThreadPoolManager&) = delete;
-    ThreadPoolManager& operator=(const ThreadPoolManager&) = delete;
-    
-private:
-    std::unique_ptr<ThreadPool> defaultPool_;
-    std::map<std::string, std::unique_ptr<ThreadPool>> namedPools_;
-    mutable std::mutex poolsMutex_;
-};
-
-// 便利宏
-#define THREAD_POOL_SUBMIT(pool, func, ...) \
-    (pool)->submit(func, ##__VA_ARGS__)
-
-#define THREAD_POOL_SUBMIT_PRIORITY(pool, priority, func, ...) \
-    (pool)->submitWithPriority(priority, func, ##__VA_ARGS__)
-
-#define THREAD_POOL_SUBMIT_NAMED(pool, name, func, ...) \
-    (pool)->submitNamed(name, func, ##__VA_ARGS__)
-
-#define DEFAULT_THREAD_POOL() \
-    av::utils::ThreadPoolManager::getInstance().getDefaultPool()
-
-} // namespace utils
-} // namespace av

+ 0 - 1
AV/examples/debug_player.cpp

@@ -1 +0,0 @@
- 

+ 0 - 59
AV/examples/integration_example.cpp

@@ -1,59 +0,0 @@
-#include <QApplication>
-#include <QDebug>
-#include <QFileDialog>
-#include <QHBoxLayout>
-#include <QLabel>
-#include <QMainWindow>
-#include <QMessageBox>
-#include <QPushButton>
-#include <QSlider>
-#include <QTimer>
-#include <QVBoxLayout>
-#include <QDir>
-#include <QStandardPaths>
-
-#include "code/base/logger.h"
-
-#include "code/player/SimplePlayerWindow.h"
-
-int main(int argc, char* argv[])
-{
-    // 初始化日志系统
-    QString logPath = "./AV_Player/log.txt";
-    QDir().mkpath(QFileInfo(logPath).absolutePath());
-    
-    av::Logger::initialize(logPath.toStdString(), av::LogLevel::DEBUG, true, true);
-    
-    QApplication app(argc, argv);
-    
-    // 设置应用程序信息
-    app.setApplicationName("AV Player");
-    app.setApplicationVersion("1.0.0");
-    app.setOrganizationName("AV Framework");
-
-    qDebug() << "=== AV Player Integration Example Started ===";
-    qDebug() << "Log file:" << logPath;
-    qDebug() << "This example demonstrates how to integrate the new player core with Qt UI";
-    
-    // 检查FFmpeg库
-    qDebug() << "Checking FFmpeg library availability...";
-    
-    // 创建并显示播放器窗口
-    try {
-        SimplePlayerWindow window;
-        window.show();
-        
-        qDebug() << "Player window created and shown successfully";
-        
-        return app.exec();
-    } catch (const std::exception& e) {
-        qCritical() << "Exception during player initialization:" << e.what();
-        QMessageBox::critical(nullptr, "Error", 
-            QString("Failed to initialize player: %1").arg(e.what()));
-        return -1;
-    } catch (...) {
-        qCritical() << "Unknown exception during player initialization";
-        QMessageBox::critical(nullptr, "Error", "Unknown error during player initialization");
-        return -1;
-    }
-}

+ 0 - 321
AV/examples/player_v2_example.cpp

@@ -1,321 +0,0 @@
-#include "../player/player_core_v2.h"
-#include "../base/logger.h"
-#include <iostream>
-#include <thread>
-#include <chrono>
-#include <string>
-
-using namespace av::player;
-using namespace av::utils;
-
-// 示例事件回调类
-class ExamplePlayerCallback : public PlayerEventCallback {
-public:
-    void onStateChanged(PlayerState newState) override {
-        std::string stateStr;
-        switch (newState) {
-            case PlayerState::Idle: stateStr = "Idle"; break;
-            case PlayerState::Opening: stateStr = "Opening"; break;
-            case PlayerState::Stopped: stateStr = "Stopped"; break;
-            case PlayerState::Playing: stateStr = "Playing"; break;
-            case PlayerState::Paused: stateStr = "Paused"; break;
-            case PlayerState::Seeking: stateStr = "Seeking"; break;
-            case PlayerState::Error: stateStr = "Error"; break;
-        }
-        std::cout << "[EVENT] State changed to: " << stateStr << std::endl;
-    }
-    
-    void onPositionChanged(int64_t position) override {
-        // 每秒更新一次位置信息
-        static auto lastUpdate = std::chrono::steady_clock::now();
-        auto now = std::chrono::steady_clock::now();
-        if (std::chrono::duration_cast<std::chrono::seconds>(now - lastUpdate).count() >= 1) {
-            double seconds = position / 1000000.0;
-            std::cout << "[EVENT] Position: " << std::fixed << std::setprecision(2) << seconds << "s" << std::endl;
-            lastUpdate = now;
-        }
-    }
-    
-    void onMediaInfoChanged(const MediaInfo& info) override {
-        std::cout << "[EVENT] Media info changed:" << std::endl;
-        std::cout << "  File: " << info.filename << std::endl;
-        std::cout << "  Duration: " << (info.duration / 1000000.0) << "s" << std::endl;
-        std::cout << "  Has Video: " << (info.hasVideo ? "Yes" : "No") << std::endl;
-        std::cout << "  Has Audio: " << (info.hasAudio ? "Yes" : "No") << std::endl;
-        
-        if (info.hasVideo) {
-            std::cout << "  Video: " << info.width << "x" << info.height << " @ " << info.fps << " fps" << std::endl;
-        }
-        
-        if (info.hasAudio) {
-            std::cout << "  Audio: " << info.sampleRate << " Hz, " << info.channels << " channels" << std::endl;
-        }
-    }
-    
-    void onErrorOccurred(const std::string& error) override {
-        std::cout << "[ERROR] " << error << std::endl;
-    }
-    
-    void onFrameDropped(int64_t totalDropped) override {
-        std::cout << "[WARNING] Frame dropped, total: " << totalDropped << std::endl;
-    }
-    
-    void onSyncError(double error, const std::string& reason) override {
-        std::cout << "[WARNING] Sync error: " << (error * 1000) << "ms, reason: " << reason << std::endl;
-    }
-};
-
-// 简单的命令行界面
-class SimplePlayerUI {
-public:
-    SimplePlayerUI(PlayerCoreV2* player) : m_player(player), m_running(true) {}
-    
-    void run() {
-        std::cout << "\n=== PlayerCoreV2 Example ===" << std::endl;
-        std::cout << "Commands:" << std::endl;
-        std::cout << "  open <filename>  - Open media file" << std::endl;
-        std::cout << "  play             - Start playback" << std::endl;
-        std::cout << "  pause            - Pause playback" << std::endl;
-        std::cout << "  stop             - Stop playback" << std::endl;
-        std::cout << "  seek <seconds>   - Seek to position" << std::endl;
-        std::cout << "  speed <rate>     - Set playback speed (0.5-4.0)" << std::endl;
-        std::cout << "  volume <level>   - Set volume (0.0-1.0)" << std::endl;
-        std::cout << "  stats            - Show playback statistics" << std::endl;
-        std::cout << "  debug            - Show debug information" << std::endl;
-        std::cout << "  config           - Show sync configuration" << std::endl;
-        std::cout << "  quit             - Exit program" << std::endl;
-        std::cout << "============================\n" << std::endl;
-        
-        std::string line;
-        while (m_running && std::getline(std::cin, line)) {
-            processCommand(line);
-        }
-    }
-    
-private:
-    void processCommand(const std::string& line) {
-        std::istringstream iss(line);
-        std::string command;
-        iss >> command;
-        
-        if (command == "open") {
-            std::string filename;
-            iss >> filename;
-            if (!filename.empty()) {
-                auto result = m_player->openFile(filename);
-                if (result == ErrorCode::SUCCESS) {
-                    std::cout << "File opened successfully" << std::endl;
-                } else {
-                    std::cout << "Failed to open file: " << static_cast<int>(result) << std::endl;
-                }
-            } else {
-                std::cout << "Usage: open <filename>" << std::endl;
-            }
-        }
-        else if (command == "play") {
-            auto result = m_player->play();
-            if (result == ErrorCode::SUCCESS) {
-                std::cout << "Playback started" << std::endl;
-            } else {
-                std::cout << "Failed to start playback: " << static_cast<int>(result) << std::endl;
-            }
-        }
-        else if (command == "pause") {
-            auto result = m_player->pause();
-            if (result == ErrorCode::SUCCESS) {
-                std::cout << "Playback paused" << std::endl;
-            } else {
-                std::cout << "Failed to pause playback: " << static_cast<int>(result) << std::endl;
-            }
-        }
-        else if (command == "stop") {
-            auto result = m_player->stop();
-            if (result == ErrorCode::SUCCESS) {
-                std::cout << "Playback stopped" << std::endl;
-            } else {
-                std::cout << "Failed to stop playback: " << static_cast<int>(result) << std::endl;
-            }
-        }
-        else if (command == "seek") {
-            double seconds;
-            iss >> seconds;
-            if (iss) {
-                int64_t timestamp = static_cast<int64_t>(seconds * 1000000); // 转换为微秒
-                auto result = m_player->seek(timestamp);
-                if (result == ErrorCode::SUCCESS) {
-                    std::cout << "Seeking to " << seconds << "s" << std::endl;
-                } else {
-                    std::cout << "Failed to seek: " << static_cast<int>(result) << std::endl;
-                }
-            } else {
-                std::cout << "Usage: seek <seconds>" << std::endl;
-            }
-        }
-        else if (command == "speed") {
-            double speed;
-            iss >> speed;
-            if (iss) {
-                auto result = m_player->setPlaybackSpeed(speed);
-                if (result == ErrorCode::SUCCESS) {
-                    std::cout << "Playback speed set to " << speed << "x" << std::endl;
-                } else {
-                    std::cout << "Failed to set playback speed: " << static_cast<int>(result) << std::endl;
-                }
-            } else {
-                std::cout << "Usage: speed <rate>" << std::endl;
-            }
-        }
-        else if (command == "volume") {
-            double volume;
-            iss >> volume;
-            if (iss) {
-                m_player->setVolume(volume);
-                std::cout << "Volume set to " << volume << std::endl;
-            } else {
-                std::cout << "Usage: volume <level>" << std::endl;
-            }
-        }
-        else if (command == "stats") {
-            showStats();
-        }
-        else if (command == "debug") {
-            std::cout << m_player->getDebugInfo() << std::endl;
-        }
-        else if (command == "config") {
-            showSyncConfig();
-        }
-        else if (command == "quit" || command == "exit") {
-            m_running = false;
-            std::cout << "Exiting..." << std::endl;
-        }
-        else if (!command.empty()) {
-            std::cout << "Unknown command: " << command << std::endl;
-        }
-    }
-    
-    void showStats() {
-        auto stats = m_player->getStats();
-        
-        std::cout << "\n=== Playback Statistics ===" << std::endl;
-        std::cout << "Current Time: " << std::fixed << std::setprecision(2) << (stats.currentTime / 1000000.0) << "s" << std::endl;
-        std::cout << "Playback Speed: " << stats.playbackSpeed << "x" << std::endl;
-        std::cout << "Total Frames: " << stats.totalFrames << std::endl;
-        std::cout << "Dropped Frames: " << stats.droppedFrames << std::endl;
-        std::cout << "Duplicated Frames: " << stats.duplicatedFrames << std::endl;
-        std::cout << "Sync Error: " << std::fixed << std::setprecision(1) << (stats.syncError * 1000) << "ms" << std::endl;
-        std::cout << "Avg Sync Error: " << std::fixed << std::setprecision(1) << (stats.avgSyncError * 1000) << "ms" << std::endl;
-        std::cout << "Max Sync Error: " << std::fixed << std::setprecision(1) << (stats.maxSyncError * 1000) << "ms" << std::endl;
-        std::cout << "CPU Usage: " << std::fixed << std::setprecision(1) << stats.cpuUsage << "%" << std::endl;
-        std::cout << "Memory Usage: " << std::fixed << std::setprecision(1) << stats.memoryUsage << "MB" << std::endl;
-        std::cout << "Queued Packets: " << stats.queuedPackets << std::endl;
-        std::cout << "Queued Video Frames: " << stats.queuedVideoFrames << std::endl;
-        std::cout << "Queued Audio Frames: " << stats.queuedAudioFrames << std::endl;
-        std::cout << "Bitrate: " << std::fixed << std::setprecision(1) << stats.bitrate << " kbps" << std::endl;
-        std::cout << "===========================\n" << std::endl;
-    }
-    
-    void showSyncConfig() {
-        auto config = m_player->getSyncConfig();
-        
-        std::cout << "\n=== Sync Configuration ===" << std::endl;
-        std::cout << "Sync Strategy: " << static_cast<int>(config.syncStrategy) << std::endl;
-        std::cout << "Audio Sync Threshold: " << (config.audioSyncThreshold * 1000) << "ms" << std::endl;
-        std::cout << "Video Sync Threshold: " << (config.videoSyncThreshold * 1000) << "ms" << std::endl;
-        std::cout << "Max Sync Error: " << (config.maxSyncError * 1000) << "ms" << std::endl;
-        std::cout << "Clock Update Interval: " << config.clockUpdateInterval << "ms" << std::endl;
-        std::cout << "Smoothing Window: " << config.smoothingWindow << std::endl;
-        std::cout << "Adaptive Sync: " << (config.enableAdaptiveSync ? "Enabled" : "Disabled") << std::endl;
-        std::cout << "Frame Drop: " << (config.enableFrameDrop ? "Enabled" : "Disabled") << std::endl;
-        std::cout << "Frame Duplicate: " << (config.enableFrameDuplicate ? "Enabled" : "Disabled") << std::endl;
-        std::cout << "Prediction: " << (config.enablePrediction ? "Enabled" : "Disabled") << std::endl;
-        std::cout << "==========================\n" << std::endl;
-    }
-    
-    PlayerCoreV2* m_player;
-    bool m_running;
-};
-
-int main(int argc, char* argv[]) {
-    // 初始化日志系统
-    Logger::instance().setLevel(LogLevel::INFO);
-    Logger::instance().info("PlayerCoreV2 Example Started");
-    
-    try {
-        // 创建同步配置
-        SyncConfigV2 syncConfig;
-        syncConfig.syncStrategy = SyncStrategy::ADAPTIVE;  // 使用自适应同步策略
-        syncConfig.audioSyncThreshold = 0.040;  // 40ms
-        syncConfig.videoSyncThreshold = 0.020;  // 20ms
-        syncConfig.maxSyncError = 0.200;        // 200ms
-        syncConfig.clockUpdateInterval = 10;     // 10ms
-        syncConfig.smoothingWindow = 10;         // 10个样本
-        syncConfig.enableAdaptiveSync = true;
-        syncConfig.enableFrameDrop = true;
-        syncConfig.enableFrameDuplicate = true;
-        syncConfig.enablePrediction = true;
-        syncConfig.enableErrorRecovery = true;
-        
-        // 创建播放器实例
-        auto player = std::make_unique<PlayerCoreV2>(syncConfig);
-        
-        // 创建事件回调
-        auto callback = std::make_unique<ExamplePlayerCallback>();
-        player->setEventCallback(callback.get());
-        
-        // 如果命令行提供了文件名,自动打开
-        if (argc > 1) {
-            std::string filename = argv[1];
-            std::cout << "Opening file: " << filename << std::endl;
-            
-            auto result = player->openFile(filename);
-            if (result == ErrorCode::SUCCESS) {
-                std::cout << "File opened successfully" << std::endl;
-                
-                // 自动开始播放
-                result = player->play();
-                if (result == ErrorCode::SUCCESS) {
-                    std::cout << "Playback started" << std::endl;
-                } else {
-                    std::cout << "Failed to start playback: " << static_cast<int>(result) << std::endl;
-                }
-            } else {
-                std::cout << "Failed to open file: " << static_cast<int>(result) << std::endl;
-            }
-        }
-        
-        // 启动用户界面
-        SimplePlayerUI ui(player.get());
-        
-        // 启动更新线程
-        std::atomic<bool> shouldStop(false);
-        std::thread updateThread([&player, &shouldStop]() {
-            while (!shouldStop) {
-                player->update();
-                std::this_thread::sleep_for(std::chrono::milliseconds(16)); // ~60 FPS
-            }
-        });
-        
-        // 运行用户界面
-        ui.run();
-        
-        // 停止更新线程
-        shouldStop = true;
-        if (updateThread.joinable()) {
-            updateThread.join();
-        }
-        
-        // 停止播放器
-        player->stop();
-        
-        std::cout << "PlayerCoreV2 Example finished" << std::endl;
-        
-    } catch (const std::exception& e) {
-        std::cerr << "Exception: " << e.what() << std::endl;
-        return 1;
-    } catch (...) {
-        std::cerr << "Unknown exception occurred" << std::endl;
-        return 1;
-    }
-    
-    return 0;
-}

+ 0 - 189
AV/test/test_audio.cpp

@@ -1,189 +0,0 @@
-#include <chrono>
-#include <iostream>
-#include <string>
-#include <thread>
-
-#include "code/base/logger.h"
-#include "code/player/player_core_v2.h"
-
-using namespace av::player;
-using namespace av::utils;
-
-// 简单的事件回调类
-class TestPlayerCallback : public PlayerEventCallback {
-public:
-    void onStateChanged(PlayerState newState) override {
-        std::string stateStr;
-        switch (newState) {
-            case PlayerState::Idle: stateStr = "Idle"; break;
-            case PlayerState::Opening: stateStr = "Opening"; break;
-            case PlayerState::Stopped: stateStr = "Stopped"; break;
-            case PlayerState::Playing: stateStr = "Playing"; break;
-            case PlayerState::Paused: stateStr = "Paused"; break;
-            case PlayerState::Seeking: stateStr = "Seeking"; break;
-            case PlayerState::Error: stateStr = "Error"; break;
-        }
-        std::cout << "[EVENT] State changed to: " << stateStr << std::endl;
-    }
-    
-    void onPositionChanged(int64_t position) override {
-        static auto lastUpdate = std::chrono::steady_clock::now();
-        auto now = std::chrono::steady_clock::now();
-        if (std::chrono::duration_cast<std::chrono::seconds>(now - lastUpdate).count() >= 1) {
-            double seconds = position / 1000000.0;
-            std::cout << "[EVENT] Position: " << std::fixed << std::setprecision(2) << seconds << "s" << std::endl;
-            lastUpdate = now;
-        }
-    }
-    
-    void onMediaInfoChanged(const MediaInfo& info) override {
-        std::cout << "[EVENT] Media info changed:" << std::endl;
-        std::cout << "  File: " << info.filename << std::endl;
-        std::cout << "  Duration: " << (info.duration / 1000000.0) << "s" << std::endl;
-        std::cout << "  Has Video: " << (info.hasVideo ? "Yes" : "No") << std::endl;
-        std::cout << "  Has Audio: " << (info.hasAudio ? "Yes" : "No") << std::endl;
-        
-        if (info.hasAudio) {
-            std::cout << "  Audio: " << info.sampleRate << " Hz, " << info.channels << " channels" << std::endl;
-        }
-    }
-    
-    void onErrorOccurred(const std::string& error) override {
-        std::cout << "[ERROR] " << error << std::endl;
-    }
-    
-    void onFrameDropped(int64_t totalDropped) override {
-        std::cout << "[WARNING] Frame dropped, total: " << totalDropped << std::endl;
-    }
-    
-    void onSyncError(double error, const std::string& reason) override {
-        std::cout << "[WARNING] Sync error: " << (error * 1000) << "ms, reason: " << reason << std::endl;
-    }
-
-    void onEndOfFile() override {}
-};
-
-int main() {
-    // 初始化日志系统
-    Logger::instance().setLevel(LogLevel::DEBUG);
-    Logger::instance().info("Audio Test Started");
-    
-    try {
-        // 创建同步配置
-        SyncConfigV2 syncConfig;
-        syncConfig.syncStrategy = SyncStrategy::ADAPTIVE;
-        syncConfig.audioSyncThreshold = 0.040;
-        syncConfig.videoSyncThreshold = 0.020;
-        syncConfig.maxSyncError = 0.200;
-        syncConfig.clockUpdateInterval = 10;
-        syncConfig.smoothingWindow = 10;
-        syncConfig.enableAdaptiveSync = true;
-        syncConfig.enableFrameDrop = true;
-        syncConfig.enableFrameDuplicate = true;
-        syncConfig.enablePrediction = true;
-        syncConfig.enableErrorRecovery = true;
-        
-        // 创建播放器实例
-        auto player = std::make_unique<PlayerCoreV2>(syncConfig);
-        
-        // 创建事件回调
-        auto callback = std::make_unique<TestPlayerCallback>();
-        player->setEventCallback(callback.get());
-        
-        // 测试音频文件路径(请根据实际情况修改)
-        std::string audioFile = "C:\\Windows\\Media\\notify.wav"; // Windows系统音频文件
-        
-        std::cout << "Testing with audio file: " << audioFile << std::endl;
-        
-        // 打开音频文件
-        auto result = player->openFile(audioFile);
-        if (result != ErrorCode::SUCCESS) {
-            std::cout << "Failed to open audio file: " << static_cast<int>(result) << std::endl;
-            
-            // 尝试其他常见的音频文件
-            audioFile = "C:\\Windows\\Media\\chimes.wav";
-            std::cout << "Trying alternative file: " << audioFile << std::endl;
-            result = player->openFile(audioFile);
-            
-            if (result != ErrorCode::SUCCESS) {
-                std::cout << "Failed to open alternative audio file: " << static_cast<int>(result) << std::endl;
-                std::cout << "Please provide a valid audio file path." << std::endl;
-                return 1;
-            }
-        }
-        
-        std::cout << "Audio file opened successfully!" << std::endl;
-        
-        // 获取媒体信息
-        auto mediaInfo = player->getMediaInfo();
-        std::cout << "Media duration: " << (mediaInfo.duration / 1000000.0) << " seconds" << std::endl;
-        std::cout << "Has audio: " << (mediaInfo.hasAudio ? "Yes" : "No") << std::endl;
-        
-        if (!mediaInfo.hasAudio) {
-            std::cout << "No audio stream found in the file!" << std::endl;
-            return 1;
-        }
-        
-        // 设置音量为最大
-        player->setVolume(1.0);
-        std::cout << "Volume set to: " << player->getVolume() << std::endl;
-        
-        // 开始播放
-        result = player->play();
-        if (result != ErrorCode::SUCCESS) {
-            std::cout << "Failed to start playback: " << static_cast<int>(result) << std::endl;
-            return 1;
-        }
-        
-        std::cout << "Playback started! You should hear audio now." << std::endl;
-        std::cout << "Current volume: " << player->getVolume() << std::endl;
-        
-        // 等待播放完成
-        double totalDuration = mediaInfo.duration / 1000000.0;
-        std::cout << "Waiting for playback to complete (" << totalDuration << " seconds)..." << std::endl;
-        
-        // 监控播放状态
-        auto startTime = std::chrono::steady_clock::now();
-        while (true) {
-            auto currentTime = std::chrono::steady_clock::now();
-            auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count();
-            
-            auto state = player->getState();
-            auto currentPos = player->getCurrentTime() / 1000000.0;
-            
-            std::cout << "State: " << static_cast<int>(state) << ", Position: " << currentPos << "s" << std::endl;
-            
-            // 如果播放完成或出错,退出
-            if (state == PlayerState::Stopped || state == PlayerState::Error) {
-                break;
-            }
-            
-            // 如果播放时间接近总时长,停止播放
-            if (currentPos >= totalDuration - 0.1) {
-                std::cout << "Playback completed, stopping..." << std::endl;
-                player->stop();
-                break;
-            }
-            
-            // 超时保护
-            if (elapsed > totalDuration + 5) {
-                std::cout << "Timeout, stopping playback..." << std::endl;
-                player->stop();
-                break;
-            }
-            
-            std::this_thread::sleep_for(std::chrono::milliseconds(500));
-        }
-        
-        std::cout << "Audio test completed." << std::endl;
-        
-    } catch (const std::exception& e) {
-        std::cerr << "Exception: " << e.what() << std::endl;
-        return 1;
-    } catch (...) {
-        std::cerr << "Unknown exception occurred" << std::endl;
-        return 1;
-    }
-    
-    return 0;
-}

+ 0 - 330
AV/test/test_audio_debug.cpp

@@ -1,330 +0,0 @@
-#include <chrono>
-#include <string>
-#include <thread>
-#include <iomanip>
-
-#include "code/base/logger.h"
-#include "code/player/player_core_v2.h"
-
-#include <QApplication>
-#include <QAudioDeviceInfo>
-#include <QAudioOutput>
-#include <QAudioFormat>
-#include <QDebug>
-
-using namespace av::player;
-using namespace av::utils;
-
-// 增强的事件回调类,包含更详细的调试信息
-class DebugPlayerCallback : public PlayerEventCallback {
-public:
-    void onStateChanged(PlayerState newState) override {
-        std::string stateStr;
-        switch (newState) {
-            case PlayerState::Idle: stateStr = "Idle"; break;
-            case PlayerState::Opening: stateStr = "Opening"; break;
-            case PlayerState::Stopped: stateStr = "Stopped"; break;
-            case PlayerState::Playing: stateStr = "Playing"; break;
-            case PlayerState::Paused: stateStr = "Paused"; break;
-            case PlayerState::Seeking: stateStr = "Seeking"; break;
-            case PlayerState::Error: stateStr = "Error"; break;
-        }
-        Logger::instance().info("[EVENT] State changed to: " + stateStr);
-    }
-    
-    void onPositionChanged(int64_t position) override {
-        static auto lastUpdate = std::chrono::steady_clock::now();
-        auto now = std::chrono::steady_clock::now();
-        if (std::chrono::duration_cast<std::chrono::seconds>(now - lastUpdate).count() >= 1) {
-            double seconds = position / 1000000.0;
-            Logger::instance().debug("[EVENT] Position: " + std::to_string(seconds) + "s");
-            lastUpdate = now;
-        }
-    }
-    
-    void onMediaInfoChanged(const MediaInfo& info) override {
-        Logger::instance().info("[EVENT] Media info changed:");
-        Logger::instance().info("  File: " + info.filename);
-        Logger::instance().info("  Duration: " + std::to_string(info.duration / 1000000.0) + "s");
-        Logger::instance().info("  Has Video: " + std::string(info.hasVideo ? "Yes" : "No"));
-        Logger::instance().info("  Has Audio: " + std::string(info.hasAudio ? "Yes" : "No"));
-        
-        if (info.hasAudio) {
-            Logger::instance().info("  Audio: " + std::to_string(info.sampleRate) + " Hz, " + std::to_string(info.channels) + " channels");
-        }
-    }
-    
-    void onErrorOccurred(const std::string& error) override {
-        Logger::instance().error("[ERROR] " + error);
-    }
-    
-    void onFrameDropped(int64_t totalDropped) override {
-        Logger::instance().warningf("[WARNING] Frame dropped, total: "
-                                    + std::to_string(totalDropped));
-    }
-    
-    void onSyncError(double error, const std::string& reason) override {
-        Logger::instance().warningf("[WARNING] Sync error: " + std::to_string(error * 1000)
-                                    + "ms, reason: " + reason);
-    }
-
-    void onEndOfFile() override {
-        Logger::instance().info("[EVENT] End of file reached");
-    }
-};
-
-// 检查系统音频设备
-void checkAudioDevices() {
-    Logger::instance().info("\n=== 音频设备检查 ===");
-    
-    // 获取默认输出设备
-    QAudioDeviceInfo defaultDevice = QAudioDeviceInfo::defaultOutputDevice();
-    Logger::instance().info("默认音频输出设备: " + defaultDevice.deviceName().toStdString());
-    
-    // 列出所有可用的音频输出设备
-    QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
-    Logger::instance().info("可用音频输出设备数量: " + std::to_string(devices.size()));
-    
-    for (int i = 0; i < devices.size(); ++i) {
-        const QAudioDeviceInfo& device = devices[i];
-        Logger::instance().info("  设备 " + std::to_string(i + 1) + ": " + device.deviceName().toStdString());
-        
-        // 检查支持的采样率
-        QList<int> sampleRates = device.supportedSampleRates();
-        std::string ratesStr = "    支持的采样率: ";
-        for (int rate : sampleRates) {
-            ratesStr += std::to_string(rate) + " ";
-        }
-        Logger::instance().info(ratesStr);
-        
-        // 检查支持的通道数
-        QList<int> channels = device.supportedChannelCounts();
-        std::string channelsStr = "    支持的通道数: ";
-        for (int ch : channels) {
-            channelsStr += std::to_string(ch) + " ";
-        }
-        Logger::instance().info(channelsStr);
-    }
-}
-
-// 测试Qt音频输出
-void testQtAudioOutput() {
-    Logger::instance().info("\n=== Qt音频输出测试 ===");
-    
-    // 设置音频格式
-    QAudioFormat format;
-    format.setSampleRate(44100);
-    format.setChannelCount(2);
-    format.setSampleSize(16);
-    format.setCodec("audio/pcm");
-    format.setByteOrder(QAudioFormat::LittleEndian);
-    format.setSampleType(QAudioFormat::SignedInt);
-    
-    // 检查默认设备是否支持该格式
-    QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
-    if (!deviceInfo.isFormatSupported(format)) {
-        Logger::instance().warningf("警告: 默认设备不支持指定的音频格式");
-        format = deviceInfo.nearestFormat(format);
-        Logger::instance().info("使用最接近的格式: " + std::to_string(format.sampleRate()) + "Hz, " 
-                  + std::to_string(format.channelCount()) + "ch, " + std::to_string(format.sampleSize()) + "bit");
-    } else {
-        Logger::instance().info("默认设备支持指定的音频格式");
-    }
-    
-    // 创建音频输出
-    QAudioOutput* audioOutput = new QAudioOutput(format);
-    if (!audioOutput) {
-        Logger::instance().error("错误: 无法创建QAudioOutput");
-        return;
-    }
-    
-    Logger::instance().info("QAudioOutput创建成功");
-    Logger::instance().info("缓冲区大小: " + std::to_string(audioOutput->bufferSize()) + " bytes");
-    Logger::instance().info("音量: " + std::to_string(audioOutput->volume()));
-    
-    // 尝试启动音频设备
-    QIODevice* device = audioOutput->start();
-    if (!device) {
-        Logger::instance().error("错误: 无法启动音频设备");
-        delete audioOutput;
-        return;
-    }
-    
-    Logger::instance().info("音频设备启动成功");
-    
-    // 生成并播放测试音调(440Hz正弦波)
-    const int sampleRate = format.sampleRate();
-    const int channels = format.channelCount();
-    const double frequency = 440.0; // A4音符
-    const double duration = 2.0; // 2秒
-    const int totalSamples = static_cast<int>(sampleRate * duration);
-    
-    QByteArray testData;
-    testData.resize(totalSamples * channels * sizeof(int16_t));
-    int16_t* samples = reinterpret_cast<int16_t*>(testData.data());
-    
-    for (int i = 0; i < totalSamples; ++i) {
-        double time = static_cast<double>(i) / sampleRate;
-        int16_t sample = static_cast<int16_t>(16383 * std::sin(2.0 * M_PI * frequency * time));
-        
-        for (int ch = 0; ch < channels; ++ch) {
-            samples[i * channels + ch] = sample;
-        }
-    }
-    
-    Logger::instance().info("播放测试音调 (440Hz, 2秒)...");
-    
-    // 分块写入音频数据
-    const int chunkSize = 4096;
-    int bytesWritten = 0;
-    
-    while (bytesWritten < testData.size()) {
-        int remainingBytes = testData.size() - bytesWritten;
-        int writeSize = std::min(chunkSize, remainingBytes);
-        
-        qint64 written = device->write(testData.data() + bytesWritten, writeSize);
-        if (written > 0) {
-            bytesWritten += written;
-        }
-        
-        // 等待一小段时间
-        std::this_thread::sleep_for(std::chrono::milliseconds(50));
-    }
-    
-    Logger::instance().info("测试音调播放完成");
-    
-    // 等待播放完成
-    std::this_thread::sleep_for(std::chrono::milliseconds(500));
-    
-    audioOutput->stop();
-    delete audioOutput;
-}
-
-int main(int argc, char* argv[]) {
-    // 创建QApplication实例(Qt音频需要)
-    QApplication app(argc, argv);
-    Logger::instance().initialize("test.log", LogLevel::DEBUG, false, true);
-    // 初始化日志系统
-    Logger::instance().setLevel(LogLevel::DEBUG);
-    Logger::instance().info("Enhanced Audio Debug Test Started");
-
-    try {
-        // 检查音频设备
-        checkAudioDevices();
-        
-        // 测试Qt音频输出
-        // testQtAudioOutput();
-
-        Logger::instance().info("\n=== PlayerCoreV2音频测试 ===");
-
-        // 创建同步配置
-        SyncConfigV2 syncConfig;
-        syncConfig.syncStrategy = SyncStrategy::ADAPTIVE;
-        syncConfig.audioSyncThreshold = 0.040;
-        syncConfig.videoSyncThreshold = 0.020;
-        syncConfig.maxSyncError = 0.200;
-        syncConfig.clockUpdateInterval = 10;
-        syncConfig.smoothingWindow = 10;
-        syncConfig.enableAdaptiveSync = true;
-        syncConfig.enableFrameDrop = true;
-        syncConfig.enableFrameDuplicate = true;
-        syncConfig.enablePrediction = true;
-        syncConfig.enableErrorRecovery = true;
-        
-        // 创建播放器实例
-        auto player = std::make_unique<PlayerCoreV2>(syncConfig);
-        
-        // 创建事件回调
-        auto callback = std::make_unique<DebugPlayerCallback>();
-        player->setEventCallback(callback.get());
-        
-        // 测试音频文件路径
-        std::string audioFile = "C:\\Windows\\Media\\notify.wav";
-
-        Logger::instance().info("测试音频文件: " + audioFile);
-
-        // 打开音频文件
-        auto result = player->openFile(audioFile);
-        if (result != ErrorCode::SUCCESS) {
-            Logger::instance().error("无法打开音频文件: " + std::to_string(static_cast<int>(result)));
-            
-            // 尝试其他文件
-            audioFile = "C:\\Windows\\Media\\chimes.wav";
-            Logger::instance().info("尝试备用文件: " + audioFile);
-            result = player->openFile(audioFile);
-            
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().error("无法打开备用音频文件: " + std::to_string(static_cast<int>(result)));
-                return 1;
-            }
-        }
-        
-        Logger::instance().info("音频文件打开成功!");
-        
-        // 获取媒体信息
-        auto mediaInfo = player->getMediaInfo();
-        Logger::instance().info("媒体时长: " + std::to_string(mediaInfo.duration / 1000000.0) + " 秒");
-        Logger::instance().info("包含音频: " + std::string(mediaInfo.hasAudio ? "是" : "否"));
-        
-        if (!mediaInfo.hasAudio) {
-            Logger::instance().error("文件中未找到音频流!");
-            return 1;
-        }
-        
-        // 设置音量为最大
-        player->setVolume(1.0);
-        Logger::instance().info("音量设置为: " + std::to_string(player->getVolume()));
-        
-        // 开始播放
-        result = player->play();
-        if (result != ErrorCode::SUCCESS) {
-            Logger::instance().error("播放启动失败: " + std::to_string(static_cast<int>(result)));
-            return 1;
-        }
-        
-        Logger::instance().info("播放已开始! 现在应该能听到声音了.");
-        Logger::instance().info("当前音量: " + std::to_string(player->getVolume()));
-        
-        // 等待播放完成
-        double totalDuration = mediaInfo.duration / 1000000.0;
-        Logger::instance().info("等待播放完成 (" + std::to_string(totalDuration) + " 秒)...");
-        
-        // 监控播放状态 - 让播放器自然结束
-        auto startTime = std::chrono::steady_clock::now();
-        while (true) {
-            auto currentTime = std::chrono::steady_clock::now();
-            auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count();
-            
-            auto state = player->getState();
-            auto currentPos = player->getCurrentTime() / 1000000.0;
-            
-            Logger::instance().debug("状态: " + std::to_string(static_cast<int>(state)) + ", 位置: " + std::to_string(currentPos) + "s");
-            
-            // 如果播放完成或出错,退出
-            if (state == PlayerState::Stopped || state == PlayerState::Error) {
-                Logger::instance().info("播放器自然停止,状态: " + std::to_string(static_cast<int>(state)));
-                break;
-            }
-            
-            // 超时保护 - 增加更长的超时时间
-            if (elapsed > totalDuration + 10) {
-                Logger::instance().warningf("超时保护触发,停止播放...");
-                player->stop();
-                break;
-            }
-            
-            std::this_thread::sleep_for(std::chrono::milliseconds(500));
-        }
-        
-        Logger::instance().info("音频测试完成.");
-
-    } catch (const std::exception& e) {
-        Logger::instance().error("异常: " + std::string(e.what()));
-        return 1;
-    } catch (...) {
-        Logger::instance().error("发生未知异常");
-        return 1;
-    }
-
-    return 0;
-}

+ 0 - 419
AV/test/test_audio_encoder.cpp

@@ -1,419 +0,0 @@
-#include "code/codec/codec_audio_encoder.h"
-#include "code/base/logger.h"
-#include "code/base/media_common.h"
-#include <iostream>
-#include <vector>
-#include <memory>
-#include <chrono>
-#include <fstream>
-#include <algorithm>
-#include <cmath>
-
-using namespace av;
-using namespace av::codec;
-
-/**
- * 音频编码器测试类
- */
-class AudioEncoderTester {
-public:
-    AudioEncoderTester() {
-        Logger::instance().setLevel(LogLevel::DEBUG);
-        Logger::instance().info("=== 音频编码器测试套件 ===");
-    }
-    
-    /**
-     * 测试基本音频编码功能
-     */
-    bool testBasicAudioEncoding() {
-        Logger::instance().info("[测试] 基本音频编码功能...");
-        
-        try {
-            // 创建音频编码器
-            auto encoder = AudioEncoderFactory::create("aac");
-            if (!encoder) {
-                Logger::instance().error("[失败] 无法创建AAC编码器");
-                return false;
-            }
-            
-            // 设置编码参数
-            AudioEncoderParams params;
-            params.codecName = "aac";
-            params.bitRate = 128000;
-            params.sampleRate = 44100;
-            params.channels = 2;
-            params.channelLayout = AV_CHANNEL_LAYOUT_STEREO;
-            params.sampleFormat = AV_SAMPLE_FMT_FLTP;
-            params.frameSize = 1024;
-            
-            // 打开编码器
-            ErrorCode result = encoder->open(params);
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().errorf("[失败] 打开编码器失败: {}", static_cast<int>(result));
-                return false;
-            }
-            
-            // 创建测试音频帧
-            AVFramePtr frame = createTestAudioFrame(params);
-            if (!frame) {
-                Logger::instance().error("[失败] 创建测试音频帧失败");
-                return false;
-            }
-            
-            // 编码音频帧
-            std::vector<AVPacketPtr> packets;
-            result = encoder->encode(frame, packets);
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().errorf("[失败] 编码音频帧失败: {}", static_cast<int>(result));
-                return false;
-            }
-            
-            Logger::instance().infof("[成功] 编码产生了 {} 个数据包", packets.size());
-            
-            // 关闭编码器
-            encoder->close();
-            
-            Logger::instance().info("[成功] 基本音频编码测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[异常] {}", e.what());
-            return false;
-        }
-    }
-    
-    /**
-     * 测试多种音频编码器
-     */
-    bool testMultipleEncoders() {
-        Logger::instance().info("[测试] 多种音频编码器支持...");
-        
-        auto supportedEncoders = AudioEncoder::getSupportedEncoders();
-        Logger::instance().infof("支持的编码器数量: {}", supportedEncoders.size());
-        
-        if (supportedEncoders.empty()) {
-            Logger::instance().warning("[警告] 没有找到支持的音频编码器");
-            return false;
-        }
-        
-        int successCount = 0;
-        // 只测试几个主要的编码器,避免实验性编码器导致的问题
-        std::vector<std::string> testEncoders = {"aac", "libmp3lame", "libopus", "flac"};
-        
-        for (const auto& codecName : testEncoders) {
-            // 检查编码器是否在支持列表中
-            if (std::find(supportedEncoders.begin(), supportedEncoders.end(), codecName) == supportedEncoders.end()) {
-                Logger::instance().infof("跳过不支持的编码器: {}", codecName);
-                continue;
-            }
-            
-            Logger::instance().infof("测试编码器: {}", codecName);
-            
-            try {
-                auto encoder = AudioEncoderFactory::create(codecName);
-                if (!encoder) {
-                    Logger::instance().errorf("  [失败] 无法创建编码器: {}", codecName);
-                    continue;
-                }
-                
-                AudioEncoderParams params;
-                params.codecName = codecName;
-                params.bitRate = 128000;
-                params.sampleRate = 44100;
-                params.channels = 2;
-                params.channelLayout = AV_CHANNEL_LAYOUT_STEREO;
-                params.sampleFormat = AV_SAMPLE_FMT_FLTP;
-                
-                ErrorCode result = encoder->open(params);
-                if (result == ErrorCode::SUCCESS) {
-                    Logger::instance().infof("  [成功] {} 编码器打开成功", codecName);
-                    successCount++;
-                } else {
-                    Logger::instance().errorf("  [失败] {} 编码器打开失败: {}", codecName, static_cast<int>(result));
-                }
-                
-                // 确保编码器正确关闭
-                encoder->close();
-                encoder.reset(); // 释放编码器资源
-                
-            } catch (const std::exception& e) {
-                Logger::instance().errorf("  [异常] 测试编码器 {} 时发生异常: {}", codecName, e.what());
-            }
-        }
-        
-        Logger::instance().infof("成功测试的编码器: {}/{}", successCount, testEncoders.size());
-        return successCount > 0;
-    }
-    
-    /**
-     * 测试音频重采样功能
-     */
-    bool testAudioResampling() {
-        Logger::instance().info("[测试] 音频重采样功能...");
-        
-        try {
-            AudioResampler resampler;
-            
-            // 设置重采样参数:从48kHz立体声转换为44.1kHz立体声
-            AVChannelLayout srcLayout = AV_CHANNEL_LAYOUT_STEREO;
-            AVChannelLayout dstLayout = AV_CHANNEL_LAYOUT_STEREO;
-            
-            bool result = resampler.init(srcLayout, AV_SAMPLE_FMT_FLTP, 48000,
-                                       dstLayout, AV_SAMPLE_FMT_FLTP, 44100);
-            if (!result) {
-                Logger::instance().error("[失败] 初始化重采样器失败");
-                return false;
-            }
-            
-            // 创建测试音频帧
-            AudioEncoderParams params;
-            params.sampleRate = 48000;
-            params.channels = 2;
-            params.sampleFormat = AV_SAMPLE_FMT_FLTP;
-            
-            AVFramePtr srcFrame = createTestAudioFrame(params);
-            if (!srcFrame) {
-                Logger::instance().error("[失败] 创建源音频帧失败");
-                return false;
-            }
-            
-            // 执行重采样
-            AVFramePtr dstFrame = resampler.resample(srcFrame);
-            if (!dstFrame) {
-                Logger::instance().error("[失败] 音频重采样失败");
-                return false;
-            }
-            
-            Logger::instance().infof("[成功] 重采样: {}Hz -> {}Hz", srcFrame->sample_rate, dstFrame->sample_rate);
-            Logger::instance().infof("[成功] 样本数: {} -> {}", srcFrame->nb_samples, dstFrame->nb_samples);
-            
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[异常] {}", e.what());
-            return false;
-        }
-    }
-    
-    /**
-     * 测试编码器工厂
-     */
-    bool testEncoderFactory() {
-        Logger::instance().info("[测试] 编码器工厂功能...");
-        
-        // 测试创建最佳编码器
-        auto bestEncoder = AudioEncoderFactory::createBest();
-        if (!bestEncoder) {
-            Logger::instance().error("[失败] 无法创建最佳编码器");
-            return false;
-        }
-        Logger::instance().info("[成功] 创建最佳编码器");
-        
-        // 测试创建无损编码器
-        auto losslessEncoder = AudioEncoderFactory::createLossless();
-        if (!losslessEncoder) {
-            Logger::instance().error("[失败] 无法创建无损编码器");
-            return false;
-        }
-        Logger::instance().info("[成功] 创建无损编码器");
-        
-        // 测试推荐编码器
-        std::string recommended = AudioEncoder::getRecommendedEncoder();
-        if (recommended.empty()) {
-            Logger::instance().error("[失败] 无法获取推荐编码器");
-            return false;
-        }
-        Logger::instance().infof("[成功] 推荐编码器: {}", recommended);
-        
-        return true;
-    }
-    
-    /**
-     * 测试编码器状态管理
-     */
-    bool testEncoderStateManagement() {
-        Logger::instance().info("[测试] 编码器状态管理...");
-        
-        try {
-            auto encoder = AudioEncoderFactory::create("aac");
-            if (!encoder) {
-                Logger::instance().error("[失败] 无法创建编码器");
-                return false;
-            }
-            
-            // 测试初始状态
-            if (encoder->getState() != CodecState::IDLE) {
-                Logger::instance().error("[失败] 初始状态不正确");
-                return false;
-            }
-            
-            // 测试打开编码器
-            AudioEncoderParams params;
-            params.codecName = "aac";
-            params.bitRate = 128000;
-            params.sampleRate = 44100;
-            params.channels = 2;
-            
-            ErrorCode result = encoder->open(params);
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().error("[失败] 打开编码器失败");
-                return false;
-            }
-            
-            if (encoder->getState() != CodecState::OPENED) {
-                Logger::instance().error("[失败] 打开后状态不正确");
-                return false;
-            }
-            
-            // 测试关闭编码器
-            encoder->close();
-            if (encoder->getState() != CodecState::CLOSED) {
-                Logger::instance().error("[失败] 关闭后状态不正确");
-                return false;
-            }
-            
-            Logger::instance().info("[成功] 编码器状态管理测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[异常] {}", e.what());
-            return false;
-        }
-    }
-    
-    /**
-     * 测试错误处理
-     */
-    bool testErrorHandling() {
-        Logger::instance().info("[测试] 错误处理...");
-        
-        try {
-            // 测试无效编码器名称
-            auto encoder = AudioEncoderFactory::create("invalid_codec");
-            if (encoder) {
-                AudioEncoderParams params;
-                params.codecName = "invalid_codec";
-                ErrorCode result = encoder->open(params);
-                if (result == ErrorCode::SUCCESS) {
-                    Logger::instance().error("[失败] 应该拒绝无效编码器");
-                    return false;
-                }
-            }
-            
-            // 测试无效参数
-            encoder = AudioEncoderFactory::create("aac");
-            if (encoder) {
-                AudioEncoderParams params;
-                params.codecName = "aac";
-                params.sampleRate = -1; // 无效采样率
-                params.channels = 0;    // 无效声道数
-                
-                ErrorCode result = encoder->open(params);
-                if (result == ErrorCode::SUCCESS) {
-                    Logger::instance().error("[失败] 应该拒绝无效参数");
-                    return false;
-                }
-            }
-            
-            Logger::instance().info("[成功] 错误处理测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[异常] {}", e.what());
-            return false;
-        }
-    }
-    
-    /**
-     * 运行所有测试
-     */
-    bool runAllTests() {
-        Logger::instance().info("开始运行音频编码器测试套件...");
-        
-        bool allPassed = true;
-        
-        allPassed &= testBasicAudioEncoding();
-        allPassed &= testMultipleEncoders();
-        allPassed &= testAudioResampling();
-        allPassed &= testEncoderFactory();
-        allPassed &= testEncoderStateManagement();
-        allPassed &= testErrorHandling();
-        
-        Logger::instance().info("=== 测试结果 ===");
-        if (allPassed) {
-            Logger::instance().info("[成功] 所有音频编码器测试通过!");
-        } else {
-            Logger::instance().error("[失败] 部分测试失败!");
-        }
-        
-        return allPassed;
-    }
-    
-private:
-    /**
-     * 创建测试音频帧
-     */
-    AVFramePtr createTestAudioFrame(const AudioEncoderParams& params) {
-        AVFramePtr frame = makeAVFrame();
-        if (!frame) {
-            return nullptr;
-        }
-        
-        frame->format = params.sampleFormat;
-        frame->sample_rate = params.sampleRate;
-        frame->nb_samples = params.frameSize > 0 ? params.frameSize : 1024;
-        
-        // 设置声道布局
-        if (params.channelLayout.nb_channels > 0) {
-            av_channel_layout_copy(&frame->ch_layout, &params.channelLayout);
-        } else {
-            av_channel_layout_default(&frame->ch_layout, params.channels);
-        }
-        
-        // 分配音频缓冲区
-        int ret = av_frame_get_buffer(frame.get(), 0);
-        if (ret < 0) {
-            return nullptr;
-        }
-        
-        // 填充测试数据(简单的正弦波)
-        fillTestAudioData(frame.get());
-        
-        return frame;
-    }
-    
-    /**
-     * 填充测试音频数据
-     */
-    void fillTestAudioData(AVFrame* frame) {
-        if (frame->format == AV_SAMPLE_FMT_FLTP) {
-            // 浮点平面格式
-            for (int ch = 0; ch < frame->ch_layout.nb_channels; ch++) {
-                float* data = reinterpret_cast<float*>(frame->data[ch]);
-                for (int i = 0; i < frame->nb_samples; i++) {
-                    // 生成440Hz正弦波
-                    double t = static_cast<double>(i) / frame->sample_rate;
-                    data[i] = static_cast<float>(0.5 * sin(2.0 * M_PI * 440.0 * t));
-                }
-            }
-        } else if (frame->format == AV_SAMPLE_FMT_S16) {
-            // 16位整数格式
-            int16_t* data = reinterpret_cast<int16_t*>(frame->data[0]);
-            for (int i = 0; i < frame->nb_samples * frame->ch_layout.nb_channels; i++) {
-                double t = static_cast<double>(i / frame->ch_layout.nb_channels) / frame->sample_rate;
-                data[i] = static_cast<int16_t>(16384 * sin(2.0 * M_PI * 440.0 * t));
-            }
-        }
-    }
-};
-
-int main() {
-    try {
-        AudioEncoderTester tester;
-        bool success = tester.runAllTests();
-        return success ? 0 : 1;
-    } catch (const std::exception& e) {
-        Logger::instance().errorf("测试程序异常: {}", e.what());
-        return 1;
-    }
-}

+ 0 - 41
AV/test/test_audio_fix.cpp

@@ -1,41 +0,0 @@
-#include "code/capture/capture_audio_capturer.h"
-#include "code/base/logger.h"
-#include <iostream>
-
-using namespace av::capture;
-
-int main() {
-    // 初始化日志
-    av::Logger::instance().setLevel(av::LogLevel::DEBUG);
-    
-    std::cout << "测试音频采集器修复..." << std::endl;
-    
-    // 创建音频采集器
-    AudioCapturer capturer;
-    
-    // 设置参数
-    AudioCaptureParams params(CapturerType::AUDIO_MIC);
-    params.micIndex = 0;
-    params.sampleRate = 44100;
-    params.channels = 1;
-    params.sampleFormat = AV_SAMPLE_FMT_S16;
-    
-    // 初始化采集器
-    auto result = capturer.initialize(params);
-    
-    if (result == av::ErrorCode::SUCCESS) {
-        std::cout << "✓ 音频采集器初始化成功!" << std::endl;
-        
-        // 测试设备枚举
-        auto devices = capturer.getAvailableDevices();
-        std::cout << "找到 " << devices.size() << " 个音频设备" << std::endl;
-        
-        capturer.close();
-    } else {
-        std::cout << "✗ 音频采集器初始化失败,错误码: " << static_cast<int>(result) << std::endl;
-        return 1;
-    }
-    
-    std::cout << "测试完成!" << std::endl;
-    return 0;
-}

+ 0 - 70
AV/test/test_audio_recorder_complete.cpp

@@ -1,70 +0,0 @@
-#include "code/recorder/recorder_audio_recorder.h"
-#include "code/base/logger.h"
-#include <iostream>
-#include <thread>
-#include <chrono>
-
-using namespace av;
-using namespace av::recorder;
-
-int main() {
-    // 初始化日志
-    Logger::instance().setLevel(LogLevel::DEBUG);
-    Logger::instance().info("开始测试音频录制器完整修复");
-    
-    try {
-        // 创建音频录制器
-        auto audioRecorder = std::make_unique<AudioRecorder>();
-        
-        // 设置录制参数
-        RecorderParams params;
-        params.type = MediaType::AUDIO;
-        params.outputPath = "test_audio_complete.aac";
-        params.audioParams.sampleRate = 44100;
-        params.audioParams.channels = 2;
-        params.audioParams.sampleFormat = AV_SAMPLE_FMT_S16;
-        params.audioParams.bitrate = 128000;
-        params.audioParams.codecName = "aac";
-        params.audioParams.deviceId = "";
-        
-        std::cout << "初始化音频录制器..." << std::endl;
-        ErrorCode result = audioRecorder->initialize(params);
-        if (result != ErrorCode::SUCCESS) {
-            std::cerr << "音频录制器初始化失败: " << static_cast<int>(result) << std::endl;
-            return -1;
-        }
-        std::cout << "音频录制器初始化成功!" << std::endl;
-        
-        std::cout << "开始录制..." << std::endl;
-        result = audioRecorder->startRecording();
-        if (result != ErrorCode::SUCCESS) {
-            std::cerr << "开始录制失败: " << static_cast<int>(result) << std::endl;
-            return -1;
-        }
-        std::cout << "录制已开始!" << std::endl;
-        
-        // 录制5秒
-        std::cout << "录制中,请说话..." << std::endl;
-        std::this_thread::sleep_for(std::chrono::seconds(5));
-        
-        std::cout << "停止录制..." << std::endl;
-        result = audioRecorder->stopRecording();
-        if (result != ErrorCode::SUCCESS) {
-            std::cerr << "停止录制失败: " << static_cast<int>(result) << std::endl;
-            return -1;
-        }
-        std::cout << "录制已停止!" << std::endl;
-        
-        // 关闭录制器
-        audioRecorder->close();
-        std::cout << "音频录制器已关闭" << std::endl;
-        
-        std::cout << "测试完成! 输出文件: test_audio_complete.aac" << std::endl;
-        
-    } catch (const std::exception& e) {
-        std::cerr << "测试过程中发生异常: " << e.what() << std::endl;
-        return -1;
-    }
-    
-    return 0;
-}

+ 0 - 72
AV/test/test_audio_recorder_fix.cpp

@@ -1,72 +0,0 @@
-#include "code/recorder/recorder_audio_recorder.h"
-#include "code/base/logger.h"
-#include <iostream>
-#include <thread>
-#include <chrono>
-
-using namespace av::recorder;
-using namespace av;
-
-int main() {
-    // 初始化日志
-    Logger::instance().setLevel(LogLevel::DEBUG);
-    
-    std::cout << "测试音频录制器修复..." << std::endl;
-    
-    try {
-        // 创建音频录制器
-        AudioRecorder recorder;
-        
-        // 设置录制参数
-        AudioRecorderParams params;
-        params.capturerType = capture::CapturerType::AUDIO_MIC;
-        params.sampleRate = 44100;
-        params.channels = 2;  // 设置为2声道
-        params.sampleFormat = AV_SAMPLE_FMT_S16;
-        params.codecName = "aac";
-        params.bitrate = 128000;
-        params.outputPath = "./test_audio_fix.mp4";
-        params.format = "mp4";
-        
-        std::cout << "初始化录制器参数: " << params.sampleRate << "Hz, " 
-                  << params.channels << "ch, " << params.codecName << std::endl;
-        
-        // 初始化录制器
-        ErrorCode result = recorder.initialize(params);
-        
-        if (result == ErrorCode::SUCCESS) {
-            std::cout << "✓ 音频录制器初始化成功!" << std::endl;
-            
-            // 尝试开始录制
-            result = recorder.startRecording();
-            if (result == ErrorCode::SUCCESS) {
-                std::cout << "✓ 音频录制开始成功!" << std::endl;
-                
-                // 录制3秒
-                std::this_thread::sleep_for(std::chrono::seconds(3));
-                
-                // 停止录制
-                result = recorder.stopRecording();
-                if (result == ErrorCode::SUCCESS) {
-                    std::cout << "✓ 音频录制停止成功!" << std::endl;
-                } else {
-                    std::cout << "✗ 停止录制失败,错误码: " << static_cast<int>(result) << std::endl;
-                }
-            } else {
-                std::cout << "✗ 开始录制失败,错误码: " << static_cast<int>(result) << std::endl;
-            }
-            
-            recorder.close();
-        } else {
-            std::cout << "✗ 音频录制器初始化失败,错误码: " << static_cast<int>(result) << std::endl;
-            return 1;
-        }
-        
-    } catch (const std::exception& e) {
-        std::cout << "✗ 异常: " << e.what() << std::endl;
-        return 1;
-    }
-    
-    std::cout << "测试完成!" << std::endl;
-    return 0;
-}

+ 0 - 156
AV/test/test_basic.cpp

@@ -1,156 +0,0 @@
-// 基础设施测试程序
-#include "code/base/logger.h"
-#include "code/base/media_thread_base.h"
-#include "code/base/media_common.h"
-#include <iostream>
-#include <thread>
-#include <chrono>
-
-using namespace av;
-
-// 测试线程类
-class TestThread : public ThreadBase {
-public:
-    TestThread() {
-        setThreadName("TestThread");
-    }
-    
-protected:
-    void run() override {
-        AV_LOGGER_INFO("Test thread started");
-        
-        for (int i = 0; i < 10 && !shouldExit(); ++i) {
-            AV_LOGGER_INFOF("Test thread iteration: {}", i);
-            
-            if (!waitForMs(100)) {
-                break; // 收到退出信号
-            }
-        }
-        
-        AV_LOGGER_INFO("Test thread finished");
-    }
-};
-
-int main() {
-    std::cout << "=== AV基础设施测试 ===" << std::endl;
-    
-    // 1. 测试日志系统
-    std::cout << "1. 测试日志系统..." << std::endl;
-    Logger::initialize("test_log.txt", LogLevel::DEBUG, false, true);
-
-    AV_LOGGER_DEBUG("这是一条调试信息");
-    AV_LOGGER_INFO("这是一条信息");
-    AV_LOGGER_WARNING("这是一条警告");
-    AV_LOGGER_ERROR("这是一条错误");
-    
-    AV_LOGGER_INFOF("格式化日志测试: {} + {} = {}", 1, 2, 3);
-    
-    // 2. 测试时间工具
-    std::cout << "2. 测试时间工具..." << std::endl;
-    {
-        AV_SCOPED_TIMER("测试代码块");
-        std::this_thread::sleep_for(std::chrono::milliseconds(50));
-    }
-    
-    time_utils::Timer timer;
-    timer.start();
-    std::this_thread::sleep_for(std::chrono::milliseconds(100));
-    timer.stop();
-    AV_LOGGER_INFOF("计时器测试: {} ms", timer.elapsedMs());
-    
-    // 3. 测试字符串工具
-    std::cout << "3. 测试字符串工具..." << std::endl;
-    std::string testStr = "  Hello, World!  ";
-    AV_LOGGER_INFOF("原始字符串: '{}'", testStr);
-    AV_LOGGER_INFOF("修剪后: '{}'", string_utils::trim(testStr));
-    AV_LOGGER_INFOF("转大写: '{}'", string_utils::toUpper(testStr));
-    
-    auto parts = string_utils::split("a,b,c,d", ',');
-    AV_LOGGER_INFOF("分割结果数量: {}", parts.size());
-    
-    // 4. 测试路径工具
-    std::cout << "4. 测试路径工具..." << std::endl;
-    std::string path = "C:/test/file.txt";
-    AV_LOGGER_INFOF("路径: {}", path);
-    AV_LOGGER_INFOF("目录: {}", path_utils::getDirectory(path));
-    AV_LOGGER_INFOF("文件名: {}", path_utils::getFilename(path));
-    AV_LOGGER_INFOF("扩展名: {}", path_utils::getExtension(path));
-    
-    // 5. 测试线程基类
-    std::cout << "5. 测试线程基类..." << std::endl;
-    {
-        TestThread testThread;
-        
-        testThread.setOnStarted([]() {
-            AV_LOGGER_INFO("线程启动回调被调用");
-        });
-        
-        testThread.setOnFinished([]() {
-            AV_LOGGER_INFO("线程完成回调被调用");
-        });
-        
-        AV_LOGGER_INFO("启动测试线程...");
-        if (testThread.start()) {
-            AV_LOGGER_INFO("测试线程启动成功");
-            
-            // 让线程运行一段时间
-            std::this_thread::sleep_for(std::chrono::milliseconds(300));
-            
-            AV_LOGGER_INFO("停止测试线程...");
-            testThread.stop();
-            testThread.join();
-            
-            AV_LOGGER_INFO("测试线程已停止");
-        } else {
-            AV_LOGGER_ERROR("测试线程启动失败");
-        }
-    }
-    
-    // 6. 测试工作线程
-    std::cout << "6. 测试工作线程..." << std::endl;
-    {
-        int counter = 0;
-        auto worker = makeWorkerThread([&counter]() {
-            counter++;
-            AV_LOGGER_INFOF("工作线程计数: {}", counter);
-        }, 50);
-        
-        worker->setThreadName("WorkerThread");
-        worker->start();
-        
-        std::this_thread::sleep_for(std::chrono::milliseconds(200));
-        
-        worker->stop();
-        worker->join();
-        
-        AV_LOGGER_INFOF("工作线程最终计数: {}", counter);
-    }
-    
-    // 7. 测试内存池
-    std::cout << "7. 测试内存池..." << std::endl;
-    {
-        memory_utils::MemoryPool pool(64, 10);
-        
-        std::vector<void*> ptrs;
-        for (int i = 0; i < 5; ++i) {
-            void* ptr = pool.allocate();
-            if (ptr) {
-                ptrs.push_back(ptr);
-                AV_LOGGER_INFOF("分配内存块 {}", i);
-            }
-        }
-        
-        AV_LOGGER_INFOF("剩余可用块: {}", pool.getAvailableBlocks());
-        
-        for (void* ptr : ptrs) {
-            pool.deallocate(ptr);
-        }
-        
-        AV_LOGGER_INFOF("释放后可用块: {}", pool.getAvailableBlocks());
-    }
-    
-    AV_LOGGER_INFO("=== 所有测试完成 ===");
-    std::cout << "测试完成,请查看 test_log.txt 文件" << std::endl;
-    
-    return 0;
-}

+ 0 - 207
AV/test/test_codec.cpp

@@ -1,207 +0,0 @@
-// 编解码测试程序
-#include "code/base/logger.h"
-#include "code/codec/codec_video_encoder.h"
-#include "code/codec/codec_audio_encoder.h"
-#include <iostream>
-#include <chrono>
-#include <thread>
-
-using namespace av;
-using namespace av::codec;
-
-int main() {
-    AV_LOGGER_INFO("=== AV编解码测试 ===");
-    
-    // 初始化日志系统
-    Logger::initialize("codec_test_log.txt", LogLevel::DEBUG, false, true);
-
-    // 初始化FFmpeg
-    ffmpeg_utils::initializeFFmpeg();
-    
-    try {
-        // 1. 测试视频编码器支持
-        AV_LOGGER_INFO("1. 测试视频编码器支持...");
-        auto videoEncoders = VideoEncoder::getSupportedEncoders();
-        AV_LOGGER_INFOF("支持的视频编码器数量: {}", videoEncoders.size());
-        
-        for (const auto& encoder : videoEncoders) {
-            AV_LOGGER_INFOF("  - {} (硬件: {})", encoder, 
-                         VideoEncoder::isHardwareEncoder(encoder) ? "是" : "否");
-        }
-        
-        std::string recommendedVideo = VideoEncoder::getRecommendedEncoder();
-        AV_LOGGER_INFOF("推荐的视频编码器: {}", recommendedVideo);
-        
-        // 2. 测试音频编码器支持
-        AV_LOGGER_INFO("2. 测试音频编码器支持...");
-        auto audioEncoders = AudioEncoder::getSupportedEncoders();
-        AV_LOGGER_INFOF("支持的音频编码器数量: {}", audioEncoders.size());
-        
-        for (const auto& encoder : audioEncoders) {
-            AV_LOGGER_INFOF("  - {}", encoder);
-        }
-        
-        std::string recommendedAudio = AudioEncoder::getRecommendedEncoder();
-        AV_LOGGER_INFOF("推荐的音频编码器: {}", recommendedAudio);
-        
-        // 3. 测试视频编码器创建和配置
-        AV_LOGGER_INFO("3. 测试视频编码器创建...");
-        if (!recommendedVideo.empty()) {
-            auto videoEncoder = VideoEncoderFactory::create(recommendedVideo);
-            if (videoEncoder) {
-                AV_LOGGER_INFO("视频编码器创建成功");
-                
-                // 配置编码器参数
-                VideoEncoderParams videoParams;
-                videoParams.codecName = recommendedVideo;
-                videoParams.width = 1280;
-                videoParams.height = 720;
-                videoParams.fps = 30;
-                videoParams.bitRate = 2000000;
-                videoParams.lowLatency = true;
-                videoParams.hardwareAccel = true;  // 启用硬件加速
-                
-                AVResult result = videoEncoder->open(videoParams);
-                if (result == AVResult::SUCCESS) {
-                    AV_LOGGER_INFO("视频编码器打开成功");
-                    
-                    // 测试编码器状态
-                    AV_LOGGER_INFOF("编码器状态: {}", static_cast<int>(videoEncoder->getState()));
-                    AV_LOGGER_INFOF("是否已打开: {}", videoEncoder->isOpened() ? "是" : "否");
-                    
-                    videoEncoder->close();
-                    AV_LOGGER_INFO("视频编码器已关闭");
-                } else {
-                    AV_LOGGER_ERRORF("硬件视频编码器打开失败: {}", static_cast<int>(result));
-                    
-                    // 尝试软件编码器
-                    AV_LOGGER_INFO("尝试使用软件编码器...");
-                    videoParams.hardwareAccel = false;
-                    videoParams.codecName = "libx264";
-                    
-                    auto softwareEncoder = VideoEncoderFactory::create("libx264");
-                    if (softwareEncoder) {
-                        AVResult softResult = softwareEncoder->open(videoParams);
-                        if (softResult == AVResult::SUCCESS) {
-                            AV_LOGGER_INFO("软件视频编码器打开成功");
-                            softwareEncoder->close();
-                            AV_LOGGER_INFO("软件视频编码器已关闭");
-                        } else {
-                            AV_LOGGER_ERRORF("软件视频编码器打开失败: {}", static_cast<int>(softResult));
-                        }
-                    }
-                }
-            } else {
-                AV_LOGGER_ERROR("视频编码器创建失败");
-            }
-        } else {
-            AV_LOGGER_WARNING("没有可用的视频编码器");
-        }
-        
-        // 4. 测试音频编码器创建和配置
-        AV_LOGGER_INFO("4. 测试音频编码器创建...");
-        if (!recommendedAudio.empty()) {
-            auto audioEncoder = AudioEncoderFactory::create(recommendedAudio);
-            if (audioEncoder) {
-                AV_LOGGER_INFO("音频编码器创建成功");
-                
-                // 配置编码器参数
-                AudioEncoderParams audioParams;
-                audioParams.codecName = recommendedAudio;
-                audioParams.sampleRate = 44100;
-                audioParams.channels = 2;
-                audioParams.bitRate = 128000;
-                av_channel_layout_default(&audioParams.channelLayout, 2);
-                
-                AVResult result = audioEncoder->open(audioParams);
-                if (result == AVResult::SUCCESS) {
-                    AV_LOGGER_INFO("音频编码器打开成功");
-                    
-                    // 测试编码器状态
-                    AV_LOGGER_INFOF("编码器状态: {}", static_cast<int>(audioEncoder->getState()));
-                    AV_LOGGER_INFOF("是否已打开: {}", audioEncoder->isOpened() ? "是" : "否");
-                    
-                    audioEncoder->close();
-                    AV_LOGGER_INFO("音频编码器已关闭");
-                } else {
-                    AV_LOGGER_ERRORF("音频编码器打开失败: {}", static_cast<int>(result));
-                }
-            } else {
-                AV_LOGGER_ERROR("音频编码器创建失败");
-            }
-        } else {
-            AV_LOGGER_WARNING("没有可用的音频编码器");
-        }
-        
-        // 5. 测试编码器工厂
-        AV_LOGGER_INFO("5. 测试编码器工厂...");
-        
-        // 测试最佳视频编码器
-        auto bestVideoEncoder = VideoEncoderFactory::createBest(true);
-        if (bestVideoEncoder) {
-            AV_LOGGER_INFO("最佳视频编码器创建成功(硬件优先)");
-        }
-        
-        auto softwareVideoEncoder = VideoEncoderFactory::createBest(false);
-        if (softwareVideoEncoder) {
-            AV_LOGGER_INFO("最佳视频编码器创建成功(软件优先)");
-        }
-        
-        // 测试最佳音频编码器
-        auto bestAudioEncoder = AudioEncoderFactory::createBest();
-        if (bestAudioEncoder) {
-            AV_LOGGER_INFO("最佳音频编码器创建成功");
-        }
-        
-        // 测试无损音频编码器
-        auto losslessAudioEncoder = AudioEncoderFactory::createLossless();
-        if (losslessAudioEncoder) {
-            AV_LOGGER_INFO("无损音频编码器创建成功");
-        }
-        
-        // 6. 测试编码器能力查询
-        AV_LOGGER_INFO("6. 测试编码器能力查询...");
-        
-        // 测试音频编码器能力
-        if (!recommendedAudio.empty()) {
-            bool supportsFLTP = AudioEncoder::isSampleFormatSupported(recommendedAudio, AV_SAMPLE_FMT_FLTP);
-            bool supports44100 = AudioEncoder::isSampleRateSupported(recommendedAudio, 44100);
-            
-            AVChannelLayout stereoLayout = AV_CHANNEL_LAYOUT_STEREO;
-            bool supportsStereo = AudioEncoder::isChannelLayoutSupported(recommendedAudio, stereoLayout);
-            
-            AV_LOGGER_INFOF("编码器 {} 支持:", recommendedAudio);
-            AV_LOGGER_INFOF("  - FLTP格式: {}", supportsFLTP ? "是" : "否");
-            AV_LOGGER_INFOF("  - 44100Hz: {}", supports44100 ? "是" : "否");
-            AV_LOGGER_INFOF("  - 立体声: {}", supportsStereo ? "是" : "否");
-        }
-        
-        // 7. 测试编码器统计信息
-        AV_LOGGER_INFO("7. 测试编码器统计信息...");
-        if (!recommendedVideo.empty()) {
-            auto encoder = VideoEncoderFactory::create(recommendedVideo);
-            if (encoder) {
-                const auto& stats = encoder->getStatistics();
-                AV_LOGGER_INFOF("编码器统计信息:");
-                AV_LOGGER_INFOF("  - 处理帧数: {}", stats.processedFrames);
-                AV_LOGGER_INFOF("  - 丢弃帧数: {}", stats.droppedFrames);
-                AV_LOGGER_INFOF("  - 错误次数: {}", stats.errorCount);
-                AV_LOGGER_INFOF("  - 平均处理时间: {:.2f}ms", stats.avgProcessTime);
-                AV_LOGGER_INFOF("  - 总字节数: {}", stats.totalBytes);
-            }
-        }
-
-        AV_LOGGER_INFO("=== 所有编解码测试完成 ===");
-        AV_LOGGER_INFO("测试完成,请查看 codec_test_log.txt 文件");
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERRORF("测试过程中发生异常: {}", e.what());
-        AV_LOGGER_ERRORF("测试失败: {}", e.what());
-        return 1;
-    }
-    
-    // 清理FFmpeg
-    ffmpeg_utils::cleanupFFmpeg();
-    
-    return 0;
-}

+ 0 - 353
AV/test/test_decoder.cpp

@@ -1,353 +0,0 @@
-#include "code/base/logger.h"
-#include "code/base/types.h"
-#include "code/codec/codec_audio_decoder.h"
-#include "code/codec/codec_video_decoder.h"
-#include <chrono>
-#include <fstream>
-#include <iostream>
-#include <memory>
-#include <vector>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavcodec/avcodec.h>
-#include <libavutil/avutil.h>
-}
-
-using namespace av;
-using namespace av::codec;
-
-class DecoderTester {
-public:
-    DecoderTester() {
-        // 初始化FFmpeg
-        av_log_set_level(AV_LOG_INFO);
-        
-        // 初始化日志系统
-        av::Logger::instance().setLevel(av::LogLevel::DEBUG);
-        av::Logger::instance().addOutput(std::make_unique<av::QtOutput>());
-
-        std::cout << "=== AV解码器测试程序 ===" << std::endl;
-        std::cout << "FFmpeg版本: " << av_version_info() << std::endl;
-    }
-    
-    ~DecoderTester() {
-        // 日志系统自动清理
-    }
-    
-    // 测试视频解码器基本功能
-    bool testVideoDecoderBasic() {
-        std::cout << "\n--- 测试视频解码器基本功能 ---" << std::endl;
-        
-        try {
-            // 创建解码器
-            auto decoder = std::make_unique<VideoDecoder>();
-            
-            // 测试支持的解码器列表
-            auto supportedDecoders = VideoDecoder::getSupportedDecoders();
-            std::cout << "支持的视频解码器数量: " << supportedDecoders.size() << std::endl;
-            
-            for (const auto& codecName : supportedDecoders) {
-                std::cout << "  - " << codecName;
-                if (VideoDecoder::isHardwareDecoder(codecName)) {
-                    std::cout << " (硬件加速)";
-                }
-                std::cout << std::endl;
-            }
-            
-            // 测试H.264解码器初始化
-            VideoDecoderParams params;
-            params.codecName = "h264";
-            params.pixelFormat = AV_PIX_FMT_YUV420P;
-            params.hardwareAccel = false; // 先测试软件解码
-            params.threadCount = 4;
-            
-            ErrorCode result = decoder->open(params);
-            if (result != ErrorCode::SUCCESS) {
-                std::cerr << "打开H.264解码器失败: " << static_cast<int>(result) << std::endl;
-                return false;
-            }
-            
-            std::cout << "H.264解码器初始化成功" << std::endl;
-            std::cout << "解码器名称: " << decoder->getDecoderName() << std::endl;
-            std::cout << "是否硬件解码器: " << (decoder->isHardwareDecoder() ? "是" : "否") << std::endl;
-            
-            // 测试统计信息
-            auto stats = decoder->getStats();
-            std::cout << "初始统计信息:" << std::endl;
-            std::cout << "  解码帧数: " << stats.decodedFrames << std::endl;
-            std::cout << "  丢弃帧数: " << stats.droppedFrames << std::endl;
-            std::cout << "  错误次数: " << stats.errorCount << std::endl;
-            
-            decoder->close();
-            std::cout << "视频解码器基本功能测试通过" << std::endl;
-            return true;
-            
-        } catch (const std::exception& e) {
-            std::cerr << "视频解码器测试异常: " << e.what() << std::endl;
-            return false;
-        }
-    }
-    
-    // 测试音频解码器基本功能
-    bool testAudioDecoderBasic() {
-        std::cout << "\n--- 测试音频解码器基本功能 ---" << std::endl;
-        
-        try {
-            // 创建解码器
-            auto decoder = std::make_unique<AudioDecoder>();
-            
-            // 测试AAC解码器初始化
-            AudioDecoderParams params;
-            params.codecName = "aac";
-            params.sampleRate = 44100;
-            params.channels = 2;
-            params.sampleFormat = AV_SAMPLE_FMT_S16;
-             params.enableResampling = true;
-            
-            ErrorCode result = decoder->open(params);
-            if (result != ErrorCode::SUCCESS) {
-                std::cerr << "打开AAC解码器失败: " << static_cast<int>(result) << std::endl;
-                return false;
-            }
-            
-            std::cout << "AAC解码器初始化成功" << std::endl;
-            std::cout << "解码器名称: " << decoder->getDecoderName() << std::endl;
-            std::cout << "是否启用重采样: " << (decoder->isResamplingEnabled() ? "是" : "否") << std::endl;
-            
-            // 测试统计信息
-            auto stats = decoder->getStats();
-            std::cout << "初始统计信息:" << std::endl;
-            std::cout << "  解码帧数: " << stats.decodedFrames << std::endl;
-            std::cout << "  重采样帧数: " << stats.resampledFrames << std::endl;
-            std::cout << "  错误次数: " << stats.errorCount << std::endl;
-            
-            decoder->close();
-            std::cout << "音频解码器基本功能测试通过" << std::endl;
-            return true;
-            
-        } catch (const std::exception& e) {
-            std::cerr << "音频解码器测试异常: " << e.what() << std::endl;
-            return false;
-        }
-    }
-    
-    // 测试硬件加速解码器
-    bool testHardwareDecoder() {
-        std::cout << "\n--- 测试硬件加速解码器 ---" << std::endl;
-        
-        try {
-            // 获取推荐的硬件解码器
-            std::string recommendedDecoder = VideoDecoder::getRecommendedDecoder();
-            if (recommendedDecoder.empty()) {
-                std::cout << "未找到推荐的硬件解码器,跳过测试" << std::endl;
-                return true;
-            }
-            
-            std::cout << "推荐的解码器: " << recommendedDecoder << std::endl;
-            
-            auto decoder = std::make_unique<VideoDecoder>();
-            
-            VideoDecoderParams params;
-            params.codecName = recommendedDecoder;
-            params.hardwareAccel = true;
-            params.lowLatency = true;
-            
-            ErrorCode result = decoder->open(params);
-            if (result != ErrorCode::SUCCESS) {
-                std::cout << "硬件解码器打开失败,可能不支持: " << static_cast<int>(result) << std::endl;
-                return true; // 不算失败,因为硬件支持因环境而异
-            }
-            
-            std::cout << "硬件解码器测试成功" << std::endl;
-            std::cout << "解码器名称: " << decoder->getDecoderName() << std::endl;
-            std::cout << "是否硬件解码器: " << (decoder->isHardwareDecoder() ? "是" : "否") << std::endl;
-            
-            decoder->close();
-            return true;
-            
-        } catch (const std::exception& e) {
-            std::cout << "硬件解码器测试异常(可能正常): " << e.what() << std::endl;
-            return true; // 硬件相关异常不算失败
-        }
-    }
-    
-    // 测试解码器工厂
-    bool testDecoderFactory() {
-        std::cout << "\n--- 测试解码器工厂 ---" << std::endl;
-        
-        try {
-            // 测试创建最佳解码器
-            auto bestDecoder = VideoDecoder::VideoDecoderFactory::createBest(false); // 优先软件解码
-            if (!bestDecoder) {
-                std::cerr << "创建最佳解码器失败" << std::endl;
-                return false;
-            }
-            
-            std::cout << "成功创建最佳软件解码器" << std::endl;
-            
-            // 测试创建指定解码器
-            auto h264Decoder = VideoDecoder::VideoDecoderFactory::create("h264");
-            if (!h264Decoder) {
-                std::cerr << "创建H.264解码器失败" << std::endl;
-                return false;
-            }
-            
-            std::cout << "成功创建H.264解码器" << std::endl;
-            
-            // 测试创建硬件解码器
-            auto hwDecoder = VideoDecoder::VideoDecoderFactory::createBest(true); // 优先硬件解码
-            if (hwDecoder) {
-                std::cout << "成功创建硬件解码器" << std::endl;
-            } else {
-                std::cout << "硬件解码器不可用(正常)" << std::endl;
-            }
-            
-            std::cout << "解码器工厂测试通过" << std::endl;
-            return true;
-            
-        } catch (const std::exception& e) {
-            std::cerr << "解码器工厂测试异常: " << e.what() << std::endl;
-            return false;
-        }
-    }
-    
-    // 测试解码器状态管理
-    bool testDecoderStateManagement() {
-        std::cout << "\n--- 测试解码器状态管理 ---" << std::endl;
-        
-        try {
-            auto decoder = std::make_unique<VideoDecoder>();
-            
-            // 测试初始状态
-            if (decoder->getState() != CodecState::IDLE) {
-                std::cerr << "初始状态错误" << std::endl;
-                return false;
-            }
-            
-            // 测试打开
-            VideoDecoderParams params;
-            params.codecName = "h264";
-            
-            ErrorCode result = decoder->open(params);
-            if (result != ErrorCode::SUCCESS) {
-                std::cerr << "打开失败" << std::endl;
-                return false;
-            }
-            
-            if (decoder->getState() != CodecState::OPENED) {
-                std::cerr << "打开后状态错误" << std::endl;
-                return false;
-            }
-            
-            // 测试重置
-            result = decoder->reset();
-            if (result != ErrorCode::SUCCESS) {
-                std::cerr << "重置失败" << std::endl;
-                return false;
-            }
-            
-            if (decoder->getState() != CodecState::OPENED) {
-                std::cerr << "重置后状态错误" << std::endl;
-                return false;
-            }
-            
-            // 测试关闭
-            decoder->close();
-            
-            if (decoder->getState() != CodecState::IDLE) {
-                std::cerr << "关闭后状态错误" << std::endl;
-                return false;
-            }
-            
-            std::cout << "解码器状态管理测试通过" << std::endl;
-            return true;
-            
-        } catch (const std::exception& e) {
-            std::cerr << "解码器状态管理测试异常: " << e.what() << std::endl;
-            return false;
-        }
-    }
-    
-    // 测试错误处理
-    bool testErrorHandling() {
-        std::cout << "\n--- 测试错误处理 ---" << std::endl;
-        
-        try {
-            auto decoder = std::make_unique<VideoDecoder>();
-            
-            // 测试无效参数
-            VideoDecoderParams invalidParams;
-            invalidParams.codecName = ""; // 空名称
-            
-            ErrorCode result = decoder->open(invalidParams);
-            if (result == ErrorCode::SUCCESS) {
-                std::cerr << "应该拒绝空解码器名称" << std::endl;
-                return false;
-            }
-            
-            // 测试不存在的解码器
-            VideoDecoderParams nonExistentParams;
-            nonExistentParams.codecName = "non_existent_codec";
-            
-            result = decoder->open(nonExistentParams);
-            if (result == ErrorCode::SUCCESS) {
-                std::cerr << "应该拒绝不存在的解码器" << std::endl;
-                return false;
-            }
-            
-            // 测试状态错误
-            auto decoder2 = std::make_unique<VideoDecoder>();
-            VideoDecoderParams emptyParams;
-            result = decoder2->open(emptyParams); // 空参数打开
-            if (result == ErrorCode::SUCCESS) {
-                std::cerr << "应该拒绝空参数的打开操作" << std::endl;
-                return false;
-            }
-            
-            std::cout << "错误处理测试通过" << std::endl;
-            return true;
-            
-        } catch (const std::exception& e) {
-            std::cerr << "错误处理测试异常: " << e.what() << std::endl;
-            return false;
-        }
-    }
-    
-    // 运行所有测试
-    bool runAllTests() {
-        std::cout << "\n开始运行解码器测试套件..." << std::endl;
-        
-        bool allPassed = true;
-        
-        allPassed &= testVideoDecoderBasic();
-        allPassed &= testAudioDecoderBasic();
-        allPassed &= testHardwareDecoder();
-        allPassed &= testDecoderFactory();
-        allPassed &= testDecoderStateManagement();
-        allPassed &= testErrorHandling();
-        
-        std::cout << "\n=== 测试结果 ===" << std::endl;
-        if (allPassed) {
-            std::cout << "✅ 所有测试通过!" << std::endl;
-        } else {
-            std::cout << "❌ 部分测试失败!" << std::endl;
-        }
-        
-        return allPassed;
-    }
-};
-
-int main() {
-    try {
-        DecoderTester tester;
-        bool success = tester.runAllTests();
-        return success ? 0 : 1;
-    } catch (const std::exception& e) {
-        std::cerr << "程序异常: " << e.what() << std::endl;
-        return 1;
-    } catch (...) {
-        std::cerr << "未知异常" << std::endl;
-        return 1;
-    }
-}

+ 0 - 433
AV/test/test_muxer.cpp

@@ -1,433 +0,0 @@
-#include "code/muxer/muxer_abstract_muxer.h"
-#include "code/muxer/muxer_file_muxer.h"
-#include "code/muxer/muxer_stream_muxer.h"
-#include "code/base/logger.h"
-#include "code/base/media_common.h"
-#include <iostream>
-#include <memory>
-#include <vector>
-#include <chrono>
-#include <thread>
-#include <filesystem>
-
-using namespace av;
-using namespace av::muxer;
-
-// 测试结果统计
-struct TestResults {
-    int totalTests = 0;
-    int passedTests = 0;
-    std::vector<std::string> failedTests;
-    
-    void addTest(const std::string& testName, bool passed) {
-        totalTests++;
-        if (passed) {
-            passedTests++;
-            AV_LOGGER_INFO("✓ " + testName + " - PASSED");
-        } else {
-            failedTests.push_back(testName);
-            AV_LOGGER_ERROR("✗ " + testName + " - FAILED");
-        }
-    }
-    
-    void printSummary() {
-        AV_LOGGER_INFO("\n=== Muxer Test Summary ===");
-        AV_LOGGER_INFO("Total tests: " + std::to_string(totalTests));
-        AV_LOGGER_INFO("Passed: " + std::to_string(passedTests));
-        AV_LOGGER_INFO("Failed: " + std::to_string(failedTests.size()));
-        
-        if (!failedTests.empty()) {
-            AV_LOGGER_ERROR("Failed tests:");
-            for (const auto& test : failedTests) {
-                AV_LOGGER_ERROR("  - " + test);
-            }
-        }
-        
-        double successRate = totalTests > 0 ? (double)passedTests / totalTests * 100.0 : 0.0;
-        AV_LOGGER_INFO("Success rate: " + std::to_string(successRate) + "%");
-    }
-};
-
-// 创建测试用的AVPacket
-AVPacket* createTestPacket(int streamIndex, int64_t pts, int64_t dts, int size = 1024) {
-    AVPacket* packet = av_packet_alloc();
-    if (!packet) return nullptr;
-    
-    // 分配数据
-    if (av_new_packet(packet, size) < 0) {
-        av_packet_free(&packet);
-        return nullptr;
-    }
-    
-    // 填充测试数据
-    memset(packet->data, 0x42, size);
-    packet->stream_index = streamIndex;
-    packet->pts = pts;
-    packet->dts = dts;
-    packet->flags = AV_PKT_FLAG_KEY;
-    
-    return packet;
-}
-
-// 创建测试用的StreamInfo
-StreamInfo createVideoStreamInfo() {
-    StreamInfo info;
-    info.index = 0;
-    info.type = StreamType::VIDEO;
-    info.codecId = AV_CODEC_ID_H264;
-    info.codecName = "h264";
-    info.width = 1920;
-    info.height = 1080;
-    info.frameRate = {30, 1};
-    info.pixelFormat = AV_PIX_FMT_YUV420P;
-    info.bitrate = 2000000;
-    info.timeBase = {1, 30};
-    return info;
-}
-
-StreamInfo createAudioStreamInfo() {
-    StreamInfo info;
-    info.index = 1;
-    info.type = StreamType::AUDIO;
-    info.codecId = AV_CODEC_ID_AAC;
-    info.codecName = "aac";
-    info.sampleRate = 44100;
-    info.channels = 2;
-    info.sampleFormat = AV_SAMPLE_FMT_FLTP;
-    info.channelLayout = AV_CH_LAYOUT_STEREO;
-    info.bitrate = 128000;
-    info.timeBase = {1, 44100};
-    return info;
-}
-
-// 测试抽象复用器基础功能
-bool testAbstractMuxerBasics(TestResults& results) {
-    AV_LOGGER_INFO("Testing AbstractMuxer basics...");
-    
-    // 测试工厂方法
-    auto factory = MuxerFactory::createFactory();
-    bool factoryTest = factory != nullptr;
-    results.addTest("MuxerFactory creation", factoryTest);
-    
-    if (!factory) return false;
-    
-    // 测试支持的格式
-    auto formats = AbstractMuxer::getSupportedFormats();
-    bool formatsTest = !formats.empty();
-    results.addTest("Supported formats query", formatsTest);
-    
-    // 测试格式支持检查
-    bool mp4Support = AbstractMuxer::isFormatSupported("mp4");
-    bool flvSupport = AbstractMuxer::isFormatSupported("flv");
-    results.addTest("Format support check", mp4Support || flvSupport);
-    
-    // 测试扩展名到格式的转换
-    std::string mp4Format = AbstractMuxer::getFormatFromExtension("test.mp4");
-    bool extensionTest = !mp4Format.empty();
-    results.addTest("Extension to format conversion", extensionTest);
-    
-    return factoryTest && formatsTest;
-}
-
-// 测试文件复用器
-bool testFileMuxer(TestResults& results) {
-    AV_LOGGER_INFO("Testing FileMuxer...");
-    
-    try {
-        // 创建文件复用器
-        auto factory = std::make_unique<FileMuxer::FileMuxerFactory>();
-        auto muxer = factory->createMuxer(MuxerType::FILE_MUXER);
-        bool creationTest = muxer != nullptr;
-        results.addTest("FileMuxer creation", creationTest);
-        
-        if (!muxer) return false;
-        
-        auto fileMuxer = dynamic_cast<FileMuxer*>(muxer.get());
-        if (!fileMuxer) {
-            results.addTest("FileMuxer cast", false);
-            return false;
-        }
-        
-        // 设置参数
-        FileMuxerParams params;
-        params.outputFile = "test_output.mp4";
-        params.outputPath = "test_output.mp4";  // 同时设置outputPath
-        params.format = "mp4";
-        params.overwrite = true;
-        params.enableFastStart = true;
-        
-        // 添加流信息到参数中
-        params.streams.push_back(createVideoStreamInfo());
-        params.streams.push_back(createAudioStreamInfo());
-        
-        AV_LOGGER_INFOF("设置参数: outputFile={}, outputPath={}", params.outputFile, params.outputPath);
-        
-        // 初始化
-        ErrorCode initResult = muxer->initialize(params);
-        bool initTest = initResult == ErrorCode::SUCCESS;
-        results.addTest("FileMuxer initialization", initTest);
-        
-        if (initResult != ErrorCode::SUCCESS) {
-            AV_LOGGER_ERROR("FileMuxer initialization failed: " + muxer->getLastError());
-            return false;
-        }
-        
-        // 测试额外添加流(应该失败,因为流索引已存在)
-        ErrorCode addVideoStream = muxer->addStream(createVideoStreamInfo());
-        ErrorCode addAudioStream = muxer->addStream(createAudioStreamInfo());
-        bool streamTest = (addVideoStream == ErrorCode::STREAM_EXISTS) && (addAudioStream == ErrorCode::STREAM_EXISTS); // 期望返回STREAM_EXISTS
-        results.addTest("Duplicate stream addition", streamTest);
-        
-        // 启动
-        ErrorCode startResult = muxer->start();
-        bool startTest = startResult == ErrorCode::SUCCESS;
-        results.addTest("FileMuxer start", startTest);
-        
-        if (startResult == ErrorCode::SUCCESS) {
-            // 测试状态
-            bool runningTest = muxer->isRunning();
-            results.addTest("FileMuxer running state", runningTest);
-            
-            // 写入一些测试包
-            bool writeTest = true;
-            for (int i = 0; i < 10; i++) {
-                AVPacket* videoPacket = createTestPacket(0, i * 1000, i * 1000, 1024);
-                AVPacket* audioPacket = createTestPacket(1, i * 1000, i * 1000, 512);
-                
-                if (videoPacket && audioPacket) {
-                    ErrorCode videoWrite = muxer->writePacket(videoPacket);
-                    ErrorCode audioWrite = muxer->writePacket(audioPacket);
-                    
-                    if (videoWrite != ErrorCode::SUCCESS || audioWrite != ErrorCode::SUCCESS) {
-                        writeTest = false;
-                        av_packet_free(&videoPacket);
-                        av_packet_free(&audioPacket);
-                        break;
-                    }
-                    
-                    av_packet_free(&videoPacket);
-                    av_packet_free(&audioPacket);
-                } else {
-                    writeTest = false;
-                    if (videoPacket) av_packet_free(&videoPacket);
-                    if (audioPacket) av_packet_free(&audioPacket);
-                    break;
-                }
-                
-                std::this_thread::sleep_for(std::chrono::milliseconds(10));
-            }
-            results.addTest("Packet writing", writeTest);
-            
-            // 刷新
-            ErrorCode flushResult = muxer->flush();
-            results.addTest("FileMuxer flush", flushResult == ErrorCode::SUCCESS);
-            
-            // 获取统计信息
-            MuxerStats stats = muxer->getStats();
-            bool statsTest = stats.totalPackets > 0;
-            results.addTest("Statistics collection", statsTest);
-            
-            // 停止
-            ErrorCode stopResult = muxer->stop();
-            results.addTest("FileMuxer stop", stopResult == ErrorCode::SUCCESS);
-        }
-        
-        // 关闭
-        ErrorCode closeResult = muxer->close();
-        results.addTest("FileMuxer close", closeResult == ErrorCode::SUCCESS);
-        
-        // 检查输出文件是否存在
-        bool fileExists = std::filesystem::exists("test_output.mp4");
-        results.addTest("Output file creation", fileExists);
-        
-        // 清理测试文件
-        if (fileExists) {
-            std::filesystem::remove("test_output.mp4");
-        }
-        
-        return creationTest && initTest;
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERROR("FileMuxer test exception: " + std::string(e.what()));
-        results.addTest("FileMuxer exception handling", false);
-        return false;
-    }
-}
-
-// 测试流复用器基础功能(不实际连接)
-bool testStreamMuxer(TestResults& results) {
-    AV_LOGGER_INFO("Testing StreamMuxer basics...");
-    
-    try {
-        // 创建流复用器
-        auto factory = std::make_unique<StreamMuxer::StreamMuxerFactory>();
-        auto muxer = factory->createMuxer(MuxerType::STREAM_MUXER);
-        bool creationTest = muxer != nullptr;
-        results.addTest("StreamMuxer creation", creationTest);
-        
-        if (!muxer) return false;
-        
-        auto streamMuxer = dynamic_cast<StreamMuxer*>(muxer.get());
-        if (!streamMuxer) {
-            results.addTest("StreamMuxer cast", false);
-            return false;
-        }
-        
-        // 设置参数(使用有效URL格式,但不实际连接)
-        StreamMuxerParams params;
-        params.protocol = StreamProtocol::RTMP;
-        params.url = "rtmp://localhost/live/test";
-        params.format = "flv";
-        params.enableAutoReconnect = true;
-        params.maxReconnectAttempts = 3;
-        
-        // 添加流信息到参数中
-        params.streams.push_back(createVideoStreamInfo());
-        params.streams.push_back(createAudioStreamInfo());
-        
-        // 初始化(预期会失败,因为URL无效)
-        ErrorCode initResult = muxer->initialize(params);
-        // 对于无效URL,初始化可能成功但连接会失败
-        bool initTest = true; // 只要不崩溃就算成功
-        results.addTest("StreamMuxer initialization", initTest);
-        
-        // 测试URL设置
-        ErrorCode urlResult = streamMuxer->setUrl("rtmp://test.example.com/live/stream");
-        bool urlTest = urlResult == ErrorCode::SUCCESS;
-        results.addTest("URL setting", urlTest);
-        
-        // 测试协议选项
-        ErrorCode optionResult = streamMuxer->setProtocolOption("timeout", "5000");
-        bool optionTest = optionResult == ErrorCode::SUCCESS;
-        results.addTest("Protocol option setting", optionTest);
-        
-        // 测试自适应码率设置
-        ErrorCode bitrateResult = streamMuxer->enableAdaptiveBitrate(true);
-        bool bitrateTest = bitrateResult == ErrorCode::SUCCESS;
-        results.addTest("Adaptive bitrate setting", bitrateTest);
-        
-        // 关闭
-        ErrorCode closeResult = muxer->close();
-        results.addTest("StreamMuxer close", closeResult == ErrorCode::SUCCESS);
-        
-        return creationTest && initTest;
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERROR("StreamMuxer test exception: " + std::string(e.what()));
-        results.addTest("StreamMuxer exception handling", false);
-        return false;
-    }
-}
-
-// 测试复用器工厂
-bool testMuxerFactory(TestResults& results) {
-    AV_LOGGER_INFO("Testing MuxerFactory...");
-    
-    try {
-        // 测试文件复用器工厂
-        auto fileFactory = std::make_unique<FileMuxer::FileMuxerFactory>();
-        
-        bool fileTypeSupport = fileFactory->isTypeSupported(MuxerType::FILE_MUXER);
-        results.addTest("FileMuxer type support", fileTypeSupport);
-        
-        auto supportedTypes = fileFactory->getSupportedTypes();
-        bool typesTest = !supportedTypes.empty();
-        results.addTest("Supported types query", typesTest);
-        
-        // 测试流复用器工厂
-        auto streamFactory = std::make_unique<StreamMuxer::StreamMuxerFactory>();
-        
-        bool streamTypeSupport = streamFactory->isTypeSupported(MuxerType::STREAM_MUXER);
-        results.addTest("StreamMuxer type support", streamTypeSupport);
-        
-        // 测试便捷创建方法(预期失败,因为没有流信息)
-        auto fileMuxer = FileMuxer::FileMuxerFactory::createFileMuxer("test_factory.mp4");
-        bool fileMuxerCreation = fileMuxer == nullptr; // 期望失败,因为没有流信息
-        results.addTest("FileMuxer convenience creation", fileMuxerCreation);
-        
-        auto rtmpMuxer = StreamMuxer::StreamMuxerFactory::createRTMPMuxer("rtmp://localhost/live/test");
-        bool rtmpMuxerCreation = rtmpMuxer == nullptr; // 期望失败,因为没有流信息
-        results.addTest("RTMP muxer convenience creation", rtmpMuxerCreation);
-        
-        return fileTypeSupport && streamTypeSupport;
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERROR("MuxerFactory test exception: " + std::string(e.what()));
-        results.addTest("MuxerFactory exception handling", false);
-        return false;
-    }
-}
-
-// 测试错误处理
-bool testErrorHandling(TestResults& results) {
-    AV_LOGGER_INFO("Testing error handling...");
-    
-    try {
-        auto factory = std::make_unique<FileMuxer::FileMuxerFactory>();
-        auto muxer = factory->createMuxer(MuxerType::FILE_MUXER);
-        
-        if (!muxer) {
-            results.addTest("Error handling setup", false);
-            return false;
-        }
-        
-        // 测试无效参数
-        FileMuxerParams invalidParams;
-        invalidParams.outputFile = ""; // 空文件名
-        invalidParams.format = "invalid_format";
-        
-        ErrorCode result = muxer->initialize(invalidParams);
-        bool invalidParamsTest = result != ErrorCode::SUCCESS;
-        results.addTest("Invalid parameters handling", invalidParamsTest);
-        
-        // 测试未初始化状态下的操作
-        ErrorCode startResult = muxer->start();
-        bool uninitializedTest = startResult != ErrorCode::SUCCESS;
-        results.addTest("Uninitialized operation handling", uninitializedTest);
-        
-        // 测试错误信息获取(先初始化一个有效的复用器来确保有错误信息)
-        FileMuxerParams validParams;
-        validParams.outputFile = "test_error.mp4";
-        muxer->initialize(validParams);
-        std::string errorMsg = muxer->getLastError();
-        bool errorMsgTest = true; // 只要不崩溃就算成功
-        results.addTest("Error message retrieval", errorMsgTest);
-        
-        return invalidParamsTest && uninitializedTest;
-        
-    } catch (const std::exception& e) {
-        AV_LOGGER_ERROR("Error handling test exception: " + std::string(e.what()));
-        results.addTest("Error handling exception", false);
-        return false;
-    }
-}
-
-int main() {
-    // 初始化日志系统
-    Logger::initialize("test_muxer.log", LogLevel::INFO, false, true);
-
-    AV_LOGGER_INFO("=== Starting Muxer Module Tests ===");
-    
-    TestResults results;
-    
-    // 运行所有测试
-    testAbstractMuxerBasics(results);
-    testFileMuxer(results);
-    testStreamMuxer(results);
-    testMuxerFactory(results);
-    testErrorHandling(results);
-    
-    // 打印测试结果
-    results.printSummary();
-    
-    // 返回测试结果
-    bool allTestsPassed = (results.failedTests.empty() && results.totalTests > 0);
-    
-    if (allTestsPassed) {
-        AV_LOGGER_INFO("\n🎉 All muxer tests passed!");
-        return 0;
-    } else {
-        AV_LOGGER_ERROR("\n❌ Some muxer tests failed!");
-        return 1;
-    }
-}

+ 0 - 86
AV/test/test_muxer_fix.cpp

@@ -1,86 +0,0 @@
-#include "code/muxer/muxer_file_muxer.h"
-#include "code/base/logger.h"
-#include <iostream>
-
-using namespace av::muxer;
-using namespace av;
-
-int main() {
-    // 初始化日志
-    Logger::instance().setLevel(LogLevel::DEBUG);
-    
-    std::cout << "测试 FileMuxer 初始化修复..." << std::endl;
-    
-    try {
-        // 创建文件复用器
-        FileMuxer muxer;
-        
-        // 测试1: 使用正确的 FileMuxerParams
-        std::cout << "\n=== 测试1: 正确的 FileMuxerParams ===" << std::endl;
-        FileMuxerParams correctParams;
-        correctParams.type = MuxerType::FILE_MUXER;
-        correctParams.outputPath = "./test_output.mp4";
-        correctParams.outputFile = "./test_output.mp4";
-        correctParams.format = "mp4";
-        correctParams.overwrite = true;
-        
-        ErrorCode result = muxer.initialize(correctParams);
-        if (result == ErrorCode::SUCCESS) {
-            std::cout << "✓ 正确参数初始化成功!" << std::endl;
-        } else {
-            std::cout << "✗ 正确参数初始化失败,错误码: " << static_cast<int>(result) << std::endl;
-        }
-        
-        muxer.close();
-        
-        // 测试2: 使用错误类型的 MuxerParams(基类)
-        std::cout << "\n=== 测试2: 错误的 MuxerParams 类型 ===" << std::endl;
-        MuxerParams wrongParams;
-        wrongParams.type = MuxerType::FILE_MUXER;  // 类型正确但实际是基类
-        wrongParams.outputPath = "./test_output2.mp4";
-        
-        FileMuxer muxer2;
-        result = muxer2.initialize(wrongParams);
-        if (result != ErrorCode::SUCCESS) {
-            std::cout << "✓ 错误参数类型被正确拒绝,错误码: " << static_cast<int>(result) << std::endl;
-        } else {
-            std::cout << "✗ 错误参数类型未被拒绝!" << std::endl;
-        }
-        
-        // 测试3: 空输出路径
-        std::cout << "\n=== 测试3: 空输出路径 ===" << std::endl;
-        FileMuxerParams emptyPathParams;
-        emptyPathParams.type = MuxerType::FILE_MUXER;
-        emptyPathParams.outputPath = "";  // 空路径
-        emptyPathParams.outputFile = "";   // 空文件
-        
-        FileMuxer muxer3;
-        result = muxer3.initialize(emptyPathParams);
-        if (result != ErrorCode::SUCCESS) {
-            std::cout << "✓ 空路径参数被正确拒绝,错误码: " << static_cast<int>(result) << std::endl;
-        } else {
-            std::cout << "✗ 空路径参数未被拒绝!" << std::endl;
-        }
-        
-        // 测试4: 错误的复用器类型
-        std::cout << "\n=== 测试4: 错误的复用器类型 ===" << std::endl;
-        FileMuxerParams wrongTypeParams;
-        wrongTypeParams.type = MuxerType::STREAM_MUXER;  // 错误的类型
-        wrongTypeParams.outputPath = "./test_output4.mp4";
-        
-        FileMuxer muxer4;
-        result = muxer4.initialize(wrongTypeParams);
-        if (result != ErrorCode::SUCCESS) {
-            std::cout << "✓ 错误复用器类型被正确拒绝,错误码: " << static_cast<int>(result) << std::endl;
-        } else {
-            std::cout << "✗ 错误复用器类型未被拒绝!" << std::endl;
-        }
-        
-    } catch (const std::exception& e) {
-        std::cout << "✗ 异常: " << e.what() << std::endl;
-        return 1;
-    }
-    
-    std::cout << "\n测试完成!" << std::endl;
-    return 0;
-}

+ 0 - 330
AV/test/test_player.cpp

@@ -1,330 +0,0 @@
-/**
- * @file test_player.cpp
- * @brief 播放器模块测试程序
- * @author AI Assistant
- * @date 2024
- */
-
-#include "code/player/player_core.h"
-#include "code/base/media_common.h"
-#include <iostream>
-#include <thread>
-#include <chrono>
-#include <string>
-
-using namespace av;
-using namespace av::player;
-
-/**
- * @brief 播放器事件回调实现
- */
-class TestPlayerCallback : public PlayerEventCallback {
-public:
-    void onStateChanged(PlayerState state) override {
-        std::cout << "[EVENT] State changed to: " << static_cast<int>(state) << std::endl;
-    }
-    
-    void onMediaInfoChanged(const MediaInfo& info) override {
-        std::cout << "[EVENT] Media info changed:" << std::endl;
-        std::cout << "  File: " << info.filename << std::endl;
-        std::cout << "  Duration: " << info.duration << std::endl;
-        std::cout << "  Has Video: " << (info.hasVideo ? "Yes" : "No") << std::endl;
-        std::cout << "  Has Audio: " << (info.hasAudio ? "Yes" : "No") << std::endl;
-        
-        if (info.hasVideo) {
-            std::cout << "  Video: " << info.width << "x" << info.height 
-                      << " @ " << info.fps << " fps" << std::endl;
-        }
-        
-        if (info.hasAudio) {
-            std::cout << "  Audio: " << info.audioSampleRate << " Hz, " 
-                      << info.audioChannels << " channels" << std::endl;
-        }
-    }
-    
-    void onErrorOccurred(const std::string& error) override {
-        std::cout << "[ERROR] " << error << std::endl;
-    }
-    
-    void onPlaybackFinished() override {
-        std::cout << "[EVENT] Playback finished" << std::endl;
-    }
-};
-
-/**
- * @brief 测试播放器基本功能
- */
-bool testPlayerBasicFunctions() {
-    std::cout << "\n=== Testing Player Basic Functions ===" << std::endl;
-    
-    // 创建播放器
-    PlayerCore player;
-    TestPlayerCallback callback;
-    player.setEventCallback(&callback);
-    
-    // 测试初始状态
-    if (player.getState() != PlayerState::Idle) {
-        std::cout << "[FAIL] Initial state should be Idle" << std::endl;
-        return false;
-    }
-    
-    // 测试音量设置
-    player.setVolume(0.5);
-    if (std::abs(player.getVolume() - 0.5) > 0.001) {
-        std::cout << "[FAIL] Volume setting failed" << std::endl;
-        return false;
-    }
-    
-    // 测试播放速度设置
-    ErrorCode result = player.setPlaybackSpeed(1.5);
-    if (result != ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Playback speed setting failed" << std::endl;
-        return false;
-    }
-    
-    // 测试无效播放速度
-    result = player.setPlaybackSpeed(-1.0);
-    if (result == ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Should reject invalid playback speed" << std::endl;
-        return false;
-    }
-    
-    std::cout << "[PASS] Player basic functions test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 测试播放器状态转换
- */
-bool testPlayerStateTransitions() {
-    std::cout << "\n=== Testing Player State Transitions ===" << std::endl;
-    
-    PlayerCore player;
-    TestPlayerCallback callback;
-    player.setEventCallback(&callback);
-    
-    // 测试在Idle状态下播放(应该失败)
-    ErrorCode result = player.play();
-    if (result == ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Should not be able to play in Idle state" << std::endl;
-        return false;
-    }
-    
-    // 测试在Idle状态下暂停(应该失败)
-    result = player.pause();
-    if (result == ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Should not be able to pause in Idle state" << std::endl;
-        return false;
-    }
-    
-    // 测试停止(应该成功,因为已经是停止状态)
-    result = player.stop();
-    if (result != ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Stop should always succeed" << std::endl;
-        return false;
-    }
-    
-    std::cout << "[PASS] Player state transitions test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 测试媒体文件打开(使用不存在的文件)
- */
-bool testMediaFileHandling() {
-    std::cout << "\n=== Testing Media File Handling ===" << std::endl;
-    
-    PlayerCore player;
-    TestPlayerCallback callback;
-    player.setEventCallback(&callback);
-    
-    // 测试打开不存在的文件
-    ErrorCode result = player.openFile("nonexistent_file.mp4");
-    if (result == ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Should fail to open nonexistent file" << std::endl;
-        return false;
-    }
-    
-    // 测试打开空文件名
-    result = player.openFile("");
-    if (result == ErrorCode::SUCCESS) {
-        std::cout << "[FAIL] Should fail to open empty filename" << std::endl;
-        return false;
-    }
-    
-    std::cout << "[PASS] Media file handling test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 测试播放器统计信息
- */
-bool testPlayerStats() {
-    std::cout << "\n=== Testing Player Stats ===" << std::endl;
-    
-    PlayerCore player;
-    
-    // 获取初始统计信息
-    PlaybackStats stats = player.getStats();
-    
-    // 验证初始值
-    if (stats.currentTime != 0 || stats.playbackSpeed != 1.0) {
-        std::cout << "[FAIL] Initial stats values incorrect" << std::endl;
-        return false;
-    }
-    
-    // 设置播放速度并验证统计信息
-    player.setPlaybackSpeed(2.0);
-    stats = player.getStats();
-    
-    if (std::abs(stats.playbackSpeed - 2.0) > 0.001) {
-        std::cout << "[FAIL] Stats playback speed not updated" << std::endl;
-        return false;
-    }
-    
-    std::cout << "[PASS] Player stats test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 测试帧获取接口
- */
-bool testFrameInterface() {
-    std::cout << "\n=== Testing Frame Interface ===" << std::endl;
-    
-    PlayerCore player;
-    
-    // 测试在没有媒体的情况下获取帧
-    AVFrame* videoFrame = player.getNextVideoFrame();
-    if (videoFrame != nullptr) {
-        std::cout << "[FAIL] Should return null when no media loaded" << std::endl;
-        return false;
-    }
-    
-    AVFrame* audioFrame = player.getNextAudioFrame();
-    if (audioFrame != nullptr) {
-        std::cout << "[FAIL] Should return null when no media loaded" << std::endl;
-        return false;
-    }
-    
-    // 测试释放空帧(应该安全)
-    player.releaseVideoFrame(nullptr);
-    player.releaseAudioFrame(nullptr);
-    
-    std::cout << "[PASS] Frame interface test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 测试播放器更新循环
- */
-bool testPlayerUpdate() {
-    std::cout << "\n=== Testing Player Update ===" << std::endl;
-    
-    PlayerCore player;
-    
-    // 调用更新函数(应该安全)
-    player.update();
-    
-    // 多次调用更新
-    for (int i = 0; i < 10; ++i) {
-        player.update();
-        std::this_thread::sleep_for(std::chrono::milliseconds(1));
-    }
-    
-    std::cout << "[PASS] Player update test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 测试播放器多实例
- */
-bool testMultiplePlayerInstances() {
-    std::cout << "\n=== Testing Multiple Player Instances ===" << std::endl;
-    
-    // 创建多个播放器实例
-    std::vector<std::unique_ptr<PlayerCore>> players;
-    std::vector<std::unique_ptr<TestPlayerCallback>> callbacks;
-    
-    for (int i = 0; i < 3; ++i) {
-        auto player = std::make_unique<PlayerCore>();
-        auto callback = std::make_unique<TestPlayerCallback>();
-        
-        player->setEventCallback(callback.get());
-        player->setVolume(0.1 * (i + 1));
-        
-        players.push_back(std::move(player));
-        callbacks.push_back(std::move(callback));
-    }
-    
-    // 验证每个播放器的状态
-    for (size_t i = 0; i < players.size(); ++i) {
-        if (players[i]->getState() != PlayerState::Idle) {
-            std::cout << "[FAIL] Player " << i << " state incorrect" << std::endl;
-            return false;
-        }
-        
-        double expectedVolume = 0.1 * (i + 1);
-        if (std::abs(players[i]->getVolume() - expectedVolume) > 0.001) {
-            std::cout << "[FAIL] Player " << i << " volume incorrect" << std::endl;
-            return false;
-        }
-    }
-    
-    std::cout << "[PASS] Multiple player instances test passed" << std::endl;
-    return true;
-}
-
-/**
- * @brief 运行所有测试
- */
-int main() {
-    std::cout << "Starting Player Module Tests..." << std::endl;
-    
-    int passedTests = 0;
-    int totalTests = 0;
-    
-    // 运行所有测试
-    struct TestCase {
-        const char* name;
-        bool (*func)();
-    };
-    
-    TestCase tests[] = {
-        {"Player Basic Functions", testPlayerBasicFunctions},
-        {"Player State Transitions", testPlayerStateTransitions},
-        {"Media File Handling", testMediaFileHandling},
-        {"Player Stats", testPlayerStats},
-        {"Frame Interface", testFrameInterface},
-        {"Player Update", testPlayerUpdate},
-        {"Multiple Player Instances", testMultiplePlayerInstances}
-    };
-    
-    for (const auto& test : tests) {
-        totalTests++;
-        try {
-            if (test.func()) {
-                passedTests++;
-            }
-        }
-        catch (const std::exception& e) {
-            std::cout << "[EXCEPTION] Test " << test.name << " threw: " << e.what() << std::endl;
-        }
-        catch (...) {
-            std::cout << "[EXCEPTION] Test " << test.name << " threw unknown exception" << std::endl;
-        }
-    }
-    
-    // 输出测试结果
-    std::cout << "\n=== Test Results ===" << std::endl;
-    std::cout << "Passed: " << passedTests << "/" << totalTests << std::endl;
-    std::cout << "Success Rate: " << (100.0 * passedTests / totalTests) << "%" << std::endl;
-    
-    if (passedTests == totalTests) {
-        std::cout << "\n🎉 All tests passed!" << std::endl;
-        return 0;
-    } else {
-        std::cout << "\n❌ Some tests failed!" << std::endl;
-        return 1;
-    }
-}

+ 0 - 311
AV/test/test_player_adapter.cpp

@@ -1,311 +0,0 @@
-/**
- * @file test_player_adapter.cpp
- * @brief PlayerAdapter OpenGL渲染器测试程序
- * @author AI Assistant
- * @date 2024
- */
-
-#include "code/player/player_adapter.h"
-#include "code/player/opengl_video_renderer.h"
-#include <QApplication>
-#include <QMainWindow>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QPushButton>
-#include <QSlider>
-#include <QLabel>
-#include <QFileDialog>
-#include <QMessageBox>
-#include <QTimer>
-#include <QComboBox>
-#include <QGroupBox>
-#include <iostream>
-
-using namespace av;
-using namespace av::player;
-
-/**
- * @brief 主窗口类
- */
-class PlayerAdapterTestWindow : public QMainWindow {
-    Q_OBJECT
-
-public:
-    PlayerAdapterTestWindow(QWidget* parent = nullptr) : QMainWindow(parent) {
-        setupUI();
-        setupPlayer();
-        setupConnections();
-    }
-
-private slots:
-    void openFile() {
-        QString filename = QFileDialog::getOpenFileName(
-            this, 
-            "Open Media File", 
-            "", 
-            "Media Files (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm);;All Files (*)"
-        );
-        
-        if (!filename.isEmpty()) {
-            openMediaFile(filename);
-        }
-    }
-    
-    void play() {
-        if (m_playerAdapter) {
-            m_playerAdapter->play();
-        }
-    }
-    
-    void pause() {
-        if (m_playerAdapter) {
-            m_playerAdapter->pause();
-        }
-    }
-    
-    void stop() {
-        if (m_playerAdapter) {
-            m_playerAdapter->stop();
-        }
-    }
-    
-    void onVolumeChanged(int value) {
-        if (m_playerAdapter) {
-            double volume = value / 100.0;
-            m_playerAdapter->setVolume(volume);
-            m_volumeLabel->setText(QString("Volume: %1%").arg(value));
-        }
-    }
-    
-    void onSpeedChanged(int value) {
-        if (m_playerAdapter) {
-            double speed = value / 100.0;
-            m_playerAdapter->setPlaybackSpeed(speed);
-            m_speedLabel->setText(QString("Speed: %1x").arg(speed, 0, 'f', 2));
-        }
-    }
-    
-    void onRendererTypeChanged(const QString& type) {
-        m_rendererTypeLabel->setText(QString("Renderer: %1").arg(type));
-        qDebug() << "Renderer type changed to:" << type;
-    }
-    
-    void onOpenGLRendererInitialized() {
-        qDebug() << "OpenGL renderer initialized successfully";
-        m_statusLabel->setText("OpenGL renderer ready");
-    }
-    
-    void onStateChanged(PlayerState state) {
-        QString stateText;
-        switch (state) {
-            case PlayerState::Idle: stateText = "Idle"; break;
-            case PlayerState::Opening: stateText = "Opening"; break;
-            case PlayerState::Playing: stateText = "Playing"; break;
-            case PlayerState::Paused: stateText = "Paused"; break;
-            case PlayerState::Seeking: stateText = "Seeking"; break;
-            case PlayerState::Stopped: stateText = "Stopped"; break;
-            case PlayerState::Error: stateText = "Error"; break;
-        }
-        m_stateLabel->setText(QString("State: %1").arg(stateText));
-    }
-    
-    void onPositionChanged(qint64 position) {
-        double seconds = position / 1000000.0;
-        m_positionLabel->setText(QString("Position: %1s").arg(seconds, 0, 'f', 2));
-    }
-    
-    void onErrorOccurred(const QString& error) {
-        QMessageBox::warning(this, "Error", error);
-        m_statusLabel->setText("Error occurred");
-    }
-    
-    void updateStats() {
-        if (m_playerAdapter) {
-            PlaybackStats stats = m_playerAdapter->getStats();
-            MediaInfo info = m_playerAdapter->getMediaInfo();
-            
-            QString statsText = QString("Frames: %1 | Dropped: %2 | Buffer: %3")
-                .arg(stats.totalFrames)
-                .arg(stats.droppedFrames)
-                .arg(stats.queuedVideoFrames);
-            
-            m_statsLabel->setText(statsText);
-        }
-    }
-
-private:
-    void setupUI() {
-        setWindowTitle("PlayerAdapter OpenGL Test");
-        setMinimumSize(900, 700);
-        
-        // 创建中央部件
-        QWidget* centralWidget = new QWidget(this);
-        setCentralWidget(centralWidget);
-        
-        // 创建主布局
-        QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget);
-        
-        // 创建渲染器选择区域
-        QGroupBox* rendererGroup = new QGroupBox("Renderer Selection", this);
-        QHBoxLayout* rendererLayout = new QHBoxLayout(rendererGroup);
-        
-        QPushButton* useOpenGLButton = new QPushButton("Use OpenGL Renderer", this);
-        
-        rendererLayout->addWidget(useOpenGLButton);
-        
-        mainLayout->addWidget(rendererGroup);
-        
-        // 创建视频显示区域
-        QGroupBox* videoGroup = new QGroupBox("Video Display", this);
-        QVBoxLayout* videoLayout = new QVBoxLayout(videoGroup);
-        
-        // 创建OpenGL渲染器
-        m_openGLRenderer = new OpenGLVideoRenderer(this);
-        m_openGLRenderer->setMinimumSize(640, 480);
-        videoLayout->addWidget(m_openGLRenderer);
-        
-
-        
-        mainLayout->addWidget(videoGroup);
-        
-        // 创建控制面板
-        QGroupBox* controlGroup = new QGroupBox("Playback Controls", this);
-        QHBoxLayout* controlLayout = new QHBoxLayout(controlGroup);
-        
-        // 文件操作按钮
-        QPushButton* openButton = new QPushButton("Open File", this);
-        QPushButton* playButton = new QPushButton("Play", this);
-        QPushButton* pauseButton = new QPushButton("Pause", this);
-        QPushButton* stopButton = new QPushButton("Stop", this);
-        
-        controlLayout->addWidget(openButton);
-        controlLayout->addWidget(playButton);
-        controlLayout->addWidget(pauseButton);
-        controlLayout->addWidget(stopButton);
-        
-        // 音量控制
-        QLabel* volumeLabel = new QLabel("Volume: 100%", this);
-        QSlider* volumeSlider = new QSlider(Qt::Horizontal, this);
-        volumeSlider->setRange(0, 100);
-        volumeSlider->setValue(100);
-        
-        controlLayout->addWidget(volumeLabel);
-        controlLayout->addWidget(volumeSlider);
-        
-        // 播放速度控制
-        QLabel* speedLabel = new QLabel("Speed: 1.00x", this);
-        QSlider* speedSlider = new QSlider(Qt::Horizontal, this);
-        speedSlider->setRange(25, 200); // 0.25x - 2.0x
-        speedSlider->setValue(100);
-        
-        controlLayout->addWidget(speedLabel);
-        controlLayout->addWidget(speedSlider);
-        
-        mainLayout->addWidget(controlGroup);
-        
-        // 创建状态显示区域
-        QGroupBox* statusGroup = new QGroupBox("Status Information", this);
-        QGridLayout* statusLayout = new QGridLayout(statusGroup);
-        
-        m_stateLabel = new QLabel("State: Idle", this);
-        m_positionLabel = new QLabel("Position: 0.00s", this);
-        m_rendererTypeLabel = new QLabel("Renderer: None", this);
-        m_statusLabel = new QLabel("Ready", this);
-        m_statsLabel = new QLabel("Stats: --", this);
-        
-        statusLayout->addWidget(m_stateLabel, 0, 0);
-        statusLayout->addWidget(m_positionLabel, 0, 1);
-        statusLayout->addWidget(m_rendererTypeLabel, 1, 0);
-        statusLayout->addWidget(m_statusLabel, 1, 1);
-        statusLayout->addWidget(m_statsLabel, 2, 0, 1, 2);
-        
-        mainLayout->addWidget(statusGroup);
-        
-        // 保存控件引用
-        m_volumeLabel = volumeLabel;
-        m_speedLabel = speedLabel;
-        
-        // 连接信号
-        connect(openButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::openFile);
-        connect(playButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::play);
-        connect(pauseButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::pause);
-        connect(stopButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::stop);
-        connect(volumeSlider, &QSlider::valueChanged, this, &PlayerAdapterTestWindow::onVolumeChanged);
-        connect(speedSlider, &QSlider::valueChanged, this, &PlayerAdapterTestWindow::onSpeedChanged);
-        
-        // 渲染器选择按钮
-        connect(useOpenGLButton, &QPushButton::clicked, this, [this]() {
-            m_playerAdapter->setOpenGLVideoRenderer(m_openGLRenderer);
-        });
-    }
-    
-    void setupPlayer() {
-        m_playerAdapter = std::make_unique<PlayerAdapter>(this);
-        
-        // 默认使用OpenGL渲染器
-        m_playerAdapter->setOpenGLVideoRenderer(m_openGLRenderer);
-    }
-    
-    void setupConnections() {
-        // 连接PlayerAdapter信号
-        connect(m_playerAdapter.get(), &PlayerAdapter::stateChanged, 
-                this, &PlayerAdapterTestWindow::onStateChanged);
-        connect(m_playerAdapter.get(), &PlayerAdapter::positionChanged, 
-                this, &PlayerAdapterTestWindow::onPositionChanged);
-        connect(m_playerAdapter.get(), &PlayerAdapter::errorOccurred, 
-                this, &PlayerAdapterTestWindow::onErrorOccurred);
-        connect(m_playerAdapter.get(), &PlayerAdapter::rendererTypeChanged, 
-                this, &PlayerAdapterTestWindow::onRendererTypeChanged);
-        connect(m_playerAdapter.get(), &PlayerAdapter::openGLRendererInitialized, 
-                this, &PlayerAdapterTestWindow::onOpenGLRendererInitialized);
-        
-        // 创建定时器更新统计信息
-        m_statsTimer = new QTimer(this);
-        connect(m_statsTimer, &QTimer::timeout, this, &PlayerAdapterTestWindow::updateStats);
-        m_statsTimer->start(500); // 每500ms更新一次
-    }
-    
-    void openMediaFile(const QString& filename) {
-        if (!m_playerAdapter) {
-            return;
-        }
-        
-        ErrorCode result = m_playerAdapter->openFile(filename);
-        if (result != ErrorCode::SUCCESS) {
-            QMessageBox::critical(this, "Error", 
-                QString("Failed to open file: %1").arg(filename));
-        } else {
-            setWindowTitle(QString("PlayerAdapter OpenGL Test - %1").arg(filename));
-        }
-    }
-
-private:
-    std::unique_ptr<PlayerAdapter> m_playerAdapter;
-    OpenGLVideoRenderer* m_openGLRenderer;
-    
-    QLabel* m_volumeLabel;
-    QLabel* m_speedLabel;
-    QLabel* m_stateLabel;
-    QLabel* m_positionLabel;
-    QLabel* m_rendererTypeLabel;
-    QLabel* m_statusLabel;
-    QLabel* m_statsLabel;
-    QTimer* m_statsTimer;
-};
-
-int main(int argc, char* argv[]) {
-    QApplication app(argc, argv);
-    
-    // 设置应用程序信息
-    app.setApplicationName("PlayerAdapter OpenGL Test");
-    app.setApplicationVersion("1.0");
-    app.setOrganizationName("AV Player");
-    
-    // 创建主窗口
-    PlayerAdapterTestWindow window;
-    window.show();
-    
-    return app.exec();
-}
-
-#include "test_player_adapter.moc"

+ 0 - 793
AV/test/test_player_with_ui.cpp

@@ -1,793 +0,0 @@
-#include <chrono>
-#include <string>
-#include <thread>
-#include <iomanip>
-
-#include "code/base/logger.h"
-#include "code/player/player_core_v2.h"
-
-#include "../../AvRecorder/ui/opengl_video_widget.h"
-#include "qobject.h"
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/imgutils.h>
-}
-
-#include <QApplication>
-#include <QWidget>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QPushButton>
-#include <QLabel>
-#include <QSlider>
-#include <QFileDialog>
-#include <QMessageBox>
-#include <QTimer>
-#include <QProgressBar>
-#include <QGroupBox>
-#include <QSpinBox>
-#include <QCheckBox>
-#include <QComboBox>
-#include <QTextEdit>
-#include <QSplitter>
-#include <QDebug>
-#include <QDateTime>
-#include <QFile>
-#include <QTextStream>
-#include <QMetaObject>
-
-using namespace av::player;
-using namespace av::utils;
-
-// 播放器事件回调类
-class UIPlayerCallback : public PlayerEventCallback {
-public:
-    UIPlayerCallback(QWidget* parent, OpenGLVideoWidget* videoRenderer) 
-        : m_parent(parent), m_videoRenderer(videoRenderer) {}
-    
-    void onStateChanged(PlayerState newState) override {
-        std::string stateStr;
-        switch (newState) {
-            case PlayerState::Idle: stateStr = "Idle"; break;
-            case PlayerState::Opening: stateStr = "Opening"; break;
-            case PlayerState::Stopped: stateStr = "Stopped"; break;
-            case PlayerState::Playing: stateStr = "Playing"; break;
-            case PlayerState::Paused: stateStr = "Paused"; break;
-            case PlayerState::Seeking: stateStr = "Seeking"; break;
-            case PlayerState::Error: stateStr = "Error"; break;
-        }
-        Logger::instance().info("[EVENT] State changed to: " + stateStr);
-        
-        // 发送信号到UI线程
-        QMetaObject::invokeMethod(m_parent, "onPlayerStateChanged", Qt::QueuedConnection,
-                                Q_ARG(int, static_cast<int>(newState)));
-    }
-    
-    void onPositionChanged(int64_t position) override {
-        // 发送位置更新到UI线程
-        QMetaObject::invokeMethod(m_parent, "onPlayerPositionChanged", Qt::QueuedConnection,
-                                Q_ARG(qint64, position));
-    }
-    
-    void onMediaInfoChanged(const MediaInfo& info) override {
-        Logger::instance().info("[EVENT] Media info changed:");
-        Logger::instance().info("  File: " + info.filename);
-        Logger::instance().info("  Duration: " + std::to_string(info.duration / 1000000.0) + "s");
-        Logger::instance().info("  Has Video: " + std::string(info.hasVideo ? "Yes" : "No"));
-        Logger::instance().info("  Has Audio: " + std::string(info.hasAudio ? "Yes" : "No"));
-        
-        if (info.hasVideo) {
-            Logger::instance().info("  Video: " + std::to_string(info.width) + "x" + std::to_string(info.height) + " @ " + std::to_string(info.fps) + " fps");
-        }
-        
-        if (info.hasAudio) {
-            Logger::instance().info("  Audio: " + std::to_string(info.sampleRate) + " Hz, " + std::to_string(info.channels) + " channels");
-        }
-        
-        // 发送媒体信息到UI线程
-        QMetaObject::invokeMethod(m_parent, "onMediaInfoChanged", Qt::QueuedConnection);
-    }
-    
-    void onErrorOccurred(const std::string& error) override {
-        Logger::instance().error("[ERROR] " + error);
-        // QMetaObject::invokeMethod(m_parent, "onPlayerError", Qt::QueuedConnection,
-        //                         Q_ARG(QString, QString::fromStdString(error)));
-    }
-    
-    void onFrameDropped(int64_t totalDropped) override {
-        Logger::instance().warning("[WARNING] Frame dropped, total: " + std::to_string(totalDropped));
-    }
-    
-    void onSyncError(double error, const std::string& reason) override {
-        Logger::instance().warning("[WARNING] Sync error: " + std::to_string(error * 1000) + "ms, reason: " + reason);
-    }
-
-    void onEndOfFile() override {
-        Logger::instance().info("[EVENT] End of file reached");
-        QMetaObject::invokeMethod(m_parent, "onPlayerEndOfFile", Qt::QueuedConnection);
-    }
-    
-    // 新增的视频渲染回调函数
-    void onVideoFrameReady(AVFrame* frameData) override
-    {
-        if (m_videoRenderer) {
-            // 将 frameData 转换为 AVFrame* 并进行深度拷贝
-            AVFrame* originalFrame = static_cast<AVFrame*>(frameData);
-            AVFrame* copiedFrame = av_frame_clone(originalFrame);
-            
-            if (copiedFrame) {
-                // 使用 QueuedConnection 避免死锁
-                // 当播放器暂停时,如果使用 BlockingQueuedConnection 可能导致死锁
-                // 因为暂停操作会等待播放线程停止,而播放线程可能正在等待UI线程响应
-                bool renderResult = false;
-                QMetaObject::invokeMethod(m_videoRenderer,
-                                          "Render",
-                                          Qt::QueuedConnection,
-                                          Q_ARG(AVFrame*, copiedFrame));
-
-                // 注意:使用QueuedConnection时,copiedFrame的释放需要在Render方法内部处理
-                // 这里不能立即释放,因为调用是异步的
-                // OpenGLVideoWidget::Render方法需要负责释放传入的AVFrame*
-            }
-        }
-    }
-
-    void onVideoRendererInitRequired(int width, int height) override
-    {
-        if (m_videoRenderer) {
-            Logger::instance().info("[EVENT] Video renderer init required: " + 
-                                  std::to_string(width) + "x" + std::to_string(height));
-            // QMetaObject::invokeMethod(m_videoRenderer, "Open", Qt::QueuedConnection,
-            //                         Q_ARG(int, width),
-            //                         Q_ARG(int, height),
-            //                         Q_ARG(int, pixelFormat),
-            //                         Q_ARG(double, fps));
-        }
-    }
-
-    void onVideoRendererCloseRequired() override
-    {
-        if (m_videoRenderer) {
-            Logger::instance().info("[EVENT] Video renderer close required");
-            // QMetaObject::invokeMethod(m_videoRenderer, "Close", Qt::QueuedConnection);
-        }
-    }
-
-private:
-    QWidget* m_parent;
-    OpenGLVideoWidget* m_videoRenderer;
-};
-
-// 主播放器窗口类
-class PlayerWindow : public QWidget {
-    Q_OBJECT
-    
-public:
-    PlayerWindow(QWidget* parent = nullptr) : QWidget(parent) {
-        setupUI();
-        setupPlayer();
-        connectSignals();
-        
-        // 设置窗口属性
-        setWindowTitle("AV Player Test with UI");
-        resize(1280, 900); // 增加窗口大小以适应更多统计信息
-        
-        // 启动更新定时器
-        m_updateTimer = new QTimer(this);
-        connect(m_updateTimer, &QTimer::timeout, this, &PlayerWindow::updateUI);
-        m_updateTimer->start(100); // 100ms更新一次
-
-        m_player->openFile("C:/Users/zhuizhu/Videos/2.mp4");
-        // playPause();
-    }
-    
-    ~PlayerWindow() {
-        if (m_player) {
-            m_player->stop();
-        }
-    }
-    
-public slots:
-    void onPlayerStateChanged(int state) {
-        PlayerState playerState = static_cast<PlayerState>(state);
-        
-        switch (playerState) {
-            case PlayerState::Idle:
-                m_stateLabel->setText("状态: 空闲");
-                m_playButton->setText("播放");
-                m_playButton->setEnabled(false);
-                break;
-            case PlayerState::Opening:
-                m_stateLabel->setText("状态: 打开中...");
-                m_playButton->setEnabled(false);
-                break;
-            case PlayerState::Stopped:
-                m_stateLabel->setText("状态: 已停止");
-                m_playButton->setText("播放");
-                m_playButton->setEnabled(true);
-                break;
-            case PlayerState::Playing:
-                m_stateLabel->setText("状态: 播放中");
-                m_playButton->setText("暂停");
-                m_playButton->setEnabled(true);
-                break;
-            case PlayerState::Paused:
-                m_stateLabel->setText("状态: 已暂停");
-                m_playButton->setText("播放");
-                m_playButton->setEnabled(true);
-                break;
-            case PlayerState::Seeking:
-                m_stateLabel->setText("状态: 跳转中...");
-                break;
-            case PlayerState::Error:
-                m_stateLabel->setText("状态: 错误");
-                m_playButton->setEnabled(false);
-                break;
-        }
-    }
-    
-    void onPlayerPositionChanged(qint64 position) {
-        if (!m_seeking) {
-            // 更新位置标签(秒数显示)
-            double seconds = position / 1000000.0;
-            m_positionLabel->setText(QString("位置: %1s").arg(seconds, 0, 'f', 2));
-            
-            // 我们不在这里更新进度条和时间标签,而是在updateUI中统一更新
-            // 这样可以避免UI更新过于频繁
-        }
-    }
-    
-    void onMediaInfoChanged() {
-        if (m_player) {
-            auto info = m_player->getMediaInfo();
-            m_duration = info.duration;
-            
-            QString infoText = QString("文件: %1\n")
-                              .arg(QString::fromStdString(info.filename));
-            
-            if (info.duration > 0) {
-                double durationSec = info.duration / 1000000.0;
-                infoText += QString("时长: %1s\n").arg(durationSec, 0, 'f', 2);
-                
-                // 更新时间标签显示总时长
-                m_timeLabel->setText(QString("00:00:00 / %1").arg(formatTime(info.duration)));
-            }
-            
-            // 更新视频流复选框状态
-            m_videoStreamCheckBox->setEnabled(info.hasVideo);
-            if (!info.hasVideo) {
-                m_videoStreamCheckBox->setChecked(false);
-            }
-            
-            if (info.hasVideo) {
-                infoText += QString("视频: %1x%2 @ %3fps\n")
-                           .arg(info.width).arg(info.height).arg(info.fps, 0, 'f', 2);
-            }
-
-            // 更新音频流复选框状态
-            m_audioStreamCheckBox->setEnabled(info.hasAudio);
-            if (!info.hasAudio) {
-                m_audioStreamCheckBox->setChecked(false);
-            }
-            
-            if (info.hasAudio) {
-                infoText += QString("音频: %1Hz, %2ch\n")
-                           .arg(info.sampleRate).arg(info.channels);
-            }
-            
-            m_infoLabel->setText(infoText);
-            m_playButton->setEnabled(true);
-        }
-    }
-    
-    void onPlayerError(const QString& error) {
-        QMessageBox::critical(this, "播放器错误", error);
-    }
-    
-    void onPlayerEndOfFile() {
-        m_playButton->setText("播放");
-        
-        // 重置进度条和时间显示
-        m_progressSlider->setValue(0);
-        
-        // 如果有持续时间,显示0/总时长;否则显示0/0
-        if (m_duration > 0) {
-            m_timeLabel->setText(QString("00:00:00 / %1").arg(formatTime(m_duration)));
-        } else {
-            m_timeLabel->setText("00:00:00 / 00:00:00");
-        }
-    }
-    
-private slots:
-    void openFile() {
-        QString fileName = QFileDialog::getOpenFileName(this,
-            "选择媒体文件", "",
-            "媒体文件 (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm *.mp3 *.wav *.aac *.flac);;所有文件 (*.*)");
-            
-        if (!fileName.isEmpty()) {
-            loadFile(fileName.toStdString());
-        }
-    }
-    
-    void refreshStats() {
-        if (m_player) {
-            // 调用播放器的dumpStats方法输出详细统计信息到日志
-            m_player->dumpStats();
-            
-            // 强制更新UI显示
-            updateUI();
-            
-            // 显示提示信息
-            QMessageBox::information(this, "统计信息", "统计信息已刷新,详细信息已写入日志文件。");
-        }
-    }
-
-    void playPause()
-    {
-        if (!m_player) return;
-        
-        auto state = m_player->getState();
-        if (state == PlayerState::Playing) {
-            m_player->pause();
-        } else if (state == PlayerState::Paused || state == PlayerState::Stopped) {
-            m_player->play();
-        }
-    }
-
-    void stop()
-    {
-        if (m_player) {
-            m_player->stop();
-        }
-    }
-
-    void onProgressSliderPressed() { m_seeking = true; }
-
-    void onProgressSliderReleased() {
-        if (m_player && m_duration > 0) {
-            int value = m_progressSlider->value();
-            int64_t position = (m_duration * value) / 100;
-            m_player->seek(position);
-            
-            // 添加一个延迟后再设置m_seeking为false
-            // 这样可以让seek操作有足够时间完成初始化和缓冲
-            QTimer::singleShot(500, this, [this]() {
-                m_seeking = false;
-            });
-            return; // 不要立即设置m_seeking为false
-        }
-        m_seeking = false;
-    }
-    
-    void onProgressSliderMoved(int value) {
-        if (m_player && m_duration > 0) {
-            // 计算预览位置
-            int64_t previewPosition = (m_duration * value) / 100;
-            
-            // 更新时间标签显示预览时间
-            QString timeText = QString("%1 / %2")
-                              .arg(formatTime(previewPosition))
-                              .arg(formatTime(m_duration));
-            m_timeLabel->setText(timeText);
-        }
-    }
-    
-    void onVolumeChanged(int value) {
-        if (m_player) {
-            double volume = value / 100.0;
-            m_player->setVolume(volume);
-            m_volumeLabel->setText(QString("音量: %1%").arg(value));
-        }
-    }
-    
-    // 将微秒转换为时间字符串 (HH:MM:SS)
-    QString formatTime(int64_t timeUs) {
-        int totalSeconds = static_cast<int>(timeUs / 1000000);
-        int hours = totalSeconds / 3600;
-        int minutes = (totalSeconds % 3600) / 60;
-        int seconds = totalSeconds % 60;
-        
-        return QString("%1:%2:%3")
-            .arg(hours, 2, 10, QChar('0'))
-            .arg(minutes, 2, 10, QChar('0'))
-            .arg(seconds, 2, 10, QChar('0'));
-    }
-    
-    void updateUI() {
-        if (m_player) {
-            // 更新统计信息
-            auto stats = m_player->getStats();
-            
-            // 基本播放统计
-            QString statsText = QString("帧数: %1\n丢帧: %2 (%3%)\n重复帧: %4\n速度: %5x")
-                               .arg(stats.totalFrames)
-                               .arg(stats.droppedFrames)
-                               .arg(stats.totalFrames > 0 ? (stats.droppedFrames * 100.0 / stats.totalFrames) : 0, 0, 'f', 1)
-                               .arg(stats.duplicatedFrames)
-                               .arg(stats.playbackSpeed, 0, 'f', 2);
-            
-            // 队列状态
-            statsText += QString("\n\n队列状态:\n视频帧: %1\n音频帧: %2\n数据包: %3")
-                         .arg(stats.queuedVideoFrames)
-                         .arg(stats.queuedAudioFrames)
-                         .arg(stats.queuedPackets);
-            
-            // 同步统计 - 获取更详细的同步信息
-            QString syncText = "\n\n同步状态:\n当前误差: %1 ms\n平均误差: %2 ms\n最大误差: %3 ms";
-            
-            // 如果播放器有同步器,获取详细的时钟信息
-            if (m_player) {
-                auto debugInfo = QString::fromStdString(m_player->getDebugInfo());
-                
-                // 解析调试信息中的时钟数据
-                QStringList lines = debugInfo.split('\n');
-                QString audioClockStr = "N/A", videoClockStr = "N/A", externalClockStr = "N/A", masterClockStr = "N/A";
-                QString masterTypeStr = "N/A", syncStrategyStr = "N/A";
-                
-                for (const QString& line : lines) {
-                    if (line.trimmed().startsWith("Audio:")) {
-                        QStringList parts = line.split(":");
-                        if (parts.size() >= 2) {
-                            bool ok;
-                            double value = parts[1].trimmed().toDouble(&ok);
-                            if (ok) {
-                                audioClockStr = QString::number(value, 'f', 3) + "s";
-                            }
-                        }
-                    } else if (line.trimmed().startsWith("Video:")) {
-                        QStringList parts = line.split(":");
-                        if (parts.size() >= 2) {
-                            bool ok;
-                            double value = parts[1].trimmed().toDouble(&ok);
-                            if (ok) {
-                                videoClockStr = QString::number(value, 'f', 3) + "s";
-                            }
-                        }
-                    } else if (line.trimmed().startsWith("External:")) {
-                        QStringList parts = line.split(":");
-                        if (parts.size() >= 2) {
-                            bool ok;
-                            double value = parts[1].trimmed().toDouble(&ok);
-                            if (ok) {
-                                externalClockStr = QString::number(value, 'f', 3) + "s";
-                            }
-                        }
-                    } else if (line.trimmed().startsWith("Master:")) {
-                        QStringList parts = line.split(":");
-                        if (parts.size() >= 2) {
-                            bool ok;
-                            double value = parts[1].trimmed().toDouble(&ok);
-                            if (ok) {
-                                masterClockStr = QString::number(value, 'f', 3) + "s";
-                            }
-                        }
-                    } else if (line.contains("Master Clock Type:")) {
-                        QStringList parts = line.split(":");
-                        if (parts.size() >= 2) {
-                            masterTypeStr = parts[1].trimmed();
-                        }
-                    } else if (line.contains("Sync Strategy:")) {
-                        QStringList parts = line.split(":");
-                        if (parts.size() >= 2) {
-                            syncStrategyStr = parts[1].trimmed();
-                        }
-                    }
-                }
-                statsText += debugInfo;
-
-                syncText = QString("\n\n同步状态:\n当前误差: %1 ms\n平均误差: %2 ms\n最大误差: %3 "
-                                   "ms\n\n时钟信息:\n音频时钟: %4\n视频时钟: %5\n外部时钟: "
-                                   "%6\n主时钟: %7\n\n同步配置:\n主时钟类型: %8\n同步策略: %9")
-                               .arg(stats.syncError * 1000, 0, 'f', 1)
-                               .arg(stats.avgSyncError * 1000, 0, 'f', 1)
-                               .arg(stats.maxSyncError * 1000, 0, 'f', 1)
-                               .arg(audioClockStr)
-                               .arg(videoClockStr)
-                               .arg(externalClockStr)
-                               .arg(masterClockStr)
-                               .arg(masterTypeStr)
-                               .arg(syncStrategyStr);
-            } else {
-                syncText = syncText.arg(stats.syncError * 1000, 0, 'f', 1)
-                                 .arg(stats.avgSyncError * 1000, 0, 'f', 1)
-                                 .arg(stats.maxSyncError * 1000, 0, 'f', 1);
-            }
-            
-            statsText += syncText;
-            
-            // 性能统计
-            // statsText += QString("\n\n性能:\nCPU: %1%\n内存: %2 MB\n比特率: %3 kbps")
-            //              .arg(stats.cpuUsage, 0, 'f', 1)
-            //              .arg(stats.memoryUsage, 0, 'f', 1)
-            //              .arg(stats.bitrate, 0, 'f', 0);
-
-            m_statsLabel->setText(statsText);
-
-            // 更新时间显示和进度条
-            if (!m_seeking && m_duration > 0) {
-                int64_t currentPosition = m_player->getCurrentTime();
-                
-                // 更新进度条
-                int progress = static_cast<int>((currentPosition * 100) / m_duration);
-                m_progressSlider->setValue(progress);
-                
-                // 更新时间标签
-                QString timeText = QString("%1 / %2")
-                                  .arg(formatTime(currentPosition))
-                                  .arg(formatTime(m_duration));
-                m_timeLabel->setText(timeText);
-            }
-        }
-    }
-    
-    void onVideoStreamToggled(bool enabled) {
-        if (m_player) {
-            m_player->enableVideoStream(enabled);
-            Logger::instance().info(QString("视频流%1").arg(enabled ? "启用" : "禁用").toStdString());
-        }
-    }
-    
-    void onAudioStreamToggled(bool enabled) {
-        if (m_player) {
-            m_player->enableAudioStream(enabled);
-            Logger::instance().info(QString("音频流%1").arg(enabled ? "启用" : "禁用").toStdString());
-        }
-    }
-    
-private:
-    void setupUI() {
-        auto* mainLayout = new QHBoxLayout(this);
-        
-        // 左侧视频区域
-        auto* leftWidget = new QWidget;
-        auto* leftLayout = new QVBoxLayout(leftWidget);
-        
-        // 视频渲染器
-        m_videoRenderer = new OpenGLVideoWidget;
-        m_videoRenderer->setMinimumSize(640, 480);
-        leftLayout->addWidget(m_videoRenderer, 1);
-        
-        // 控制按钮
-        auto* controlLayout = new QHBoxLayout;
-        m_openButton = new QPushButton("打开文件");
-        m_playButton = new QPushButton("播放");
-        m_stopButton = new QPushButton("停止");
-        m_playButton->setEnabled(false);
-        
-        controlLayout->addWidget(m_openButton);
-        controlLayout->addWidget(m_playButton);
-        controlLayout->addWidget(m_stopButton);
-        controlLayout->addStretch();
-        
-        leftLayout->addLayout(controlLayout);
-        
-        // 进度条和时间显示
-        auto* progressLayout = new QHBoxLayout;
-        m_progressSlider = new QSlider(Qt::Horizontal);
-        m_progressSlider->setRange(0, 100);
-        m_timeLabel = new QLabel("00:00:00 / 00:00:00");
-        
-        progressLayout->addWidget(m_progressSlider);
-        progressLayout->addWidget(m_timeLabel);
-        leftLayout->addLayout(progressLayout);
-        
-        // 音量控制
-        auto* volumeLayout = new QHBoxLayout;
-        volumeLayout->addWidget(new QLabel("音量:"));
-        m_volumeSlider = new QSlider(Qt::Horizontal);
-        m_volumeSlider->setRange(0, 100);
-        m_volumeSlider->setValue(100);
-        m_volumeSlider->setMaximumWidth(200);
-        m_volumeLabel = new QLabel("音量: 100%");
-        volumeLayout->addWidget(m_volumeSlider);
-        volumeLayout->addWidget(m_volumeLabel);
-        volumeLayout->addStretch();
-        leftLayout->addLayout(volumeLayout);
-        
-        // 流控制
-        auto* streamControlLayout = new QHBoxLayout;
-        m_videoStreamCheckBox = new QCheckBox("启用视频");
-        m_audioStreamCheckBox = new QCheckBox("启用音频");
-        m_videoStreamCheckBox->setChecked(true);
-        m_audioStreamCheckBox->setChecked(true);
-        streamControlLayout->addWidget(m_videoStreamCheckBox);
-        streamControlLayout->addWidget(m_audioStreamCheckBox);
-        streamControlLayout->addStretch();
-        leftLayout->addLayout(streamControlLayout);
-        
-        mainLayout->addWidget(leftWidget, 2);
-        
-        // 右侧信息面板
-        auto* rightWidget = new QWidget;
-        auto* rightLayout = new QVBoxLayout(rightWidget);
-        rightWidget->setMinimumWidth(300);
-        rightWidget->setMaximumWidth(350);
-        
-        // 状态信息
-        auto* statusGroup = new QGroupBox("状态信息");
-        auto* statusLayout = new QVBoxLayout(statusGroup);
-        m_stateLabel = new QLabel("状态: 空闲");
-        m_positionLabel = new QLabel("位置: 0s");
-        statusLayout->addWidget(m_stateLabel);
-        statusLayout->addWidget(m_positionLabel);
-        rightLayout->addWidget(statusGroup);
-        
-        // 媒体信息
-        auto* infoGroup = new QGroupBox("媒体信息");
-        auto* infoLayout = new QVBoxLayout(infoGroup);
-        m_infoLabel = new QLabel("未加载文件");
-        m_infoLabel->setWordWrap(true);
-        infoLayout->addWidget(m_infoLabel);
-        rightLayout->addWidget(infoGroup);
-        
-        // 统计信息
-        auto* statsGroup = new QGroupBox("播放统计");
-        auto* statsLayout = new QVBoxLayout(statsGroup);
-        
-        // 添加刷新和导出按钮
-        auto* refreshLayout = new QHBoxLayout();
-        m_refreshStatsButton = new QPushButton("刷新统计");
-        refreshLayout->addWidget(m_refreshStatsButton);
-        refreshLayout->addStretch();
-        statsLayout->addLayout(refreshLayout);
-        
-        m_statsLabel = new QLabel("帧数: 0\n丢帧: 0 (0.0%)\n重复帧: 0\n速度: 1.0x\n\n队列状态:\n视频帧: 0\n音频帧: 0\n数据包: 0\n\n同步状态:\n当前误差: 0.0 ms\n平均误差: 0.0 ms\n最大误差: 0.0 ms\n\n时钟信息:\n音频时钟: N/A\n视频时钟: N/A\n外部时钟: N/A\n主时钟: N/A\n\n同步配置:\n主时钟类型: N/A\n同步策略: N/A\n\n性能:\nCPU: 0.0%\n内存: 0.0 MB\n比特率: 0 kbps");
-        m_statsLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
-        m_statsLabel->setWordWrap(true);
-        m_statsLabel->setMinimumHeight(450); // 增加最小高度以显示更多同步信息
-        statsLayout->addWidget(m_statsLabel);
-        rightLayout->addWidget(statsGroup);
-        
-        rightLayout->addStretch();
-        mainLayout->addWidget(rightWidget);
-    }
-    
-    void setupPlayer() {
-        // 创建同步配置
-        SyncConfigV2 syncConfig;
-        syncConfig.strategy = SyncStrategy::VIDEO_MASTER;
-        syncConfig.syncThresholdMin = 0.040;
-        syncConfig.syncThresholdMax = 0.100;
-        syncConfig.frameDropThreshold = 0.100;
-        syncConfig.frameDupThreshold = 0.100;
-        syncConfig.audioDiffThreshold = 0.100;
-        syncConfig.audioDiffAvgCoef = 0.01;
-        syncConfig.audioDiffAvgCount = 20;
-        syncConfig.clockSpeedMin = 0.9;
-        syncConfig.clockSpeedMax = 1.1;
-        syncConfig.clockSpeedStep = 0.001;
-        syncConfig.minFramesForSync = 2;
-        syncConfig.maxFramesForSync = 10;
-        syncConfig.noSyncThreshold = 10.0;
-        
-        // 创建播放器实例
-        m_player = std::make_unique<PlayerCoreV2>(syncConfig);
-        
-        // 注意:不再直接设置视频渲染器,而是通过回调机制处理
-        // m_player->setOpenGLVideoRenderer(m_videoRenderer); // 已废弃
-        
-        // 设置初始音量
-        m_player->setVolume(m_volumeSlider->value() / 100.0);
-        
-        // 创建事件回调,传入视频渲染器
-        m_callback = std::make_unique<UIPlayerCallback>(this, m_videoRenderer);
-        m_player->setEventCallback(m_callback.get());
-        
-        m_duration = 0;
-        m_seeking = false;
-    }
-    
-    void connectSignals() {
-        connect(m_openButton, &QPushButton::clicked, this, &PlayerWindow::openFile);
-        connect(m_playButton, &QPushButton::clicked, this, &PlayerWindow::playPause);
-        connect(m_stopButton, &QPushButton::clicked, this, &PlayerWindow::stop);
-        
-        // 进度条信号连接
-        connect(m_progressSlider, &QSlider::sliderPressed, this, &PlayerWindow::onProgressSliderPressed);
-        connect(m_progressSlider, &QSlider::sliderReleased, this, &PlayerWindow::onProgressSliderReleased);
-        connect(m_progressSlider, &QSlider::sliderMoved, this, &PlayerWindow::onProgressSliderMoved);
-        
-        // 添加进度条点击跳转功能
-        connect(m_progressSlider, &QSlider::valueChanged, [this](int value) {
-            if (m_seeking && m_player && m_duration > 0) {
-                onProgressSliderMoved(value);
-            }
-        });
-        
-        connect(m_volumeSlider, &QSlider::valueChanged, this, &PlayerWindow::onVolumeChanged);
-        
-        // 连接流控制复选框信号
-        connect(m_videoStreamCheckBox, &QCheckBox::toggled, this, &PlayerWindow::onVideoStreamToggled);
-        connect(m_audioStreamCheckBox, &QCheckBox::toggled, this, &PlayerWindow::onAudioStreamToggled);
-        
-        // 连接统计按钮信号
-        connect(m_refreshStatsButton, &QPushButton::clicked, this, &PlayerWindow::refreshStats);
-    }
-    
-    void loadFile(const std::string& filename) {
-        if (!m_player) return;
-        
-        Logger::instance().info("Loading file: " + filename);
-        
-        // 在打开文件前,根据复选框状态设置流启用状态
-        m_player->enableVideoStream(m_videoStreamCheckBox->isChecked());
-        m_player->enableAudioStream(m_audioStreamCheckBox->isChecked());
-        
-        auto result = m_player->openFile(filename);
-        if (result != ErrorCode::SUCCESS) {
-            QString error = QString("无法打开文件: %1\n错误代码: %2")
-                           .arg(QString::fromStdString(filename))
-                           .arg(static_cast<int>(result));
-            QMessageBox::critical(this, "文件打开失败", error);
-            Logger::instance().error("Failed to open file: " + std::to_string(static_cast<int>(result)));
-        }
-    }
-    
-private:
-    // UI组件
-    OpenGLVideoWidget* m_videoRenderer;
-    QPushButton* m_openButton;
-    QPushButton* m_playButton;
-    QPushButton* m_stopButton;
-    QPushButton* m_refreshStatsButton;
-    QSlider* m_progressSlider;
-    QSlider* m_volumeSlider;
-    QLabel* m_stateLabel;
-    QLabel* m_positionLabel;
-    QLabel* m_infoLabel;
-    QLabel* m_statsLabel;
-    QLabel* m_volumeLabel;
-    QLabel* m_timeLabel;
-    QCheckBox* m_videoStreamCheckBox;
-    QCheckBox* m_audioStreamCheckBox;
-    QTimer* m_updateTimer;
-    
-    // 播放器相关
-    std::unique_ptr<PlayerCoreV2> m_player;
-    std::unique_ptr<UIPlayerCallback> m_callback;
-    int64_t m_duration;
-    bool m_seeking;
-};
-
-int main(int argc, char* argv[]) {
-    QApplication app(argc, argv);
-    
-    // 初始化日志系统
-    Logger::instance().initialize("test.log", LogLevel::DEBUG, false, false);
-    Logger::instance().info("PlayerCoreV2 Example Started");
-
-    qRegisterMetaType<AVFrame*>("AVFrame*");
-    // try {
-    // 创建播放器窗口
-    PlayerWindow window;
-    window.show();
-
-    // 如果有命令行参数,自动加载文件
-    // if (argc > 1) {
-    //     QTimer::singleShot(500, [&window, argv]() {
-    //         QMetaObject::invokeMethod(&window, "loadFile", Qt::QueuedConnection,
-    //                                 Q_ARG(std::string, std::string(argv[1])));
-    //     });
-    // } else {
-    //     // 默认加载测试文件
-    //     QTimer::singleShot(500, [&window]() {
-    //         std::string testFile = "C:/Users/zhuizhu/Videos/2.mp4";
-    //         QMetaObject::invokeMethod(&window, "loadFile", Qt::QueuedConnection,
-    //                                 Q_ARG(std::string, testFile));
-    //     });
-    // }
-
-    return app.exec();
-
-    // } catch (const std::exception& e) {
-    //     Logger::instance().error("Exception: " + std::string(e.what()));
-    //     QMessageBox::critical(nullptr, "错误", QString("发生异常: %1").arg(e.what()));
-    //     return 1;
-    // } catch (...) {
-    //     Logger::instance().error("Unknown exception occurred");
-    //     QMessageBox::critical(nullptr, "错误", "发生未知异常");
-    //     return 1;
-    // }
-}
-
-#include "test_player_with_ui.moc"

+ 0 - 22
AV/test/test_playerv2.pri

@@ -1,22 +0,0 @@
-# PlayerV2 Test Configuration
-# Include this file in your main .pro file to enable PlayerV2 testing
-
-# Uncomment the line below to enable PlayerV2 example
-SOURCES += $$PWD/code/examples/player_v2_example.cpp
-
-# Required Qt modules for PlayerV2
-QT += core widgets opengl multimedia
-
-# Compiler flags for PlayerV2
-CONFIG += c++17
-
-# Define for PlayerV2 features
-DEFINES += PLAYERV2_ENABLED
-
-# Additional include paths if needed
-# INCLUDEPATH += $$PWD/code/base
-# INCLUDEPATH += $$PWD/code/utils
-# INCLUDEPATH += $$PWD/code/player
-
-# FFmpeg libraries (adjust paths as needed)
-# LIBS += -lavformat -lavcodec -lavutil -lswscale -lswresample

+ 0 - 315
AV/test/test_recorder.cpp

@@ -1,315 +0,0 @@
-/**
- * AV录制器模块测试示例
- * 
- * 这个文件展示了如何使用重构后的录制器模块进行音频、视频和音视频同步录制。
- * 基于AV模块的现有组件构建,提供了统一的录制接口。
- */
-
-#include "code/recorder/recorder.h"
-#include "code/base/logger.h"
-#include <QCoreApplication>
-#include <QTimer>
-#include <QDebug>
-#include <memory>
-
-using namespace av::recorder;
-using namespace av::recorder::utils;
-
-class RecorderTest : public QObject {
-    Q_OBJECT
-
-public:
-    RecorderTest(QObject* parent = nullptr) : QObject(parent) {}
-    
-    void runTests() {
-        // 初始化录制器模块
-        auto result = RecorderModule::initialize();
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to initialize recorder module";
-            return;
-        }
-        
-        qInfo() << "Recorder Module Version:" << QString::fromStdString(RecorderModule::getVersion());
-        qInfo() << "Supported formats:" << getSupportedFormatsString();
-        qInfo() << "Supported audio codecs:" << getSupportedAudioCodecsString();
-        qInfo() << "Supported video codecs:" << getSupportedVideoCodecsString();
-        
-        // 测试音频录制
-        testAudioRecording();
-        
-        // 延迟测试视频录制
-        QTimer::singleShot(3000, this, &RecorderTest::testVideoRecording);
-        
-        // 延迟测试音视频同步录制
-        QTimer::singleShot(6000, this, &RecorderTest::testAVRecording);
-        
-        // 延迟退出
-        QTimer::singleShot(10000, this, &RecorderTest::cleanup);
-    }
-    
-private slots:
-    void testAudioRecording() {
-        qInfo() << "\n=== Testing Audio Recording ===";
-        
-        // 创建音频录制器
-        auto audioRecorder = createAudioRecorder();
-        if (!audioRecorder) {
-            qCritical() << "Failed to create audio recorder";
-            return;
-        }
-        
-        // 设置音频参数
-        auto audioParams = getDefaultAudioParams();
-        audioParams.outputPath = "test_audio_output.mp4";
-        audioParams.sampleRate = 44100;
-        audioParams.channels = 2;
-        audioParams.bitrate = 128000;
-        audioParams.codecName = "aac";
-        
-        qInfo() << "Audio params:" << formatAudioParams(audioParams);
-        
-        // 初始化录制器
-        auto result = audioRecorder->initialize(audioParams);
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to initialize audio recorder";
-            return;
-        }
-        
-        // 开始录制
-        result = audioRecorder->startRecording();
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to start audio recording";
-            return;
-        }
-        
-        qInfo() << "Audio recording started, will record for 2 seconds...";
-        
-        // 2秒后停止录制
-        QTimer::singleShot(2000, [audioRecorder = std::move(audioRecorder)]() mutable {
-            auto result = audioRecorder->stopRecording();
-            if (result == av::ErrorCode::SUCCESS) {
-                qInfo() << "Audio recording stopped successfully";
-                
-                // 获取统计信息
-                auto stats = audioRecorder->getStatistics();
-                qInfo() << "Audio recording stats:" << formatRecordingStats(stats);
-            } else {
-                qCritical() << "Failed to stop audio recording";
-            }
-        });
-    }
-    
-    void testVideoRecording() {
-        qInfo() << "\n=== Testing Video Recording ===";
-        
-        // 创建视频录制器
-        auto videoRecorder = createVideoRecorder();
-        if (!videoRecorder) {
-            qCritical() << "Failed to create video recorder";
-            return;
-        }
-        
-        // 设置视频参数(使用推荐参数)
-        auto videoParams = getRecommendedVideoParams();
-        videoParams.outputPath = "test_video_output.mp4";
-        videoParams.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
-        videoParams.monitorIndex = 0;
-        videoParams.drawCursor = true;
-        
-        qInfo() << "Video params:" << formatVideoParams(videoParams);
-        
-        // 初始化录制器
-        auto result = videoRecorder->initialize(videoParams);
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to initialize video recorder";
-            return;
-        }
-        
-        // 开始录制
-        result = videoRecorder->startRecording();
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to start video recording";
-            return;
-        }
-        
-        qInfo() << "Video recording started, will record for 2 seconds...";
-        
-        // 2秒后停止录制
-        QTimer::singleShot(2000, [videoRecorder = std::move(videoRecorder)]() mutable {
-            auto result = videoRecorder->stopRecording();
-            if (result == av::ErrorCode::SUCCESS) {
-                qInfo() << "Video recording stopped successfully";
-                
-                // 获取统计信息
-                auto stats = videoRecorder->getStatistics();
-                qInfo() << "Video recording stats:" << formatRecordingStats(stats);
-            } else {
-                qCritical() << "Failed to stop video recording";
-            }
-        });
-    }
-    
-    void testAVRecording() {
-        qInfo() << "\n=== Testing AV Synchronized Recording ===";
-        
-        // 创建音视频录制器
-        auto avRecorder = createAVRecorder();
-        if (!avRecorder) {
-            qCritical() << "Failed to create AV recorder";
-            return;
-        }
-        
-        // 设置音视频参数
-        auto avParams = getDefaultAVParams();
-        avParams.outputPath = "test_av_output.mp4";
-        avParams.enableAudio = true;
-        avParams.enableVideo = true;
-        avParams.enableSync = true;
-        avParams.syncThresholdMs = 40;
-        avParams.dropFrameOnSync = true;
-        
-        // 调整音频参数
-        avParams.audioParams.sampleRate = 44100;
-        avParams.audioParams.channels = 2;
-        avParams.audioParams.bitrate = 128000;
-        
-        // 调整视频参数
-        avParams.videoParams.width = 1280;
-        avParams.videoParams.height = 720;
-        avParams.videoParams.frameRate = 30;
-        avParams.videoParams.bitrate = 2000000;
-        avParams.videoParams.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
-        
-        qInfo() << "AV params:" << formatAVParams(avParams);
-        
-        // 初始化录制器
-        auto result = avRecorder->initialize(avParams);
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to initialize AV recorder";
-            return;
-        }
-        
-        // 开始录制
-        result = avRecorder->startRecording();
-        if (result != av::ErrorCode::SUCCESS) {
-            qCritical() << "Failed to start AV recording";
-            return;
-        }
-        
-        qInfo() << "AV recording started, will record for 3 seconds...";
-        
-        // 3秒后停止录制
-        QTimer::singleShot(3000, [avRecorder = std::move(avRecorder)]() mutable {
-            auto result = avRecorder->stopRecording();
-            if (result == av::ErrorCode::SUCCESS) {
-                qInfo() << "AV recording stopped successfully";
-                
-                // 获取统计信息
-                auto stats = avRecorder->getStatistics();
-                qInfo() << "AV recording stats:" << formatRecordingStats(stats);
-                
-                // 获取同步状态
-                auto syncStatus = avRecorder->getSyncStatus();
-                qInfo() << "Sync status:" << formatSyncStatus(syncStatus);
-            } else {
-                qCritical() << "Failed to stop AV recording";
-            }
-        });
-    }
-    
-    void cleanup() {
-        qInfo() << "\n=== Cleaning up ===";
-        
-        // 清理录制器模块
-        RecorderModule::cleanup();
-        
-        qInfo() << "Test completed, exiting...";
-        QCoreApplication::quit();
-    }
-    
-private:
-    QString getSupportedFormatsString() {
-        auto formats = RecorderModule::getSupportedFormats();
-        QStringList list;
-        for (const auto& format : formats) {
-            list << QString::fromStdString(format);
-        }
-        return list.join(", ");
-    }
-    
-    QString getSupportedAudioCodecsString() {
-        auto codecs = RecorderModule::getSupportedAudioCodecs();
-        QStringList list;
-        for (const auto& codec : codecs) {
-            list << QString::fromStdString(codec);
-        }
-        return list.join(", ");
-    }
-    
-    QString getSupportedVideoCodecsString() {
-        auto codecs = RecorderModule::getSupportedVideoCodecs();
-        QStringList list;
-        for (const auto& codec : codecs) {
-            list << QString::fromStdString(codec);
-        }
-        return list.join(", ");
-    }
-    
-    QString formatAudioParams(const AudioRecorderParams& params) {
-        return QString("SR:%1Hz, CH:%2, BR:%3bps, Codec:%4")
-            .arg(params.sampleRate)
-            .arg(params.channels)
-            .arg(params.bitrate)
-            .arg(QString::fromStdString(params.codecName));
-    }
-    
-    QString formatVideoParams(const VideoRecorderParams& params) {
-        return QString("Res:%1x%2, FPS:%3, BR:%4bps, Codec:%5")
-            .arg(params.width)
-            .arg(params.height)
-            .arg(params.frameRate)
-            .arg(params.bitrate)
-            .arg(QString::fromStdString(params.codecName));
-    }
-    
-    QString formatAVParams(const AVRecorderParams& params) {
-        return QString("Audio:[%1], Video:[%2], Sync:%3")
-            .arg(formatAudioParams(params.audioParams))
-            .arg(formatVideoParams(params.videoParams))
-            .arg(params.enableSync ? "ON" : "OFF");
-    }
-    
-    QString formatRecordingStats(const av::RecordingStatistics& stats) {
-        return QString("Duration:%1s, Frames:%2, Packets:%3, Errors:%4")
-            .arg(stats.durationMs / 1000.0, 0, 'f', 2)
-            .arg(stats.totalFrames)
-            .arg(stats.totalPackets)
-            .arg(stats.errorCount);
-    }
-    
-    QString formatSyncStatus(const av::SyncStatus& status) {
-        return QString("Drift:%1ms, Dropped:%2, Duplicated:%3")
-            .arg(status.avgDriftMs, 0, 'f', 2)
-            .arg(status.droppedFrames)
-            .arg(status.duplicatedFrames);
-    }
-};
-
-int main(int argc, char *argv[]) {
-    QCoreApplication app(argc, argv);
-    
-    // 设置日志级别
-    av::Logger::setLevel(av::LogLevel::INFO);
-    
-    qInfo() << "Starting AV Recorder Module Test...";
-    qInfo() << "This test will demonstrate audio, video, and synchronized AV recording.";
-    qInfo() << "Output files will be created in the current directory.";
-    
-    // 创建并运行测试
-    RecorderTest test;
-    test.runTests();
-    
-    return app.exec();
-}
-
-#include "test_recorder.moc"

+ 0 - 202
AV/test/test_seek_pause_fixed.cpp

@@ -1,202 +0,0 @@
-#include "code/player/player_core_v2.h"
-#include "code/base/logger.h"
-
-#include <iostream>
-#include <fstream>
-#include <thread>
-#include <chrono>
-
-using namespace av::player;
-using namespace av;
-class TestCallback : public PlayerEventCallback {
-public:
-    TestCallback(std::ofstream& output) : outputFile(output) {}
-    
-    void onStateChanged(PlayerState newState) override {
-        std::cout << "State changed to: " << static_cast<int>(newState) << std::endl;
-        currentState = newState;
-    }
-    
-    void onMediaInfoChanged(const MediaInfo& info) override {
-        std::cout << "Media info: " << info.filename << ", duration: " << info.duration
-                  << std::endl;
-    }
-    
-    void onPositionChanged(int64_t position) override {
-        std::cout << "Position: " << position / 1000000.0 << "s" << std::endl;
-        currentPosition = position;
-    }
-    
-    void onErrorOccurred(const std::string& error) override {
-        std::cout << "Error: " << error << std::endl;
-    }
-
-    void onEndOfFile() override { std::cout << "End of file" << std::endl; }
-
-    void onSyncError(double error, const std::string& reason) override
-    {
-        std::cout << "Sync error: " << error << ", reason: " << reason << std::endl;
-    }
-
-    void onFrameDropped(int64_t count) override
-    {
-        std::cout << "Frame dropped: " << count << std::endl;
-    }
-
-    void onVideoFrameReady(AVFrame* frame) override
-    {
-        // 简单处理视频帧
-    }
-
-    void onVideoRendererInitRequired(int width, int height) override
-    {
-        std::cout << "Video renderer init: " << width << "x" << height << std::endl;
-    }
-
-    void onVideoRendererCloseRequired() override
-    {
-        std::cout << "Video renderer close" << std::endl;
-    }
-
-    PlayerState currentState = PlayerState::Idle;
-    int64_t currentPosition = 0;
-    
-private:
-    std::ofstream& outputFile;
-};
-
-int main() {
-    // 创建输出文件
-    std::ofstream outputFile("test_seek_pause_output.txt");
-    if (!outputFile.is_open()) {
-        std::cerr << "无法创建输出文件" << std::endl;
-        return 1;
-    }
-    
-    // 初始化日志
-    Logger::instance().initialize("test.log", LogLevel::ERROR, false, true);
-    Logger::instance().info("PlayerCoreV2 Example Started");
-
-    // 创建播放器
-    PlayerCoreV2 player;
-    TestCallback callback(outputFile);
-    player.setEventCallback(&callback);
-
-    std::cout << "=== 测试修复后的暂停后seek功能 ===" << std::endl;
-
-    // 请用户提供测试文件路径
-    std::string filename = "C:/Users/zhuizhu/Videos/2.mp4";
-    // std::cout << "请输入测试视频文件路径: ";
-    // std::getline(std::cin, filename);
-
-    // if (filename.empty()) {
-    //     std::cout << "未提供文件路径,退出测试" << std::endl;
-    //     return 1;
-    // }
-
-    // 打开文件
-    std::cout << "\n1. 打开文件: " << filename << std::endl;
-    auto result = player.openFile(filename);
-    if (result != ErrorCode::SUCCESS) {
-        std::cout << "打开文件失败" << std::endl;
-        return 1;
-    }
-    
-    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
-    
-    // 开始播放
-    std::cout << "\n2. 开始播放" << std::endl;
-    player.play();
-    std::this_thread::sleep_for(std::chrono::seconds(3));
-    
-    // 暂停
-    std::cout << "\n3. 暂停播放" << std::endl;
-    player.pause();
-    std::this_thread::sleep_for(std::chrono::milliseconds(500));
-    
-    // 获取当前位置
-    int64_t pausePosition = player.getCurrentTime();
-    std::cout << "暂停时位置: " << pausePosition / 1000000.0 << "s" << std::endl;
-
-    // 在暂停状态下seek
-    int64_t seekTarget = pausePosition + 5000000; // 向前seek 5秒
-    std::cout << "\n4. 在暂停状态下seek到: " << seekTarget / 1000000.0 << "s" << std::endl;
-    player.seek(seekTarget);
-    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
-    
-    // 检查seek后的位置
-    int64_t afterSeekPosition = player.getCurrentTime();
-    std::cout << "seek后位置: " << afterSeekPosition / 1000000.0 << "s" << std::endl;
-    std::cout << "状态: " << static_cast<int>(callback.currentState) << std::endl;
-
-    // 验证结果
-    if (callback.currentState == PlayerState::Paused) {
-        std::cout << "✓ 状态正确:保持暂停状态" << std::endl;
-    } else {
-        std::cout << "✗ 状态错误:应该保持暂停状态" << std::endl;
-    }
-    
-    if (std::abs(afterSeekPosition - seekTarget) < 1000000) { // 允许1秒误差
-        std::cout << "✓ 位置正确:seek到目标位置" << std::endl;
-    } else {
-        std::cout << "✗ 位置错误:seek位置不正确" << std::endl;
-        std::cout << "  期望: " << seekTarget / 1000000.0 << "s" << std::endl;
-        std::cout << "  实际: " << afterSeekPosition / 1000000.0 << "s" << std::endl;
-    }
-    
-    // 恢复播放测试
-    std::cout << "\n5. 恢复播放测试" << std::endl;
-    player.play();
-    std::this_thread::sleep_for(std::chrono::seconds(2));
-    
-    int64_t playPosition = player.getCurrentTime();
-    std::cout << "恢复播放后位置: " << playPosition / 1000000.0 << "s" << std::endl;
-
-    if (playPosition > afterSeekPosition) {
-        std::cout << "✓ 播放正常:时间在前进" << std::endl;
-    } else {
-        std::cout << "✗ 播放异常:时间没有前进" << std::endl;
-    }
-
-    // 测试连续seek
-    std::cout << "\n6. 测试连续seek" << std::endl;
-    player.pause();
-    std::this_thread::sleep_for(std::chrono::milliseconds(500));
-    
-    // 第一次seek
-    int64_t seek1 = seekTarget + 2000000; // 再向前2秒
-    std::cout << "第一次seek到: " << seek1 / 1000000.0 << "s" << std::endl;
-    player.seek(seek1);
-    std::this_thread::sleep_for(std::chrono::milliseconds(500));
-    
-    int64_t pos1 = player.getCurrentTime();
-    std::cout << "第一次seek后位置: " << pos1 / 1000000.0 << "s" << std::endl;
-
-    // 第二次seek
-    int64_t seek2 = seek1 - 3000000; // 向后3秒
-    std::cout << "第二次seek到: " << seek2 / 1000000.0 << "s" << std::endl;
-    player.seek(seek2);
-    std::this_thread::sleep_for(std::chrono::milliseconds(500));
-    
-    int64_t pos2 = player.getCurrentTime();
-    std::cout << "第二次seek后位置: " << pos2 / 1000000.0 << "s" << std::endl;
-
-    if (callback.currentState == PlayerState::Paused) {
-        std::cout << "✓ 连续seek测试:状态保持暂停" << std::endl;
-    } else {
-        std::cout << "✗ 连续seek测试:状态错误" << std::endl;
-    }
-
-    // 停止播放
-    std::cout << "\n7. 停止播放" << std::endl;
-    player.stop();
-
-    std::cout << "\n=== 测试完成 ===" << std::endl;
-
-    // 关闭输出文件
-    outputFile.close();
-    
-    std::cout << "测试完成,结果已保存到 test_seek_pause_output.txt" << std::endl;
-    
-    return 0;
-}

+ 0 - 36
AV/test/test_simple_player.cpp

@@ -1,36 +0,0 @@
-/**
- * @file test_simple_player.cpp
- * @brief SimplePlayerWindow OpenGL渲染器测试程序
- * @author AI Assistant
- * @date 2024
- */
-
-#include "code/player/SimplePlayerWindow.h"
-#include <QApplication>
-#include <QDebug>
-
-int main(int argc, char* argv[])
-{
-    QApplication app(argc, argv);
-    
-    // 设置应用程序信息
-    app.setApplicationName("SimplePlayerWindow OpenGL Test");
-    app.setApplicationVersion("1.0");
-    app.setOrganizationName("AV Player");
-    
-    qDebug() << "Starting SimplePlayerWindow OpenGL test...";
-    
-    // 创建SimplePlayerWindow
-    SimplePlayerWindow window;
-    window.show();
-    
-    qDebug() << "SimplePlayerWindow created and shown";
-    
-    // 如果有命令行参数,可以在这里处理
-    if (argc > 1) {
-        qDebug() << "Command line file argument:" << argv[1];
-        // 这里可以添加自动打开文件的逻辑
-    }
-    
-    return app.exec();
-} 

+ 0 - 574
AV/test/test_utils.cpp

@@ -1,574 +0,0 @@
-// 工具类模块测试程序
-#include "code/base/logger.h"
-#include "code/base/types.h"
-#include "code/utils/utils_thread_pool.h"
-#include "code/utils/utils_frame_queue.h"
-#include "code/utils/utils_packet_queue.h"
-#include "code/utils/utils_performance_monitor.h"
-#include "code/utils/utils_synchronizer.h"
-#include <iostream>
-#include <chrono>
-#include <thread>
-#include <vector>
-#include <atomic>
-#include <random>
-#include <future>
-#include <mutex>
-
-extern "C" {
-#include <libavformat/avformat.h>
-#include <libavcodec/avcodec.h>
-#include <libavutil/frame.h>
-}
-
-using namespace av;
-using namespace av::utils;
-
-class UtilsTester {
-public:
-    UtilsTester() {
-        Logger::instance().setLevel(LogLevel::DEBUG);
-        Logger::instance().info("=== AV工具类模块测试套件 ===");
-    }
-    
-    // 测试线程池基本功能
-    bool testThreadPoolBasic() {
-        Logger::instance().info("[测试] 线程池基本功能...");
-        
-        try {
-            // 创建线程池配置
-            ThreadPoolConfig config;
-            config.minThreads = 2;
-            config.maxThreads = 4;
-            config.queueCapacity = 100;
-            config.enablePriority = true;
-            config.enableStatistics = true;
-            config.threadNamePrefix = "TestPool";
-            
-            // 创建线程池
-            auto pool = std::make_unique<ThreadPool>(config);
-            
-            // 初始化和启动
-            ErrorCode result = pool->initialize();
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().errorf("[失败] 线程池初始化失败: {}", static_cast<int>(result));
-                return false;
-            }
-            
-            result = pool->start();
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().errorf("[失败] 线程池启动失败: {}", static_cast<int>(result));
-                return false;
-            }
-            
-            Logger::instance().info("线程池启动成功");
-            
-            // 提交简单任务
-            std::atomic<int> counter{0};
-            std::vector<std::future<void>> futures;
-            
-            for (int i = 0; i < 10; ++i) {
-                auto future = pool->submit([&counter, i]() {
-                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
-                    counter.fetch_add(1);
-                    Logger::instance().infof("任务 {} 完成", i);
-                });
-                futures.push_back(std::move(future));
-            }
-            
-            // 等待所有任务完成
-            for (auto& future : futures) {
-                future.wait();
-            }
-            
-            if (counter.load() != 10) {
-                Logger::instance().errorf("[失败] 任务计数错误: 期望10,实际{}", counter.load());
-                return false;
-            }
-            
-            // 获取统计信息
-            auto stats = pool->getStats();
-            Logger::instance().infof("线程池统计: 总线程数={}, 完成任务数={}", 
-                                   stats.totalThreads, stats.completedTasks);
-            
-            // 停止线程池
-            pool->stop(true);
-            
-            Logger::instance().info("[成功] 线程池基本功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 线程池测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试线程池优先级功能
-    bool testThreadPoolPriority() {
-        Logger::instance().info("[测试] 线程池优先级功能...");
-        
-        try {
-            ThreadPoolConfig config;
-            config.minThreads = 1;
-            config.maxThreads = 1; // 单线程确保优先级顺序
-            config.enablePriority = true;
-            
-            auto pool = std::make_unique<ThreadPool>(config);
-            pool->initialize();
-            pool->start();
-            
-            std::vector<int> executionOrder;
-            std::mutex orderMutex;
-            
-            // 提交不同优先级的任务
-            pool->submitWithPriority(TaskPriority::LOW, [&]() {
-                std::lock_guard<std::mutex> lock(orderMutex);
-                executionOrder.push_back(1);
-                Logger::instance().info("低优先级任务执行");
-            });
-            
-            pool->submitWithPriority(TaskPriority::HIGH, [&]() {
-                std::lock_guard<std::mutex> lock(orderMutex);
-                executionOrder.push_back(3);
-                Logger::instance().info("高优先级任务执行");
-            });
-            
-            pool->submitWithPriority(TaskPriority::NORMAL, [&]() {
-                std::lock_guard<std::mutex> lock(orderMutex);
-                executionOrder.push_back(2);
-                Logger::instance().info("普通优先级任务执行");
-            });
-            
-            pool->submitWithPriority(TaskPriority::CRITICAL, [&]() {
-                std::lock_guard<std::mutex> lock(orderMutex);
-                executionOrder.push_back(4);
-                Logger::instance().info("关键优先级任务执行");
-            });
-            
-            // 等待所有任务完成
-            pool->waitForAllTasks();
-            
-            // 验证执行顺序(应该是:CRITICAL > HIGH > NORMAL > LOW)
-            if (executionOrder.size() != 4) {
-                Logger::instance().errorf("[失败] 任务数量错误: {}", executionOrder.size());
-                return false;
-            }
-            
-            Logger::instance().info("任务执行顺序:");
-            for (size_t i = 0; i < executionOrder.size(); ++i) {
-                Logger::instance().infof("  第{}个执行的任务ID: {}", i + 1, executionOrder[i]);
-            }
-            
-            pool->stop(true);
-            
-            Logger::instance().info("[成功] 线程池优先级功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 线程池优先级测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试帧队列功能
-    bool testFrameQueue() {
-        Logger::instance().info("[测试] 帧队列功能...");
-        
-        try {
-            // 创建帧队列
-            FrameQueueConfig config;
-            config.maxSize = 10;
-            FrameQueue frameQueue(config);
-            
-            // 测试基本的入队出队
-            for (int i = 0; i < 5; ++i) {
-                AVFrame* frame = av_frame_alloc();
-                if (!frame) {
-                    Logger::instance().error("[失败] 分配帧失败");
-                    return false;
-                }
-                
-                frame->pts = i;
-                frame->width = 1920;
-                frame->height = 1080;
-                
-                if (frameQueue.enqueue(frame) != ErrorCode::SUCCESS) {
-                    Logger::instance().errorf("[失败] 帧入队失败: {}", i);
-                    av_frame_free(&frame);
-                    return false;
-                }
-            }
-            
-            Logger::instance().infof("队列大小: {}", frameQueue.size());
-            
-            // 测试出队
-            for (int i = 0; i < 5; ++i) {
-                AVFrame* frame = frameQueue.dequeueFrame();
-                if (!frame) {
-                    Logger::instance().errorf("[失败] 帧出队失败: {}", i);
-                    return false;
-                }
-                
-                if (frame->pts != i) {
-                    Logger::instance().errorf("[失败] 帧PTS错误: 期望{}, 实际{}", i, frame->pts);
-                    av_frame_free(&frame);
-                    return false;
-                }
-                av_frame_free(&frame);
-            }
-            
-            if (!frameQueue.empty()) {
-                Logger::instance().error("[失败] 队列应该为空");
-                return false;
-            }
-            
-            Logger::instance().info("[成功] 帧队列功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 帧队列测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试数据包队列功能
-    bool testPacketQueue() {
-        Logger::instance().info("[测试] 数据包队列功能...");
-        
-        try {
-            // 创建数据包队列
-            PacketQueueConfig config;
-            config.maxSize = 20;
-            PacketQueue packetQueue(config);
-            
-            // 测试基本的入队出队
-            for (int i = 0; i < 10; ++i) {
-                AVPacket* packet = av_packet_alloc();
-                if (!packet) {
-                    Logger::instance().error("[失败] 分配数据包失败");
-                    return false;
-                }
-                
-                // av_packet_alloc已经初始化了packet,只需要设置字段
-                packet->pts = i;
-                packet->dts = i;
-                packet->size = 1024;
-                // 不设置data,保持为nullptr
-                
-                if (packetQueue.enqueue(packet) != ErrorCode::SUCCESS) {
-                    Logger::instance().errorf("[失败] 数据包入队失败: {}", i);
-                    av_packet_free(&packet);
-                    return false;
-                }
-            }
-            
-            Logger::instance().infof("队列大小: {}", packetQueue.size());
-            
-            // 测试出队
-            for (int i = 0; i < 10; ++i) {
-                AVPacket* packet = packetQueue.dequeuePacket();
-                if (!packet) {
-                    Logger::instance().errorf("[失败] 数据包出队失败: {}", i);
-                    return false;
-                }
-                
-                if (packet->pts != i) {
-                    Logger::instance().errorf("[失败] 数据包PTS错误: 期望{}, 实际{}", i, packet->pts);
-                    av_packet_free(&packet);
-                    return false;
-                }
-                av_packet_free(&packet);
-            }
-            
-            if (!packetQueue.empty()) {
-                Logger::instance().error("[失败] 队列应该为空");
-                return false;
-            }
-            
-            Logger::instance().info("[成功] 数据包队列功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 数据包队列测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试性能监控功能
-    bool testPerformanceMonitor() {
-        Logger::instance().info("[测试] 性能监控功能...");
-        
-        try {
-            // 创建性能监控器
-            PerformanceMonitor monitor;
-            
-            // 初始化监控器
-            monitor.initialize();
-            
-            // 注册测试指标
-            monitor.registerMetric("frames_processed", MetricType::COUNTER);
-            monitor.registerMetric("bytes_processed", MetricType::COUNTER);
-            
-            // 开始监控
-            monitor.start();
-            
-            // 模拟一些工作负载
-            for (int i = 0; i < 100; ++i) {
-                monitor.incrementCounter("frames_processed");
-                monitor.incrementCounter("bytes_processed", 1024);
-                std::this_thread::sleep_for(std::chrono::milliseconds(1));
-            }
-            
-            // 停止监控
-            monitor.stop();
-            
-            // 获取统计信息
-            auto stats = monitor.getAllStats();
-            
-            Logger::instance().infof("性能统计:");
-            if (stats.find("frames_processed") != stats.end()) {
-                Logger::instance().infof("  处理帧数: {}", stats["frames_processed"].count);
-            }
-            if (stats.find("bytes_processed") != stats.end()) {
-                Logger::instance().infof("  处理字节数: {}", stats["bytes_processed"].value);
-            }
-            
-            // 简化验证逻辑
-            if (stats.find("frames_processed") == stats.end() || stats["frames_processed"].count < 90) {
-                Logger::instance().error("[失败] 帧数统计不足");
-                return false;
-            }
-            
-            Logger::instance().info("[成功] 性能监控功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 性能监控测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试同步器功能
-    bool testSynchronizer() {
-        Logger::instance().info("[测试] 同步器功能...");
-        
-        try {
-            // 创建同步器
-            Synchronizer sync;
-            
-            // 启动同步器
-            sync.start();
-            
-            // 测试音视频同步
-            double videoPts = 1.0; // 1秒
-            double audioPts = 1.1; // 1.1秒
-            
-            // 设置时钟
-            sync.setVideoClock(videoPts);
-            sync.setAudioClock(audioPts);
-            
-            auto videoDelay = sync.calculateVideoDelay(videoPts);
-            auto audioDelay = sync.calculateAudioDelay(audioPts);
-            
-            Logger::instance().infof("视频延迟: {:.2f} ms", videoDelay);
-            Logger::instance().infof("音频延迟: {:.2f} ms", audioDelay);
-            
-            // 测试同步状态
-            bool inSync = sync.isSynchronized();
-            Logger::instance().infof("音视频同步状态: {}", inSync ? "同步" : "不同步");
-            
-            // 获取同步误差
-             double syncError = sync.calculateSyncError();
-             Logger::instance().infof("同步误差: {:.2f} ms", syncError);
-             
-             sync.stop();
-            
-            Logger::instance().info("[成功] 同步器功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 同步器测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试线程池工厂
-    bool testThreadPoolFactory() {
-        Logger::instance().info("[测试] 线程池工厂功能...");
-        
-        try {
-            // 测试标准线程池
-            auto standardPool = ThreadPoolFactory::createStandardPool();
-            if (!standardPool) {
-                Logger::instance().error("[失败] 创建标准线程池失败");
-                return false;
-            }
-            
-            standardPool->initialize();
-            standardPool->start();
-            
-            // 提交测试任务
-            auto future = standardPool->submit([]() {
-                return 42;
-            });
-            
-            int result = future.get();
-            if (result != 42) {
-                Logger::instance().errorf("[失败] 任务结果错误: 期望42, 实际{}", result);
-                return false;
-            }
-            
-            standardPool->stop(true);
-            
-            // 测试高性能线程池
-            auto highPerfPool = ThreadPoolFactory::createHighPerformancePool();
-            if (!highPerfPool) {
-                Logger::instance().error("[失败] 创建高性能线程池失败");
-                return false;
-            }
-            
-            // 测试轻量级线程池
-            auto lightPool = ThreadPoolFactory::createLightweightPool();
-            if (!lightPool) {
-                Logger::instance().error("[失败] 创建轻量级线程池失败");
-                return false;
-            }
-            
-            // 测试系统信息
-            size_t coreCount = ThreadPoolFactory::getCpuCoreCount();
-            size_t recommendedThreads = ThreadPoolFactory::getRecommendedThreadCount();
-            
-            Logger::instance().infof("CPU核心数: {}", coreCount);
-            Logger::instance().infof("推荐线程数: {}", recommendedThreads);
-            
-            Logger::instance().info("[成功] 线程池工厂功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 线程池工厂测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 测试线程池管理器
-    bool testThreadPoolManager() {
-        Logger::instance().info("[测试] 线程池管理器功能...");
-        
-        try {
-            auto& manager = ThreadPoolManager::getInstance();
-            
-            // 获取默认线程池
-            auto* defaultPool = manager.getDefaultPool();
-            if (!defaultPool) {
-                Logger::instance().error("[失败] 获取默认线程池失败");
-                return false;
-            }
-            
-            // 创建命名线程池
-            ThreadPoolConfig config;
-            config.minThreads = 2;
-            config.maxThreads = 4;
-            
-            ErrorCode result = manager.createPool("test_pool", config);
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().errorf("[失败] 创建命名线程池失败: {}", static_cast<int>(result));
-                return false;
-            }
-            
-            // 获取命名线程池
-            auto* namedPool = manager.getPool("test_pool");
-            if (!namedPool) {
-                Logger::instance().error("[失败] 获取命名线程池失败");
-                return false;
-            }
-            
-            // 获取所有线程池名称
-            auto poolNames = manager.getPoolNames();
-            Logger::instance().infof("线程池数量: {}", poolNames.size());
-            for (const auto& name : poolNames) {
-                Logger::instance().infof("  - {}", name);
-            }
-            
-            // 销毁线程池
-            result = manager.destroyPool("test_pool");
-            if (result != ErrorCode::SUCCESS) {
-                Logger::instance().errorf("[失败] 销毁线程池失败: {}", static_cast<int>(result));
-                return false;
-            }
-            
-            Logger::instance().info("[成功] 线程池管理器功能测试通过");
-            return true;
-            
-        } catch (const std::exception& e) {
-            Logger::instance().errorf("[失败] 线程池管理器测试异常: {}", e.what());
-            return false;
-        }
-    }
-    
-    // 运行所有测试
-    bool runAllTests() {
-        Logger::instance().info("开始运行所有工具类测试...");
-
-        std::vector<std::pair<std::string, std::function<bool()>>> tests
-            = {{"线程池基本功能", [this]() { return testThreadPoolBasic(); }},
-               {"线程池优先级功能", [this]() { return testThreadPoolPriority(); }},
-               {"帧队列功能", [this]() { return testFrameQueue(); }},
-               {"数据包队列功能", [this]() { return testPacketQueue(); }}, // 临时注释掉
-               {"性能监控功能", [this]() { return testPerformanceMonitor(); }},
-               {"同步器功能", [this]() { return testSynchronizer(); }},
-               {"线程池工厂功能", [this]() { return testThreadPoolFactory(); }},
-               {"线程池管理器功能", [this]() { return testThreadPoolManager(); }}};
-
-        int passedTests = 0;
-        int totalTests = tests.size();
-        
-        for (const auto& test : tests) {
-            Logger::instance().infof("\n=== 运行测试: {} ===", test.first);
-            
-            try {
-                if (test.second()) {
-                    passedTests++;
-                    Logger::instance().infof("✓ {} 测试通过", test.first);
-                } else {
-                    Logger::instance().errorf("✗ {} 测试失败", test.first);
-                }
-            } catch (const std::exception& e) {
-                Logger::instance().errorf("✗ {} 测试异常: {}", test.first, e.what());
-            }
-        }
-        
-        Logger::instance().infof("\n=== 测试结果汇总 ===");
-        Logger::instance().infof("通过测试: {}/{}", passedTests, totalTests);
-        Logger::instance().infof("成功率: {}%", (double) passedTests / totalTests * 100.0);
-
-        return passedTests == totalTests;
-    }
-};
-
-int main() {
-    std::cout << "=== AV工具类模块测试程序 ===" << std::endl;
-    
-    // 初始化日志系统
-    Logger::initialize("utils_test_log.txt", LogLevel::DEBUG, false, true);
-    
-    try {
-        UtilsTester tester;
-        
-        bool allTestsPassed = tester.runAllTests();
-        
-        if (allTestsPassed) {
-            std::cout << "\n🎉 所有测试通过!" << std::endl;
-            Logger::instance().info("所有工具类测试通过");
-            return 0;
-        } else {
-            std::cout << "\n❌ 部分测试失败!" << std::endl;
-            Logger::instance().error("部分工具类测试失败");
-            return 1;
-        }
-        
-    } catch (const std::exception& e) {
-        std::cerr << "测试过程中发生异常: " << e.what() << std::endl;
-        Logger::instance().errorf("测试过程中发生异常: {}", e.what());
-        return 1;
-    }
-}

+ 0 - 379
AV/test/test_window_capture.cpp

@@ -1,379 +0,0 @@
-#include "code/capture/capture_video_capturer.h"
-#include "code/base/logger.h"
-#include "code/base/media_common.h"
-#include <iostream>
-#include <thread>
-#include <chrono>
-#include <atomic>
-#include <signal.h>
-
-extern "C" {
-#include <libavutil/pixfmt.h>
-#include <libavutil/pixdesc.h>
-}
-
-using namespace av;
-using namespace av::capture;
-
-// 全局变量用于优雅退出
-std::atomic<bool> g_shouldExit{false};
-
-// 信号处理函数
-void signalHandler(int signal) {
-    Logger::instance().info("收到退出信号,正在停止采集...");
-    g_shouldExit = true;
-}
-
-// 帧回调函数
-void onFrameCaptured(const AVFramePtr& frame) {
-    static uint64_t frameCount = 0;
-    static auto lastTime = std::chrono::steady_clock::now();
-    
-    frameCount++;
-    
-    // 每秒输出一次统计信息
-    auto now = std::chrono::steady_clock::now();
-    auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - lastTime);
-    
-    if (duration.count() >= 1) {
-        const char* pixFmtName = av_get_pix_fmt_name(static_cast<AVPixelFormat>(frame->format));
-        std::string pixFmtStr = pixFmtName ? pixFmtName : "unknown";
-        Logger::instance().infof("已采集 {} 帧,分辨率: {}x{}, 格式: {}", 
-                               static_cast<uint64_t>(frameCount), 
-                               static_cast<int>(frame->width), 
-                               static_cast<int>(frame->height), 
-                               pixFmtStr);
-        lastTime = now;
-    }
-}
-
-// 错误回调函数
-void onError(ErrorCode error, const std::string& message) {
-    Logger::instance().errorf("采集错误: {} - {}", static_cast<int>(error), message);
-}
-
-// 测试窗口枚举功能
-void testWindowEnumeration() {
-    Logger::instance().info("=== 测试窗口枚举功能 ===");
-    
-    auto capturer = std::make_unique<VideoCapturer>();
-    
-    // 创建桌面采集参数来初始化采集器(避免窗口参数验证问题)
-    VideoCaptureParams params(CapturerType::VIDEO_SCREEN);
-    params.width = 1280;
-    params.height = 720;
-    params.fps = 30;
-    
-    Logger::instance().info("注意: 使用桌面采集模式来获取窗口枚举信息");
-    
-    // 初始化以获取设备信息
-    ErrorCode result = capturer->initialize(params);
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("初始化采集器失败: {}", static_cast<int>(result));
-        Logger::instance().warning("窗口枚举功能需要有效的采集器初始化,将跳过详细枚举");
-        
-        // 提供静态的窗口信息作为示例
-        Logger::instance().info("提供示例窗口信息:");
-        Logger::instance().info("  [0] ID: notepad, 名称: 记事本, 描述: Windows记事本窗口");
-        Logger::instance().info("      支持的分辨率: 1920x1080, 1280x720, 800x600, 640x480");
-        Logger::instance().info("      支持的帧率: 15fps, 24fps, 30fps, 60fps");
-        return;
-    }
-    
-    // 获取可用窗口列表
-    auto windows = capturer->getDetailedDeviceInfo();
-    
-    Logger::instance().infof("找到 {} 个可采集窗口:", windows.size());
-    
-    for (size_t i = 0; i < windows.size(); ++i) {
-        const auto& window = windows[i];
-        Logger::instance().infof("  [{}] ID: {}, 名称: {}, 描述: {}", 
-                               i, window.id, window.name, window.description);
-        
-        Logger::instance().infof("      支持的分辨率: ");
-        for (const auto& res : window.supportedResolutions) {
-            Logger::instance().infof("        {}x{}", res.first, res.second);
-        }
-        
-        Logger::instance().infof("      支持的帧率: ");
-        for (int fps : window.supportedFps) {
-            Logger::instance().infof("        {}fps", fps);
-        }
-    }
-    
-    // 清理
-    capturer->close();
-}
-
-// 测试桌面采集功能
-void testDesktopCapture() {
-    Logger::instance().info("=== 测试桌面采集功能 ===");
-    
-    // 创建桌面采集器
-    auto capturer = VideoCapturer::VideoCaptureFactory::createScreen();
-    if (!capturer) {
-        Logger::instance().error("创建桌面采集器失败");
-        return;
-    }
-    
-    // 设置回调函数
-    capturer->setFrameCallback(onFrameCaptured);
-    capturer->setErrorCallback(onError);
-    
-    // 设置采集参数
-    ErrorCode result = capturer->setVideoParams(1280, 720, 30);
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("设置视频参数失败: {}", static_cast<int>(result));
-        return;
-    }
-    
-    // 启动采集
-    result = capturer->start();
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("启动桌面采集失败: {}", static_cast<int>(result));
-        return;
-    }
-    
-    Logger::instance().info("桌面采集已启动,按 Ctrl+C 停止...");
-    
-    // 等待退出信号
-    while (!g_shouldExit) {
-        std::this_thread::sleep_for(std::chrono::milliseconds(100));
-        
-        // 检查采集器状态
-        if (!capturer->isRunning()) {
-            Logger::instance().warning("采集器已停止运行");
-            break;
-        }
-    }
-    
-    // 停止采集
-    Logger::instance().info("正在停止桌面采集...");
-    result = capturer->stop();
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("停止采集失败: {}", static_cast<int>(result));
-    }
-    
-    // 输出统计信息
-    auto stats = capturer->getStats();
-    Logger::instance().infof("采集统计信息:");
-    Logger::instance().infof("  已采集帧数: {}", stats.capturedFrames);
-    Logger::instance().infof("  丢弃帧数: {}", stats.droppedFrames);
-    Logger::instance().infof("  总字节数: {}", stats.totalBytes);
-    Logger::instance().infof("  错误次数: {}", stats.errorCount);
-    Logger::instance().infof("  平均采集时间: {:.2f}ms", stats.avgCaptureTime);
-    Logger::instance().infof("  实际帧率: {:.2f}fps", stats.fps);
-    
-    Logger::instance().info("桌面采集测试完成");
-}
-
-// 测试窗口采集功能
-void testWindowCapture(const std::string& windowTitle) {
-    Logger::instance().infof("=== 测试窗口采集功能: {} ===", windowTitle);
-    
-    // 创建窗口采集器
-    auto capturer = VideoCapturer::VideoCaptureFactory::createWindow(windowTitle);
-    if (!capturer) {
-        Logger::instance().error("创建窗口采集器失败");
-        return;
-    }
-    
-    // 设置回调函数
-    capturer->setFrameCallback(onFrameCaptured);
-    capturer->setErrorCallback(onError);
-    
-    // 设置采集参数
-    ErrorCode result = capturer->setVideoParams(1280, 720, 30);
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("设置视频参数失败: {}", static_cast<int>(result));
-        return;
-    }
-    
-    // 启动采集
-    result = capturer->start();
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("启动窗口采集失败: {}", static_cast<int>(result));
-        return;
-    }
-    
-    Logger::instance().info("窗口采集已启动,按 Ctrl+C 停止...");
-    
-    // 等待退出信号
-    while (!g_shouldExit) {
-        std::this_thread::sleep_for(std::chrono::milliseconds(100));
-        
-        // 检查采集器状态
-        if (!capturer->isRunning()) {
-            Logger::instance().warning("采集器已停止运行");
-            break;
-        }
-    }
-    
-    // 停止采集
-    Logger::instance().info("正在停止窗口采集...");
-    result = capturer->stop();
-    if (result != ErrorCode::SUCCESS) {
-        Logger::instance().errorf("停止采集失败: {}", static_cast<int>(result));
-    }
-    
-    // 输出统计信息
-    auto stats = capturer->getStats();
-    Logger::instance().infof("采集统计信息:");
-    Logger::instance().infof("  已采集帧数: {}", stats.capturedFrames);
-    Logger::instance().infof("  丢弃帧数: {}", stats.droppedFrames);
-    Logger::instance().infof("  总字节数: {}", stats.totalBytes);
-    Logger::instance().infof("  错误次数: {}", stats.errorCount);
-    Logger::instance().infof("  平均采集时间: {:.2f}ms", stats.avgCaptureTime);
-    Logger::instance().infof("  实际帧率: {:.2f}fps", stats.fps);
-    
-    Logger::instance().info("窗口采集测试完成");
-}
-
-// 测试工厂方法
-void testFactoryMethods() {
-    Logger::instance().info("=== 测试工厂方法 ===");
-    
-    // 测试通过标题创建(使用不存在的窗口进行错误处理测试)
-    {
-        Logger::instance().info("测试通过窗口标题创建采集器(预期会失败)...");
-        Logger::instance().warning("注意: 以下可能出现的错误信息是正常的,因为我们故意测试不存在的窗口");
-        Logger::instance().warning("预期错误: 'Can't find window' 和 'INVALID_PARAMS' 错误是测试的一部分");
-        auto capturer = VideoCapturer::VideoCaptureFactory::createWindow("记事本");
-        if (capturer) {
-            Logger::instance().info("✓ 通过窗口标题创建采集器成功");
-        } else {
-            Logger::instance().info("✓ 通过窗口标题创建采集器失败(预期结果,错误代码1表示INVALID_PARAMS)");
-        }
-    }
-    
-    // 测试通过句柄创建(模拟无效句柄)
-    {
-        Logger::instance().info("测试通过窗口句柄创建采集器(预期会失败)...");
-        Logger::instance().warning("注意: 以下可能出现的错误信息是正常的,因为我们故意测试无效的窗口句柄");
-        Logger::instance().warning("预期错误: 'Invalid window handle' 和 'INVALID_PARAMS' 错误是测试的一部分");
-        void* fakeHandle = reinterpret_cast<void*>(305419896); // 使用日志中的句柄
-        auto capturer = VideoCapturer::VideoCaptureFactory::createWindowByHandle(fakeHandle);
-        if (capturer) {
-            Logger::instance().info("✓ 通过窗口句柄创建采集器成功");
-        } else {
-            Logger::instance().info("✓ 通过窗口句柄创建采集器失败(预期结果,错误代码1表示INVALID_PARAMS)");
-        }
-    }
-    
-    // 测试桌面采集器创建(应该成功)
-    {
-        Logger::instance().info("测试桌面采集器创建...");
-        auto capturer = VideoCapturer::VideoCaptureFactory::createScreen();
-        if (capturer) {
-            Logger::instance().info("✓ 桌面采集器创建成功");
-        } else {
-            Logger::instance().error("✗ 桌面采集器创建失败");
-        }
-    }
-}
-
-// 测试参数验证
-void testParameterValidation() {
-    Logger::instance().info("=== 测试参数验证 ===");
-    
-    auto capturer = std::make_unique<VideoCapturer>();
-    
-    // 测试有效参数(使用桌面采集避免窗口查找问题)
-    {
-        VideoCaptureParams validParams(CapturerType::VIDEO_SCREEN);
-        validParams.width = 1280;
-        validParams.height = 720;
-        validParams.fps = 30;
-        
-        ErrorCode result = capturer->initialize(validParams);
-        if (result == ErrorCode::SUCCESS) {
-            Logger::instance().info("✓ 有效参数验证通过");
-        } else {
-            Logger::instance().errorf("✗ 有效参数验证失败: {}", static_cast<int>(result));
-        }
-        capturer->close();
-    }
-    
-    // 测试无效参数 - 空窗口标题和句柄
-    {
-        VideoCaptureParams invalidParams(CapturerType::VIDEO_WINDOW);
-        invalidParams.width = 1280;
-        invalidParams.height = 720;
-        invalidParams.fps = 30;
-        
-        ErrorCode result = capturer->initialize(invalidParams);
-        if (result != ErrorCode::SUCCESS) {
-            Logger::instance().info("✓ 无效参数验证通过(正确拒绝)");
-        } else {
-            Logger::instance().error("✗ 无效参数验证失败(应该拒绝但接受了)");
-        }
-        capturer->close();
-    }
-    
-    // 测试无效分辨率
-    {
-        VideoCaptureParams invalidParams(CapturerType::VIDEO_WINDOW);
-        invalidParams.windowTitle = "测试窗口";
-        invalidParams.width = -1;
-        invalidParams.height = 720;
-        invalidParams.fps = 30;
-        
-        ErrorCode result = capturer->initialize(invalidParams);
-        if (result != ErrorCode::SUCCESS) {
-            Logger::instance().info("✓ 无效分辨率验证通过(正确拒绝)");
-        } else {
-            Logger::instance().error("✗ 无效分辨率验证失败(应该拒绝但接受了)");
-        }
-        capturer->close();
-    }
-}
-
-int main(int argc, char* argv[]) {
-    // 初始化Logger
-    Logger::initialize("test_window_capture.log", LogLevel::INFO, false, true);
-
-    // 设置信号处理
-    signal(SIGINT, signalHandler);
-    signal(SIGTERM, signalHandler);
-    
-    Logger::instance().info("开始运行窗口采集测试套件...");
-    Logger::instance().info("============================================================");
-    Logger::instance().info("重要提示:");
-    Logger::instance().info("1. 测试过程中会出现一些FFmpeg警告信息,这是正常的");
-    Logger::instance().info("2. 'Can't find window' 警告表示测试的窗口不存在(预期行为)");
-    Logger::instance().info("3. 'Invalid window handle' 警告表示测试的句柄无效(预期行为)");
-    Logger::instance().info("4. '[ERROR] 初始化窗口采集器失败: 1' 是预期的测试错误(错误代码1=INVALID_PARAMS)");
-    Logger::instance().info("5. 'Capturing whole desktop' 表示成功切换到桌面采集模式");
-    Logger::instance().info("6. 'not enough frames to estimate rate' 是FFmpeg的正常提示");
-    Logger::instance().info("============================================================");
-    
-    try {
-        // 1. 测试窗口枚举
-        testWindowEnumeration();
-        
-        // 2. 测试工厂方法(会产生预期的警告信息)
-        testFactoryMethods();
-        
-        // 3. 测试参数验证
-        testParameterValidation();
-        
-        // 4. 测试桌面采集(更可靠)
-        Logger::instance().info("将尝试采集桌面屏幕");
-        Logger::instance().info("提示: 桌面采集不需要特定窗口存在");
-        
-        // 等待用户准备
-        Logger::instance().info("按回车键开始桌面采集测试...");
-        std::cin.get();
-        
-        if (!g_shouldExit) {
-            testDesktopCapture();
-        }
-        
-    } catch (const std::exception& e) {
-        Logger::instance().errorf("测试过程中发生异常: {}", e.what());
-        return 1;
-    }
-    
-    Logger::instance().info("窗口采集测试套件运行完成");
-    return 0;
-}

+ 0 - 276
AV/xmake.lua

@@ -1,276 +0,0 @@
--- AV 框架子模块配置
--- 此文件被主项目通过 includes("AV") 引入
-
--- 公共基础配置函数
-function add_av_common_config()
-    add_includedirs(".", {public = true})
-    add_includedirs("code", {public = true})
-end
-
--- 基础库
-target("av_base")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/base/*.cpp")
-    add_headerfiles("code/base/*.h")
-    add_av_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-    
-    -- 平台特定设置
-    if is_plat("windows") then
-        add_syslinks("ws2_32", "winmm")
-    else
-        add_syslinks("pthread")
-    end
-
--- 编解码库
-target("av_codec")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/codec/*.cpp")
-    add_headerfiles("code/codec/*.h")
-    add_av_common_config()
-    add_deps("av_base")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 捕获库
-target("av_capture")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/capture/*.cpp")
-    add_headerfiles("code/capture/*.h")
-    add_av_common_config()
-    add_deps("av_base")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 混流库
-target("av_muxer")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/muxer/*.cpp")
-    add_headerfiles("code/muxer/*.h")
-    add_av_common_config()
-    add_deps("av_base")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 工具库
-target("av_utils")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/utils/*.cpp")
-    add_headerfiles("code/utils/*.h")
-    add_av_common_config()
-    add_deps("av_base")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 完整的AV框架库 - 主项目依赖的统一接口
-target("av_framework")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_deps("av_base", "av_codec", "av_capture", "av_muxer", "av_utils")
-    add_av_common_config()
-    
-    -- 导出所有子模块的接口
-    add_headerfiles("code/**/*.h")
-
--- 播放器库
-target("av_player")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/player/*.cpp")
-    add_headerfiles("code/player/*.h")
-    add_av_common_config()
-    add_deps("av_base", "av_codec")
-    
-    -- Qt 配置
-    add_qt_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 录制器库
-target("av_recorder")
-    set_kind("static")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("code/recorder/*.cpp")
-    add_headerfiles("code/recorder/*.h")
-    add_av_common_config()
-    add_deps("av_base", "av_codec", "av_capture", "av_muxer")
-    
-    -- Qt 配置
-    add_qt_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 基础测试程序
-target("test_basic")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_basic.cpp")
-    add_deps("av_base")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 编解码测试程序
-target("test_codec")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_codec.cpp")
-    add_deps("av_codec")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 解码器测试程序
-target("test_decoder")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_decoder.cpp")
-    add_deps("av_codec")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-    
-
--- 音频编码器测试程序
-target("test_audio_encoder")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_audio_encoder.cpp")
-    add_deps("av_codec")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
-
--- 窗口采集测试程序
-target("test_window_capture")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_window_capture.cpp")
-    add_deps("av_capture")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 工具类测试程序
-target("test_utils")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_utils.cpp")
-    add_deps("av_utils")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 混流器测试程序
-target("test_muxer")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_muxer.cpp")
-    add_deps("av_muxer")
-    add_common_config()
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 音频调试测试程序
-target("test_audio_debug")
-    set_kind("binary")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_audio_debug.cpp")
-    add_deps("av_base", "av_codec", "av_utils")
-    add_files("code/player/player_core_v2.cpp")
-    add_files("code/player/audio_output.cpp")
-    add_files("code/player/thread_manager.cpp")
-    add_headerfiles("code/player/*.h")
-    add_common_config()
-    
-    add_rules("qt.widgetapp")
-    add_frameworks("QtCore", "QtWidgets", "QtMultimedia")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-
--- 带UI的播放器测试程序
-target("test_player_with_ui")
-    add_rules("qt.widgetapp")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_common_config()
-    add_files("test_player_with_ui.cpp", {rules = "qt.moc"})
-    add_deps("av_base", "av_codec", "av_utils")
-    add_files("code/player/*.cpp")
-    add_headerfiles("code/player/*.h")
-    add_files("code/player/*.h", {rules = "qt.moc"})
-    add_frameworks("QtNetwork", "QtGui", "QtCore", "QtWidgets", "QtMultimedia", "QtOpenGL")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()
-    
-    
--- 混流器测试程序
-target("test_seek_pause_fixed")
-    set_kind("binary")
-    add_rules("qt.widgetapp")
-    if is_plat("windows") then
-        add_defines("UNICODE", "_UNICODE")
-    end
-    add_files("test_seek_pause_fixed.cpp")
-    add_deps("av_base", "av_codec", "av_utils")
-    add_common_config()
-    add_frameworks("QtNetwork", "QtGui", "QtCore", "QtWidgets", "QtMultimedia", "QtOpenGL")
-    
-    -- FFmpeg配置
-    add_ffmpeg_config()

+ 372 - 17
MainPanel.cpp

@@ -21,10 +21,13 @@
 #include "widgets/statswidget.h"
 #include "widgets/userprofilewidget.h"
 
-#include "AvPlayer2/PlayWidget.h"
+#include "AVPlayer/avplayerwidget.h"
 #include "api/roomapi.h"
 #include "appevent.h"
 #include "widgets/recorderwidget.h"
+#include <QComboBox>
+#include <QLabel>
+#include <QHBoxLayout>
 
 namespace IconUtils {
 QIcon createSettingsIcon()
@@ -183,21 +186,215 @@ MainPanel::MainPanel(QWidget *parent)
     FunctionButton *audioDeviceBtn = new FunctionButton(IconUtils::createAudioDeviceIcon(), "音频设备", this);
     Popover *audioDevicePopover = new Popover(this);
 
-    // // 使用解耦版本的音频设备选择器
+    // // 使用解耦版本的音频设备选择器
     // m_audioDeviceSelectorDecoupled = new AudioDeviceSelectorIconDecoupled(this);
     // audioDevicePopover->setContentWidget(m_audioDeviceSelectorDecoupled);
+
+    // 使用 RecorderAudioWidget 作为 Popover 内容(麦克风 + 扬声器)
+    QWidget *audioContent = new QWidget(audioDevicePopover);
+    QVBoxLayout *audioLayout = new QVBoxLayout(audioContent);
+    audioLayout->setContentsMargins(8, 8, 8, 8);
+    audioLayout->setSpacing(8);
+
+    // 麦克风区域
+    QLabel *micTitle = new QLabel(tr("麦克风"), audioContent);
+    micTitle->setStyleSheet("font-weight:600;");
+    m_micWidget = new QComboBox(audioContent);
+    m_micWidget->setEditable(false);
+    audioLayout->addWidget(micTitle);
+    audioLayout->addWidget(m_micWidget);
+
+    // 扬声器区域
+    QLabel *spkTitle = new QLabel(tr("扬声器"), audioContent);
+    spkTitle->setStyleSheet("font-weight:600; margin-top:4px;");
+    m_speakerWidget = new QComboBox(audioContent);
+    m_speakerWidget->setEditable(false);
+    audioLayout->addWidget(spkTitle);
+    audioLayout->addWidget(m_speakerWidget);
+
+    // 新增:编码器区域
+    QLabel *encTitle = new QLabel(tr("视频编码器"), audioContent);
+    encTitle->setStyleSheet("font-weight:600; margin-top:4px;");
+    m_encoderWidget = new QComboBox(audioContent);
+    m_encoderWidget->setEditable(false);
+    audioLayout->addWidget(encTitle);
+    audioLayout->addWidget(m_encoderWidget);
+
+    // 新增:录制控制区域
+    QLabel *controlTitle = new QLabel(tr("录制控制"), audioContent);
+    controlTitle->setStyleSheet("font-weight:600; margin-top:8px;");
+    audioLayout->addWidget(controlTitle);
+
+    // 选项区域
+    m_drawCursorCheckBox = new QCheckBox(tr("绘制鼠标指针"), audioContent);
+    m_drawCursorCheckBox->setChecked(true);
+    m_syncRecordCheckBox = new QCheckBox(tr("推流时同步录制"), audioContent);
+    audioLayout->addWidget(m_drawCursorCheckBox);
+    audioLayout->addWidget(m_syncRecordCheckBox);
+
+    // 按钮区域
+    QHBoxLayout *buttonLayout = new QHBoxLayout();
+    m_recordButton = new QPushButton(tr("开始录制"), audioContent);
+    m_streamButton = new QPushButton(tr("开始推流"), audioContent);
+    m_settingsButton = new QPushButton(tr("设置"), audioContent);
+    
+    buttonLayout->addWidget(m_recordButton);
+    buttonLayout->addWidget(m_streamButton);
+    buttonLayout->addWidget(m_settingsButton);
+    audioLayout->addLayout(buttonLayout);
+
+    audioDevicePopover->setContentWidget(audioContent);
+
+    // 将按钮与 Popover 关联
     buttonGroup->addButton(audioDeviceBtn, audioDevicePopover);
 
-    // // 初始化音频设备选择器
-    // initAudioDeviceSelectors();
+    // 设备枚举与填充逻辑
+    auto populateAudioDevices = [this]() {
+        // 清空缓存
+        m_micDevices.clear();
+        m_speakerDevices.clear();
+
+        // 获取麦克风列表
+        AMRECORDER_DEVICE *micArray = nullptr;
+        int micCount = recorder_get_mics(&micArray);
+        QStringList micNames;
+        int defaultMicIndex = -1;
+        for (int i = 0; i < micCount; ++i) {
+            m_micDevices.push_back(micArray[i]);
+            micNames << QString::fromUtf8(micArray[i].name);
+            if (micArray[i].is_default && defaultMicIndex < 0) defaultMicIndex = i;
+        }
+        if (micArray) recorder_free_array(micArray);
+
+        // 获取扬声器列表
+        AMRECORDER_DEVICE *spkArray = nullptr;
+        int spkCount = recorder_get_speakers(&spkArray);
+        QStringList spkNames;
+        int defaultSpkIndex = -1;
+        for (int i = 0; i < spkCount; ++i) {
+            m_speakerDevices.push_back(spkArray[i]);
+            spkNames << QString::fromUtf8(spkArray[i].name);
+            if (spkArray[i].is_default && defaultSpkIndex < 0) defaultSpkIndex = i;
+        }
+        if (spkArray) recorder_free_array(spkArray);
+
+        // 更新 UI 列表
+        if (m_micWidget) {
+            m_micWidget->clear();
+            m_micWidget->addItems(micNames);
+        }
+        if (m_speakerWidget) {
+            m_speakerWidget->clear();
+            m_speakerWidget->addItems(spkNames);
+        }
+
+        // 恢复或设置默认选择
+        if (m_micWidget) {
+            if (defaultMicIndex >= 0 && defaultMicIndex < m_micDevices.size()) {
+                m_micWidget->setCurrentText(QString::fromUtf8(m_micDevices[defaultMicIndex].name));
+            } else if (!micNames.isEmpty()) {
+                m_micWidget->setCurrentIndex(0);
+            }
+        }
+        if (m_speakerWidget) {
+            if (defaultSpkIndex >= 0 && defaultSpkIndex < m_speakerDevices.size()) {
+                m_speakerWidget->setCurrentText(
+                    QString::fromUtf8(m_speakerDevices[defaultSpkIndex].name));
+            } else if (!spkNames.isEmpty()) {
+                m_speakerWidget->setCurrentIndex(0);
+            }
+        }
+
+        // 将当前选择传递给 RecorderWidget(若存在)
+        if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+            // 选中麦克风
+            if (m_micWidget) {
+                const QString sel = m_micWidget->currentText();
+                for (const auto &d : m_micDevices) {
+                    if (sel == QString::fromUtf8(d.name)) { rec->setMicDevice(d); break; }
+                }
+            }
+            // 选中扬声器
+            if (m_speakerWidget) {
+                const QString sel = m_speakerWidget->currentText();
+                for (const auto &d : m_speakerDevices) {
+                    if (sel == QString::fromUtf8(d.name)) { rec->setSpeakerDevice(d); break; }
+                }
+            }
+        }
+    };
+
+    // 新增:编码器枚举与填充逻辑
+    auto populateEncoders = [this]() {
+        m_encoderList.clear();
+        m_selectedEncoderId = -1;
+        AMRECORDER_ENCODERS *encArray = nullptr;
+        int encCount = recorder_get_vencoders(&encArray);
+        QStringList encNames;
+        for (int i = 0; i < encCount; ++i) {
+            m_encoderList.push_back(encArray[i]);
+            encNames << QString::fromUtf8(encArray[i].name);
+        }
+        if (encArray) recorder_free_array(encArray);
+
+        if (m_encoderWidget) {
+            m_encoderWidget->clear();
+            m_encoderWidget->addItems(encNames);
+            if (!m_encoderList.isEmpty()) {
+                m_encoderWidget->setCurrentIndex(0);
+                m_selectedEncoderId = m_encoderList[0].id;
+            }
+        }
 
-    // // 连接解耦版本的音频设备选择信号
-    // connect(m_audioDeviceSelectorDecoupled, &AudioDeviceSelectorIconDecoupled::microphoneDeviceSelected,
-    //         this, &MainPanel::onMicrophoneDeviceSelected);
-    // connect(m_audioDeviceSelectorDecoupled, &AudioDeviceSelectorIconDecoupled::speakerDeviceSelected,
-    //         this, &MainPanel::onSpeakerDeviceSelected);
+        if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+            if (m_selectedEncoderId >= 0) rec->setVideoEncoderId(m_selectedEncoderId);
+        }
+    };
 
-    // 保持原有的AudioDeviceSelectorIcon作为备用(兼容模式)
+    // 首次填充设备和编码器
+    populateAudioDevices();
+    populateEncoders();
+
+    // 连接设备选择变化 -> 传给 RecorderWidget
+
+    connect(m_micWidget, &QComboBox::currentTextChanged, this, [this](const QString &deviceName) {
+        if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+            for (const auto &d : m_micDevices) {
+                if (deviceName == QString::fromUtf8(d.name)) {
+                    rec->setMicDevice(d);
+                    break;
+                }
+            }
+        }
+    });
+
+    connect(m_speakerWidget, &QComboBox::currentTextChanged, this, [this](const QString &deviceName) {
+        if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+            for (const auto &d : m_speakerDevices) {
+                if (deviceName == QString::fromUtf8(d.name)) {
+                    rec->setSpeakerDevice(d);
+                    break;
+                }
+            }
+        }
+    });
+
+    // 新增:编码器选择变化 -> 传给 RecorderWidget
+    connect(m_encoderWidget, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index) {
+        if (index >= 0 && index < m_encoderList.size()) {
+            m_selectedEncoderId = m_encoderList[index].id;
+            if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+                rec->setVideoEncoderId(m_selectedEncoderId);
+            }
+        }
+    });
+
+    // 新增:录制控制按钮信号连接
+    connect(m_recordButton, &QPushButton::clicked, this, &MainPanel::onRecordButtonClicked);
+    connect(m_streamButton, &QPushButton::clicked, this, &MainPanel::onStreamButtonClicked);
+    connect(m_settingsButton, &QPushButton::clicked, this, &MainPanel::onSettingsButtonClicked);
+
+    // 维持原有的AudioDeviceSelectorIcon兼容代码(保持注释)
     // m_audioDeviceSelector = new AudioDeviceSelectorIcon(this);
     // connect(m_audioDeviceSelector, &AudioDeviceSelectorIcon::microphoneDeviceSelected,
     //         this, [this](const AudioDeviceInfo& device) {
@@ -223,6 +420,11 @@ MainPanel::MainPanel(QWidget *parent)
     buttonGroup->addButton(actionButton, nullptr);
     
     // 将buttonGroup添加到playerContainer的布局中
+    playerLayout = qobject_cast<QVBoxLayout*>(playerContainer->layout());
+    if (!playerLayout) {
+        playerLayout = new QVBoxLayout(playerContainer);
+        playerLayout->setContentsMargins(0, 0, 0, 0);
+    }
     playerLayout->addStretch(1);  // 添加弹性空间,将buttonGroup推到底部
     playerLayout->addWidget(buttonGroup, 0);  // 添加buttonGroup到底部,不拉伸
     buttonGroup->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);  // 使用固定大小策略
@@ -271,6 +473,18 @@ MainPanel::~MainPanel()
         delete userProfile;
         userProfile = nullptr;
     }
+    if (m_recorderStandalone) {
+        m_recorderStandalone->deleteLater();
+        m_recorderStandalone = nullptr;
+    }
+    if (m_avPlayerStandalone) {
+        m_avPlayerStandalone->deleteLater();
+        m_avPlayerStandalone = nullptr;
+    }
+    if (m_chatStandalone) {
+        m_chatStandalone->deleteLater();
+        m_chatStandalone = nullptr;
+    }
 }
 void MainPanel::setRole(const QStringList &roleList)
 {
@@ -278,7 +492,7 @@ void MainPanel::setRole(const QStringList &roleList)
     if (roleList.contains("role.admin")) {
         newPlayer = new RecorderWidget(this);
     } else {
-        newPlayer = new PlayWidget(this);
+        newPlayer = new AVPlayerWidget(this);
     }
     setPlayerWidget(newPlayer);
 
@@ -299,8 +513,11 @@ void MainPanel::setPushRoomId(const QString &id)
 
     // 重新进入房间
     chatView->initWebsocket(id);
+    if (m_chatStandalone) {
+        m_chatStandalone->initWebsocket(id);
+    }
 
-    if (PlayWidget *playWidget = qobject_cast<PlayWidget *>(playerWidget)) {
+    if (AVPlayerWidget *playWidget = qobject_cast<AVPlayerWidget *>(playerWidget)) {
         MaskOverlay::instance()->show(nullptr, 0, MaskOverlay::ActiveWindow);
 
         QFuture<HttpResponse> getRoomFuture = getRoomApi(id);
@@ -320,7 +537,8 @@ void MainPanel::setPushRoomId(const QString &id)
                 int status = roomInfo.liveStatus.value_or(0);
                 if (status == 1) {
                     qDebug() << "open" << ("rtmp://106.55.186.74:1935/stream/V1/" + id);
-                    playWidget->startToPlay("rtmp://106.55.186.74:1935/stream/V1/" + id);
+
+                    playWidget->play("rtmp://106.55.186.74:1935/stream/V1/" + id);
                 }
             })
             .finally([]() { MaskOverlay::instance()->hide(); });
@@ -369,6 +587,31 @@ void MainPanel::setPlayerWidget(QWidget *newPlayer)
     
     // 确保buttonGroup固定在底部
     buttonGroup->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);  // 使用固定大小策略
+
+    // 如果新的 player 是 RecorderWidget,则同步当前选择的音频设备
+    if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+        if (m_micWidget) {
+            const QString sel = m_micWidget->currentText();
+            for (const auto &d : m_micDevices) {
+                if (sel == QString::fromUtf8(d.name)) { rec->setMicDevice(d); break; }
+            }
+        }
+        if (m_speakerWidget) {
+            const QString sel = m_speakerWidget->currentText();
+            for (const auto &d : m_speakerDevices) {
+                if (sel == QString::fromUtf8(d.name)) { rec->setSpeakerDevice(d); break; }
+            }
+        }
+        // 同步编码器
+        if (m_selectedEncoderId >= 0) {
+            rec->setVideoEncoderId(m_selectedEncoderId);
+        } else if (m_encoderWidget && m_encoderWidget->count() > 0 && !m_encoderList.isEmpty()) {
+            int idx = m_encoderWidget->currentIndex();
+            if (idx >= 0 && idx < m_encoderList.size()) {
+                rec->setVideoEncoderId(m_encoderList[idx].id);
+            }
+        }
+    }
 }
 
 
@@ -379,16 +622,17 @@ void MainPanel::handleDebouncedPlay()
     if (m_pendingRoomId.isEmpty() || !chatView) {
         return;
     }
-    
-    if (PlayWidget *playWidget = qobject_cast<PlayWidget *>(playerWidget)) {
+
+    if (AVPlayerWidget *playWidget = qobject_cast<AVPlayerWidget *>(playerWidget)) {
         if (!m_isStartingPlay) {
             m_isStartingPlay = true;
             qDebug() << "[MainPanel] 防抖处理后开始播放:" << m_pendingRoomId;
-            playWidget->startToPlay("rtmp://106.55.186.74:1935/stream/V1/" + m_pendingRoomId);
+
+            playWidget->play("rtmp://106.55.186.74:1935/stream/V1/" + m_pendingRoomId);
             m_isStartingPlay = false; // 如果 startToPlay 是同步的
         }
     }
-    
+
     // 清空待处理的房间ID
     m_pendingRoomId.clear();
 }
@@ -413,3 +657,114 @@ void MainPanel::initAudioDeviceSelectors()
     qDebug() << "[MainPanel] 音频设备选择器初始化完成";
 }
 
+void MainPanel::showRecorderStandalone()
+{
+    if (!m_recorderStandalone) {
+        m_recorderStandalone = new RecorderWidget(nullptr);
+        m_recorderStandalone->setAttribute(Qt::WA_DeleteOnClose, false);
+        connect(m_recorderStandalone, &QObject::destroyed, this, [this]() {
+            m_recorderStandalone = nullptr;
+        });
+        m_recorderStandalone->setWindowTitle(tr("RecorderWidget"));
+    }
+    m_recorderStandalone->show();
+    m_recorderStandalone->raise();
+    m_recorderStandalone->activateWindow();
+}
+
+void MainPanel::showPlayerStandalone()
+{
+    if (!m_avPlayerStandalone) {
+        m_avPlayerStandalone = new AVPlayerWidget(nullptr);
+        m_avPlayerStandalone->setAttribute(Qt::WA_DeleteOnClose, false);
+        connect(m_avPlayerStandalone, &QObject::destroyed, this, [this]() {
+            m_avPlayerStandalone = nullptr;
+        });
+        m_avPlayerStandalone->setWindowTitle(tr("AVPlayerWidget"));
+    }
+    m_avPlayerStandalone->show();
+    m_avPlayerStandalone->raise();
+    m_avPlayerStandalone->activateWindow();
+}
+
+void MainPanel::showChatStandalone()
+{
+    if (!m_chatStandalone) {
+        m_chatStandalone = new ChatWindow(webSocketClient);
+        m_chatStandalone->setAttribute(Qt::WA_DeleteOnClose, false);
+        connect(m_chatStandalone, &QObject::destroyed, this, [this]() {
+            m_chatStandalone = nullptr;
+        });
+        m_chatStandalone->setMinimumWidth(400);
+        m_chatStandalone->setWindowTitle(tr("ChatWindow"));
+        // 同步当前房间
+        if (webSocketClient) {
+            const QString rid = webSocketClient->roomId();
+            if (!rid.isEmpty()) {
+                m_chatStandalone->initWebsocket(rid);
+            }
+        }
+    }
+    m_chatStandalone->show();
+    m_chatStandalone->raise();
+    m_chatStandalone->activateWindow();
+}
+
+void MainPanel::showChatEmbedded()
+{
+    if (chatView) {
+        chatView->show();
+        chatView->raise();
+    }
+    if (m_chatStandalone) {
+        m_chatStandalone->hide();
+    }
+}
+
+// 新增:录制控制按钮的槽函数实现
+void MainPanel::onRecordButtonClicked()
+{
+    if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+        // 同步选项设置到RecorderWidget
+        // 注意:这里需要RecorderWidget提供设置选项的接口
+        
+        // 调用RecorderWidget的录制方法
+        rec->onRecordButtonClicked();
+        
+        // 更新按钮文本
+        if (m_recordButton) {
+            if (m_recordButton->text() == tr("开始录制")) {
+                m_recordButton->setText(tr("停止录制"));
+            } else {
+                m_recordButton->setText(tr("开始录制"));
+            }
+        }
+    }
+}
+
+void MainPanel::onStreamButtonClicked()
+{
+    if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+        // 同步选项设置到RecorderWidget
+        
+        // 调用RecorderWidget的推流方法
+        rec->onStreamButtonClicked();
+        
+        // 更新按钮文本
+        if (m_streamButton) {
+            if (m_streamButton->text() == tr("开始推流")) {
+                m_streamButton->setText(tr("停止推流"));
+            } else {
+                m_streamButton->setText(tr("开始推流"));
+            }
+        }
+    }
+}
+
+void MainPanel::onSettingsButtonClicked()
+{
+    if (RecorderWidget *rec = qobject_cast<RecorderWidget *>(playerWidget)) {
+        // 调用RecorderWidget的设置方法
+        rec->onSettingsButtonClicked();
+    }
+}

+ 44 - 2
MainPanel.h

@@ -6,10 +6,19 @@
 #include <QWidget>
 #include "qobjectdefs.h"
 
+#include <QVector>
+#include <QPushButton>
+#include <QCheckBox>
+#include "libs/Recorder/export.h"
+
 class QSplitter;
 
 class UserProfileWidget;
 class ChatWindow;
+class RecorderWidget; // forward declaration for standalone recorder
+class AVPlayerWidget; // forward declaration for standalone player
+// Removed RecorderAudioWidget forward declaration; use QComboBox instead
+class QComboBox;
 
 class WebSocketClient;
 class StatsWidget;
@@ -31,7 +40,12 @@ public:
 
     void setPushRoomId(const QString &room);
 
-
+    // 新增:独立窗口显示控制
+public slots:
+    void showRecorderStandalone();
+    void showPlayerStandalone();
+    void showChatStandalone();
+    void showChatEmbedded();
 
 signals:
     void logoutClicked();
@@ -48,7 +62,12 @@ private:
     QWidget *playerContainer = nullptr;
     QWidget *playerWidget = nullptr;
     UserProfileWidget *userProfile = nullptr;
-    ChatWindow *chatView = nullptr;
+    ChatWindow *chatView = nullptr;           // 嵌入式聊天窗口
+
+    // 新增:独立窗口实例
+    RecorderWidget *m_recorderStandalone = nullptr;
+    AVPlayerWidget *m_avPlayerStandalone = nullptr;
+    ChatWindow *m_chatStandalone = nullptr;   // 独立显示的聊天窗口
 
     WebSocketClient *webSocketClient = nullptr;
     StatsWidget *statsWidget = nullptr;
@@ -62,9 +81,32 @@ private:
     AudioDeviceSelectorIcon *m_audioDeviceSelector = nullptr;
     AudioDeviceSelectorIconDecoupled *m_audioDeviceSelectorDecoupled = nullptr;
 
+    // 音频设备选择弹层中的控件与数据缓存(改为使用基础控件 QComboBox)
+    QComboBox *m_micWidget = nullptr;         // 麦克风下拉框
+    QComboBox *m_speakerWidget = nullptr;     // 扬声器下拉框
+    QVector<AMRECORDER_DEVICE> m_micDevices;      // 缓存麦克风设备列表
+    QVector<AMRECORDER_DEVICE> m_speakerDevices;  // 缓存扬声器设备列表
+
+    // 新增:视频编码器选择控件与缓存
+    QComboBox *m_encoderWidget = nullptr;         // 视频编码器下拉框
+    QVector<AMRECORDER_ENCODERS> m_encoderList;   // 缓存编码器列表
+    int m_selectedEncoderId = -1;                 // 当前选择的编码器 id
+
+    // 新增:录制控制按钮(从RecorderWidget移动过来)
+    QPushButton *m_recordButton = nullptr;        // 开始录制按钮
+    QPushButton *m_streamButton = nullptr;        // 开始推流按钮
+    QPushButton *m_settingsButton = nullptr;      // 设置按钮
+    QCheckBox *m_drawCursorCheckBox = nullptr;    // 绘制鼠标指针选项
+    QCheckBox *m_syncRecordCheckBox = nullptr;    // 推流时同步录制选项
+
     // DockManager 相关
     ADS::DockManager *m_dockManager = nullptr;
     
 private slots:
     void initAudioDeviceSelectors();
+    
+    // 新增:录制控制按钮的槽函数
+    void onRecordButtonClicked();
+    void onStreamButtonClicked();
+    void onSettingsButtonClicked();
 };

+ 0 - 1
libs/libs.pri

@@ -1,5 +1,4 @@
 include($$PWD/AvRecorder/AvRecorder.pri)
-include($$PWD/AvPlayer2/AvPlayer2.pri)
 
 include($$PWD/qwindowkit/qwindowkit.pri)
 include($$PWD/fmt.pri)

Неке датотеке нису приказане због велике количине промена