zhuizhu 8 months ago
parent
commit
f3807d0957

+ 5 - 38
AV/code/player/audio_output.cpp

@@ -336,35 +336,14 @@ bool AudioOutput::writeFrame(const AVFramePtr& frame)
     }
     
     // 使用Synchronizer进行时间同步
-    if (frame->pts != AV_NOPTS_VALUE && m_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_synchronizer->setAudioClock(audioPts, timeBase);
-        
-        // 计算同步延迟
-        double delay = 0.0;
-        auto decision = m_synchronizer->shouldPlayAudioFrame(audioPts, timeBase);
-        ErrorCode result = decision.action == av::utils::FrameAction::DISPLAY ? ErrorCode::SUCCESS : ErrorCode::PROCESSING_ERROR;
-        delay = decision.delay;
-        
-        if (result == ErrorCode::SUCCESS && delay > 0) {
-            // 应用播放速度控制
-            delay = delay / m_playbackSpeed;
-            
-            // 限制最大延迟时间,避免异常情况
-            const double MAX_DELAY = 0.1;  // 100ms
-            if (delay > 0 && delay < MAX_DELAY) {
-                int delayUs = static_cast<int>(delay * 1000000);
-                av_usleep(delayUs);
-            }
-        }
-        
-        m_lastAudioPts = audioPts * timeBase;  // 转换为秒用于记录
+
+        m_lastAudioPts = audioPts * timeBase; // 转换为秒用于记录
     }
-    
+
     // 转换音频帧格式
     QByteArray audioData = convertFrame(frame);
     if (audioData.isEmpty()) {
@@ -437,12 +416,7 @@ void AudioOutput::setPlaybackSpeed(double speed)
 {
     speed = std::max(0.1, std::min(4.0, speed));
     m_playbackSpeed = speed;
-    
-    // 同时更新Synchronizer的播放速度
-    if (m_synchronizer) {
-        m_synchronizer->setPlaybackSpeed(speed);
-    }
-    
+
     av::Logger::instance().debug("Audio playback speed set to: " + std::to_string(speed));
 }
 
@@ -475,13 +449,6 @@ bool AudioOutput::isPlaying() const
     return m_playing;
 }
 
-void AudioOutput::setSynchronizer(std::shared_ptr<av::utils::SynchronizerV2> synchronizer)
-{
-    QMutexLocker locker(&m_mutex);
-    m_synchronizer = synchronizer;
-    av::Logger::instance().info("Audio output synchronizer set");
-}
-
 void AudioOutput::onStateChanged(QAudio::State state)
 {
     switch (state) {

+ 3 - 11
AV/code/player/audio_output.h

@@ -110,12 +110,6 @@ public:
      */
     bool isPlaying() const;
 
-    /**
-     * 设置同步器
-     * @param synchronizer 外部同步器实例
-     */
-    void setSynchronizer(std::shared_ptr<av::utils::SynchronizerV2> synchronizer);
-
 private slots:
     void onStateChanged(QAudio::State state);
 
@@ -163,11 +157,9 @@ private:
     // 状态
     std::atomic<bool> m_initialized;
     std::atomic<bool> m_playing;
-    
-    // 时间同步 - 使用Synchronizer进行统一管理
-    std::shared_ptr<av::utils::SynchronizerV2> m_synchronizer;
-    double m_lastAudioPts;  // 上一次的音频PTS
-    
+
+    double m_lastAudioPts; // 上一次的音频PTS
+
     mutable QMutex m_mutex;
 };
 

+ 0 - 645
AV/code/player/opengl_video_renderer.cpp

@@ -1,645 +0,0 @@
-#include "../base/logger.h"
-
-#include "opengl_video_renderer.h"
-
-#include <QPainter>
-#include <QResizeEvent>
-#include <QApplication>
-#include <QDebug>
-#include <QOpenGLContext>
-#include <QSurfaceFormat>
-#include <algorithm>
-
-extern "C" {
-#include <libavutil/imgutils.h>
-#include <libswscale/swscale.h>
-}
-
-namespace av {
-namespace player {
-
-// 顶点着色器源码 - 参考yuvopenglwidget.cpp
-static const char* vertexShaderSource = R"(
-attribute vec4 vertexIn;
-attribute vec2 textureIn;
-varying vec2 TexCoord;
-
-void main(void) {
-    gl_Position = vertexIn;
-    TexCoord = textureIn;
-}
-)";
-
-// 片段着色器源码 (YUV420P) - 参考yuvopenglwidget.cpp
-static const char* fragmentShaderSource = R"(
-varying mediump vec2 TexCoord;
-uniform sampler2D yTexture;
-uniform sampler2D uTexture;
-uniform sampler2D vTexture;
-
-void main(void) {
-    vec3 yuv;
-    vec3 rgb;
-    yuv.r = texture2D(yTexture, TexCoord).r;
-    yuv.g = texture2D(uTexture, TexCoord).r - 0.5;
-    yuv.b = texture2D(vTexture, TexCoord).r - 0.5;
-    rgb = mat3(1.0, 1.0, 1.0, 0.0, -0.138, 1.816, 1.540, -0.459, 0.0) * yuv;
-    gl_FragColor = vec4(rgb, 1.0);
-}
-)";
-
-OpenGLVideoRenderer::OpenGLVideoRenderer(QWidget* parent)
-    : QOpenGLWidget(parent)
-    , m_videoWidth(0)
-    , m_videoHeight(0)
-    , m_inputFormat(AV_PIX_FMT_NONE)
-    , m_fps(25.0)
-    , m_textureY(0)
-    , m_textureU(0)
-    , m_textureV(0)
-    , m_swsContext(nullptr)
-    , m_yuvBuffer(nullptr)
-    , m_yuvBufferSize(0)
-    , m_backgroundColor(Qt::black)
-    , m_keepAspectRatio(true)
-    , m_renderQuality(1.0f)
-    , m_vSyncEnabled(true)
-    , m_initialized(false)
-    , m_glInitialized(false)
-    , m_hasFrame(false)
-    , m_updateTimer(new QTimer(this))
-{
-    // 设置OpenGL格式
-    QSurfaceFormat format;
-    format.setVersion(3, 3);
-    format.setProfile(QSurfaceFormat::CoreProfile);
-    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
-    format.setSwapInterval(m_vSyncEnabled ? 1 : 0);
-    setFormat(format);
-    
-    // 设置基本属性
-    setMinimumSize(320, 240);
-    setFocusPolicy(Qt::StrongFocus);
-    
-    // 连接更新定时器
-    connect(m_updateTimer, &QTimer::timeout, this, &OpenGLVideoRenderer::updateDisplay);
-    m_updateTimer->setSingleShot(true);
-
-    // av::Logger::instance().info("OpenGLVideoRenderer created");
-}
-
-OpenGLVideoRenderer::~OpenGLVideoRenderer()
-{
-    // 清理OpenGL资源
-    makeCurrent();
-    cleanupOpenGLResources();
-    
-    // 删除纹理
-    if (m_textureY) glDeleteTextures(1, &m_textureY);
-    if (m_textureU) glDeleteTextures(1, &m_textureU);
-    if (m_textureV) glDeleteTextures(1, &m_textureV);
-    
-    doneCurrent();
-    
-    if (m_swsContext) {
-        sws_freeContext(m_swsContext);
-        m_swsContext = nullptr;
-    }
-    if (m_yuvBuffer) {
-        av_free(m_yuvBuffer);
-        m_yuvBuffer = nullptr;
-    }
-    // av::Logger::instance().info("OpenGLVideoRenderer destroyed");
-}
-
-void OpenGLVideoRenderer::initializeGL()
-{
-    // av::Logger::instance().info("Initializing OpenGL context");
-
-    // 初始化OpenGL函数
-    initializeOpenGLFunctions();
-    
-    // 设置清除颜色
-    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
-    
-    // 启用混合
-    glEnable(GL_BLEND);
-    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-    
-    // 初始化OpenGL资源
-    if (initializeOpenGLResources()) {
-        m_glInitialized = true;
-        // av::Logger::instance().info("OpenGL resources initialized successfully");
-    } else {
-        // av::Logger::instance().error("Failed to initialize OpenGL resources");
-    }
-}
-
-void OpenGLVideoRenderer::paintGL()
-{
-    if (!m_glInitialized || !m_hasFrame) {
-        // 绘制背景
-        glClear(GL_COLOR_BUFFER_BIT);
-        return;
-    }
-    
-    QMutexLocker locker(&m_mutex);
-    
-    // 清除缓冲区
-    glClear(GL_COLOR_BUFFER_BIT);
-    
-    // 渲染当前帧
-    renderCurrentFrame();
-    
-    // 检查OpenGL错误
-    checkGLError("paintGL");
-}
-
-void OpenGLVideoRenderer::resizeGL(int width, int height)
-{
-    if (!m_glInitialized) {
-        return;
-    }
-
-    // av::Logger::instance().debugf("Resizing OpenGL viewport to %dx%d", width, height);
-
-    // 设置视口
-    glViewport(0, 0, width, height);
-    
-    // 更新投影矩阵
-    setupProjectionMatrix();
-}
-
-void OpenGLVideoRenderer::resizeEvent(QResizeEvent* event)
-{
-    QOpenGLWidget::resizeEvent(event);
-    
-    // 触发重绘
-    if (m_glInitialized) {
-        update();
-    }
-}
-
-bool OpenGLVideoRenderer::initialize(int width, int height, AVPixelFormat pixelFormat, double fps)
-{
-    QMutexLocker locker(&m_mutex);
-    
-    if (m_initialized) {
-        // av::Logger::instance().warning("OpenGL video renderer already initialized");
-        return true;
-    }
-    
-    if (width <= 0 || height <= 0) {
-        // av::Logger::instance().error("Invalid video dimensions");
-        return false;
-    }
-    
-    if (fps <= 0) {
-        fps = 25.0; // 默认帧率
-    }
-    
-    m_videoWidth = width;
-    m_videoHeight = height;
-    m_inputFormat = pixelFormat;
-    m_fps = fps;
-    
-    // 初始化图像转换器
-    if (m_inputFormat != AV_PIX_FMT_YUV420P) {
-        m_swsContext = sws_getContext(
-            m_videoWidth, m_videoHeight, m_inputFormat,
-            m_videoWidth, m_videoHeight, AV_PIX_FMT_YUV420P,
-            SWS_BILINEAR, nullptr, nullptr, nullptr
-        );
-        
-        if (!m_swsContext) {
-            // av::Logger::instance().error("Failed to create SwsContext");
-            return false;
-        }
-        
-        // 分配YUV缓冲区
-        m_yuvBufferSize = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, m_videoWidth, m_videoHeight, 1);
-        m_yuvBuffer = static_cast<uint8_t*>(av_malloc(m_yuvBufferSize));
-        if (!m_yuvBuffer) {
-            // av::Logger::instance().error("Failed to allocate YUV buffer");
-            return false;
-        }
-    }
-    
-    // 设置控件大小提示
-    setMinimumSize(m_videoWidth / 4, m_videoHeight / 4);
-    
-    m_initialized = true;
-    // av::Logger::instance().info(
-    //   QString("OpenGL video renderer initialized: %1x%2 @ %3fps").arg(width).arg(height).arg(fps).toStdString());
-
-    return true;
-}
-
-bool OpenGLVideoRenderer::renderFrame(const AVFramePtr& frame)
-{
-    // 使用Logger输出调试信息
-    std::string debugMsg = "[VideoRenderer] renderFrame called - frame: " + 
-                          std::to_string(reinterpret_cast<uintptr_t>(frame.get())) + 
-                          ", initialized: " + std::to_string(m_initialized.load()) + 
-                          ", glInitialized: " + std::to_string(m_glInitialized);
-    av::Logger::instance().debug(debugMsg);
-    
-    if (!frame || !m_initialized) {
-        av::Logger::instance().warning("[VideoRenderer] renderFrame failed - frame or not initialized");
-        return false;
-    }
-    
-    std::string frameInfo = "[VideoRenderer] Frame info - width: " + std::to_string(frame->width) + 
-                           ", height: " + std::to_string(frame->height) + 
-                           ", format: " + std::to_string(frame->format) + 
-                           ", linesize[0]: " + std::to_string(frame->linesize[0]) + 
-                           ", linesize[1]: " + std::to_string(frame->linesize[1]) + 
-                           ", linesize[2]: " + std::to_string(frame->linesize[2]);
-    av::Logger::instance().debug(frameInfo);
-    
-    QMutexLocker locker(&m_mutex);
-    
-    // 更新纹理数据
-    updateTextures(frame);
-    
-    // 标记有帧数据
-    m_hasFrame = true;
-    
-    // 触发更新显示
-    if (!m_updateTimer->isActive()) {
-        int interval = static_cast<int>(1000.0 / m_fps); // 根据帧率计算间隔
-        m_updateTimer->start(interval);
-    }
-    
-    av::Logger::instance().debug("[VideoRenderer] renderFrame completed successfully");
-    return true;
-}
-
-void OpenGLVideoRenderer::clear()
-{
-    QMutexLocker locker(&m_mutex);
-    m_hasFrame = false;
-    update();
-}
-
-void OpenGLVideoRenderer::setKeepAspectRatio(bool keepAspectRatio)
-{
-    if (m_keepAspectRatio != keepAspectRatio) {
-        m_keepAspectRatio = keepAspectRatio;
-        if (m_glInitialized) {
-            setupProjectionMatrix();
-            update();
-        }
-    }
-}
-
-bool OpenGLVideoRenderer::getKeepAspectRatio() const
-{
-    return m_keepAspectRatio;
-}
-
-void OpenGLVideoRenderer::setBackgroundColor(const QColor& color)
-{
-    if (m_backgroundColor != color) {
-        m_backgroundColor = color;
-        if (m_glInitialized) {
-            glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
-            update();
-        }
-    }
-}
-
-QSize OpenGLVideoRenderer::getVideoSize() const
-{
-    return QSize(m_videoWidth, m_videoHeight);
-}
-
-QSize OpenGLVideoRenderer::getDisplaySize() const
-{
-    return size();
-}
-
-bool OpenGLVideoRenderer::isInitialized() const
-{
-    return m_initialized && m_glInitialized;
-}
-
-void OpenGLVideoRenderer::setRenderQuality(float quality)
-{
-    m_renderQuality = std::clamp(quality, 0.0f, 1.0f);
-    if (m_glInitialized) {
-        update();
-    }
-}
-
-void OpenGLVideoRenderer::setVSync(bool enable)
-{
-    m_vSyncEnabled = enable;
-    if (m_glInitialized) {
-        QSurfaceFormat format = context()->format();
-        format.setSwapInterval(enable ? 1 : 0);
-        context()->setFormat(format);
-    }
-}
-
-void OpenGLVideoRenderer::updateDisplay()
-{
-    if (m_glInitialized) {
-        update();
-    }
-}
-
-bool OpenGLVideoRenderer::initializeOpenGLResources()
-{
-    // 初始化着色器程序
-    if (!initializeShaders()) {
-        return false;
-    }
-    
-    // 初始化顶点数据
-    if (!initializeVertexData()) {
-        return false;
-    }
-    
-    // 创建纹理
-    if (!createTextures()) {
-        return false;
-    }
-    
-    return true;
-}
-
-void OpenGLVideoRenderer::cleanupOpenGLResources()
-{
-    m_shaderProgram.reset();
-    m_vertexBuffer.reset();
-    m_indexBuffer.reset();
-    m_vao.reset();
-    
-    // 纹理在析构函数中删除,这里不需要处理
-    
-    m_glInitialized = false;
-}
-
-bool OpenGLVideoRenderer::initializeShaders()
-{
-    m_shaderProgram = std::make_unique<QOpenGLShaderProgram>();
-    
-    // 添加顶点着色器
-    if (!m_shaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource)) {
-        // av::Logger::instance().error("Failed to compile vertex shader: " + m_shaderProgram->log().toStdString());
-        return false;
-    }
-    
-    // 添加片段着色器
-    if (!m_shaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource)) {
-        // av::Logger::instance().error("Failed to compile fragment shader: " + m_shaderProgram->log().toStdString());
-        return false;
-    }
-    
-    // 绑定属性位置 - 参考yuvopenglwidget.cpp
-    m_shaderProgram->bindAttributeLocation("vertexIn", 0);
-    m_shaderProgram->bindAttributeLocation("textureIn", 1);
-    
-    // 链接着色器程序
-    if (!m_shaderProgram->link()) {
-        // av::Logger::instance().error("Failed to link shader program: " + m_shaderProgram->log().toStdString());
-        return false;
-    }
-
-    // av::Logger::instance().info("Shader program initialized successfully");
-    return true;
-}
-
-bool OpenGLVideoRenderer::initializeVertexData()
-{
-    // 参考yuvopenglwidget.cpp的顶点数据设置
-    static const GLfloat vertices[] = {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f};
-    static const GLfloat texCoords[] = {0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f};
-    
-    // 创建VAO
-    m_vao = std::make_unique<QOpenGLVertexArrayObject>();
-    m_vao->create();
-    m_vao->bind();
-    
-    // 设置顶点,纹理数组并启用
-    glVertexAttribPointer(0, 2, GL_FLOAT, 0, 0, vertices);
-    glEnableVertexAttribArray(0);
-    glVertexAttribPointer(1, 2, GL_FLOAT, 0, 0, texCoords);
-    glEnableVertexAttribArray(1);
-    
-    m_vao->release();
-
-    // av::Logger::instance().info("Vertex data initialized successfully");
-    return true;
-}
-
-bool OpenGLVideoRenderer::createTextures()
-{
-    // 参考yuvopenglwidget.cpp创建纹理
-    // 创建Y纹理
-    glGenTextures(1, &m_textureY);
-    glBindTexture(GL_TEXTURE_2D, m_textureY);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-    
-    // 创建U纹理
-    glGenTextures(1, &m_textureU);
-    glBindTexture(GL_TEXTURE_2D, m_textureU);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-    
-    // 创建V纹理
-    glGenTextures(1, &m_textureV);
-    glBindTexture(GL_TEXTURE_2D, m_textureV);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-
-    // av::Logger::instance().info("Textures created successfully");
-    return true;
-}
-
-void OpenGLVideoRenderer::updateTextures(const AVFramePtr& frame)
-{
-    if (!m_glInitialized || !frame) {
-        av::Logger::instance().warning("[VideoRenderer] updateTextures failed - glInitialized: " + 
-                                       std::to_string(m_glInitialized) + ", frame: " + 
-                                       std::to_string(reinterpret_cast<uintptr_t>(frame.get())));
-        return;
-    }
-    
-    av::Logger::instance().debug("[VideoRenderer] updateTextures - video size: " + 
-                                std::to_string(m_videoWidth) + "x" + std::to_string(m_videoHeight) + 
-                                ", input format: " + std::to_string(m_inputFormat) + 
-                                ", frame format: " + std::to_string(frame->format) +
-                                ", linesize: [" + std::to_string(frame->linesize[0]) + ", " + 
-                                std::to_string(frame->linesize[1]) + ", " + std::to_string(frame->linesize[2]) + "]");
-    
-    // 转换帧格式(如果需要)
-    AVFrame* yuvFrame = frame.get();
-    if (m_inputFormat != AV_PIX_FMT_YUV420P && m_swsContext) {
-        // 创建临时帧
-        AVFrame* tempFrame = av_frame_alloc();
-        tempFrame->format = AV_PIX_FMT_YUV420P;
-        tempFrame->width = m_videoWidth;
-        tempFrame->height = m_videoHeight;
-        av_image_fill_arrays(tempFrame->data, tempFrame->linesize, m_yuvBuffer, 
-                           AV_PIX_FMT_YUV420P, m_videoWidth, m_videoHeight, 1);
-        
-        // 转换格式
-        sws_scale(m_swsContext, frame->data, frame->linesize, 0, m_videoHeight,
-                 tempFrame->data, tempFrame->linesize);
-        
-        yuvFrame = tempFrame;
-        
-        // 更新Y纹理数据
-        glActiveTexture(GL_TEXTURE0);
-        glBindTexture(GL_TEXTURE_2D, m_textureY);
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, yuvFrame->linesize[0]);
-        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_videoWidth, m_videoHeight, 
-                       GL_RED, GL_UNSIGNED_BYTE, yuvFrame->data[0]);
-        
-        // 更新U纹理数据
-        glActiveTexture(GL_TEXTURE1);
-        glBindTexture(GL_TEXTURE_2D, m_textureU);
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, yuvFrame->linesize[1]);
-        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_videoWidth / 2, m_videoHeight / 2, 
-                       GL_RED, GL_UNSIGNED_BYTE, yuvFrame->data[1]);
-        
-        // 更新V纹理数据
-        glActiveTexture(GL_TEXTURE2);
-        glBindTexture(GL_TEXTURE_2D, m_textureV);
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, yuvFrame->linesize[2]);
-        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_videoWidth / 2, m_videoHeight / 2, 
-                       GL_RED, GL_UNSIGNED_BYTE, yuvFrame->data[2]);
-        
-        // 重置像素存储参数
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
-        
-        av_frame_free(&tempFrame);
-    } else {
-        // 参考yuvopenglwidget.cpp的纹理更新方式
-        av::Logger::instance().debug("[VideoRenderer] Updating textures for YUV420P format");
-        
-        // Y分量
-        glActiveTexture(GL_TEXTURE0);
-        glBindTexture(GL_TEXTURE_2D, m_textureY);
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, frame->linesize[0]);
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, frame->width, frame->height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame->data[0]);
-        
-        // U分量
-        glActiveTexture(GL_TEXTURE1);
-        glBindTexture(GL_TEXTURE_2D, m_textureU);
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, frame->linesize[1]);
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, frame->width >> 1, frame->height >> 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame->data[1]);
-        
-        // V分量
-        glActiveTexture(GL_TEXTURE2);
-        glBindTexture(GL_TEXTURE_2D, m_textureV);
-        glPixelStorei(GL_UNPACK_ROW_LENGTH, frame->linesize[2]);
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, frame->width >> 1, frame->height >> 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame->data[2]);
-    }
-    
-    // 重置像素存储参数
-    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
-    
-    // 检查OpenGL错误
-    checkGLError("updateTextures");
-    
-    // 强制更新显示
-    update();
-}
-
-QRectF OpenGLVideoRenderer::calculateDisplayRect() const
-{
-    QSize widgetSize = size();
-    QSize videoSize(m_videoWidth, m_videoHeight);
-    
-    if (!m_keepAspectRatio) {
-        return QRectF(-1.0f, -1.0f, 2.0f, 2.0f);
-    }
-    
-    // 计算保持宽高比的显示矩形
-    float widgetAspect = static_cast<float>(widgetSize.width()) / widgetSize.height();
-    float videoAspect = static_cast<float>(videoSize.width()) / videoSize.height();
-    
-    QRectF rect;
-    if (widgetAspect > videoAspect) {
-        // 控件更宽,以高度为准
-        float width = 2.0f * videoAspect / widgetAspect;
-        rect = QRectF(-width / 2.0f, -1.0f, width, 2.0f);
-    } else {
-        // 控件更高,以宽度为准
-        float height = 2.0f * widgetAspect / videoAspect;
-        rect = QRectF(-1.0f, -height / 2.0f, 2.0f, height);
-    }
-    
-    return rect;
-}
-
-void OpenGLVideoRenderer::setupProjectionMatrix()
-{
-    if (!m_shaderProgram) {
-        return;
-    }
-    
-    QRectF displayRect = calculateDisplayRect();
-    
-    // 创建投影矩阵
-    QMatrix4x4 projection;
-    projection.setToIdentity();
-    projection.ortho(displayRect.left(), displayRect.right(), 
-                    displayRect.bottom(), displayRect.top(), -1.0f, 1.0f);
-    
-    m_shaderProgram->bind();
-    m_shaderProgram->setUniformValue("projection", projection);
-    m_shaderProgram->release();
-}
-
-void OpenGLVideoRenderer::renderCurrentFrame()
-{
-    if (!m_shaderProgram || !m_vao) {
-        return;
-    }
-    
-    m_shaderProgram->bind();
-    m_vao->bind();
-    
-    // 参考yuvopenglwidget.cpp的纹理绑定和uniform设置
-    glActiveTexture(GL_TEXTURE0);
-    glBindTexture(GL_TEXTURE_2D, m_textureY);
-    glUniform1i(m_shaderProgram->uniformLocation("yTexture"), 0);
-    
-    glActiveTexture(GL_TEXTURE1);
-    glBindTexture(GL_TEXTURE_2D, m_textureU);
-    glUniform1i(m_shaderProgram->uniformLocation("uTexture"), 1);
-    
-    glActiveTexture(GL_TEXTURE2);
-    glBindTexture(GL_TEXTURE_2D, m_textureV);
-    glUniform1i(m_shaderProgram->uniformLocation("vTexture"), 2);
-    
-    // 参考yuvopenglwidget.cpp使用GL_TRIANGLE_STRIP绘制
-    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
-    
-    m_vao->release();
-    m_shaderProgram->release();
-}
-
-bool OpenGLVideoRenderer::checkGLError(const QString& operation)
-{
-    GLenum error = glGetError();
-    if (error != GL_NO_ERROR) {
-        // av::Logger::instance().error("OpenGL error in " + operation.toStdString() + ": " + std::to_string(error));
-        return false;
-    }
-    return true;
-}
-
-} // namespace player
-} // namespace av

