#include "recorder_video_recorder.h"
#include "../base/logger.h"
#include "../capture/capture_video_capturer.h"
#include "../codec/codec_video_encoder.h"
#include "../muxer/muxer_file_muxer.h"
#include <algorithm>
#include <chrono>

extern "C" {
#include <libavcodec/avcodec.h>
}

namespace av {
namespace recorder {

VideoRecorder::VideoRecorder()
    : AbstractRecorder(MediaType::VIDEO)
    , shouldStop_(false)
    , isPaused_(false)
    , avgCaptureTime_(0.0)
    , avgEncodeTime_(0.0)
    , consecutiveDrops_(0) {
    
    threadPool_ = std::make_unique<utils::ThreadPool>(); // 3个工作线程
    
    // 配置帧队列参数
    utils::FrameQueueConfig frameQueueConfig;
    frameQueueConfig.maxSize = 30;
    frameQueue_ = std::make_unique<utils::FrameQueue>(frameQueueConfig); // 30帧缓冲
    
    lastFrameTime_ = std::chrono::steady_clock::now();
    lastCaptureTime_ = std::chrono::steady_clock::now();
    lastEncodeTime_ = std::chrono::steady_clock::now();
}

VideoRecorder::~VideoRecorder() {
    close();
}

ErrorCode VideoRecorder::initialize(const RecorderParams& params) {
    if (!validateParams(params)) {
        return ErrorCode::INVALID_PARAMS;
    }
    
    videoParams_ = static_cast<const VideoRecorderParams&>(params);
    params_ = params;
    
    // 计算帧间隔
    frameInterval_ = std::chrono::microseconds(1000000 / videoParams_.frameRate);
    
    // 初始化各个组件
    ErrorCode result = initializeCapturer();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    result = initializeEncoder();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    result = initializeMuxer();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    setState(RecorderState::INITIALIZED);
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::startRecording() {
    if (getState() != RecorderState::INITIALIZED && getState() != RecorderState::STOPPED) {
        return ErrorCode::INVALID_STATE;
    }
    
    shouldStop_ = false;
    isPaused_ = false;
    consecutiveDrops_ = 0;
    
    // 重置统计信息
    {
        std::lock_guard<std::mutex> lock(statsMutex_);
        captureStats_ = CaptureStats{};
    }
    
    // 启动采集器
    if (capturer_) {
        ErrorCode result = capturer_->start();
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to start video capturer: {}", static_cast<int>(result));
            return result;
        }
    }
    
    // 启动复用器
    if (muxer_) {
        ErrorCode result = muxer_->start();
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to start muxer: {}", static_cast<int>(result));
            return result;
        }
        AV_LOGGER_INFO("Muxer started successfully");
    }
    
    // 启动处理线程
    processingThread_ = std::make_unique<std::thread>(&VideoRecorder::videoProcessingThread, this);
    frameRateThread_ = std::make_unique<std::thread>(&VideoRecorder::frameRateControlThread, this);
    
    setState(RecorderState::RECORDING);
    resetStats();
    