+ 0 - 223
AV/code/player/opengl_video_renderer.h

@@ -1,223 +0,0 @@
-#ifndef AV_PLAYER_OPENGL_VIDEO_RENDERER_H
-#define AV_PLAYER_OPENGL_VIDEO_RENDERER_H
-
-#include <QOpenGLWidget>
-#include <QOpenGLFunctions>
-#include <QOpenGLTexture>
-#include <QOpenGLShaderProgram>
-#include <QOpenGLBuffer>
-#include <QOpenGLVertexArrayObject>
-#include <QtOpenGL/qgl.h>
-#include <QMutex>
-#include <QTimer>
-#include <memory>
-#include <atomic>
-
-extern "C" {
-#include <libavutil/frame.h>
-#include <libavutil/pixfmt.h>
-#include <libswscale/swscale.h>
-}
-
-#include "../base/media_common.h"
-
-namespace av {
-namespace player {
-
-/**
- * OpenGL视频渲染器类
- * 使用QOpenGLWidget进行硬件加速的视频渲染
- * 支持YUV420P、NV12等常见格式
- */
-class OpenGLVideoRenderer : public QOpenGLWidget, protected QOpenGLFunctions
-{
-    Q_OBJECT
-
-public:
-    explicit OpenGLVideoRenderer(QWidget* parent = nullptr);
-    ~OpenGLVideoRenderer();
-
-    /**
-     * 初始化视频渲染器
-     * @param width 视频宽度
-     * @param height 视频高度
-     * @param pixelFormat 像素格式
-     * @param fps 视频帧率(默认25fps)
-     * @return 是否成功
-     */
-    bool initialize(int width, int height, AVPixelFormat pixelFormat, double fps = 25.0);
-
-    /**
-     * 渲染视频帧
-     * @param frame 视频帧
-     * @return 是否成功
-     */
-    bool renderFrame(const AVFramePtr& frame);
-
-    /**
-     * 清空显示
-     */
-    void clear();
-
-    /**
-     * 设置保持宽高比
-     * @param keepAspectRatio 是否保持宽高比
-     */
-    void setKeepAspectRatio(bool keepAspectRatio);
-
-    /**
-     * 获取是否保持宽高比
-     */
-    bool getKeepAspectRatio() const;
-
-    /**
-     * 设置背景颜色
-     * @param color 背景颜色
-     */
-    void setBackgroundColor(const QColor& color);
-
-    /**
-     * 获取视频尺寸
-     */
-    QSize getVideoSize() const;
-
-    /**
-     * 获取显示尺寸
-     */
-    QSize getDisplaySize() const;
-
-    /**
-     * 是否已初始化
-     */
-    bool isInitialized() const;
-
-    /**
-     * 设置渲染质量
-     * @param quality 质量级别 (0-1)
-     */
-    void setRenderQuality(float quality);
-
-    /**
-     * 启用/禁用垂直同步
-     * @param enable 是否启用
-     */
-    void setVSync(bool enable);
-
-protected:
-    // OpenGL相关
-    void initializeGL() override;
-    void paintGL() override;
-    void resizeGL(int width, int height) override;
-
-    // 事件处理
-    void resizeEvent(QResizeEvent* event) override;
-
-private slots:
-    void updateDisplay();
-
-private:
-    /**
-     * 初始化OpenGL资源
-     */
-    bool initializeOpenGLResources();
-
-    /**
-     * 清理OpenGL资源
-     */
-    void cleanupOpenGLResources();
-
-    /**
-     * 初始化着色器程序
-     */
-    bool initializeShaders();       
-
-    /**
-     * 初始化顶点数据
-     */
-    bool initializeVertexData();
-
-    /**
-     * 创建纹理
-     */
-    bool createTextures();
-
-    /**
-     * 更新纹理数据
-     */
-    void updateTextures(const AVFramePtr& frame);
-
-    /**
-     * 计算显示矩形
-     */
-    QRectF calculateDisplayRect() const;
-
-    /**
-     * 设置投影矩阵
-     */
-    void setupProjectionMatrix();
-
-    /**
-     * 渲染当前帧
-     */
-    void renderCurrentFrame();
-
-    /**
-     * 检查OpenGL错误
-     */
-    bool checkGLError(const QString& operation);
-
-private:
-    // 视频参数
-    int m_videoWidth;
-    int m_videoHeight;
-    AVPixelFormat m_inputFormat;
-    double m_fps;
-    
-    // OpenGL资源
-    std::unique_ptr<QOpenGLShaderProgram> m_shaderProgram;
-    std::unique_ptr<QOpenGLBuffer> m_vertexBuffer;
-    std::unique_ptr<QOpenGLBuffer> m_indexBuffer;
-    std::unique_ptr<QOpenGLVertexArrayObject> m_vao;
-    
-    // 纹理 - 参考yuvopenglwidget.cpp
-    GLuint m_textureY;
-    GLuint m_textureU;
-    GLuint m_textureV;
-    
-    // 图像转换器
-    SwsContext* m_swsContext;
-    uint8_t* m_yuvBuffer;
-    int m_yuvBufferSize;
-    
-    // 显示相关
-    QColor m_backgroundColor;
-    bool m_keepAspectRatio;
-    float m_renderQuality;
-    bool m_vSyncEnabled;
-    
-    // 状态
-    std::atomic<bool> m_initialized;
-    std::atomic<bool> m_glInitialized;
-    std::atomic<bool> m_hasFrame;
-
-    // 更新定时器
-    QTimer* m_updateTimer;
-    
-    // 线程安全
-    mutable QMutex m_mutex;
-    
-    // 当前帧数据
-    struct FrameData {
-        int width;
-        int height;
-        std::vector<uint8_t> yData;
-        std::vector<uint8_t> uData;
-        std::vector<uint8_t> vData;
-    };
-    FrameData m_currentFrame;
-};
-
-} // namespace player
-} // namespace av
-
-#endif // AV_PLAYER_OPENGL_VIDEO_RENDERER_H

+ 2 - 4
AV/code/player/player.pri

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

+ 137 - 279
AV/code/player/player_core_v2.cpp

@@ -19,9 +19,9 @@
 
 namespace av {
 namespace player {
-
 PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
-    : m_eventCallback(nullptr)
+    : m_state(PlayerState::Idle)
+    , m_eventCallback(nullptr)
     , m_formatContext(nullptr)
     , m_openGLVideoRenderer(nullptr)
     , m_volume(1.0)
@@ -38,10 +38,9 @@ PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
     , m_errorCount(0)
     , m_buffering(false)
     , m_bufferHealth(1.0)
-    , m_state(PlayerState::Idle) {
-    
+{
     Logger::instance().info("PlayerCoreV2 created");
-    
+
     try {
         // 初始化FFmpeg
         if (!initializeFFmpeg()) {
@@ -80,25 +79,25 @@ PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
         }
         
         // 创建改进的同步器
-        m_synchronizer = std::make_unique<SynchronizerV2>(syncConfig);
-        if (!m_synchronizer) {
-            Logger::instance().error("Failed to create synchronizer");
-            setState(PlayerState::Error);
-            return;
-        }
-        
+        // m_synchronizer = std::make_unique<Synchronizer>(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_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>();
@@ -135,7 +134,7 @@ PlayerCoreV2::PlayerCoreV2(const SyncConfigV2& syncConfig)
         
         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);
@@ -241,11 +240,11 @@ ErrorCode PlayerCoreV2::play() {
     }
     
     // 启动同步器
-    if (m_synchronizer->start() != ErrorCode::SUCCESS) {
-        Logger::instance().error("Failed to start synchronizer");
-        return ErrorCode::SYNC_ERROR;
-    }
-    
+    // if (m_synchronizer->start() != ErrorCode::SUCCESS) {
+    //     Logger::instance().error("Failed to start synchronizer");
+    //     return ErrorCode::SYNC_ERROR;
+    // }
+
     // 记录播放开始时间
     m_playStartTime = std::chrono::steady_clock::now();
     
@@ -324,12 +323,12 @@ ErrorCode PlayerCoreV2::pause() {
         Logger::instance().debug("Not playing, cannot pause");
         return ErrorCode::INVALID_STATE;
     }
-    
-    // 暂停同步器
-    if (m_synchronizer->pause() != ErrorCode::SUCCESS) {
-        Logger::instance().warning("Failed to pause synchronizer");
-    }
-    
+
+    // // 暂停同步器
+    // if (m_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();
@@ -356,12 +355,12 @@ ErrorCode PlayerCoreV2::stop() {
         Logger::instance().debug("Already stopped");
         return ErrorCode::SUCCESS;
     }
-    
-    // 停止同步器
-    if (m_synchronizer) {
-        m_synchronizer->stop();
-    }
-    
+
+    // // 停止同步器
+    // if (m_synchronizer) {
+    //     m_synchronizer->stop();
+    // }
+
     // 停止音频输出
     if (m_audioOutput) {
         m_audioOutput->stop();
@@ -410,12 +409,12 @@ ErrorCode PlayerCoreV2::seek(int64_t timestamp) {
     // 更新基准时间为跳转目标时间
     m_baseTime = timestamp;
     m_playStartTime = std::chrono::steady_clock::now();
-    
-    // 重置同步器
-    if (m_synchronizer) {
-        m_synchronizer->reset();
-    }
-    
+
+    // // 重置同步器
+    // if (m_synchronizer) {
+    //     m_synchronizer->reset();
+    // }
+
     // 清空队列
     flushBuffers();
     
@@ -436,12 +435,12 @@ ErrorCode PlayerCoreV2::setPlaybackSpeed(double speed) {
     
     std::lock_guard<std::mutex> lock(m_mutex);
     m_playbackSpeed = speed;
-    
-    // 设置同步器的播放速度
-    if (m_synchronizer) {
-        m_synchronizer->setPlaybackSpeed(speed);
-    }
-    
+
+    // // 设置同步器的播放速度
+    // if (m_synchronizer) {
+    //     m_synchronizer->setPlaybackSpeed(speed);
+    // }
+
     // 设置音频输出的播放速度
     if (m_audioOutput) {
         m_audioOutput->setPlaybackSpeed(speed);
@@ -471,17 +470,17 @@ PlaybackStats PlayerCoreV2::getStats() const {
     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.syncError;
-        stats.avgSyncError = syncStats.avgSyncError;
-        stats.maxSyncError = syncStats.maxSyncError;
-        stats.droppedFrames = syncStats.droppedFrames;
-        stats.duplicatedFrames = syncStats.duplicatedFrames;
-    }
-    
+
+    // // 更新同步统计
+    // if (m_synchronizer) {
+    //     auto syncStats = m_synchronizer->getStats();
+    //     stats.syncError = syncStats.syncError;
+    //     // stats.avgSyncError = syncStats.avgSyncError;
+    //     // stats.maxSyncError = syncStats.maxSyncError;
+    //     stats.droppedFrames = syncStats.droppedFrames;
+    //     stats.duplicatedFrames = syncStats.duplicatedFrames;
+    // }
+
     return stats;
 }
 
@@ -521,18 +520,18 @@ void PlayerCoreV2::setVolume(double volume) {
     Logger::instance().debug("Volume set to: " + std::to_string(volume));
 }
 
-void PlayerCoreV2::setSyncConfig(const SyncConfigV2& config) {
-    if (m_synchronizer) {
-        m_synchronizer->setConfig(config);
-    }
-}
+// void PlayerCore::setSyncConfig(const SyncConfig& config) {
+//     // if (m_synchronizer) {
+//     //     m_synchronizer->setConfig(config);
+//     // }
+// }
 
-SyncConfigV2 PlayerCoreV2::getSyncConfig() const {
-    if (m_synchronizer) {
-        return m_synchronizer->getConfig();
-    }
-    return SyncConfigV2();
-}
+// SyncConfig PlayerCoreV2::getSyncConfig() const {
+//     if (m_synchronizer) {
+//         return m_synchronizer->getConfig();
+//     }
+//     return SyncConfig();
+// }
 
 void PlayerCoreV2::setOpenGLVideoRenderer(OpenGLVideoWidget* renderer) {
     m_openGLVideoRenderer = renderer;
@@ -605,11 +604,11 @@ std::string PlayerCoreV2::getDebugInfo() const {
     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();
-    }
-    
+
+    // if (m_synchronizer) {
+    //     oss << "\n" << m_synchronizer->getDebugInfo();
+    // }
+
     return oss.str();
 }
 
@@ -704,21 +703,21 @@ bool PlayerCoreV2::openMediaFile(const std::string& filename) {
         Logger::instance().info("Audio stream found: " + std::to_string(m_mediaInfo.sampleRate) + " Hz, " + 
                                std::to_string(m_mediaInfo.channels) + " channels");
     }
-    
-    // 设置同步器的流信息
-    if (m_synchronizer) {
-        m_synchronizer->setStreamInfo(m_mediaInfo.hasAudio, m_mediaInfo.hasVideo);
-        Logger::instance().info("Synchronizer stream info set: hasAudio=" + std::to_string(m_mediaInfo.hasAudio) + 
-                               ", hasVideo=" + std::to_string(m_mediaInfo.hasVideo));
-        
-        // 在设置流信息后初始化同步器,确保主时钟选择基于正确的流信息
-        if (m_synchronizer->initialize() != ErrorCode::SUCCESS) {
-            Logger::instance().error("Failed to initialize synchronizer");
-            return false;
-        }
-        Logger::instance().info("Synchronizer initialized with correct stream info");
-    }
-    
+
+    // // 设置同步器的流信息
+    // if (m_synchronizer) {
+    //     m_synchronizer->setStreamInfo(m_mediaInfo.hasAudio, m_mediaInfo.hasVideo);
+    //     Logger::instance().info("Synchronizer stream info set: hasAudio=" + std::to_string(m_mediaInfo.hasAudio) +
+    //                            ", hasVideo=" + std::to_string(m_mediaInfo.hasVideo));
+
+    //     // 在设置流信息后初始化同步器,确保主时钟选择基于正确的流信息
+    //     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;
 }
@@ -843,13 +842,6 @@ bool PlayerCoreV2::setupAudioDecoder() {
         avcodec_free_context(&codecContext);
         return false;
     }
-    
-    // 设置音频输出的同步器
-    if (m_audioOutput && m_synchronizer) {
-        m_audioOutput->setSynchronizer(std::shared_ptr<SynchronizerV2>(m_synchronizer.get(), [](SynchronizerV2*) {}));
-        Logger::instance().info("Audio output synchronizer set");
-    }
-    
     // 释放解码器上下文
     avcodec_free_context(&codecContext);
     
@@ -931,10 +923,10 @@ void PlayerCoreV2::cleanup() {
         avformat_close_input(&m_formatContext);
         m_formatContext = nullptr;
     }
-    
-    if (m_synchronizer) {
-        m_synchronizer->close();
-    }
+
+    // if (m_synchronizer) {
+    //     m_synchronizer->close();
+    // }
 }
 
 void PlayerCoreV2::setState(PlayerState newState) {
@@ -987,12 +979,12 @@ void PlayerCoreV2::attemptRecovery() {
         handleError("Too many sync errors");
         return;
     }
-    
-    // 重置同步器
-    if (m_synchronizer) {
-        m_synchronizer->reset();
-    }
-    
+
+    // // 重置同步器
+    // if (m_synchronizer) {
+    //     m_synchronizer->reset();
+    // }
+
     // 清空部分缓冲区
     if (m_videoFrameQueue) {
         m_videoFrameQueue->clear();
@@ -1008,10 +1000,10 @@ void PlayerCoreV2::handleError(const std::string& error) {
 }
 
 void PlayerCoreV2::updateSynchronization() {
-    if (!m_synchronizer || !m_threadsRunning) {
-        return;
-    }
-    
+    // if (!m_synchronizer || !m_threadsRunning) {
+    //     return;
+    // }
+
     // 同步器会在内部自动更新
     // 这里可以添加额外的同步逻辑
 }
@@ -1397,16 +1389,13 @@ void PlayerCoreV2::audioDecodeThreadFunc() {
 
 void PlayerCoreV2::videoPlayThreadFunc() {
     Logger::instance().info("Video play thread started");
-    
-    auto lastFrameTime = std::chrono::steady_clock::now();
-    double targetFrameInterval = 1000.0 / m_mediaInfo.fps; // 毫秒
-    
+
     while (!m_threadsShouldStop) {
-        if (!m_videoFrameQueue || !m_synchronizer) {
+        if (!m_videoFrameQueue /*|| !m_synchronizer*/) {
             std::this_thread::sleep_for(std::chrono::milliseconds(10));
             continue;
         }
-        
+
         // 获取视频帧,使用超时避免无限阻塞
         AVFrame* frame = m_videoFrameQueue->pop(100); // 100ms超时
         if (!frame) {
@@ -1418,79 +1407,24 @@ void PlayerCoreV2::videoPlayThreadFunc() {
         }
         
         Logger::instance().debug("Video play thread got frame, pts=" + std::to_string(frame->pts));
-        
-        // 获取视频流的时间基准
-        double timeBase = 0.0;
-        if (frame->pts != AV_NOPTS_VALUE) {
-            AVStream* videoStream = m_formatContext->streams[m_mediaInfo.videoStreamIndex];
-            timeBase = av_q2d(videoStream->time_base);
-        }
-        
-        // 检查是否应该显示这一帧 (直接传递原始PTS和时间基准)
-        auto decision = m_synchronizer->shouldDisplayVideoFrame(frame->pts, timeBase);
-        
-        // 记录视频帧决策日志
-        Logger::instance().debug("Video frame decision: action=" + std::to_string(static_cast<int>(decision.action)) + 
-                                ", delay=" + std::to_string(decision.delay) + 
-                                ", syncError=" + std::to_string(decision.syncError));
-        
-        // 只有在决定显示帧时才更新视频时钟
-        if (decision.action == av::utils::FrameAction::DISPLAY && frame->pts != AV_NOPTS_VALUE) {
-            m_synchronizer->setVideoClock(frame->pts, timeBase);
+
+        // 尝试获取下一帧的PTS来计算精确的帧持续时间
+        double nextPts = AV_NOPTS_VALUE;
+        if (m_videoFrameQueue->size() > 0) {
+            AVFrame* nextFrame = m_videoFrameQueue->peekFrame();
+            if (nextFrame && nextFrame->pts != AV_NOPTS_VALUE) {
+                nextPts = nextFrame->pts;
+            }
         }
-        
+
         // 创建智能指针管理帧内存
         AVFramePtr framePtr(frame);
-        
-        switch (decision.action) {
-            case av::utils::FrameAction::DISPLAY:
-                // 显示帧
-                if (m_openGLVideoRenderer) {
-                    m_openGLVideoRenderer->Render(framePtr.get());
-                }
-                
-                // 计算下一帧的延迟 - 使用FFmpeg的精确延迟
-                if (decision.delay > 0) {
-                    // 限制最大延迟时间,避免异常情况
-                    const double MAX_DELAY = 0.1;  // 100ms
-                    double actualDelay = std::min(decision.delay, MAX_DELAY);
-                    int delayUs = static_cast<int>(actualDelay * 1000000);
-                    av_usleep(delayUs);
-                }
-                break;
-                
-            case av::utils::FrameAction::DROP:
-                // 丢弃帧
-                Logger::instance().debug("Dropping video frame");
-                break;
-
-            case av::utils::FrameAction::Frame_DUPLICATE:
-                // 重复显示上一帧(这里简化处理)
-                if (m_openGLVideoRenderer) {
-                    m_openGLVideoRenderer->Render(framePtr.get());
-                }
-                break;
-                
-            case av::utils::FrameAction::DELAY:
-                // 延迟显示 - 使用FFmpeg的精确延迟
-                {
-                    const double MAX_DELAY = 0.1;  // 100ms
-                    double actualDelay = std::min(decision.delay, MAX_DELAY);
-                    int delayUs = static_cast<int>(actualDelay * 1000000);
-                    av_usleep(delayUs);
-                    if (m_openGLVideoRenderer) {
-                        m_openGLVideoRenderer->Render(framePtr.get());
-                    }
-                }
-                break;
+        // 显示帧
+        if (m_openGLVideoRenderer) {
+            m_openGLVideoRenderer->Render(framePtr.get());
         }
-        
-        // framePtr 会自动释放内存,无需手动调用 av_frame_free
-        
-        // 更新帧时间
-        lastFrameTime = std::chrono::steady_clock::now();
     }
-    
+
     Logger::instance().info("Video play thread finished");
 }
 
@@ -1499,11 +1433,11 @@ void PlayerCoreV2::audioPlayThreadFunc() {
     
     int frameCount = 0;
     while (!m_threadsShouldStop) {
-        if (!m_audioFrameQueue || !m_synchronizer || !m_audioOutput) {
+        if (!m_audioFrameQueue || /* !m_synchronizer ||*/ !m_audioOutput) {
             std::this_thread::sleep_for(std::chrono::milliseconds(10));
             continue;
         }
-        
+
         // 获取音频帧,使用较长的超时时间以确保能接收到EOF帧
         AVFrame* frame = m_audioFrameQueue->pop(100); // 100ms超时
         if (!frame) {
@@ -1529,97 +1463,21 @@ void PlayerCoreV2::audioPlayThreadFunc() {
         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));
-        
-        // 获取音频流的时间基准
-        double timeBase = 0.0;
-        if (frame->pts != AV_NOPTS_VALUE) {
-            AVStream* audioStream = m_formatContext->streams[m_mediaInfo.audioStreamIndex];
-            timeBase = av_q2d(audioStream->time_base);
-            
-            // 添加调试信息
-            Logger::instance().debug("Audio PTS info: pts=" + std::to_string(frame->pts) + 
-                                   ", time_base=" + std::to_string(timeBase));
-        }
-        
-        // 检查是否应该播放这一帧 (直接传递原始PTS和时间基准)
-        auto decision = m_synchronizer->shouldPlayAudioFrame(frame->pts, timeBase);
-        
-        // 只有在决定播放帧时才更新音频时钟
-        if (decision.action == av::utils::FrameAction::DISPLAY && frame->pts != AV_NOPTS_VALUE) {
-            m_synchronizer->setAudioClock(frame->pts, timeBase);
-        }
-        
-        Logger::instance().debug("Audio frame decision: action=" + std::to_string(static_cast<int>(decision.action)) + 
-                                ", delay=" + std::to_string(decision.delay));
-        
+
         // 创建智能指针管理帧内存
         AVFramePtr framePtr(frame);
-        
-        switch (decision.action) {
-            case av::utils::FrameAction::DISPLAY:
-                // 播放音频帧
-                {
-                    Logger::instance().debug("Writing audio frame to output device");
-                    bool writeResult = m_audioOutput->writeFrame(framePtr);
-                    Logger::instance().debug("Audio frame write result: " + std::to_string(writeResult));
-                    
-                    // 如果写入失败,等待一段时间避免快速循环
-                    if (!writeResult) {
-                        Logger::instance().warning("Audio frame write failed, waiting before next frame");
-                        std::this_thread::sleep_for(std::chrono::milliseconds(10));
-                    }
-                }
-                
-                // 如果需要延迟 - 使用FFmpeg的精确延迟
-                if (decision.delay > 0) {
-                    const double MAX_DELAY = 0.1;  // 100ms
-                    double actualDelay = std::min(decision.delay, MAX_DELAY);
-                    int delayUs = static_cast<int>(actualDelay * 1000000);
-                    av_usleep(delayUs);
-                }
-                break;
-                
-            case av::utils::FrameAction::DROP:
-                // 丢弃音频帧
-                Logger::instance().debug("Dropping audio frame");
-                break;
+        {
+            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));
 
-            case av::utils::FrameAction::Frame_DUPLICATE:
-                // 重复播放(音频中较少使用)
-                {
-                    Logger::instance().debug("Duplicating audio frame");
-                    bool writeResult = m_audioOutput->writeFrame(framePtr);
-                    Logger::instance().debug("Audio frame duplicate write result: " + std::to_string(writeResult));
-                    
-                    // 如果写入失败,等待一段时间避免快速循环
-                    if (!writeResult) {
-                        Logger::instance().warning("Audio frame duplicate write failed, waiting before next frame");
-                        std::this_thread::sleep_for(std::chrono::milliseconds(10));
-                    }
-                }
-                break;
-                
-            case av::utils::FrameAction::DELAY:
-                // 延迟播放 - 使用FFmpeg的精确延迟
-                {
-                    const double MAX_DELAY = 0.1;  // 100ms
-                    double actualDelay = std::min(decision.delay, MAX_DELAY);
-                    int delayUs = static_cast<int>(actualDelay * 1000000);
-                    av_usleep(delayUs);
-                    
-                    Logger::instance().debug("Writing delayed audio frame to output device");
-                    bool writeResult = m_audioOutput->writeFrame(framePtr);
-                    Logger::instance().debug("Audio frame delayed write result: " + std::to_string(writeResult));
-                    
-                    // 如果写入失败,等待一段时间避免快速循环
-                    if (!writeResult) {
-                        Logger::instance().warning("Audio frame delayed write failed, waiting before next frame");
-                        av_usleep(10000);  // 10ms
-                    }
-                }
-                break;
+            // 如果写入失败,等待一段时间避免快速循环
+            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
     }
     

+ 4 - 4
AV/code/player/player_core_v2.h

@@ -164,9 +164,9 @@ public:
     double getVolume() const { return m_volume; }
     
     // 同步控制
-    void setSyncConfig(const SyncConfigV2& config);
-    SyncConfigV2 getSyncConfig() const;
-    
+    // void setSyncConfig(const SyncConfig& config);
+    // SyncConfig getSyncConfig() const;
+
     // OpenGL渲染器设置
     void setOpenGLVideoRenderer(OpenGLVideoWidget* renderer);
     OpenGLVideoWidget* getOpenGLVideoRenderer() const { return m_openGLVideoRenderer; }
@@ -267,7 +267,7 @@ private:
     std::unique_ptr<av::utils::FrameQueue> m_audioFrameQueue;
     
     // 改进的同步器
-    std::unique_ptr<SynchronizerV2> m_synchronizer;
+    // std::unique_ptr<SynchronizerV2> m_synchronizer;
 
     // 音频输出
     std::unique_ptr<AudioOutput> m_audioOutput;

+ 93 - 0
AV/code/utils/test_synchronizer_v2.cpp

@@ -0,0 +1,93 @@
+#include "utils_synchronizer_v2.h"
+#include <iostream>
+#include <thread>
+#include <chrono>
+
+using namespace av::utils;
+
+int main() {
+    std::cout << "=== SynchronizerV2 Test ===\n";
+    
+    // 创建同步器
+    SyncConfigV2 config;
+    config.strategy = SyncStrategy::AUDIO_MASTER;
+    
+    SynchronizerV2 sync(config);
+    
+    // 初始化和启动
+    auto result = sync.initialize();
+    if (result != ErrorCode::SUCCESS) {
+        std::cout << "Failed to initialize synchronizer\n";
+        return -1;
+    }
+    
+    sync.setStreamInfo(true, true); // 有音频和视频流
+    
+    result = sync.start();
+    if (result != ErrorCode::SUCCESS) {
+        std::cout << "Failed to start synchronizer\n";
+        return -1;
+    }
+    
+    std::cout << "Synchronizer started successfully\n";
+    
+    // 模拟音视频时钟更新
+    double audioTime = 0.0;
+    double videoTime = 0.0;
+    double frame_last_duration = 0.033;
+
+    for (int i = 0; i < 10; ++i) {
+        // 更新音频时钟
+        sync.setClock(ClockType::AUDIO, audioTime, i);
+        
+        // 更新视频时钟(稍微不同步)
+        videoTime = audioTime + 0.02; // 20ms ahead
+        sync.setClock(ClockType::VIDEO, videoTime, i);
+        
+        std::cout << "\nFrame " << i << ":\n";
+        std::cout << "  Audio Clock: " << sync.getClock(ClockType::AUDIO) << "s\n";
+        std::cout << "  Video Clock: " << sync.getClock(ClockType::VIDEO) << "s\n";
+        std::cout << "  Master Clock: " << sync.getMasterClock() << "s\n";
+        
+        // 测试视频帧延迟计算
+        double delay = sync.computeTargetDelay(frame_last_duration, videoTime);
+        std::cout << "  Computed video delay: " << delay << "s\n";
+
+        // 模拟音频同步
+        short audio_buffer[2048];
+        int original_size = 1920;
+        int synced_size = sync.synchronizeAudio(audio_buffer, original_size, audioTime);
+        std::cout << "  Original audio size: " << original_size << ", Synced audio size: " << synced_size << "\n";
+
+        audioTime += 0.033; // 30fps interval
+        
+        // 短暂延迟
+        std::this_thread::sleep_for(std::chrono::milliseconds(10));
+    }
+    
+    // 测试暂停和恢复
+    std::cout << "\nTesting pause/resume...\n";
+    sync.pause();
+    // std::cout << "Paused: " << (sync.isPaused() ? "true" : "false") << "\n";
+    
+    sync.resume();
+    // std::cout << "Resumed: " << (sync.isPaused() ? "false" : "true") << "\n";
+    
+    // 测试同步策略切换
+    std::cout << "\nTesting sync strategy change...\n";
+    sync.setSyncStrategy(SyncStrategy::VIDEO_MASTER);
+    std::cout << "New strategy: " << static_cast<int>(sync.getSyncStrategy()) << "\n";
+    // std::cout << "Master clock type: " << static_cast<int>(sync.getMasterClockType()) << "\n";
+    
+    // 测试播放速度
+    std::cout << "\nTesting playback speed...\n";
+    sync.setClockSpeed(ClockType::AUDIO, 1.5);
+    // std::cout << "Playback speed: " << sync.getPlaybackSpeed() << "\n";
+    
+    // 停止同步器
+    sync.stop();
+    std::cout << "\nSynchronizer stopped\n";
+    
+    std::cout << "\n=== Test Completed ===\n";
+    return 0;
+}

+ 29 - 4
AV/code/utils/utils_frame_queue.cpp

@@ -2,6 +2,7 @@
 #include "../base/logger.h"
 #include <algorithm>
 #include <shared_mutex>
+#include <deque>
 
 namespace av {
 namespace utils {
@@ -76,7 +77,7 @@ ErrorCode FrameQueue::enqueue(std::unique_ptr<FrameQueueItem> item) {
     }
     
     // 添加到队列
-    queue_.push(std::move(item));
+    queue_.push_back(std::move(item));
     
     // 更新统计信息
     if (config_.enableStats) {
@@ -94,6 +95,30 @@ ErrorCode FrameQueue::enqueue(std::unique_ptr<FrameQueueItem> item) {
     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();
+}
+
+AVFrame* FrameQueue::peekFrame() const {
+    const FrameQueueItem* item = peek();
+    return item ? item->frame : nullptr;
+}
+
 std::unique_ptr<FrameQueueItem> FrameQueue::dequeue() {
     return dequeue(config_.timeoutMs);
 }
@@ -119,7 +144,7 @@ std::unique_ptr<FrameQueueItem> FrameQueue::dequeue(int timeoutMs) {
     
     // 取出队列头部元素
     auto item = std::move(queue_.front());
-    queue_.pop();
+    queue_.pop_front();
     
     // 更新统计信息
     if (config_.enableStats) {
@@ -170,7 +195,7 @@ void FrameQueue::clear() {
     std::lock_guard<std::mutex> lock(queueMutex_);
     
     while (!queue_.empty()) {
-        queue_.pop();
+        queue_.pop_front();
     }
     
     Logger::instance().debug("Frame queue cleared");
@@ -295,7 +320,7 @@ void FrameQueue::dropOldestFrame() {
             dropCallback_(*oldestItem, "Drop oldest frame");
         }
         
-        queue_.pop();
+        queue_.pop_front();
         
         std::lock_guard<std::mutex> statsLock(statsMutex_);
         stats_.totalDropped++;

+ 8 - 3
AV/code/utils/utils_frame_queue.h

@@ -2,7 +2,7 @@
 #define AV_UTILS_FRAME_QUEUE_H
 
 #include "../base/types.h"
-#include <queue>
+#include <deque>
 #include <mutex>
 #include <condition_variable>
 #include <atomic>
@@ -129,6 +129,11 @@ public:
     AVFrame* dequeueFrame();
     AVFrame* dequeueFrame(int timeoutMs);
     
+    // 预览方法(不移除队列中的帧)
+    const FrameQueueItem* peek() const;
+    const FrameQueueItem* peek(int index) const;  // 预览第index个帧(0为队首)
+    AVFrame* peekFrame() const;  // 预览队首帧的AVFrame
+    
     // 兼容性方法 (push/pop 别名)
     ErrorCode push(AVFrame* frame, int streamIndex = -1) {
         return enqueue(frame, streamIndex);
@@ -188,8 +193,8 @@ protected:
 private:
     FrameQueueConfig config_;
     
-    // 队列数据
-    std::queue<std::unique_ptr<FrameQueueItem>> queue_;
+    // 队列数据 - 使用deque以支持随机访问
+    std::deque<std::unique_ptr<FrameQueueItem>> queue_;
     mutable std::mutex queueMutex_;
     std::condition_variable notEmpty_;
     std::condition_variable notFull_;

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

@@ -1,1537 +0,0 @@
-#include "utils_synchronizer_v2.h"
-#include "../base/logger.h"
-#include <algorithm>
-#include <cmath>
-#include <sstream>
-#include <iomanip>
-
-namespace av {
-namespace utils {
-SynchronizerV2::SynchronizerV2(const SyncConfigV2& config)
-    : config_(config)
-    , state_(SyncState::IDLE)
-    , masterClockType_(ClockType::AUDIO)
-    , initialized_(false)
-    , running_(false)
-    , paused_(false)
-    , recoveryAttempts_(0)
-    , lastSyncError_(0.0)
-{
-    // 初始化时钟
-    audioClock_ = ClockInfo();
-    videoClock_ = ClockInfo();
-    externalClock_ = ClockInfo();
-    
-    // 初始化历史记录
-    audioClockHistory_.clear();
-    videoClockHistory_.clear();
-    syncErrorHistory_.clear();
-    
-    Logger::instance().info("SynchronizerV2 created with strategy: " + 
-                           std::to_string(static_cast<int>(config_.strategy)));
-}
-
-SynchronizerV2::~SynchronizerV2() {
-    close();
-    Logger::instance().info("SynchronizerV2 destroyed");
-}
-
-ErrorCode SynchronizerV2::initialize() {
-    if (initialized_) {
-        return ErrorCode::ALREADY_INITIALIZED;
-    }
-    
-    std::lock_guard<std::mutex> clockLock(clockMutex_);
-    std::lock_guard<std::mutex> statsLock(statsMutex_);
-    
-    // 重置所有时钟
-    resetClock(ClockType::AUDIO);
-    resetClock(ClockType::VIDEO);
-    resetClock(ClockType::EXTERNAL);
-    
-    // 选择主时钟
-    selectMasterClock();
-    
-    // 重置统计信息
-    stats_ = SyncStatsV2();
-    stats_.lastUpdateTime = std::chrono::steady_clock::now();
-    
-    // 设置开始时间
-    startTime_ = std::chrono::steady_clock::now();
-    lastClockUpdate_ = startTime_;
-    lastStatsUpdate_ = startTime_;
-    
-    state_ = SyncState::IDLE;
-    initialized_ = true;
-    recoveryAttempts_ = 0;
-    
-    Logger::instance().info("SynchronizerV2 initialized");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SynchronizerV2::start() {
-    if (!initialized_) {
-        return ErrorCode::NOT_INITIALIZED;
-    }
-    
-    if (running_) {
-        return ErrorCode::ALREADY_STARTED;
-    }
-    
-    running_ = true;
-    paused_ = false;
-    state_ = SyncState::INITIALIZING;
-    
-    startTime_ = std::chrono::steady_clock::now();
-    lastClockUpdate_ = startTime_;
-    
-    // 按照packets_sync.cpp的init_clock逻辑初始化外部时钟
-    // 外部时钟应该初始化为NAN,而不是系统时间
-    {
-        std::lock_guard<std::mutex> lock(clockMutex_);
-        if (std::isnan(externalClock_.pts)) {
-            // 严格按照packets_sync.cpp的init_clock实现
-            // 外部时钟初始化为NAN,不使用系统时间
-            double currentTime = av_gettime_relative() / 1000000.0;
-            externalClock_.pts = std::numeric_limits<double>::quiet_NaN();  // 初始化为NAN
-            externalClock_.pts_drift = 0.0;       // 初始化pts_drift
-            externalClock_.lastUpdate = currentTime;
-            externalClock_.speed = 1.0;
-            externalClock_.serial = -1;
-            externalClock_.paused = false;
-            externalClock_.time = currentTime;
-            externalClock_.drift = 0.0;
-            externalClock_.smoothedPts = std::numeric_limits<double>::quiet_NaN();
-        }
-    }
-    
-    // 启动后立即进入同步状态
-    state_ = SyncState::SYNCING;
-    
-    Logger::instance().info("SynchronizerV2 started");
-    return ErrorCode::SUCCESS;
-}
-
-void SynchronizerV2::setStreamInfo(bool hasAudio, bool hasVideo) {
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    hasAudioStream_ = hasAudio;
-    hasVideoStream_ = hasVideo;
-    
-    Logger::instance().info("Stream info updated: hasAudio=" + std::to_string(hasAudio) + 
-                           ", hasVideo=" + std::to_string(hasVideo));
-    
-    // 重新选择主时钟
-    selectMasterClock();
-}
-
-ErrorCode SynchronizerV2::stop() {
-    if (!running_) {
-        return ErrorCode::NOT_STARTED;
-    }
-    
-    running_ = false;
-    paused_ = false;
-    state_ = SyncState::IDLE;
-    
-    Logger::instance().info("SynchronizerV2 stopped");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SynchronizerV2::pause() {
-    if (!running_) {
-        return ErrorCode::NOT_STARTED;
-    }
-    
-    if (paused_) {
-        return ErrorCode::ALREADY_PAUSED;
-    }
-    
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    
-    paused_ = true;
-    
-    // 暂停所有时钟
-    pauseClock(ClockType::AUDIO, true);
-    pauseClock(ClockType::VIDEO, true);
-    pauseClock(ClockType::EXTERNAL, true);
-    
-    Logger::instance().info("SynchronizerV2 paused");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SynchronizerV2::resume() {
-    if (!running_) {
-        return ErrorCode::NOT_STARTED;
-    }
-    
-    if (!paused_) {
-        return ErrorCode::NOT_PAUSED;
-    }
-    
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    
-    paused_ = false;
-    
-    // 恢复所有时钟
-    pauseClock(ClockType::AUDIO, false);
-    pauseClock(ClockType::VIDEO, false);
-    pauseClock(ClockType::EXTERNAL, false);
-    
-    state_ = SyncState::SYNCING;
-    
-    Logger::instance().info("SynchronizerV2 resumed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SynchronizerV2::reset() {
-    std::lock_guard<std::mutex> clockLock(clockMutex_);
-    std::lock_guard<std::mutex> statsLock(statsMutex_);
-    std::lock_guard<std::mutex> historyLock(historyMutex_);
-    
-    // 重置时钟
-    resetClock(ClockType::AUDIO);
-    resetClock(ClockType::VIDEO);
-    resetClock(ClockType::EXTERNAL);
-    
-    // 重置统计信息
-    stats_ = SyncStatsV2();
-    stats_.lastUpdateTime = std::chrono::steady_clock::now();
-    
-    // 清空历史记录
-    audioClockHistory_.clear();
-    videoClockHistory_.clear();
-    syncErrorHistory_.clear();
-    
-    // 重置状态
-    state_ = running_ ? SyncState::SYNCING : SyncState::IDLE;
-    recoveryAttempts_ = 0;
-    lastSyncError_ = 0.0;
-    
-    // 重新选择主时钟
-    selectMasterClock();
-    
-    Logger::instance().info("SynchronizerV2 reset");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SynchronizerV2::close() {
-    if (running_) {
-        stop();
-    }
-    
-    initialized_ = false;
-    
-    Logger::instance().info("SynchronizerV2 closed");
-    return ErrorCode::SUCCESS;
-}
-
-ErrorCode SynchronizerV2::setAudioClock(int64_t pts, double timeBase, int serial) {
-    return updateClock(ClockType::AUDIO, pts, timeBase, serial);
-}
-
-ErrorCode SynchronizerV2::setVideoClock(int64_t pts, double timeBase, int serial) {
-    return updateClock(ClockType::VIDEO, pts, timeBase, serial);
-}
-
-ErrorCode SynchronizerV2::setExternalClock(int64_t pts, double timeBase, int serial) {
-    return updateClock(ClockType::EXTERNAL, pts, timeBase, serial);
-}
-
-int64_t SynchronizerV2::getAudioClock(bool predict) const {
-    return getClock(ClockType::AUDIO, predict);
-}
-
-int64_t SynchronizerV2::getVideoClock(bool predict) const {
-    return getClock(ClockType::VIDEO, predict);
-}
-
-int64_t SynchronizerV2::getExternalClock(bool predict) const {
-    return getClock(ClockType::EXTERNAL, predict);
-}
-
-int64_t SynchronizerV2::getMasterClock(bool predict) const {
-    return getClock(masterClockType_, predict);
-}
-
-FrameDecision SynchronizerV2::shouldDisplayVideoFrame(int64_t pts, double timeBase, double duration) {
-    FrameDecision decision;
-    decision.actualPts = pts;
-    
-    if (!running_ || paused_) {
-        decision.action = FrameAction::DELAY;
-        decision.delay = 0.01; // 10ms
-        decision.reason = paused_ ? "Paused" : "Not running";
-        return decision;
-    }
-    
-    // 参考AVPlayer2的视频帧显示决策算法
-    double delay = duration > 0 ? duration : (1.0 / 25.0); // 默认25fps
-    
-    // 如果视频是主时钟,直接显示
-    if (masterClockType_ == ClockType::VIDEO) {
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = delay;
-        decision.reason = "Video master";
-        decision.targetPts = pts;
-        return decision;
-    }
-    
-    // 获取主时钟并计算同步误差
-    int64_t masterClock = getMasterClock(false); // 不使用预测,获取当前值
-    decision.targetPts = masterClock;
-    
-    double videoPts = ptsToSeconds(pts, timeBase);
-    double masterPts = ptsToSeconds(masterClock, timeBase);
-    double diff = videoPts - masterPts;
-    decision.syncError = diff;
-    
-    // 添加调试日志(仅在同步误差较大时)
-    if (std::abs(diff) > 1.0) { // 超过1秒时记录
-        Logger::instance().warning("Large video sync error: videoPTS=" + 
-                                  std::to_string(videoPts) + "s, masterPTS=" + 
-                                  std::to_string(masterPts) + "s, diff=" + 
-                                  std::to_string(diff) + "s, masterClock=" + 
-                                  std::to_string(masterClock) + ", timeBase=" + 
-                                  std::to_string(timeBase));
-    }
-    
-    // 参考packets_sync.cpp的AV_NOSYNC_THRESHOLD检查
-    if (std::isnan(diff) || std::isinf(diff) || std::abs(diff) >= config_.noSyncThreshold) {
-        // 同步误差过大,强制显示帧,不进行同步校正
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = delay;
-        decision.reason = "Large sync error, force display (diff: " + std::to_string(diff * 1000) + "ms)";
-        decision.targetPts = pts;
-
-        Logger::instance().warningf(
-            "Video sync error exceeds AV_NOSYNC_THRESHOLD: " + std::to_string(diff * 1000) + "ms");
-        return decision;
-    }
-    
-    // 参考AVPlayer2的compute_target_delay算法进行同步调整
-    double sync_threshold = std::max(config_.syncThreshold, std::min(0.1, delay));
-    
-    // 检查差异是否在合理范围内(避免异常值)
-    if (!std::isnan(diff) && std::abs(diff) < config_.maxSyncError) {
-        if (diff <= -sync_threshold) {
-            // 视频落后太多,丢帧追赶
-            decision.action = FrameAction::DROP;
-            decision.reason = "Video too slow, drop frame";
-            
-            // 通知丢帧
-            if (frameDropCallback_) {
-                frameDropCallback_(ClockType::VIDEO, pts);
-            }
-            
-            // 更新统计
-            std::lock_guard<std::mutex> lock(statsMutex_);
-            stats_.droppedFrames++;
-            
-        } else if (diff >= sync_threshold && delay > config_.frameDupThreshold) {
-            // 视频超前且延迟足够大,增加延迟
-            decision.action = FrameAction::DELAY;
-            decision.delay = delay + diff;
-            decision.reason = "Video too fast, increase delay";
-            
-        } else if (diff >= sync_threshold) {
-            // 视频超前但延迟较小,重复帧
-            decision.action = FrameAction::Frame_DUPLICATE;
-            decision.delay = 2 * delay;
-            decision.reason = "Video too fast, duplicate frame";
-            
-            // 通知重复帧
-            if (frameDuplicateCallback_) {
-                frameDuplicateCallback_(ClockType::VIDEO, pts);
-            }
-            
-            // 更新统计
-            std::lock_guard<std::mutex> lock(statsMutex_);
-            stats_.duplicatedFrames++;
-            
-        } else {
-            // 正常显示
-            decision.action = FrameAction::DISPLAY;
-            decision.delay = delay;
-            decision.reason = "Normal display";
-        }
-    } else {
-        // 同步误差过大或异常,需要智能处理
-        if (std::isnan(diff) || std::isinf(diff)) {
-            // 异常值,强制显示
-            decision.action = FrameAction::DISPLAY;
-            decision.delay = delay;
-            decision.reason = "Invalid sync value, force display";
-        } else if (diff < -config_.maxSyncError) {
-            // 视频严重落后,丢帧追赶
-            decision.action = FrameAction::DROP;
-            decision.reason = "Video severely behind, drop frame";
-            
-            // 通知丢帧
-            if (frameDropCallback_) {
-                frameDropCallback_(ClockType::VIDEO, pts);
-            }
-            
-            // 更新统计
-            std::lock_guard<std::mutex> lock(statsMutex_);
-            stats_.droppedFrames++;
-        } else if (diff > config_.maxSyncError) {
-            // 视频严重超前,大幅延迟
-            decision.action = FrameAction::DELAY;
-            decision.delay = std::min(delay + diff, 0.5); // 最大延迟500ms
-            decision.reason = "Video severely ahead, large delay";
-        } else {
-            // 其他情况,使用默认延迟
-            decision.action = FrameAction::DISPLAY;
-            decision.delay = delay;
-            decision.reason = "Sync error large, default display";
-        }
-        
-        // 触发恢复机制
-        if (state_ != SyncState::RECOVERING && recoveryAttempts_ < config_.maxRecoveryAttempts) {
-            state_ = SyncState::RECOVERING;
-            recoveryAttempts_++;
-        }
-    }
-    
-    // 更新统计
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.totalFrames++;
-        stats_.syncError = diff;
-        
-        // 更新平均同步误差
-        if (stats_.totalFrames == 1) {
-            stats_.avgSyncError = std::abs(diff);
-        } else {
-            stats_.avgSyncError = stats_.avgSyncError * 0.9 + std::abs(diff) * 0.1;
-        }
-        
-        // 更新最大同步误差
-        stats_.maxSyncError = std::max(stats_.maxSyncError, std::abs(diff));
-    }
-    
-    return decision;
-}
-
-FrameDecision SynchronizerV2::shouldPlayAudioFrame(int64_t pts, double timeBase, double duration) {
-    FrameDecision decision;
-    decision.actualPts = pts;
-    
-    if (!running_ || paused_) {
-        decision.action = FrameAction::DELAY;
-        decision.delay = 0.01; // 10ms
-        decision.reason = paused_ ? "Paused" : "Not running";
-        return decision;
-    }
-    
-    // 参考AVPlayer2的音频帧播放决策算法
-    double delay = duration > 0 ? duration : 0.02; // 默认20ms
-    
-    // 如果音频是主时钟,直接播放
-    if (masterClockType_ == ClockType::AUDIO) {
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = delay;
-        decision.reason = "Audio master";
-        decision.targetPts = pts;
-        return decision;
-    }
-    
-    // 获取主时钟并计算同步误差
-    int64_t masterClock = getMasterClock(false); // 不使用预测,获取当前值
-    decision.targetPts = masterClock;
-    
-    // 检查主时钟是否有效
-    if (masterClock == AV_NOPTS_VALUE) {
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = delay;
-        decision.reason = "Master clock invalid, force play";
-        return decision;
-    }
-    
-    double audioPts = ptsToSeconds(pts, timeBase);
-    double masterPts = ptsToSeconds(masterClock, timeBase);
-    double diff = audioPts - masterPts;
-    decision.syncError = diff;
-    
-    // 参考packets_sync.cpp的AV_NOSYNC_THRESHOLD检查
-    if (std::isnan(diff) || std::isinf(diff) || std::abs(diff) >= config_.noSyncThreshold) {
-        // 同步误差过大,不进行同步修正,直接播放
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = delay;
-        decision.reason = "Sync error too large (>" + std::to_string(config_.noSyncThreshold) + "s), no sync";
-        
-        // 记录大误差日志
-        if (std::abs(diff) > 1.0) {
-            Logger::instance().warning("Large audio sync error: audioPTS=" + 
-                                      std::to_string(audioPts) + "s, masterPTS=" + 
-                                      std::to_string(masterPts) + "s, diff=" + 
-                                      std::to_string(diff) + "s");
-        }
-        
-        return decision;
-    }
-    
-    // 参考packets_sync.cpp的音频同步算法
-    double sync_threshold = config_.syncThreshold;
-    
-    // 正常同步处理
-    if (diff <= -sync_threshold) {
-        // 音频落后太多,丢帧追赶
-        decision.action = FrameAction::DROP;
-        decision.reason = "Audio too slow, drop frame (diff=" + std::to_string(diff * 1000) + "ms)";
-        
-        // 通知丢帧
-        if (frameDropCallback_) {
-            frameDropCallback_(ClockType::AUDIO, pts);
-        }
-        
-        // 更新统计
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.droppedFrames++;
-        
-    } else if (diff >= sync_threshold) {
-        // 音频超前,延迟播放
-        decision.action = FrameAction::DELAY;
-        decision.delay = delay + diff;
-        decision.reason = "Audio too fast, delay (diff=" + std::to_string(diff * 1000) + "ms)";
-        
-    } else {
-        // 正常播放
-        decision.action = FrameAction::DISPLAY;
-        decision.delay = delay;
-        decision.reason = "Normal play (diff=" + std::to_string(diff * 1000) + "ms)";
-    }
-    
-    // 更新统计
-    {
-        std::lock_guard<std::mutex> lock(statsMutex_);
-        stats_.totalFrames++;
-        stats_.syncError = diff;
-        
-        // 更新平均同步误差
-        if (stats_.totalFrames == 1) {
-            stats_.avgSyncError = std::abs(diff);
-        } else {
-            stats_.avgSyncError = stats_.avgSyncError * 0.9 + std::abs(diff) * 0.1;
-        }
-        
-        // 更新最大同步误差
-        stats_.maxSyncError = std::max(stats_.maxSyncError, std::abs(diff));
-    }
-    
-    return decision;
-}
-
-double SynchronizerV2::calculateTargetDelay(int64_t pts, double timeBase, ClockType clockType) {
-    if (!running_) {
-        return 0.0;
-    }
-    
-    // 参考packets_sync.cpp的compute_target_delay算法
-    double delay = 0.0;
-    
-    // 基础帧延迟
-    if (clockType == ClockType::VIDEO) {
-        delay = 1.0 / 25.0; // 默认25fps,40ms
-    } else {
-        delay = 0.0; // 音频不需要基础延迟
-    }
-    
-    // 如果不是视频主时钟模式,需要进行同步调整
-    if (masterClockType_ != ClockType::VIDEO && clockType == ClockType::VIDEO) {
-        // 获取主时钟
-        int64_t masterClock = getMasterClock(true);
-        if (masterClock == AV_NOPTS_VALUE) {
-            return delay; // 主时钟无效,返回基础延迟
-        }
-        
-        // 计算视频时钟与主时钟的差异
-        double videoPts = ptsToSeconds(pts, timeBase);
-        double masterPts = ptsToSeconds(masterClock, timeBase);
-        double diff = videoPts - masterPts;
-        
-        // 参考packets_sync.cpp的AV_NOSYNC_THRESHOLD检查
-        if (std::isnan(diff) || std::isinf(diff) || std::abs(diff) >= config_.noSyncThreshold) {
-            // 同步误差过大,不进行同步校正,返回基础延迟
-            return delay;
-        }
-        
-        // 计算同步阈值,参考packets_sync.cpp的动态阈值算法
-        double sync_threshold = std::max(config_.syncThreshold, std::min(0.1, delay));
-        
-        // 检查差异是否在合理范围内(避免异常值)
-        if (!std::isnan(diff) && std::abs(diff) < config_.maxSyncError) {
-            if (diff <= -sync_threshold) {
-                // 视频落后,减少延迟以追赶
-                delay = std::max(0.0, delay + diff);
-            } else if (diff >= sync_threshold && delay > config_.frameDupThreshold) {
-                // 视频超前且延迟足够大,增加延迟
-                delay = delay + diff;
-            } else if (diff >= sync_threshold) {
-                // 视频超前但延迟较小,加倍延迟
-                delay = 2 * delay;
-            }
-        }
-    }
-    
-    return delay;
-}
-
-bool SynchronizerV2::shouldDropFrame(int64_t pts, double timeBase, ClockType clockType) {
-    if (!running_ || clockType == masterClockType_) {
-        return false;
-    }
-    
-    int64_t masterClock = getMasterClock();
-    if (masterClock == AV_NOPTS_VALUE) {
-        return false; // 主时钟无效,不丢帧
-    }
-    
-    double ptsInSeconds = ptsToSeconds(pts, timeBase);
-    double masterClockInSeconds = ptsToSeconds(masterClock, timeBase);
-    double diff = ptsInSeconds - masterClockInSeconds;
-    
-    // 参考packets_sync.cpp的AV_NOSYNC_THRESHOLD检查
-    if (std::isnan(diff) || std::isinf(diff) || std::abs(diff) >= config_.noSyncThreshold) {
-        return false; // 同步误差过大,不丢帧
-    }
-    
-    return diff < -config_.frameDropThreshold;
-}
-
-bool SynchronizerV2::shouldDuplicateFrame(int64_t pts, double timeBase, ClockType clockType) {
-    if (!running_ || clockType == masterClockType_) {
-        return false;
-    }
-    
-    int64_t masterClock = getMasterClock();
-    if (masterClock == AV_NOPTS_VALUE) {
-        return false; // 主时钟无效,不复制帧
-    }
-    
-    double ptsInSeconds = ptsToSeconds(pts, timeBase);
-    double masterClockInSeconds = ptsToSeconds(masterClock, timeBase);
-    double diff = ptsInSeconds - masterClockInSeconds;
-    
-    // 参考packets_sync.cpp的AV_NOSYNC_THRESHOLD检查
-    if (std::isnan(diff) || std::isinf(diff) || std::abs(diff) >= config_.noSyncThreshold) {
-        return false; // 同步误差过大,不复制帧
-    }
-    
-    return diff > config_.frameDupThreshold;
-}
-
-double SynchronizerV2::calculateSyncError() const {
-    if (!running_) {
-        return 0.0;
-    }
-    
-    double audioClock = getAudioClock();
-    double videoClock = getVideoClock();
-    
-    if (audioClock <= 0 || videoClock <= 0) {
-        return 0.0;
-    }
-    
-    return std::abs(audioClock - videoClock);
-}
-
-// 内部版本,假设调用者已经持有clockMutex_锁
-double SynchronizerV2::calculateSyncErrorInternal() const {
-    if (!running_) {
-        return 0.0;
-    }
-    
-    // 直接计算时钟值,避免调用getClock导致死锁,使用packets_sync.cpp的算法
-    double audioClock = 0.0;
-    double videoClock = 0.0;
-    double currentTime = getSystemTime();
-    
-    // 计算音频时钟,使用packets_sync.cpp的get_clock算法
-    if (!std::isnan(audioClock_.pts)) {
-        if (audioClock_.paused) {
-            audioClock = audioClock_.pts;
-        } else {
-            // 使用packets_sync.cpp的算法:pts + pts_drift + (current_time - last_updated) * speed
-            audioClock = audioClock_.pts + audioClock_.pts_drift + (currentTime - audioClock_.lastUpdate) * audioClock_.speed;
-        }
-    }
-    
-    // 计算视频时钟,使用packets_sync.cpp的get_clock算法
-    if (!std::isnan(videoClock_.pts)) {
-        if (videoClock_.paused) {
-            videoClock = videoClock_.pts;
-        } else {
-            // 使用packets_sync.cpp的算法:pts + pts_drift + (current_time - last_updated) * speed
-            videoClock = videoClock_.pts + videoClock_.pts_drift + (currentTime - videoClock_.lastUpdate) * videoClock_.speed;
-        }
-    }
-    
-    if (audioClock <= 0 || videoClock <= 0) {
-        return 0.0;
-    }
-    
-    return std::abs(audioClock - videoClock);
-}
-
-double SynchronizerV2::calculateAudioDelay(int64_t pts, double timeBase) const {
-    if (masterClockType_ == ClockType::AUDIO) {
-        return 0.0;
-    }
-    
-    int64_t masterClock = getMasterClock();
-    double ptsInSeconds = ptsToSeconds(pts, timeBase);
-    double masterClockInSeconds = ptsToSeconds(masterClock, timeBase);
-    return ptsInSeconds - masterClockInSeconds;
-}
-
-double SynchronizerV2::calculateVideoDelay(int64_t pts, double timeBase) const {
-    if (masterClockType_ == ClockType::VIDEO) {
-        return 0.0;
-    }
-    
-    int64_t masterClock = getMasterClock();
-    double ptsInSeconds = ptsToSeconds(pts, timeBase);
-    double masterClockInSeconds = ptsToSeconds(masterClock, timeBase);
-    return ptsInSeconds - masterClockInSeconds;
-}
-
-void SynchronizerV2::setConfig(const SyncConfigV2& config) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_ = config;
-    
-    // 重新选择主时钟
-    selectMasterClock();
-    
-    Logger::instance().info("SynchronizerV2 config updated");
-}
-
-SyncConfigV2 SynchronizerV2::getConfig() const {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    return config_;
-}
-
-void SynchronizerV2::setSyncStrategy(SyncStrategy strategy) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.strategy = strategy;
-    selectMasterClock();
-    
-    Logger::instance().info("Sync strategy set to: " + std::to_string(static_cast<int>(strategy)));
-}
-
-SyncStrategy SynchronizerV2::getSyncStrategy() const {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    return config_.strategy;
-}
-
-void SynchronizerV2::setPlaybackSpeed(double speed) {
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    
-    audioClock_.speed = speed;
-    videoClock_.speed = speed;
-    externalClock_.speed = speed;
-    
-    Logger::instance().info("Playback speed set to: " + std::to_string(speed) + "x");
-}
-
-double SynchronizerV2::getPlaybackSpeed() const {
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    return audioClock_.speed;
-}
-
-bool SynchronizerV2::isSynchronized() const {
-    return state_ == SyncState::SYNCHRONIZED;
-}
-
-SyncStatsV2 SynchronizerV2::getStats() const {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    SyncStatsV2 stats = stats_;
-    
-    // 更新当前时钟值
-    stats.audioClock = getAudioClock();
-    stats.videoClock = getVideoClock();
-    stats.externalClock = getExternalClock();
-    stats.masterClock = getMasterClock();
-    stats.state = state_;
-    stats.masterClockType = masterClockType_;
-    
-    return stats;
-}
-
-void SynchronizerV2::resetStats() {
-    std::lock_guard<std::mutex> lock(statsMutex_);
-    stats_ = SyncStatsV2();
-    stats_.lastUpdateTime = std::chrono::steady_clock::now();
-    
-    Logger::instance().info("SynchronizerV2 stats reset");
-}
-
-void SynchronizerV2::setSyncEventCallback(SyncEventCallback callback) {
-    syncEventCallback_ = callback;
-}
-
-void SynchronizerV2::setFrameDropCallback(FrameDropCallback callback) {
-    frameDropCallback_ = callback;
-}
-
-void SynchronizerV2::setFrameDuplicateCallback(FrameDuplicateCallback callback) {
-    frameDuplicateCallback_ = callback;
-}
-
-void SynchronizerV2::setSyncErrorCallback(SyncErrorCallback callback) {
-    syncErrorCallback_ = callback;
-}
-
-void SynchronizerV2::enableAdaptiveSync(bool enable) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.enableAdaptiveSync = enable;
-    
-    Logger::instance().info("Adaptive sync " + std::string(enable ? "enabled" : "disabled"));
-}
-
-void SynchronizerV2::enablePrediction(bool enable) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.enablePrediction = enable;
-    
-    Logger::instance().info("Prediction " + std::string(enable ? "enabled" : "disabled"));
-}
-
-void SynchronizerV2::setClockUpdateInterval(double interval) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.clockUpdateInterval = interval;
-    
-    Logger::instance().info("Clock update interval set to: " + std::to_string(interval * 1000) + "ms");
-}
-
-void SynchronizerV2::setSmoothingWindow(int window) {
-    std::lock_guard<std::mutex> lock(configMutex_);
-    config_.smoothingWindow = window;
-    
-    // 调整历史记录大小
-    std::lock_guard<std::mutex> historyLock(historyMutex_);
-    while (audioClockHistory_.size() > static_cast<size_t>(window)) {
-        audioClockHistory_.pop_front();
-    }
-    while (videoClockHistory_.size() > static_cast<size_t>(window)) {
-        videoClockHistory_.pop_front();
-    }
-    while (syncErrorHistory_.size() > static_cast<size_t>(window)) {
-        syncErrorHistory_.pop_front();
-    }
-    
-    Logger::instance().info("Smoothing window set to: " + std::to_string(window));
-}
-
-std::string SynchronizerV2::getDebugInfo() const {
-    std::ostringstream oss;
-    
-    SyncStatsV2 stats = getStats();
-    
-    oss << std::fixed << std::setprecision(3);
-    oss << "SynchronizerV2 Debug Info:\n";
-    oss << "  State: " << static_cast<int>(stats.state) << "\n";
-    oss << "  Master Clock: " << static_cast<int>(stats.masterClockType) << "\n";
-    oss << "  Audio Clock: " << stats.audioClock << "s\n";
-    oss << "  Video Clock: " << stats.videoClock << "s\n";
-    oss << "  External Clock: " << stats.externalClock << "s\n";
-    oss << "  Master Clock: " << stats.masterClock << "s\n";
-    oss << "  Sync Error: " << stats.syncError * 1000 << "ms\n";
-    oss << "  Avg Sync Error: " << stats.avgSyncError * 1000 << "ms\n";
-    oss << "  Max Sync Error: " << stats.maxSyncError * 1000 << "ms\n";
-    oss << "  Total Frames: " << stats.totalFrames << "\n";
-    oss << "  Dropped Frames: " << stats.droppedFrames << "\n";
-    oss << "  Duplicated Frames: " << stats.duplicatedFrames << "\n";
-    oss << "  Running: " << (running_ ? "Yes" : "No") << "\n";
-    oss << "  Paused: " << (paused_ ? "Yes" : "No") << "\n";
-    
-    return oss.str();
-}
-
-void SynchronizerV2::dumpClockInfo() const {
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    
-    Logger::instance().info("Clock Info Dump:");
-    Logger::instance().info("  Audio - PTS: " + std::to_string(audioClock_.pts) + 
-                           ", Speed: " + std::to_string(audioClock_.speed) + 
-                           ", Paused: " + (audioClock_.paused ? "Yes" : "No"));
-    Logger::instance().info("  Video - PTS: " + std::to_string(videoClock_.pts) + 
-                           ", Speed: " + std::to_string(videoClock_.speed) + 
-                           ", Paused: " + (videoClock_.paused ? "Yes" : "No"));
-    Logger::instance().info("  External - PTS: " + std::to_string(externalClock_.pts) + 
-                           ", Speed: " + std::to_string(externalClock_.speed) + 
-                           ", Paused: " + (externalClock_.paused ? "Yes" : "No"));
-}
-
-// 私有方法实现
-
-ErrorCode SynchronizerV2::updateClock(ClockType type, int64_t pts, double timeBase, int serial) {
-    if (!initialized_) {
-        return ErrorCode::NOT_INITIALIZED;
-    }
-    
-    // 参考packets_sync.cpp的set_clock_at实现,确保与AVPlayer2一致
-    double currentTime = getSystemTime();
-    double ptsInSeconds = ptsToSeconds(pts, timeBase);
-    
-    // 在锁内更新时钟数据
-    {
-        std::lock_guard<std::mutex> lock(clockMutex_);
-        
-        ClockInfo* clock = nullptr;
-        switch (type) {
-            case ClockType::AUDIO:
-                clock = &audioClock_;
-                break;
-            case ClockType::VIDEO:
-                clock = &videoClock_;
-                break;
-            case ClockType::EXTERNAL:
-                clock = &externalClock_;
-                break;
-            default:
-                return ErrorCode::INVALID_PARAMS;
-        }
-        
-        // 检查序列号,参考packets_sync.cpp的序列号检查机制
-        if (serial != 0 && clock->serial != serial) {
-            // 序列号不匹配,可能是seek操作,重置时钟
-            resetClock(type);
-            clock->serial = serial;
-        }
-        
-        // 严格按照packets_sync.cpp的set_clock_at算法更新时钟
-        if (pts != AV_NOPTS_VALUE) {
-            // 参考packets_sync.cpp: clock->pts_drift = pts - time
-            clock->pts_drift = ptsInSeconds - currentTime;
-            clock->pts = ptsInSeconds;  // 存储转换后的秒值,与packets_sync.cpp一致
-            clock->lastUpdate = currentTime;
-        } else {
-            clock->pts = std::numeric_limits<double>::quiet_NaN();
-            clock->pts_drift = 0.0;
-            clock->lastUpdate = currentTime;
-        }
-        
-        clock->time = currentTime;
-        clock->serial = serial;
-        
-        // 添加调试日志
-        static int logCounter = 0;
-        if (++logCounter % 100 == 0) { // 每100次更新记录一次
-            std::string clockName = (type == ClockType::AUDIO) ? "Audio" : 
-                                   (type == ClockType::VIDEO) ? "Video" : "External";
-            Logger::instance().info("Clock Update [" + clockName + "]: PTS=" + 
-                                  std::to_string(pts) + ", PTSSeconds=" + 
-                                  std::to_string(ptsInSeconds) + ", SystemTime=" + 
-                                  std::to_string(currentTime) + ", Drift=" + 
-                                  std::to_string(clock->drift));
-        }
-        
-        // 平滑处理(保持原有逻辑,但确保使用正确的PTS值)
-        if (config_.smoothingWindow > 1) {
-            clock->smoothedPts = smoothClock(type, static_cast<int64_t>(ptsInSeconds * AV_TIME_BASE));
-        } else {
-            clock->smoothedPts = static_cast<int64_t>(ptsInSeconds * AV_TIME_BASE);
-        }
-        
-        // 更新历史记录(转换为AV_TIME_BASE格式)
-        updateClockHistory(type, static_cast<int64_t>(ptsInSeconds * AV_TIME_BASE));
-        
-        // 如果这是主时钟,同步外部时钟到主时钟
-        if (type == masterClockType_ && type != ClockType::EXTERNAL) {
-            syncClockToSlave(&externalClock_, clock);
-        }
-        
-        // 定期更新统计信息
-        auto now = std::chrono::steady_clock::now();
-        if (std::chrono::duration_cast<std::chrono::milliseconds>(now - lastStatsUpdate_).count() > 100) {
-            updateStats();
-            lastStatsUpdate_ = now;
-        }
-    } // 释放clockMutex_锁
-    
-    // 在锁外更新同步状态,避免死锁
-    updateSyncState();
-    
-    return ErrorCode::SUCCESS;
-}
-
-int64_t SynchronizerV2::getClock(ClockType type, bool predict) const {
-    std::lock_guard<std::mutex> lock(clockMutex_);
-    
-    const ClockInfo* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &audioClock_;
-            break;
-        case ClockType::VIDEO:
-            clock = &videoClock_;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &externalClock_;
-            break;
-        case ClockType::SYSTEM:
-            return static_cast<int64_t>(getSystemTime() * AV_TIME_BASE);
-        default:
-            return AV_NOPTS_VALUE;
-    }
-    
-    // 严格按照packets_sync.cpp的get_clock实现
-    // 检查时钟是否有效(pts不为NAN,与packets_sync.cpp一致)
-    if (std::isnan(clock->pts)) {
-        return AV_NOPTS_VALUE;
-    }
-    
-    double clockValue;
-    if (clock->paused) {
-        // 暂停状态下,直接返回暂停时的PTS值
-        clockValue = clock->pts;
-    } else {
-        // 运行状态下,使用packets_sync.cpp的get_clock算法
-        // get_clock算法:pts_drift + time - (time - last_updated) * (1.0 - speed)
-        // 等价于:pts + pts_drift + (current_time - last_updated) * speed
-        double currentTime = av_gettime_relative() / 1000000.0;
-        clockValue = clock->pts_drift + currentTime - (currentTime - clock->lastUpdate) * (1.0 - clock->speed);
-    }
-    
-    // 转换为AV_TIME_BASE时间基准
-    int64_t currentPts = static_cast<int64_t>(clockValue * AV_TIME_BASE);
-    
-    // 如果启用预测
-    if (predict && config_.enablePrediction) {
-        return predictClock(type, config_.predictionWindow);
-    }
-    
-    return currentPts;
-}
-
-void SynchronizerV2::resetClock(ClockType type) {
-    ClockInfo* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &audioClock_;
-            break;
-        case ClockType::VIDEO:
-            clock = &videoClock_;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &externalClock_;
-            break;
-        default:
-            return;
-    }
-    
-    // 严格按照packets_sync.cpp的init_clock实现
-    // init_clock调用set_clock(c, NAN, -1),而set_clock使用av_gettime_relative
-    double currentTime = av_gettime_relative() / 1000000.0;
-
-    // 统一初始化所有时钟,与packets_sync.cpp保持一致
-    clock->speed = 1.0;
-    clock->paused = false;
-    
-    // 调用set_clock(c, NAN, -1)的等价操作
-    clock->pts = std::numeric_limits<double>::quiet_NaN();  // 使用NAN,与packets_sync.cpp一致
-    clock->pts_drift = clock->pts - currentTime;  // set_clock_at的逻辑
-    clock->lastUpdate = currentTime;
-    clock->serial = -1;
-    
-    // 保留SynchronizerV2特有的字段
-    clock->time = currentTime;
-    clock->drift = 0.0;
-    clock->smoothedPts = AV_NOPTS_VALUE;
-}
-
-// 严格按照packets_sync.cpp的sync_clock_to_slave实现
-void SynchronizerV2::syncClockToSlave(ClockInfo* slave, const ClockInfo* master) {
-    if (!slave || !master) {
-        return;
-    }
-    
-    double currentTime = getSystemTime();
-    
-    // 计算主时钟当前值,使用packets_sync.cpp的get_clock算法
-    double masterClock = std::numeric_limits<double>::quiet_NaN();
-    if (!std::isnan(master->pts)) {
-        if (master->paused) {
-            masterClock = master->pts;
-        } else {
-            // 使用packets_sync.cpp的get_clock算法:pts_drift + time - (time - last_updated) * (1.0 - speed)
-            masterClock = master->pts_drift + currentTime - (currentTime - master->lastUpdate) * (1.0 - master->speed);
-        }
-    }
-    
-    // 计算从时钟当前值,使用packets_sync.cpp的get_clock算法
-    double slaveClock = std::numeric_limits<double>::quiet_NaN();
-    if (!std::isnan(slave->pts)) {
-        if (slave->paused) {
-            slaveClock = slave->pts;
-        } else {
-            // 使用packets_sync.cpp的get_clock算法:pts_drift + time - (time - last_updated) * (1.0 - speed)
-            slaveClock = slave->pts_drift + currentTime - (currentTime - slave->lastUpdate) * (1.0 - slave->speed);
-        }
-    }
-    
-    // 参考packets_sync.cpp的sync_clock_to_slave逻辑
-    if (!std::isnan(masterClock) && 
-        (std::isnan(slaveClock) || std::abs(masterClock - slaveClock) > config_.noSyncThreshold)) {
-        // 按照packets_sync.cpp的set_clock_at算法同步从时钟到主时钟
-        slave->pts = masterClock;
-        slave->pts_drift = masterClock - currentTime;
-        slave->lastUpdate = currentTime;
-        slave->serial = master->serial;
-        
-        // 保留SynchronizerV2特有的字段
-        slave->time = currentTime;
-        slave->drift = masterClock - currentTime;
-    }
-}
-
-void SynchronizerV2::pauseClock(ClockType type, bool pause) {
-    ClockInfo* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &audioClock_;
-            break;
-        case ClockType::VIDEO:
-            clock = &videoClock_;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &externalClock_;
-            break;
-        default:
-            return;
-    }
-    
-    if (clock->paused != pause) {
-        double currentTime = getSystemTime();
-        
-        if (pause) {
-            // 暂停时保存当前PTS,使用packets_sync.cpp的get_clock算法计算当前值
-            if (!clock->paused && !std::isnan(clock->pts)) {
-                clock->pts = clock->pts_drift + currentTime - (currentTime - clock->lastUpdate) * (1.0 - clock->speed);
-                clock->pts_drift = 0.0;  // 暂停后drift重置为0
-            }
-        } else {
-            // 恢复时重新设置pts_drift,参考packets_sync.cpp的set_clock_at
-            if (!std::isnan(clock->pts)) {
-                clock->pts_drift = clock->pts - currentTime;
-            }
-        }
-        
-        clock->paused = pause;
-        clock->lastUpdate = currentTime;
-        clock->time = currentTime;  // 保留SynchronizerV2特有字段
-    }
-}
-
-void SynchronizerV2::selectMasterClock() {
-    ClockType newMasterClock = masterClockType_;
-    
-    switch (config_.strategy) {
-        case SyncStrategy::AUDIO_MASTER:
-            newMasterClock = ClockType::AUDIO;
-            break;
-            
-        case SyncStrategy::VIDEO_MASTER:
-            newMasterClock = ClockType::VIDEO;
-            break;
-            
-        case SyncStrategy::EXTERNAL_MASTER:
-            newMasterClock = ClockType::EXTERNAL;
-            break;
-            
-        case SyncStrategy::ADAPTIVE: {
-            // 参考AVPlayer2的自适应主时钟选择算法
-            if (config_.enableAdaptiveSync) {
-                bool hasAudio = (hasAudioStream_ && !std::isnan(audioClock_.pts) && !audioClock_.paused);
-                 bool hasVideo = (hasVideoStream_ && !std::isnan(videoClock_.pts) && !videoClock_.paused);
-                 
-                 if (hasAudio && hasVideo) {
-                     // 音视频都存在时,评估时钟质量
-                     double currentTime = getSystemTime();
-                     
-                     // 计算音频时钟的稳定性
-                     double audioStability = 1.0;
-                     if (audioClock_.time > 0) {
-                         double audioAge = currentTime - audioClock_.time;
-                         audioStability = std::exp(-audioAge / 2.0); // 2秒衰减
-                     }
-                     
-                     // 计算视频时钟的稳定性
-                     double videoStability = 1.0;
-                     if (videoClock_.time > 0) {
-                         double videoAge = currentTime - videoClock_.time;
-                         videoStability = std::exp(-videoAge / 2.0); // 2秒衰减
-                     }
-                     
-                     // 考虑时钟漂移
-                     double audioDrift = std::abs(audioClock_.drift);
-                     double videoDrift = std::abs(videoClock_.drift);
-                     
-                     // 音频时钟通常更稳定,给予优先权
-                     double audioScore = audioStability * 1.2 / (1.0 + audioDrift * 10.0);
-                     double videoScore = videoStability / (1.0 + videoDrift * 10.0);
-                     
-                     if (audioScore > videoScore && audioScore > 0.3) {
-                         newMasterClock = ClockType::AUDIO;
-                     } else if (videoScore > 0.3) {
-                         newMasterClock = ClockType::VIDEO;
-                     } else {
-                         newMasterClock = ClockType::EXTERNAL;
-                     }
-                 } else if (hasAudio) {
-                     // 只有音频
-                     newMasterClock = ClockType::AUDIO;
-                 } else if (hasVideo) {
-                     // 只有视频
-                     newMasterClock = ClockType::VIDEO;
-                 } else {
-                     // 都没有,使用外部时钟
-                     newMasterClock = ClockType::EXTERNAL;
-                 }
-            } else {
-                // 简单逻辑:优先音频,但要检查时钟有效性
-                bool hasValidAudio = (hasAudioStream_ && !std::isnan(audioClock_.pts));
-                bool hasValidVideo = (hasVideoStream_ && !std::isnan(videoClock_.pts));
-                
-                if (hasValidAudio) {
-                    newMasterClock = ClockType::AUDIO;
-                } else if (hasValidVideo) {
-                    newMasterClock = ClockType::VIDEO;
-                } else {
-                    // 音视频时钟都无效,使用外部时钟
-                    newMasterClock = ClockType::EXTERNAL;
-                }
-            }
-            break;
-        }
-    }
-    
-    // 如果选择外部时钟作为主时钟,但外部时钟无效,则初始化它
-    if (newMasterClock == ClockType::EXTERNAL && std::isnan(externalClock_.pts)) {
-        double currentTime = av_gettime_relative() / 1000000.0;
-        externalClock_.pts = currentTime;
-        externalClock_.pts_drift = 0.0;
-        externalClock_.lastUpdate = currentTime;
-        externalClock_.time = currentTime;
-        externalClock_.serial = 0;
-        externalClock_.paused = false;
-        externalClock_.speed = 1.0;
-        externalClock_.drift = 0.0;
-        
-        Logger::instance().info("External clock initialized as master with current time: " + std::to_string(currentTime));
-    }
-    
-    // 只有当主时钟真正改变时才更新和记录日志
-    if (newMasterClock != masterClockType_) {
-        ClockType oldMasterClock = masterClockType_;
-        masterClockType_ = newMasterClock;
-        
-        // 获取时钟状态信息用于调试
-        std::string audioStatus = "invalid";
-        std::string videoStatus = "invalid";
-        std::string externalStatus = "invalid";
-        
-        if (!std::isnan(audioClock_.pts)) {
-            audioStatus = "valid(pts=" + std::to_string(audioClock_.pts) + ")";
-        }
-        if (!std::isnan(videoClock_.pts)) {
-            videoStatus = "valid(pts=" + std::to_string(videoClock_.pts) + ")";
-        }
-        if (!std::isnan(externalClock_.pts)) {
-            externalStatus = "valid(pts=" + std::to_string(externalClock_.pts) + ")";
-        }
-        
-        Logger::instance().info("Master clock changed from "
-                                + std::to_string(static_cast<int>(oldMasterClock))
-                                + " to " + std::to_string(static_cast<int>(masterClockType_.load()))
-                                + " (hasAudio=" + std::to_string(hasAudioStream_.load())
-                                + ", hasVideo=" + std::to_string(hasVideoStream_.load())
-                                + ", audio=" + audioStatus
-                                + ", video=" + videoStatus
-                                + ", external=" + externalStatus + ")");
-    }
-}
-
-void SynchronizerV2::updateSyncState() {
-    if (!running_) {
-        state_ = SyncState::IDLE;
-        return;
-    }
-    
-    if (paused_) {
-        return;
-    }
-    
-    double syncError = calculateSyncErrorInternal();
-    
-    SyncState newState = state_;
-    bool needRecovery = false;
-    
-    // 参考AVPlayer2的同步状态管理算法
-    if (syncError <= config_.syncThreshold) {
-        // 同步误差在可接受范围内
-        if (state_ == SyncState::RECOVERING || state_ == SyncState::INITIALIZING) {
-            // 从恢复或初始化状态转为同步状态
-            newState = SyncState::SYNCHRONIZED;
-            recoveryAttempts_ = 0;
-        } else if (state_ != SyncState::SYNCHRONIZED) {
-            newState = SyncState::SYNCHRONIZED;
-        }
-    } else if (syncError <= config_.adaptiveThreshold) {
-        // 轻微漂移状态
-        if (state_ == SyncState::SYNCHRONIZED) {
-            newState = SyncState::DRIFT;
-        } else if (state_ == SyncState::RECOVERING) {
-            // 恢复中但误差仍较大,继续恢复
-            double recoveryDuration = getCurrentTime() - recoveryStartTime_;
-            if (recoveryDuration > 3.0) { // 3秒恢复超时
-                if (recoveryAttempts_ < config_.maxRecoveryAttempts) {
-                    needRecovery = true;
-                } else {
-                    newState = SyncState::ERROR;
-                }
-            }
-        }
-    } else if (syncError <= config_.maxSyncError) {
-        // 同步误差较大但仍在可恢复范围内
-        if (state_ != SyncState::RECOVERING) {
-            newState = SyncState::ERROR;
-            if (recoveryAttempts_ < config_.maxRecoveryAttempts) {
-                needRecovery = true;
-                newState = SyncState::RECOVERING;
-            }
-        } else {
-            // 已在恢复状态,检查恢复超时
-            double recoveryDuration = getCurrentTime() - recoveryStartTime_;
-            if (recoveryDuration > 5.0) { // 5秒恢复超时
-                if (recoveryAttempts_ < config_.maxRecoveryAttempts) {
-                    needRecovery = true;
-                } else {
-                    newState = SyncState::ERROR;
-                }
-            }
-        }
-    } else {
-        // 同步误差过大
-        newState = SyncState::ERROR;
-        // 标记需要恢复,但不在这里直接调用attemptRecovery避免死锁
-        if (recoveryAttempts_ < config_.maxRecoveryAttempts) {
-            needRecovery = true;
-            newState = SyncState::RECOVERING;
-        }
-    }
-    
-    // 检查长时间失同步的情况
-    if (newState == SyncState::ERROR && recoveryAttempts_ >= config_.maxRecoveryAttempts) {
-        static double lastResetTime = 0;
-        double currentTime = getCurrentTime();
-        if (currentTime - lastResetTime > 10.0) { // 10秒重置一次
-            // 尝试重新初始化同步
-            recoveryAttempts_ = 0;
-            newState = SyncState::INITIALIZING;
-            lastResetTime = currentTime;
-            Logger::instance().warning("Sync error persists, attempting full reset");
-        }
-    }
-    
-    if (newState != state_) {
-        SyncState oldState = state_;
-        state_ = newState;
-        notifyStateChange(newState);
-        
-        Logger::instance().info("Sync state changed from " + std::to_string(static_cast<int>(oldState)) + 
-                               " to " + std::to_string(static_cast<int>(newState)));
-    }
-    
-    // 如果需要恢复,现在可以安全地调用恢复操作(因为updateSyncState现在在锁外被调用)
-    if (needRecovery) {
-        performDelayedRecovery();
-    }
-}
-
-void SynchronizerV2::updateStats() {
-    // 统计信息在其他方法中已经更新
-}
-
-int64_t SynchronizerV2::smoothClock(ClockType type, int64_t newPts) {
-    std::lock_guard<std::mutex> lock(historyMutex_);
-    
-    std::deque<int64_t>* history = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            history = &audioClockHistory_;
-            break;
-        case ClockType::VIDEO:
-            history = &videoClockHistory_;
-            break;
-        default:
-            return newPts;
-    }
-    
-    if (history->empty() || newPts == AV_NOPTS_VALUE) {
-        return newPts;
-    }
-    
-    // 简单的指数移动平均
-    int64_t lastSmoothed = history->back();
-    if (lastSmoothed == AV_NOPTS_VALUE) {
-        return newPts;
-    }
-    
-    double smoothed = static_cast<double>(lastSmoothed) * (1.0 - config_.smoothingFactor) + 
-                     static_cast<double>(newPts) * config_.smoothingFactor;
-    return static_cast<int64_t>(smoothed);
-}
-
-int64_t SynchronizerV2::predictClock(ClockType type, double futureTime) const {
-    // 注意:此方法假设调用者已经持有clockMutex_锁
-    // 不能再调用getClock,否则会导致死锁
-    
-    const ClockInfo* clock = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            clock = &audioClock_;
-            break;
-        case ClockType::VIDEO:
-            clock = &videoClock_;
-            break;
-        case ClockType::EXTERNAL:
-            clock = &externalClock_;
-            break;
-        default:
-            return AV_NOPTS_VALUE;
-    }
-    
-    if (clock->paused || std::isnan(clock->pts)) {
-        return static_cast<int64_t>(clock->pts * AV_TIME_BASE);
-    }
-    
-    // 计算当前时间(不调用getClock避免死锁),使用packets_sync.cpp的get_clock算法
-    double currentTime = getSystemTime();
-    // 使用packets_sync.cpp的算法:pts + pts_drift + (current_time - last_updated) * speed
-    double currentPtsSeconds = clock->pts + clock->pts_drift + (currentTime - clock->lastUpdate) * clock->speed;
-    
-    return static_cast<int64_t>((currentPtsSeconds + futureTime * clock->speed) * AV_TIME_BASE);
-}
-
-void SynchronizerV2::updateClockHistory(ClockType type, int64_t pts) {
-    std::lock_guard<std::mutex> lock(historyMutex_);
-    
-    std::deque<int64_t>* history = nullptr;
-    switch (type) {
-        case ClockType::AUDIO:
-            history = &audioClockHistory_;
-            break;
-        case ClockType::VIDEO:
-            history = &videoClockHistory_;
-            break;
-        default:
-            return;
-    }
-    
-    history->push_back(pts);
-    while (history->size() > static_cast<size_t>(config_.smoothingWindow)) {
-        history->pop_front();
-    }
-}
-
-void SynchronizerV2::attemptRecovery() {
-    recoveryAttempts_++;
-    lastRecoveryTime_ = std::chrono::steady_clock::now();
-    
-    Logger::instance().warning("Attempting sync recovery, attempt: " + std::to_string(recoveryAttempts_));
-    
-    // 重置时钟漂移
-    {
-        std::lock_guard<std::mutex> lock(clockMutex_);
-        audioClock_.drift = 0.0;
-        videoClock_.drift = 0.0;
-        externalClock_.drift = 0.0;
-    }
-    
-    // 可能需要重新选择主时钟(在锁外面调用避免死锁)
-    if (config_.enableAdaptiveSync) {
-        selectMasterClock();
-    }
-}
-
-void SynchronizerV2::performDelayedRecovery() {
-    // 这个方法在不持有clockMutex_的情况下被调用
-    // 执行实际的恢复操作
-    
-    // 检查恢复间隔,避免过于频繁的恢复
-    auto now = std::chrono::steady_clock::now();
-    auto timeSinceLastRecovery = std::chrono::duration<double>(now - lastRecoveryTime_).count();
-    if (timeSinceLastRecovery < 1.0) { // 至少间隔1秒
-        return;
-    }
-    
-    recoveryAttempts_++;
-    lastRecoveryTime_ = now;
-    
-    Logger::instance().warning("Performing delayed sync recovery, attempt: " + std::to_string(recoveryAttempts_));
-    
-    // 重置时钟漂移
-    {
-        std::lock_guard<std::mutex> lock(clockMutex_);
-        audioClock_.drift = 0.0;
-        videoClock_.drift = 0.0;
-        externalClock_.drift = 0.0;
-    }
-    
-    // 只有在恢复次数较少时才重新选择主时钟,避免频繁切换
-    if (config_.enableAdaptiveSync && recoveryAttempts_ <= 3) {
-        selectMasterClock();
-    }
-}
-
-double SynchronizerV2::getCurrentTime() const {
-    auto now = std::chrono::steady_clock::now();
-    return std::chrono::duration<double>(now - startTime_).count();
-}
-
-double SynchronizerV2::getSystemTime() const {
-    return av_gettime_relative() / 1000000.0;
-}
-
-void SynchronizerV2::notifyStateChange(SyncState newState) {
-    if (syncEventCallback_) {
-        syncEventCallback_(state_, newState);
-    }
-}
-
-void SynchronizerV2::notifyFrameDrop(ClockType type, int64_t pts) {
-    if (frameDropCallback_) {
-        frameDropCallback_(type, pts);
-    }
-}
-
-void SynchronizerV2::notifyFrameDuplicate(ClockType type, int64_t pts) {
-    if (frameDuplicateCallback_) {
-        frameDuplicateCallback_(type, pts);
-    }
-}
-
-void SynchronizerV2::notifySyncError(double error, const std::string& reason) {
-    if (syncErrorCallback_) {
-        syncErrorCallback_(error, reason);
-    }
-}
-
-// PTS转换辅助方法实现
-double SynchronizerV2::ptsToSeconds(int64_t pts, double timeBase) const {
-    if (pts == AV_NOPTS_VALUE) {
-        return 0.0;
-    }
-    return pts * timeBase;
-}
-
-int64_t SynchronizerV2::secondsToPts(double seconds, double timeBase) const {
-    if (timeBase <= 0.0) {
-        return AV_NOPTS_VALUE;
-    }
-    return static_cast<int64_t>(seconds / timeBase);
-}
-
-} // namespace utils
-} // namespace av

+ 2 - 349
AV/code/utils/utils_synchronizer_v2.h

@@ -4,14 +4,13 @@
 #pragma once
 
 #include "../base/types.h"
-#include "../base/logger.h"
-#include <memory>
 #include <atomic>
-#include <mutex>
 #include <chrono>
 #include <deque>
 #include <functional>
 #include <limits>
+#include <memory>
+#include <mutex>
 
 extern "C" {
 #include <libavutil/avutil.h>
@@ -21,352 +20,6 @@ extern "C" {
 namespace av {
 namespace utils {
 
-// 同步错误常量
-const ErrorCode SYNC_ERROR = ErrorCode::PROCESSING_ERROR;
-
-/**
- * 改进的时钟类型
- */
-enum class ClockType {
-    AUDIO,
-    VIDEO,
-    EXTERNAL,
-    SYSTEM
-};
-
-/**
- * 同步策略
- */
-enum class SyncStrategy {
-    AUDIO_MASTER,       // 音频为主时钟
-    VIDEO_MASTER,       // 视频为主时钟
-    EXTERNAL_MASTER,    // 外部时钟为主
-    ADAPTIVE            // 自适应选择
-};
-
-/**
- * 同步状态
- */
-enum class SyncState {
-    IDLE,               // 空闲
-    INITIALIZING,       // 初始化中
-    SYNCING,           // 同步中
-    SYNCHRONIZED,      // 已同步
-    DRIFT,             // 轻微漂移
-    ERROR,             // 同步错误
-    RECOVERING         // 恢复中
-};
-
-/**
- * 时钟信息结构 - 与packets_sync.cpp的Clock结构保持一致
- */
-struct ClockInfo {
-    double pts = std::numeric_limits<double>::quiet_NaN(); // 当前PTS,以秒为单位(与packets_sync.cpp一致)
-    double pts_drift = 0.0;      // clock base minus time at which we updated the clock
-    double lastUpdate = 0.0;     // 最后更新时间
-    double speed = 1.0;          // 播放速度
-    int serial = 0;              // 序列号  clock is based on a packet with this serial
-    bool paused = false;         // 是否暂停
-
-    // SynchronizerV2特有的扩展字段(保持向后兼容)
-    double time = 0.0;                                          // 系统时间
-    double drift = 0.0;                                         // 时钟漂移(兼容字段)
-    int64_t smoothedPts = AV_NOPTS_VALUE;                       // 平滑后的PTS
-
-    ClockInfo() { 
-        double currentTime = av_gettime_relative() / 1000000.0;
-        lastUpdate = currentTime;
-        time = currentTime;
-    }
-};
-
-/**
- * 同步配置 - 基于AVPlayer2的packets_sync.cpp优化
- */
-struct SyncConfigV2 {
-    SyncStrategy syncStrategy = SyncStrategy::ADAPTIVE;  // 同步策略
-    
-    // 同步阈值 - 参考packets_sync.h的定义
-    double syncThreshold = 0.04;           // AV_SYNC_THRESHOLD_MIN - 40ms
-    double audioSyncThreshold = 0.04;      // 40ms - 音频同步阈值
-    double videoSyncThreshold = 0.04;      // 40ms - 视频同步阈值
-    double maxSyncError = 0.1;              // AV_SYNC_THRESHOLD_MAX - 100ms
-    double frameDropThreshold = 0.05;      // 50ms - 丢帧阈值
-    double frameDupThreshold = 0.1;        // AV_SYNC_FRAMEDUP_THRESHOLD - 100ms
-    double noSyncThreshold = 10.0;         // AV_NOSYNC_THRESHOLD - 10s,超过此值不进行同步
-    
-    // 帧控制
-    bool enableFrameDrop = true;           // 启用丢帧
-    bool enableFrameDuplicate = true;      // 启用重复帧
-    
-    // 时钟更新参数
-    double clockUpdateInterval = 0.01;     // 10ms - 时钟更新间隔
-    int smoothingWindow = 10;              // 平滑窗口大小
-    double smoothingFactor = 0.1;          // 平滑因子
-    
-    // 自适应参数
-    bool enableAdaptiveSync = true;
-    double adaptiveThreshold = 0.02;       // 20ms - 自适应阈值
-    int adaptiveWindow = 30;               // 自适应窗口
-    
-    // 恢复参数
-    double recoveryThreshold = 0.2;        // 200ms - 恢复阈值
-    int maxRecoveryAttempts = 5;           // 最大恢复尝试次数
-    bool enableErrorRecovery = true;       // 启用错误恢复
-    
-    // 性能参数
-    bool enablePrediction = true;          // 启用预测
-    double predictionWindow = 0.1;         // 100ms - 预测窗口
-    
-    // 兼容性字段 (保持向后兼容)
-    SyncStrategy strategy = SyncStrategy::ADAPTIVE;  // 与syncStrategy相同
-};
-
-/**
- * 同步统计信息
- */
-struct SyncStatsV2 {
-    // 时钟值
-    double audioClock = 0.0;
-    double videoClock = 0.0;
-    double externalClock = 0.0;
-    double masterClock = 0.0;
-    
-    // 延迟信息
-    double audioDelay = 0.0;
-    double videoDelay = 0.0;
-    double syncError = 0.0;
-    double avgSyncError = 0.0;
-    double maxSyncError = 0.0;
-    
-    // 帧处理统计
-    uint64_t totalFrames = 0;
-    uint64_t droppedFrames = 0;
-    uint64_t duplicatedFrames = 0;
-    uint64_t syncAdjustments = 0;
-    
-    // 状态信息
-    SyncState state = SyncState::IDLE;
-    ClockType masterClockType = ClockType::AUDIO;
-    std::chrono::steady_clock::time_point lastUpdateTime;
-    
-    // 性能指标
-    double cpuUsage = 0.0;
-    double memoryUsage = 0.0;
-};
-
-/**
- * 帧决策结果
- */
-enum class FrameAction {
-    DISPLAY,         // 正常显示
-    DROP,            // 丢弃帧
-    Frame_DUPLICATE, // 重复帧
-    DELAY            // 延迟显示
-};
-
-/**
- * 帧决策信息
- */
-struct FrameDecision {
-    FrameAction action = FrameAction::DISPLAY;
-    double delay = 0.0;                     // 延迟时间
-    int64_t targetPts = AV_NOPTS_VALUE;     // 目标PTS (FFmpeg原生格式)
-    int64_t actualPts = AV_NOPTS_VALUE;     // 实际PTS (FFmpeg原生格式)
-    double syncError = 0.0;                 // 同步误差
-    std::string reason;                     // 决策原因
-};
-
-/**
- * 回调函数类型
- */
-using SyncEventCallback = std::function<void(SyncState oldState, SyncState newState)>;
-using FrameDropCallback = std::function<void(ClockType clockType, int64_t pts)>;
-using FrameDuplicateCallback = std::function<void(ClockType clockType, int64_t pts)>;
-using SyncErrorCallback = std::function<void(double error, const std::string& reason)>;
-
-/**
- * 改进的同步器类 - 基于AVPlayer2的经验重新设计
- * 
- * 主要改进:
- * 1. 更精确的时钟管理和同步算法
- * 2. 自适应同步策略
- * 3. 更好的错误恢复机制
- * 4. 性能优化和预测算法
- * 5. 详细的统计和监控
- */
-class SynchronizerV2 {
-public:
-    explicit SynchronizerV2(const SyncConfigV2& config = SyncConfigV2());
-    ~SynchronizerV2();
-    
-    // 生命周期管理
-    ErrorCode initialize();
-    ErrorCode start();
-    ErrorCode stop();
-    ErrorCode pause();
-    ErrorCode resume();
-    ErrorCode reset();
-    
-    // 设置流信息
-    void setStreamInfo(bool hasAudio, bool hasVideo);
-    ErrorCode close();
-    
-    // 时钟设置与获取
-    ErrorCode setAudioClock(int64_t pts, double timeBase, int serial = 0);
-    ErrorCode setVideoClock(int64_t pts, double timeBase, int serial = 0);
-    ErrorCode setExternalClock(int64_t pts, double timeBase, int serial = 0);
-    
-    // 时钟获取 - 支持预测
-    int64_t getAudioClock(bool predict = false) const;
-    int64_t getVideoClock(bool predict = false) const;
-    int64_t getExternalClock(bool predict = false) const;
-    int64_t getMasterClock(bool predict = false) const;
-    ClockType getMasterClockType() const { return masterClockType_; }
-    
-    // 同步决策 - 核心功能 (需要传入时间基准进行转换)
-    FrameDecision shouldDisplayVideoFrame(int64_t pts, double timeBase, double duration = 0.0);
-    FrameDecision shouldPlayAudioFrame(int64_t pts, double timeBase, double duration = 0.0);
-    double calculateTargetDelay(int64_t pts, double timeBase, ClockType clockType);
-    
-    // 同步控制
-    bool shouldDropFrame(int64_t pts, double timeBase, ClockType clockType);
-    bool shouldDuplicateFrame(int64_t pts, double timeBase, ClockType clockType);
-    double calculateSyncError() const;
-    double calculateAudioDelay(int64_t pts, double timeBase) const;
-    double calculateVideoDelay(int64_t pts, double timeBase) const;
-    
-    // 配置管理
-    void setConfig(const SyncConfigV2& config);
-    SyncConfigV2 getConfig() const;
-    void setSyncStrategy(SyncStrategy strategy);
-    SyncStrategy getSyncStrategy() const;
-    void setPlaybackSpeed(double speed);
-    double getPlaybackSpeed() const;
-    
-    // 状态查询
-    SyncState getState() const { return state_; }
-    bool isSynchronized() const;
-    bool isRunning() const { return running_; }
-    bool isPaused() const { return paused_; }
-    
-    // 统计信息
-    SyncStatsV2 getStats() const;
-    void resetStats();
-    
-    // 回调设置
-    void setSyncEventCallback(SyncEventCallback callback);
-    void setFrameDropCallback(FrameDropCallback callback);
-    void setFrameDuplicateCallback(FrameDuplicateCallback callback);
-    void setSyncErrorCallback(SyncErrorCallback callback);
-    
-    // 高级功能
-    void enableAdaptiveSync(bool enable);
-    void enablePrediction(bool enable);
-    void setClockUpdateInterval(double interval);
-    void setSmoothingWindow(int window);
-    
-    // 调试和监控
-    std::string getDebugInfo() const;
-    void dumpClockInfo() const;
-
-private:
-    // 内部时钟管理
-    ErrorCode updateClock(ClockType type, int64_t pts, double timeBase, int serial);
-    int64_t getClock(ClockType type, bool predict = false) const;
-    void resetClock(ClockType type);
-    void pauseClock(ClockType type, bool pause);
-    void syncClockToSlave(ClockInfo* slave, const ClockInfo* master);
-    
-    // PTS转换辅助方法
-    double ptsToSeconds(int64_t pts, double timeBase) const;
-    int64_t secondsToPts(double seconds, double timeBase) const;
-    
-    // 同步算法
-    void updateMasterClock();
-    void selectMasterClock();
-    void updateSyncState();
-    void updateStats();
-    
-    // 平滑和预测
-    int64_t smoothClock(ClockType type, int64_t newPts);
-    int64_t predictClock(ClockType type, double futureTime) const;
-    void updateClockHistory(ClockType type, int64_t pts);
-    
-    // 自适应算法
-    void adaptiveSyncUpdate();
-    bool shouldSwitchMasterClock();
-    void handleSyncError(double error);
-    
-    // 错误恢复
-    void attemptRecovery();
-    void performDelayedRecovery();
-    void resetSyncState();
-    
-    // 工具函数
-    double getCurrentTime() const;
-    double getSystemTime() const;
-    void notifyStateChange(SyncState newState);
-    void notifyFrameDrop(ClockType type, int64_t pts);
-    void notifyFrameDuplicate(ClockType type, int64_t pts);
-    void notifySyncError(double error, const std::string& reason);
-    
-    // 内部版本,假设调用者已经持有clockMutex_锁
-    double calculateSyncErrorInternal() const;
-    
-private:
-    // 配置
-    SyncConfigV2 config_;
-    mutable std::mutex configMutex_;
-    
-    // 状态
-    std::atomic<SyncState> state_{SyncState::IDLE};
-    std::atomic<ClockType> masterClockType_{ClockType::AUDIO};
-    std::atomic<bool> initialized_{false};
-    std::atomic<bool> running_{false};
-    std::atomic<bool> paused_{false};
-    
-    // 时钟
-    ClockInfo audioClock_;
-    ClockInfo videoClock_;
-    ClockInfo externalClock_;
-    mutable std::mutex clockMutex_;
-    
-    // 历史记录
-    std::deque<int64_t> audioClockHistory_;
-    std::deque<int64_t> videoClockHistory_;
-    std::deque<double> syncErrorHistory_;
-    mutable std::mutex historyMutex_;
-    
-    // 统计信息
-    SyncStatsV2 stats_;
-    mutable std::mutex statsMutex_;
-    
-    // 时间记录
-    std::chrono::steady_clock::time_point startTime_;
-    std::chrono::steady_clock::time_point lastClockUpdate_;
-    std::chrono::steady_clock::time_point lastStatsUpdate_;
-
-    // 自适应参数
-    int recoveryAttempts_ = 0;
-    double lastSyncError_ = 0.0;
-    double recoveryStartTime_ = 0.0;
-    std::chrono::steady_clock::time_point lastRecoveryTime_;
-    
-    // 状态变化回调
-    std::function<void(SyncState, ClockType)> stateChangeCallback_;
-    
-    // 回调函数
-    SyncEventCallback syncEventCallback_;
-    FrameDropCallback frameDropCallback_;
-    FrameDuplicateCallback frameDuplicateCallback_;
-    SyncErrorCallback syncErrorCallback_;
-    
-    // 流信息
-    std::atomic<bool> hasAudioStream_{false};
-    std::atomic<bool> hasVideoStream_{false};
-};
-
 } // namespace utils
 } // namespace av
 

+ 1 - 9
AV/test_player_with_ui.cpp

@@ -1,10 +1,3 @@
-/**
- * @file test_player_with_ui.cpp
- * @brief 带有视频播放界面的综合测试程序
- * @author AI Assistant
- * @date 2024
- */
-
 #include <chrono>
 #include <string>
 #include <thread>
@@ -12,7 +5,6 @@
 
 #include "code/base/logger.h"
 #include "code/player/player_core_v2.h"
-#include "code/player/opengl_video_renderer.h"
 
 #include <QApplication>
 #include <QWidget>
@@ -373,7 +365,7 @@ private:
     void setupPlayer() {
         // 创建同步配置
         SyncConfigV2 syncConfig;
-        syncConfig.syncStrategy = SyncStrategy::ADAPTIVE;
+        syncConfig.strategy = SyncStrategy::VIDEO_MASTER;
         syncConfig.audioSyncThreshold = 0.040;
         syncConfig.videoSyncThreshold = 0.020;
         syncConfig.maxSyncError = 0.200;

+ 15 - 0
AV/xmake.lua

@@ -198,6 +198,21 @@ target("test_audio_encoder")
         add_links("avcodec", "avformat", "avutil", "swscale", "swresample")
         add_links("avdevice", "avfilter", "postproc")
     end
+
+-- 同步器测试程序
+target("test_synchronizer_v2")
+    set_kind("binary")
+    add_files("code/utils/test_synchronizer_v2.cpp")
+    add_deps("av_utils")
+    set_targetdir("$(buildir)/bin")
+    
+    -- FFmpeg库链接
+    if is_plat("windows") then
+        add_includedirs(ffmpeg_include)
+        add_linkdirs(ffmpeg_lib)
+        add_links("avcodec", "avformat", "avutil", "swscale", "swresample")
+        add_links("avdevice", "avfilter", "postproc")
+    end
     
 
 -- 窗口采集测试程序