    AV_LOGGER_INFOF("Video recording started: {}x{} @ {}fps", 
             videoParams_.width, videoParams_.height, videoParams_.frameRate);
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::stopRecording() {
    if (getState() != RecorderState::RECORDING && getState() != RecorderState::PAUSED) {
        return ErrorCode::INVALID_STATE;
    }
    
    shouldStop_ = true;
    isPaused_ = false;
    
    // 通知所有等待的线程
    frameCondition_.notify_all();
    
    // 等待处理线程结束
    if (processingThread_ && processingThread_->joinable()) {
        processingThread_->join();
        processingThread_.reset();
    }
    
    if (frameRateThread_ && frameRateThread_->joinable()) {
        frameRateThread_->join();
        frameRateThread_.reset();
    }
    
    // 停止采集器
    if (capturer_) {
        capturer_->stop();
    }
    
    // 刷新编码器
    if (encoder_) {
        std::vector<AVPacketPtr> packets;
        encoder_->finishEncode(packets);
        
        for (const auto& packet : packets) {
            if (muxer_) {
                muxer_->writePacket(packet.get());
            }
        }
    }
    
    // 关闭复用器
    if (muxer_) {
        muxer_->close();
    }
    
    setState(RecorderState::STOPPED);
    
    AV_LOGGER_INFO("Video recording stopped");
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::pauseRecording() {
    if (getState() != RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    isPaused_ = true;
    setState(RecorderState::PAUSED);
    
    AV_LOGGER_INFO("Video recording paused");
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::resumeRecording() {
    if (getState() != RecorderState::PAUSED) {
        return ErrorCode::INVALID_STATE;
    }
    
    isPaused_ = false;
    setState(RecorderState::RECORDING);
    frameCondition_.notify_all();
    
    AV_LOGGER_INFO("Video recording resumed");
    return ErrorCode::SUCCESS;
}

void VideoRecorder::close() {
    if (getState() == RecorderState::RECORDING || getState() == RecorderState::PAUSED) {
        stopRecording();
    }
    
    cleanup();
    setState(RecorderState::IDLE);
}

ErrorCode VideoRecorder::setCaptureSource(VideoCaptureMethod method, const std::string& source) {
    if (getState() == RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    videoParams_.captureMethod = method;
    videoParams_.deviceId = source;
    
    // 重新初始化采集器
    if (capturer_) {
        capturer_->close();
        return initializeCapturer();
    }
    
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::setCaptureWindow(void* windowHandle) {
    if (getState() == RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    videoParams_.captureMethod = VideoCaptureMethod::WINDOW_CAPTURE;
    videoParams_.windowHandle = windowHandle;
    
    if (capturer_) {
        capturer_->close();
        return initializeCapturer();
    }
    
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::setCaptureMonitor(int monitorIndex) {
    if (getState() == RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    videoParams_.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
    videoParams_.monitorIndex = monitorIndex;
    
    if (capturer_) {
        capturer_->close();
        return initializeCapturer();
    }
    
    return ErrorCode::SUCCESS;
}

AVFramePtr VideoRecorder::getCurrentFrame() const {
    std::lock_guard<std::mutex> lock(currentFrameMutex_);
    if (!currentFrame_) {
        return nullptr;
    }
    
    // 创建新的frame并复制数据
    AVFramePtr frame = makeAVFrame();
    if (!frame) {
        return nullptr;
    }
    
    if (av_frame_ref(frame.get(), currentFrame_.get()) < 0) {
        return nullptr;
    }
    
    return frame;
}

void VideoRecorder::setDrawCursor(bool draw) {
    videoParams_.drawCursor = draw;
    // TODO: 通知采集器更新设置
}

VideoRecorder::CaptureStats VideoRecorder::getCaptureStats() const {
    std::lock_guard<std::mutex> lock(statsMutex_);
    return captureStats_;
}

std::vector<std::string> VideoRecorder::getAvailableDevices(VideoCaptureMethod method) const {
    // TODO: 根据method参数返回对应类型的设备列表
    (void)method; // 避免未使用参数警告
    auto capturer = std::make_unique<capture::VideoCapturer>();
    return capturer->getAvailableDevices();
}

std::vector<std::pair<uint32_t, uint32_t>> VideoRecorder::getSupportedResolutions() const {
    // 返回常见的分辨率列表
    return {
        {1920, 1080}, {1680, 1050}, {1600, 900}, {1440, 900},
        {1366, 768}, {1280, 1024}, {1280, 800}, {1280, 720},
        {1024, 768}, {800, 600}, {640, 480}
    };
}

bool VideoRecorder::validateParams(const RecorderParams& params) {
    const auto& videoParams = static_cast<const VideoRecorderParams&>(params);
    
    if (videoParams.width == 0 || videoParams.height == 0) {
        AV_LOGGER_ERRORF("Invalid video dimensions: {}x{}", videoParams.width, videoParams.height);
        return false;
    }
    
    if (videoParams.frameRate == 0 || videoParams.frameRate > 120) {
        AV_LOGGER_ERRORF("Invalid frame rate: {}", videoParams.frameRate);
        return false;
    }
    
    if (videoParams.outputPath.empty()) {
        AV_LOGGER_ERROR("Output path is empty");
        return false;
    }
    
    return true;
}

void VideoRecorder::videoProcessingThread() {
    AV_LOGGER_INFO("Video processing thread started");
    
    try {
        while (!shouldStop_) {
            if (isPaused_) {
                std::unique_lock<std::mutex> lock(frameMutex_);
                frameCondition_.wait(lock, [this] { return !isPaused_ || shouldStop_; });
                continue;
            }
            
            // 从队列获取帧
            AVFramePtr frame = frameQueue_->pop(100);
            if (!frame) {
                continue;
            }
            
            // 验证帧的有效性
            if (frame->width <= 0 || frame->height <= 0) {
                AV_LOGGER_WARNING("Invalid frame dimensions, skipping");
                continue;
            }
            auto encodeStart = std::chrono::steady_clock::now();
            
            // 处理视频帧
            AVFramePtr processedFrame = processVideoFrame(std::move(frame));
            if (!processedFrame) {
                updateStats(false);
                continue;
            }
            
            // 在编码前创建预览副本（编码后processedFrame将被move走）
            AVFramePtr previewFrame = nullptr;
            try {
                previewFrame = makeAVFrame();
                if (previewFrame) {
                    previewFrame->format = processedFrame->format;
                    previewFrame->width = processedFrame->width;
                    previewFrame->height = processedFrame->height;
                    previewFrame->pts = processedFrame->pts;
                    
                    if (av_frame_get_buffer(previewFrame.get(), 32) >= 0 &&
                        av_frame_copy(previewFrame.get(), processedFrame.get()) >= 0 &&
                        av_frame_copy_props(previewFrame.get(), processedFrame.get()) >= 0) {
                        // 预览副本创建成功
                    } else {
                        previewFrame.reset(); // 创建失败，清空指针
                    }
                }
            } catch (const std::exception& e) {
                AV_LOGGER_DEBUGF("Failed to create preview frame: {}", e.what());
                previewFrame.reset();
            }
            
            // 编码视频帧
            if (encoder_) {
                // 在编码前进行最后的帧有效性检查
                if (!processedFrame->data[0]) {
                    AV_LOGGER_ERROR("严重错误：即将编码的帧数据指针为空");
                    updateStats(false);
                    continue;
                }
                
                AV_LOGGER_DEBUGF("准备编码帧: width={}, height={}, format={}, data_ptr={}", 
                                processedFrame->width, processedFrame->height, 
                                processedFrame->format, static_cast<void*>(processedFrame->data[0]));
                
                std::vector<AVPacketPtr> packets;
                // 使用move语义明确转移所有权，避免潜在的双重释放
                ErrorCode result = encoder_->encode(std::move(processedFrame), packets);
                
                auto encodeEnd = std::chrono::steady_clock::now();
                auto encodeTime = std::chrono::duration_cast<std::chrono::microseconds>(encodeEnd - encodeStart).count() / 1000.0;
                
                if (result == ErrorCode::SUCCESS && !packets.empty()) {
                    size_t totalSize = 0;
                    for (const auto& packet : packets) {
                        if (packet && packet->size > 0) {
                            onVideoPacketEncoded(packet);
                            totalSize += packet->size;
                        }
                    }
                    updateStats(true, totalSize);
                    
                    // 更新编码时间统计
                    avgEncodeTime_ = (avgEncodeTime_ * 0.9) + (encodeTime * 0.1);
                } else {
                    updateStats(false);
                    consecutiveDrops_++;
                    AV_LOGGER_ERRORF("Video encoding failed: {}", static_cast<int>(result));
                }
            }
            
            // 更新当前帧（用于预览）
            if (previewFrame) {
                try {
                    std::lock_guard<std::mutex> lock(currentFrameMutex_);
                    currentFrame_ = std::move(previewFrame);
                } catch (const std::exception& e) {
                    AV_LOGGER_ERRORF("Error updating current frame: {}", e.what());
                }
            }

            
            // 计算实际帧率
            calculateActualFrameRate();
        }
    } catch (const std::exception& e) {
        AV_LOGGER_ERRORF("Video processing thread crashed with exception: {}", e.what());
    } catch (...) {
        AV_LOGGER_ERROR("Video processing thread crashed with unknown exception");
    }
    
    AV_LOGGER_INFO("Video processing thread stopped");
}

void VideoRecorder::frameRateControlThread() {
    AV_LOGGER_INFO("Frame rate control thread started");
    
    auto nextFrameTime = std::chrono::steady_clock::now();
    
    while (!shouldStop_) {
        if (isPaused_) {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            nextFrameTime = std::chrono::steady_clock::now();
            continue;
        }
        
        // 等待到下一帧时间
        std::this_thread::sleep_until(nextFrameTime);
        nextFrameTime += frameInterval_;
        
        // 检查是否过载
        bool isOverloaded = checkOverload();
        
        {
            std::lock_guard<std::mutex> lock(statsMutex_);
            captureStats_.isOverloaded = isOverloaded;
            captureStats_.captureOverhead = avgCaptureTime_;
            captureStats_.encodeTime = avgEncodeTime_;
        }
        
        if (isOverloaded) {
            // 如果过载，跳过一些帧
            nextFrameTime += frameInterval_;
            consecutiveDrops_++;
        }
    }
    
    AV_LOGGER_INFO("Frame rate control thread stopped");
}

void VideoRecorder::onVideoFrameCaptured(const AVFramePtr& frame) {
    if (shouldStop_ || isPaused_ || !frame) {
        return;
    }
    
    // 验证帧数据的有效性
    if (frame->width <= 0 || frame->height <= 0 || !frame->data[0]) {
        AV_LOGGER_WARNING("Invalid frame data, skipping");
        return;
    }
    
    auto captureEnd = std::chrono::steady_clock::now();
    auto captureTime = std::chrono::duration_cast<std::chrono::microseconds>(captureEnd - lastCaptureTime_).count() / 1000.0;
    lastCaptureTime_ = captureEnd;
    
    // 更新采集时间统计
    avgCaptureTime_ = (avgCaptureTime_ * 0.9) + (captureTime * 0.1);
    
    try {
        // 创建帧的副本以避免内存管理问题
        AVFramePtr frameCopy = makeAVFrame();
        if (!frameCopy) {
            AV_LOGGER_ERROR("创建帧副本失败");
            consecutiveDrops_++;
            updateStats(false);
            return;
        }
        
        // 复制帧属性
        frameCopy->format = frame->format;
        frameCopy->width = frame->width;
        frameCopy->height = frame->height;
        frameCopy->pts = frame->pts;
        
        // 分配独立的缓冲区
        if (av_frame_get_buffer(frameCopy.get(), 32) < 0) {
            AV_LOGGER_ERROR("分配帧缓冲区失败");
            consecutiveDrops_++;
            updateStats(false);
            return;
        }
        
        // 复制帧数据（创建真正的副本，避免引用计数问题）
        if (av_frame_copy(frameCopy.get(), frame.get()) < 0) {
            AV_LOGGER_ERROR("复制帧数据失败");
            consecutiveDrops_++;
            updateStats(false);
            return;
        }
        
        // 复制帧属性
        if (av_frame_copy_props(frameCopy.get(), frame.get()) < 0) {
            AV_LOGGER_ERROR("复制帧属性失败");
            consecutiveDrops_++;
            updateStats(false);
            return;
        }
        
        // 使用新的安全接口将帧加入队列
        if (frameQueue_->push(std::move(frameCopy)) != ErrorCode::SUCCESS) {
            // 队列满，丢弃帧 - 智能指针自动清理
            consecutiveDrops_++;
            updateStats(false);
            AV_LOGGER_DEBUG("Frame queue full, dropped frame");
        }
    } catch (const std::exception& e) {
        AV_LOGGER_ERRORF("Error in onVideoFrameCaptured: {}", e.what());
        consecutiveDrops_++;
        updateStats(false);
    }
}

void VideoRecorder::onVideoPacketEncoded(const AVPacketPtr& packet) {
    if (muxer_ && packet) {
        ErrorCode result = muxer_->writePacket(packet.get());
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to write video packet: {}", static_cast<int>(result));
        }
    }
}

ErrorCode VideoRecorder::initializeCapturer() {
    capturer_ = std::make_unique<capture::VideoCapturer>();
    
    // 根据采集方法设置参数
    capture::CapturerType capturerType;
    std::string deviceId;
    
    switch (videoParams_.captureMethod) {
        case VideoCaptureMethod::SCREEN_CAPTURE:
            capturerType = capture::CapturerType::VIDEO_SCREEN;
            deviceId = std::to_string(videoParams_.monitorIndex);
            break;
        case VideoCaptureMethod::WINDOW_CAPTURE:
            capturerType = capture::CapturerType::VIDEO_WINDOW;
            // TODO: 设置窗口句柄
            break;
        case VideoCaptureMethod::CAMERA_CAPTURE:
            capturerType = capture::CapturerType::VIDEO_CAMERA;
            deviceId = videoParams_.deviceId;
            break;
        default:
            capturerType = capture::CapturerType::VIDEO_SCREEN;
            break;
    }
    
    capture::VideoCaptureParams capturerParams(capturerType);
    capturerParams.deviceId = deviceId;
    
    // 设置视频参数
    capturerParams.width = videoParams_.width;
    capturerParams.height = videoParams_.height;
    capturerParams.fps = videoParams_.frameRate;
    capturerParams.pixelFormat = videoParams_.pixelFormat;
    
    // 调试信息：检查参数值
    AV_LOGGER_INFOF("Setting capturer params: width={}, height={}, fps={}", 
                   capturerParams.width, capturerParams.height, capturerParams.fps);
    
    // 确保参数有效
    if (capturerParams.width <= 0 || capturerParams.height <= 0) {
        AV_LOGGER_ERRORF("Invalid video dimensions from videoParams_: {}x{}", 
                        videoParams_.width, videoParams_.height);
        // 使用默认值
        capturerParams.width = 1920;
        capturerParams.height = 1080;
        AV_LOGGER_INFOF("Using default dimensions: {}x{}", 
                       capturerParams.width, capturerParams.height);
    }
    
    // 根据采集方法设置特定参数
    switch (videoParams_.captureMethod) {
        case VideoCaptureMethod::SCREEN_CAPTURE:
            capturerParams.screenIndex = videoParams_.monitorIndex;
            capturerParams.captureCursor = videoParams_.drawCursor;
            break;
        case VideoCaptureMethod::WINDOW_CAPTURE:
            capturerParams.windowHandle = videoParams_.windowHandle;
            capturerParams.captureCursor = videoParams_.drawCursor;
            break;
        case VideoCaptureMethod::CAMERA_CAPTURE:
            capturerParams.cameraIndex = 0; // 默认使用第一个摄像头，可以根据deviceId解析
            break;
    }
    
    ErrorCode result = capturer_->initialize(capturerParams);
    if (result != ErrorCode::SUCCESS) {
        AV_LOGGER_ERRORF("Failed to initialize video capturer: {}", static_cast<int>(result));
        return result;
    }
    
    // 设置回调
    capturer_->setFrameCallback([this](const AVFramePtr& frame) {
        onVideoFrameCaptured(frame);
    });
    
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::initializeEncoder() {
    encoder_ = std::make_unique<codec::VideoEncoder>();
    
    // 创建视频编码器参数
    codec::VideoEncoderParams encoderParams;
    encoderParams.type = MediaType::VIDEO;
    
    // 如果指定的编码器名称无效，则自动选择最佳编码器
    std::string codecName = videoParams_.codecName;
    if (codecName.empty() || codecName == "h264") {
        codecName = codec::VideoEncoder::getRecommendedEncoder();
        if (codecName.empty()) {
            codecName = "libx264";  // 最后的回退选项
        }
        AV_LOGGER_INFOF("Auto-selected encoder: {}", codecName);
    }
    
    encoderParams.codecName = codecName;
    encoderParams.width = videoParams_.width;
    encoderParams.height = videoParams_.height;
    encoderParams.fps = videoParams_.frameRate;
    encoderParams.bitRate = videoParams_.bitrate;  // 注意字段名称差异
    encoderParams.gopSize = videoParams_.keyFrameInterval;  // GOP大小对应关键帧间隔
    encoderParams.maxBFrames = 0;  // 使用默认值，VideoRecorderParams中没有此字段
    encoderParams.preset = videoParams_.preset;
    encoderParams.tune = "";  // 使用默认值，VideoRecorderParams中没有此字段
    encoderParams.lowLatency = false;  // 使用默认值，VideoRecorderParams中没有此字段
    encoderParams.hardwareAccel = true;  // 使用默认值，VideoRecorderParams中没有此字段
    encoderParams.pixelFormat = videoParams_.pixelFormat;
    
    AV_LOGGER_INFOF("Setting encoder params: codec={}, width={}, height={}, fps={}, bitRate={}", 
                   encoderParams.codecName, encoderParams.width, encoderParams.height, 
                   encoderParams.fps, encoderParams.bitRate);
    
    ErrorCode result = encoder_->open(encoderParams);
    if (result != ErrorCode::SUCCESS) {
        AV_LOGGER_ERRORF("Failed to initialize video encoder: {}", static_cast<int>(result));
        return result;
    }
    
    // 更新实际使用的编码器名称
    videoParams_.codecName = codecName;
    AV_LOGGER_INFOF("Updated videoParams_.codecName to: {}", videoParams_.codecName);
    
    return ErrorCode::SUCCESS;
}

ErrorCode VideoRecorder::initializeMuxer() {
    muxer_ = std::make_unique<muxer::FileMuxer>();
    
    // 创建 FileMuxerParams 而不是基类 MuxerParams
    muxer::FileMuxerParams fileMuxerParams;
    fileMuxerParams.outputPath = videoParams_.outputPath;
    fileMuxerParams.outputFile = videoParams_.outputPath;  // FileMuxerParams 需要设置 outputFile
    fileMuxerParams.format = videoParams_.format;
    fileMuxerParams.overwrite = true;  // 允许覆盖已存在文件
    fileMuxerParams.enableFastStart = true;  // 启用快速开始
    
    // 添加视频流信息
    muxer::StreamInfo videoStream;
    videoStream.index = 0;
    videoStream.type = muxer::StreamType::VIDEO;
    videoStream.codecName = videoParams_.codecName;
    
    // 从编码器获取 codecId
    const AVCodec* codec = avcodec_find_encoder_by_name(videoParams_.codecName.c_str());
    if (codec) {
        videoStream.codecId = codec->id;
        AV_LOGGER_INFOF("设置编解码器ID: {} ({})", static_cast<int>(codec->id), codec->name);
    } else {
        AV_LOGGER_ERRORF("无法找到编码器: {}", videoParams_.codecName);
        return ErrorCode::CODEC_NOT_FOUND;
    }
    
    videoStream.width = videoParams_.width;
    videoStream.height = videoParams_.height;
    videoStream.frameRate = {static_cast<int>(videoParams_.frameRate), 1};
    videoStream.pixelFormat = videoParams_.pixelFormat;
    videoStream.bitrate = videoParams_.bitrate;
    videoStream.timeBase = {1, static_cast<int>(videoParams_.frameRate)};
    
    fileMuxerParams.streams.push_back(videoStream);
    
    AV_LOGGER_INFOF("Initializing muxer with outputFile: {}, format: {}, video stream: {}x{}@{}fps, codecId: {}", 
                   fileMuxerParams.outputFile, fileMuxerParams.format, 
                   videoStream.width, videoStream.height, videoParams_.frameRate, 
                   static_cast<int>(videoStream.codecId));
    
    ErrorCode result = muxer_->initialize(fileMuxerParams);
    if (result != ErrorCode::SUCCESS) {
        AV_LOGGER_ERRORF("Failed to initialize muxer: {}", static_cast<int>(result));
        return result;
    }
    
    return ErrorCode::SUCCESS;
}

AVFramePtr VideoRecorder::processVideoFrame(AVFramePtr frame) {
    if (!frame) {
        return nullptr;
    }
    
    // TODO: 实现视频帧处理（缩放、格式转换等）
    // 使用移动语义转移所有权，避免拷贝
    // 如果将来需要修改帧数据，再考虑创建副本
    return std::move(frame);
}

void VideoRecorder::calculateActualFrameRate() {
    auto now = std::chrono::steady_clock::now();
    frameTimestamps_.push_back(now);
    
    // 保持队列大小
    while (frameTimestamps_.size() > MAX_FRAME_TIMESTAMPS) {
        frameTimestamps_.pop_front();
    }
    
    // 计算帧率
    if (frameTimestamps_.size() >= 2) {
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
            frameTimestamps_.back() - frameTimestamps_.front()).count();
        
        if (duration > 0) {
            double fps = (frameTimestamps_.size() - 1) * 1000.0 / duration;
            
            std::lock_guard<std::mutex> lock(statsMutex_);
            captureStats_.actualFrameRate = fps;
        }
    }
}

bool VideoRecorder::checkOverload() const {
    // 检查编码时间是否超过帧间隔
    double frameIntervalMs = 1000.0 / videoParams_.frameRate;
    return (avgCaptureTime_ + avgEncodeTime_) > (frameIntervalMs * 0.8); // 80%阈值
}

void VideoRecorder::cleanup() {
    shouldStop_ = true;
    
    // 停止处理线程
    frameCondition_.notify_all();
    
    if (processingThread_ && processingThread_->joinable()) {
        processingThread_->join();
        processingThread_.reset();
    }
    
    if (frameRateThread_ && frameRateThread_->joinable()) {
        frameRateThread_->join();
        frameRateThread_.reset();
    }
    
    // 清理采集器
    if (capturer_) {
        capturer_->stop();
        capturer_->close();
        capturer_.reset();
    }
    
    // 清理编码器
    if (encoder_) {
        encoder_->close();
        encoder_.reset();
    }
    
    // 清理复用器
    if (muxer_) {
        muxer_->close();
        muxer_.reset();
    }
    
    // 清理线程池
    if (threadPool_) {
        threadPool_.reset();
    }
    
    // 清理帧队列
    if (frameQueue_) {
        frameQueue_->clear();
    }
    
    // 清理当前帧
    {
        std::lock_guard<std::mutex> lock(currentFrameMutex_);
        currentFrame_.reset();
    }
}

} // namespace recorder
} // namespace av
