zhuizhu 8 月之前
父节点
当前提交
ac0fccdba3

+ 1 - 1
AV/.xmake/windows/x64/cache/config

@@ -2,6 +2,6 @@
     recheck = false,
     options = { },
     mtimes = {
-        ["xmake.lua"] = 1753538152
+        ["xmake.lua"] = 1753543374
     }
 }

+ 16 - 16
AV/.xmake/windows/x64/cache/detect

@@ -1,29 +1,29 @@
 {
-    find_program_msvc_arch_x64_plat_windows_checktoolld = {
-        ["link.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\link.exe]]
-    },
-    find_program_msvc_arch_x64_plat_windows_checktoolcc = {
+    find_program = {
+        ["C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\cl.exe]],
+        nim = false,
         ["cl.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\cl.exe]]
     },
-    find_program_msvc_arch_x64_plat_windows_checktoolar = {
+    ["lib.detect.has_flags"] = {
+        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_/W3"] = true,
+        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_-DNDEBUG"] = true,
+        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx__-nologo_-O2"] = true,
+        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_cl_sourceDependencies"] = true,
+        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_/utf-8"] = true
+    },
+    find_program_msvc_arch_x64_plat_windows_checktoolld = {
         ["link.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\link.exe]]
     },
     find_program_msvc_arch_x64_plat_windows_checktoolcxx = {
         ["cl.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\cl.exe]]
     },
-    find_program = {
-        ["C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\cl.exe]],
-        ["cl.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\cl.exe]],
-        nim = false
-    },
     find_programver = {
         ["C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe"] = "19.39.33523"
     },
-    ["lib.detect.has_flags"] = {
-        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_-DNDEBUG"] = true,
-        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_/utf-8"] = true,
-        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_cl_sourceDependencies"] = true,
-        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx_cxflags_-nologo_/W3"] = true,
-        ["windows_x64_C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe_19.39.33523_cxx__-nologo_-O2"] = true
+    find_program_msvc_arch_x64_plat_windows_checktoolar = {
+        ["link.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\link.exe]]
+    },
+    find_program_msvc_arch_x64_plat_windows_checktoolcc = {
+        ["cl.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\cl.exe]]
     }
 }

+ 50 - 29
AV/.xmake/windows/x64/cache/history

@@ -1,33 +1,5 @@
 {
     cmdlines = {
-        [[xmake lua "D:\\\\Program Files\\\\xmake\\\\modules\\\\private\\\\utils\\\\statistics.lua"]],
-        [[xmake lua "D:\\\\Program Files\\\\xmake\\\\actions\\\\build\\\\cleaner.lua"]],
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake -r",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
-        "xmake ",
         "xmake ",
         "xmake ",
         "xmake ",
@@ -43,6 +15,55 @@
         "xmake build test_audio_encoder",
         "xmake build test_audio_encoder",
         "xmake build test_audio_encoder",
-        "xmake build test_audio_encoder"
+        "xmake build test_audio_encoder",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake build test_window_capture",
+        "xmake run test_window_capture",
+        "xmake build test_window_capture",
+        "xmake run test_window_capture",
+        "xmake run test_window_capture",
+        "xmake build test_window_capture",
+        "xmake run test_window_capture",
+        "xmake build test_window_capture",
+        "xmake run test_window_capture",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build av_utils",
+        "xmake build",
+        "xmake build test_utils",
+        "xmake build test_utils",
+        "xmake build test_utils",
+        "xmake build",
+        "xmake build test_utils",
+        "xmake build test_utils",
+        "xmake build test_utils",
+        "xmake build test_utils"
     }
 }

文件差异内容过多而无法显示
+ 146 - 9
AV/.xmake/windows/x64/cache/toolchain


+ 14 - 3
AV/AV.pri

@@ -10,7 +10,12 @@ HEADERS += \
     $$PWD/code/codec/codec_audio_decoder.h \
     $$PWD/code/codec/codec_audio_encoder.h \
     $$PWD/code/codec/codec_video_decoder.h \
-    $$PWD/code/codec/codec_video_encoder.h
+    $$PWD/code/codec/codec_video_encoder.h \
+    $$PWD/code/utils/utils_frame_queue.h \
+    $$PWD/code/utils/utils_packet_queue.h \
+    $$PWD/code/utils/utils_performance_monitor.h \
+    $$PWD/code/utils/utils_synchronizer.h \
+    $$PWD/code/utils/utils_thread_pool.h
 
 SOURCES += \
     $$PWD/code/base/media_common.cpp \
@@ -23,14 +28,20 @@ SOURCES += \
     $$PWD/code/codec/codec_audio_decoder.cpp \
     $$PWD/code/codec/codec_audio_encoder.cpp \
     $$PWD/code/codec/codec_video_decoder.cpp \
-    $$PWD/code/codec/codec_video_encoder.cpp
+    $$PWD/code/codec/codec_video_encoder.cpp \
+    $$PWD/code/utils/utils_frame_queue.cpp \
+    $$PWD/code/utils/utils_packet_queue.cpp \
+    $$PWD/code/utils/utils_performance_monitor.cpp \
+    $$PWD/code/utils/utils_synchronizer.cpp \
+    $$PWD/code/utils/utils_thread_pool.cpp
 
 
 # SOURCES += $$PWD/test_basic.cpp
 # SOURCES += $$PWD/test_codec.cpp
 # SOURCES += $$PWD/test_decoder.cpp
 # SOURCES += $$PWD/test_audio_encoder.cpp
-SOURCES += $$PWD/test_window_capture.cpp
+# SOURCES += $$PWD/test_window_capture.cpp
+SOURCES += $$PWD/test_utils.cpp
 
 
 

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

@@ -95,6 +95,20 @@ enum class ErrorCode {
     QUEUE_FULL,
     DEVICE_NOT_FOUND,
     END_OF_STREAM,
+    ALREADY_EXISTS,
+    NOT_FOUND,
+    TIMEOUT,
+    COPY_FAILED,
+    INVALID_PARAMETER,
+    NOT_STARTED,
+    NOT_PAUSED,
+    ALREADY_INITIALIZED,
+    NOT_INITIALIZED,
+    ALREADY_STARTED,
+    ALREADY_PAUSED,
+    INITIALIZATION_FAILED,
+    FILE_OPERATION_FAILED,
+    OPERATION_FAILED,
     UNKNOWN_ERROR
 };
 

+ 26 - 26
AV/code/utils/utils_frame_queue.cpp

@@ -6,11 +6,11 @@
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 FrameQueue::FrameQueue(const FrameQueueConfig& config)
     : config_(config) {
-    Logger::debug("FrameQueue created with max size: {}", config_.maxSize);
+    Logger::instance().debugf("FrameQueue created with max size: {}", config_.maxSize);
 }
 
 FrameQueue::~FrameQueue() {
@@ -18,7 +18,7 @@ FrameQueue::~FrameQueue() {
     notEmpty_.notify_all();
     notFull_.notify_all();
     clear();
-    Logger::debug("FrameQueue destroyed");
+    Logger::instance().debug("FrameQueue destroyed");
 }
 
 ErrorCode FrameQueue::enqueue(std::unique_ptr<FrameQueueItem> item) {
@@ -41,7 +41,7 @@ ErrorCode FrameQueue::enqueue(std::unique_ptr<FrameQueueItem> item) {
         std::lock_guard<std::mutex> statsLock(statsMutex_);
         stats_.totalDropped++;
         
-        Logger::debug("Frame dropped by smart drop policy");
+        Logger::instance().debug("Frame dropped by smart drop policy");
         return ErrorCode::SUCCESS;
     }
     
@@ -58,14 +58,14 @@ ErrorCode FrameQueue::enqueue(std::unique_ptr<FrameQueueItem> item) {
                 std::lock_guard<std::mutex> statsLock(statsMutex_);
                 stats_.totalDropped++;
                 
-                Logger::debug("Frame dropped - queue full");
+                Logger::instance().debug("Frame dropped - queue full");
                 return ErrorCode::SUCCESS;
             }
         } else {
             // 等待队列有空间
             if (!notFull_.wait_for(lock, std::chrono::milliseconds(config_.timeoutMs),
                                   [this] { return queue_.size() < config_.maxSize || shutdown_; })) {
-                Logger::warning("Enqueue timeout");
+                Logger::instance().warning("Enqueue timeout");
                 return ErrorCode::TIMEOUT;
             }
             
@@ -173,7 +173,7 @@ void FrameQueue::clear() {
         queue_.pop();
     }
     
-    Logger::debug("Frame queue cleared");
+    Logger::instance().debug("Frame queue cleared");
 }
 
 void FrameQueue::flush() {
@@ -195,13 +195,13 @@ void FrameQueue::setMaxSize(size_t maxSize) {
         }
     }
     
-    Logger::debug("Frame queue max size set to: {}", maxSize);
+    Logger::instance().debugf("Frame queue max size set to: {}", maxSize);
 }
 
 void FrameQueue::setDropPolicy(bool dropOnFull, bool dropOldest) {
     config_.dropOnFull = dropOnFull;
     config_.dropOldest = dropOldest;
-    Logger::debug("Drop policy set: dropOnFull={}, dropOldest={}", dropOnFull, dropOldest);
+    Logger::instance().debugf("Drop policy set: dropOnFull={}, dropOldest={}", dropOnFull, dropOldest);
 }
 
 size_t FrameQueue::size() const {
@@ -233,7 +233,7 @@ FrameQueueStats FrameQueue::getStats() const {
 void FrameQueue::resetStats() {
     std::lock_guard<std::mutex> lock(statsMutex_);
     stats_ = FrameQueueStats();
-    Logger::debug("Frame queue stats reset");
+    Logger::instance().debug("Frame queue stats reset");
 }
 
 void FrameQueue::enableFrameDrop(bool enable, double maxLatency, int dropRatio) {
@@ -241,7 +241,7 @@ void FrameQueue::enableFrameDrop(bool enable, double maxLatency, int dropRatio)
     config_.maxLatency = maxLatency;
     config_.dropRatio = dropRatio;
     
-    Logger::debug("Frame drop enabled: {}, maxLatency: {}ms, dropRatio: {}", 
+    Logger::instance().debugf("Frame drop enabled: {}, maxLatency: {}ms, dropRatio: {}", 
                  enable, maxLatency, dropRatio);
 }
 
@@ -255,7 +255,7 @@ void FrameQueue::setBlocking(bool blocking) {
         notEmpty_.notify_all();
         notFull_.notify_all();
     }
-    Logger::debug("Frame queue blocking mode: {}", blocking);
+    Logger::instance().debugf("Frame queue blocking mode: {}", blocking);
 }
 
 void FrameQueue::wakeup() {
@@ -300,7 +300,7 @@ void FrameQueue::dropOldestFrame() {
         std::lock_guard<std::mutex> statsLock(statsMutex_);
         stats_.totalDropped++;
         
-        Logger::debug("Dropped oldest frame");
+        Logger::instance().debug("Dropped oldest frame");
     }
 }
 
@@ -359,24 +359,24 @@ bool FrameQueue::shouldDropByRatio() const {
 // 多流帧队列实现
 MultiStreamFrameQueue::MultiStreamFrameQueue(const FrameQueueConfig& config)
     : defaultConfig_(config) {
-    Logger::debug("MultiStreamFrameQueue created");
+    Logger::instance().debug("MultiStreamFrameQueue created");
 }
 
 MultiStreamFrameQueue::~MultiStreamFrameQueue() {
     clear();
-    Logger::debug("MultiStreamFrameQueue destroyed");
+    Logger::instance().debug("MultiStreamFrameQueue destroyed");
 }
 
 ErrorCode MultiStreamFrameQueue::addStream(int streamIndex, const FrameQueueConfig& config) {
     std::unique_lock<std::shared_mutex> lock(streamsMutex_);
     
     if (streamQueues_.find(streamIndex) != streamQueues_.end()) {
-        Logger::warning("Stream {} already exists", streamIndex);
+        Logger::instance().warningf("Stream {} already exists", streamIndex);
         return ErrorCode::ALREADY_EXISTS;
     }
     
     streamQueues_[streamIndex] = std::make_unique<FrameQueue>(config);
-    Logger::debug("Added stream: {}", streamIndex);
+    Logger::instance().debugf("Added stream: {}", streamIndex);
     
     return ErrorCode::SUCCESS;
 }
@@ -386,12 +386,12 @@ ErrorCode MultiStreamFrameQueue::removeStream(int streamIndex) {
     
     auto it = streamQueues_.find(streamIndex);
     if (it == streamQueues_.end()) {
-        Logger::warning("Stream {} not found", streamIndex);
+        Logger::instance().warningf("Stream {} not found", streamIndex);
         return ErrorCode::NOT_FOUND;
     }
     
     streamQueues_.erase(it);
-    Logger::debug("Removed stream: {}", streamIndex);
+    Logger::instance().debugf("Removed stream: {}", streamIndex);
     
     return ErrorCode::SUCCESS;
 }
@@ -500,7 +500,7 @@ void MultiStreamFrameQueue::clear() {
         pair.second->clear();
     }
     
-    Logger::debug("All stream queues cleared");
+    Logger::instance().debug("All stream queues cleared");
 }
 
 void MultiStreamFrameQueue::clearStream(int streamIndex) {
@@ -509,7 +509,7 @@ void MultiStreamFrameQueue::clearStream(int streamIndex) {
     auto it = streamQueues_.find(streamIndex);
     if (it != streamQueues_.end()) {
         it->second->clear();
-        Logger::debug("Stream {} queue cleared", streamIndex);
+        Logger::instance().debugf("Stream {} queue cleared", streamIndex);
     }
 }
 
@@ -520,7 +520,7 @@ void MultiStreamFrameQueue::flush() {
         pair.second->flush();
     }
     
-    Logger::debug("All stream queues flushed");
+    Logger::instance().debug("All stream queues flushed");
 }
 
 void MultiStreamFrameQueue::flushStream(int streamIndex) {
@@ -529,7 +529,7 @@ void MultiStreamFrameQueue::flushStream(int streamIndex) {
     auto it = streamQueues_.find(streamIndex);
     if (it != streamQueues_.end()) {
         it->second->flush();
-        Logger::debug("Stream {} queue flushed", streamIndex);
+        Logger::instance().debugf("Stream {} queue flushed", streamIndex);
     }
 }
 
@@ -607,7 +607,7 @@ void MultiStreamFrameQueue::resetStats() {
         pair.second->resetStats();
     }
     
-    Logger::debug("All stream queue stats reset");
+    Logger::instance().debug("All stream queue stats reset");
 }
 
 void MultiStreamFrameQueue::resetStats(int streamIndex) {
@@ -616,7 +616,7 @@ void MultiStreamFrameQueue::resetStats(int streamIndex) {
     auto it = streamQueues_.find(streamIndex);
     if (it != streamQueues_.end()) {
         it->second->resetStats();
-        Logger::debug("Stream {} queue stats reset", streamIndex);
+        Logger::instance().debugf("Stream {} queue stats reset", streamIndex);
     }
 }
 
@@ -627,7 +627,7 @@ void MultiStreamFrameQueue::setBlocking(bool blocking) {
         pair.second->setBlocking(blocking);
     }
     
-    Logger::debug("All stream queues blocking mode: {}", blocking);
+    Logger::instance().debugf("All stream queues blocking mode: {}", blocking);
 }
 
 void MultiStreamFrameQueue::wakeupAll() {

+ 2 - 2
AV/code/utils/utils_frame_queue.h

@@ -21,7 +21,7 @@ extern "C" {
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // 帧队列项
 struct FrameQueueItem {
@@ -192,7 +192,7 @@ private:
     FrameQueueStats stats_;
     
     // 丢帧控制
-    std::atomic<uint64_t> frameCounter_{0};
+    mutable std::atomic<uint64_t> frameCounter_{0};
     std::function<bool(const FrameQueueItem&)> frameDropCallback_;
     
     // 回调函数

+ 40 - 37
AV/code/utils/utils_packet_queue.cpp

@@ -1,16 +1,16 @@
 #include "utils_packet_queue.h"
-#include "../base/base_logger.h"
+#include "../base/logger.h"
 #include <algorithm>
 #include <shared_mutex>
 
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 PacketQueue::PacketQueue(const PacketQueueConfig& config)
     : config_(config) {
-    Logger::debug("PacketQueue created with max size: {}, max bytes: {}", 
+    Logger::instance().debugf("PacketQueue created with max size: {}, max bytes: {}", 
                  config_.maxSize, config_.maxBytes);
 }
 
@@ -19,7 +19,7 @@ PacketQueue::~PacketQueue() {
     notEmpty_.notify_all();
     notFull_.notify_all();
     clear();
-    Logger::debug("PacketQueue destroyed");
+    Logger::instance().debug("PacketQueue destroyed");
 }
 
 ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
@@ -33,7 +33,7 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
     
     // 检查流过滤
     if (!isStreamAllowed(item->streamIndex)) {
-        Logger::debug("Packet dropped - stream {} not allowed", item->streamIndex);
+        Logger::instance().debugf("Packet dropped - stream {} not allowed", item->streamIndex);
         return ErrorCode::SUCCESS;
     }
     
@@ -48,7 +48,7 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
         std::lock_guard<std::mutex> statsLock(statsMutex_);
         stats_.totalDropped++;
         
-        Logger::debug("Packet dropped by smart drop policy");
+        Logger::instance().debug("Packet dropped by smart drop policy");
         return ErrorCode::SUCCESS;
     }
     
@@ -73,7 +73,7 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
                 std::lock_guard<std::mutex> statsLock(statsMutex_);
                 stats_.totalDropped++;
                 
-                Logger::debug("Packet dropped - queue full");
+                Logger::instance().debug("Packet dropped - queue full");
                 return ErrorCode::SUCCESS;
             }
         } else {
@@ -84,7 +84,7 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
                                       size_t newBytes = totalBytes_.load();
                                       return (newSize < config_.maxSize && newBytes < config_.maxBytes) || shutdown_; 
                                   })) {
-                Logger::warning("Enqueue timeout");
+                Logger::instance().warning("Enqueue timeout");
                 return ErrorCode::TIMEOUT;
             }
             
@@ -99,6 +99,9 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
         totalBytes_ += item->packet->size;
     }
     
+    // 在move之前保存item的引用,用于后续的统计和回调
+    const PacketQueueItem& itemRef = *item;
+    
     // 添加到队列
     if (config_.priorityQueue) {
         enqueueToPriorityQueue(std::move(item));
@@ -108,7 +111,7 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
     
     // 更新统计信息
     if (config_.enableStats) {
-        updateStats(*item, true);
+        updateStats(itemRef, true);
     }
     
     // 通知等待的消费者
@@ -116,7 +119,7 @@ ErrorCode PacketQueue::enqueue(std::unique_ptr<PacketQueueItem> item) {
     
     // 回调
     if (enqueueCallback_) {
-        enqueueCallback_(*item);
+        enqueueCallback_(itemRef);
     }
     
     return ErrorCode::SUCCESS;
@@ -227,7 +230,7 @@ ErrorCode PacketQueue::enqueueWithPriority(AVPacket* packet, int priority, int s
 
 std::unique_ptr<PacketQueueItem> PacketQueue::dequeueHighestPriority() {
     if (!config_.priorityQueue) {
-        Logger::warning("Priority queue not enabled");
+        Logger::instance().warning("Priority queue not enabled");
         return dequeue();
     }
     
@@ -248,7 +251,7 @@ void PacketQueue::clear() {
     }
     
     totalBytes_ = 0;
-    Logger::debug("Packet queue cleared");
+    Logger::instance().debug("Packet queue cleared");
 }
 
 void PacketQueue::flush() {
@@ -272,18 +275,18 @@ void PacketQueue::setMaxSize(size_t maxSize) {
         currentSize = config_.priorityQueue ? priorityQueue_.size() : normalQueue_.size();
     }
     
-    Logger::debug("Packet queue max size set to: {}", maxSize);
+    Logger::instance().debugf("Packet queue max size set to: {}", maxSize);
 }
 
 void PacketQueue::setMaxBytes(size_t maxBytes) {
     config_.maxBytes = maxBytes;
-    Logger::debug("Packet queue max bytes set to: {}", maxBytes);
+    Logger::instance().debugf("Packet queue max bytes set to: {}", maxBytes);
 }
 
 void PacketQueue::setDropPolicy(bool dropOnFull, bool dropOldest) {
     config_.dropOnFull = dropOnFull;
     config_.dropOldest = dropOldest;
-    Logger::debug("Drop policy set: dropOnFull={}, dropOldest={}", dropOnFull, dropOldest);
+    Logger::instance().debugf("Drop policy set: dropOnFull={}, dropOldest={}", dropOnFull, dropOldest);
 }
 
 void PacketQueue::enablePriorityQueue(bool enable) {
@@ -321,7 +324,7 @@ void PacketQueue::enablePriorityQueue(bool enable) {
     }
     
     config_.priorityQueue = enable;
-    Logger::debug("Priority queue {}", enable ? "enabled" : "disabled");
+    Logger::instance().debugf("Priority queue {}", enable ? "enabled" : "disabled");
 }
 
 size_t PacketQueue::size() const {
@@ -367,7 +370,7 @@ PacketQueueStats PacketQueue::getStats() const {
 void PacketQueue::resetStats() {
     std::lock_guard<std::mutex> lock(statsMutex_);
     stats_ = PacketQueueStats();
-    Logger::debug("Packet queue stats reset");
+    Logger::instance().debug("Packet queue stats reset");
 }
 
 void PacketQueue::enablePacketDrop(bool enable, double maxLatency, int dropRatio) {
@@ -375,7 +378,7 @@ void PacketQueue::enablePacketDrop(bool enable, double maxLatency, int dropRatio
     config_.maxLatency = maxLatency;
     config_.dropRatio = dropRatio;
     
-    Logger::debug("Packet drop enabled: {}, maxLatency: {}ms, dropRatio: {}", 
+    Logger::instance().debugf("Packet drop enabled: {}, maxLatency: {}ms, dropRatio: {}", 
                  enable, maxLatency, dropRatio);
 }
 
@@ -389,7 +392,7 @@ void PacketQueue::setBlocking(bool blocking) {
         notEmpty_.notify_all();
         notFull_.notify_all();
     }
-    Logger::debug("Packet queue blocking mode: {}", blocking);
+    Logger::instance().debugf("Packet queue blocking mode: {}", blocking);
 }
 
 void PacketQueue::wakeup() {
@@ -401,14 +404,14 @@ void PacketQueue::setStreamFilter(const std::vector<int>& allowedStreams) {
     std::lock_guard<std::mutex> lock(streamFilterMutex_);
     allowedStreams_ = allowedStreams;
     hasStreamFilter_ = !allowedStreams.empty();
-    Logger::debug("Stream filter set with {} allowed streams", allowedStreams.size());
+    Logger::instance().debugf("Stream filter set with {} allowed streams", allowedStreams.size());
 }
 
 void PacketQueue::clearStreamFilter() {
     std::lock_guard<std::mutex> lock(streamFilterMutex_);
     allowedStreams_.clear();
     hasStreamFilter_ = false;
-    Logger::debug("Stream filter cleared");
+    Logger::instance().debug("Stream filter cleared");
 }
 
 // 内部方法实现
@@ -458,7 +461,7 @@ void PacketQueue::dropOldestPacket() {
             std::lock_guard<std::mutex> statsLock(statsMutex_);
             stats_.totalDropped++;
             
-            Logger::debug("Dropped oldest packet from priority queue");
+            Logger::instance().debug("Dropped oldest packet from priority queue");
         }
     } else {
         if (!normalQueue_.empty()) {
@@ -477,7 +480,7 @@ void PacketQueue::dropOldestPacket() {
             std::lock_guard<std::mutex> statsLock(statsMutex_);
             stats_.totalDropped++;
             
-            Logger::debug("Dropped oldest packet from normal queue");
+            Logger::instance().debug("Dropped oldest packet from normal queue");
         }
     }
 }
@@ -547,7 +550,7 @@ void PacketQueue::dropNonKeyPackets() {
         }
     }
     
-    Logger::debug("Dropped non-key packets, kept {} key packets", keyPackets.size());
+    Logger::instance().debugf("Dropped non-key packets, kept {} key packets", keyPackets.size());
 }
 
 void PacketQueue::updateStats(const PacketQueueItem& item, bool isEnqueue) {
@@ -652,24 +655,24 @@ std::unique_ptr<PacketQueueItem> PacketQueue::dequeueFromPriorityQueue() {
 // 多流包队列实现
 MultiStreamPacketQueue::MultiStreamPacketQueue(const PacketQueueConfig& config)
     : defaultConfig_(config) {
-    Logger::debug("MultiStreamPacketQueue created");
+    Logger::instance().debug("MultiStreamPacketQueue created");
 }
 
 MultiStreamPacketQueue::~MultiStreamPacketQueue() {
     clear();
-    Logger::debug("MultiStreamPacketQueue destroyed");
+    Logger::instance().debug("MultiStreamPacketQueue destroyed");
 }
 
 ErrorCode MultiStreamPacketQueue::addStream(int streamIndex, const PacketQueueConfig& config) {
     std::unique_lock<std::shared_mutex> lock(streamsMutex_);
     
     if (streamQueues_.find(streamIndex) != streamQueues_.end()) {
-        Logger::warning("Stream {} already exists", streamIndex);
+        Logger::instance().warningf("Stream {} already exists", streamIndex);
         return ErrorCode::ALREADY_EXISTS;
     }
     
     streamQueues_[streamIndex] = std::make_unique<PacketQueue>(config);
-    Logger::debug("Added stream: {}", streamIndex);
+    Logger::instance().debugf("Added stream: {}", streamIndex);
     
     return ErrorCode::SUCCESS;
 }
@@ -679,12 +682,12 @@ ErrorCode MultiStreamPacketQueue::removeStream(int streamIndex) {
     
     auto it = streamQueues_.find(streamIndex);
     if (it == streamQueues_.end()) {
-        Logger::warning("Stream {} not found", streamIndex);
+        Logger::instance().warningf("Stream {} not found", streamIndex);
         return ErrorCode::NOT_FOUND;
     }
     
     streamQueues_.erase(it);
-    Logger::debug("Removed stream: {}", streamIndex);
+    Logger::instance().debugf("Removed stream: {}", streamIndex);
     
     return ErrorCode::SUCCESS;
 }
@@ -864,7 +867,7 @@ void MultiStreamPacketQueue::clear() {
         }
     }
     
-    Logger::debug("All stream queues cleared");
+    Logger::instance().debug("All stream queues cleared");
 }
 
 void MultiStreamPacketQueue::clearStream(int streamIndex) {
@@ -873,7 +876,7 @@ void MultiStreamPacketQueue::clearStream(int streamIndex) {
     auto it = streamQueues_.find(streamIndex);
     if (it != streamQueues_.end()) {
         it->second->clear();
-        Logger::debug("Stream {} queue cleared", streamIndex);
+        Logger::instance().debugf("Stream {} queue cleared", streamIndex);
     }
 }
 
@@ -884,7 +887,7 @@ void MultiStreamPacketQueue::flush() {
         pair.second->flush();
     }
     
-    Logger::debug("All stream queues flushed");
+    Logger::instance().debug("All stream queues flushed");
 }
 
 void MultiStreamPacketQueue::flushStream(int streamIndex) {
@@ -893,7 +896,7 @@ void MultiStreamPacketQueue::flushStream(int streamIndex) {
     auto it = streamQueues_.find(streamIndex);
     if (it != streamQueues_.end()) {
         it->second->flush();
-        Logger::debug("Stream {} queue flushed", streamIndex);
+        Logger::instance().debugf("Stream {} queue flushed", streamIndex);
     }
 }
 
@@ -993,7 +996,7 @@ void MultiStreamPacketQueue::resetStats() {
         pair.second->resetStats();
     }
     
-    Logger::debug("All stream queue stats reset");
+    Logger::instance().debug("All stream queue stats reset");
 }
 
 void MultiStreamPacketQueue::resetStats(int streamIndex) {
@@ -1002,7 +1005,7 @@ void MultiStreamPacketQueue::resetStats(int streamIndex) {
     auto it = streamQueues_.find(streamIndex);
     if (it != streamQueues_.end()) {
         it->second->resetStats();
-        Logger::debug("Stream {} queue stats reset", streamIndex);
+        Logger::instance().debugf("Stream {} queue stats reset", streamIndex);
     }
 }
 
@@ -1013,7 +1016,7 @@ void MultiStreamPacketQueue::setBlocking(bool blocking) {
         pair.second->setBlocking(blocking);
     }
     
-    Logger::debug("All stream queues blocking mode: {}", blocking);
+    Logger::instance().debugf("All stream queues blocking mode: {}", blocking);
 }
 
 void MultiStreamPacketQueue::wakeupAll() {

+ 5 - 2
AV/code/utils/utils_packet_queue.h

@@ -4,11 +4,14 @@
 #include "../base/types.h"
 #include <queue>
 #include <mutex>
+#include <shared_mutex>
 #include <condition_variable>
 #include <atomic>
 #include <chrono>
 #include <memory>
 #include <functional>
+#include <map>
+#include <vector>
 
 extern "C" {
 #include <libavcodec/packet.h>
@@ -18,7 +21,7 @@ extern "C" {
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // 包队列项
 struct PacketQueueItem {
@@ -245,7 +248,7 @@ private:
     PacketQueueStats stats_;
     
     // 丢包控制
-    std::atomic<uint64_t> packetCounter_{0};
+    mutable std::atomic<uint64_t> packetCounter_{0};
     std::function<bool(const PacketQueueItem&)> packetDropCallback_;
     
     // 流过滤

+ 16 - 15
AV/code/utils/utils_performance_monitor.cpp

@@ -1,11 +1,12 @@
 #include "utils_performance_monitor.h"
-#include "../base/base_logger.h"
+#include "../base/logger.h"
 #include <algorithm>
 #include <sstream>
 #include <fstream>
 #include <iomanip>
 #include <thread>
 #include <cmath>
+#include <chrono>
 
 #ifdef _WIN32
 #include <windows.h>
@@ -22,7 +23,7 @@
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // PerformanceMonitor 实现
 PerformanceMonitor::PerformanceMonitor(const MonitorConfig& config)
@@ -58,11 +59,11 @@ ErrorCode PerformanceMonitor::initialize() {
         lastReportTime_ = startTime_;
         
         initialized_.store(true);
-        LOG_INFO("Performance monitor initialized successfully");
+        Logger::instance().info("Performance monitor initialized successfully");
         
         return ErrorCode::SUCCESS;
     } catch (const std::exception& e) {
-        LOG_ERROR("Failed to initialize performance monitor: {}", e.what());
+        Logger::instance().errorf("Failed to initialize performance monitor: {}", e.what());
         return ErrorCode::INITIALIZATION_FAILED;
     }
 }
@@ -79,7 +80,7 @@ ErrorCode PerformanceMonitor::start() {
     running_.store(true);
     monitoring_.store(config_.enableMonitoring);
     
-    LOG_INFO("Performance monitor started");
+    Logger::instance().info("Performance monitor started");
     return ErrorCode::SUCCESS;
 }
 
@@ -91,7 +92,7 @@ ErrorCode PerformanceMonitor::stop() {
     running_.store(false);
     monitoring_.store(false);
     
-    LOG_INFO("Performance monitor stopped");
+    Logger::instance().info("Performance monitor stopped");
     return ErrorCode::SUCCESS;
 }
 
@@ -104,7 +105,7 @@ ErrorCode PerformanceMonitor::reset() {
     startTime_ = std::chrono::steady_clock::now();
     lastReportTime_ = startTime_;
     
-    LOG_INFO("Performance monitor reset");
+    Logger::instance().info("Performance monitor reset");
     return ErrorCode::SUCCESS;
 }
 
@@ -124,7 +125,7 @@ ErrorCode PerformanceMonitor::close() {
     
     initialized_.store(false);
     
-    LOG_INFO("Performance monitor closed");
+    Logger::instance().info("Performance monitor closed");
     return ErrorCode::SUCCESS;
 }
 
@@ -153,7 +154,7 @@ ErrorCode PerformanceMonitor::registerMetric(const std::string& name, MetricType
     }
     
     if (config_.enableLogging) {
-        LOG_DEBUG("Registered metric: {} (type: {})", name, static_cast<int>(type));
+        Logger::instance().debugf("Registered metric: {} (type: {})", name, static_cast<int>(type));
     }
     
     return ErrorCode::SUCCESS;
@@ -174,7 +175,7 @@ ErrorCode PerformanceMonitor::unregisterMetric(const std::string& name) {
     historyData_.erase(name);
     
     if (config_.enableLogging) {
-        LOG_DEBUG("Unregistered metric: {}", name);
+        Logger::instance().debugf("Unregistered metric: {}", name);
     }
     
     return ErrorCode::SUCCESS;
@@ -490,7 +491,7 @@ ErrorCode PerformanceMonitor::exportToFile(const std::string& filename) const {
         
         return ErrorCode::SUCCESS;
     } catch (const std::exception& e) {
-        LOG_ERROR("Failed to export performance report: {}", e.what());
+        Logger::instance().errorf("Failed to export performance report: {}", e.what());
         return ErrorCode::FILE_OPERATION_FAILED;
     }
 }
@@ -567,7 +568,7 @@ void PerformanceMonitor::checkAlerts(const std::string& name, double value) {
 }
 
 void PerformanceMonitor::logMetricUpdate(const std::string& name, double value) {
-    LOG_DEBUG("Metric updated: {} = {}", name, value);
+    Logger::instance().debugf("Metric updated: {} = {}", name, value);
 }
 
 void PerformanceMonitor::updateStatistics(PerformanceStats& stats, double value) {
@@ -580,8 +581,8 @@ void PerformanceMonitor::updateStatistics(PerformanceStats& stats, double value)
         stats.maxValue = value;
         stats.avgValue = value;
     } else {
-        stats.minValue = std::min(stats.minValue, value);
-        stats.maxValue = std::max(stats.maxValue, value);
+        stats.minValue = (std::min)(stats.minValue, value);
+        stats.maxValue = (std::max)(stats.maxValue, value);
         stats.avgValue = (stats.avgValue * (stats.count - 1) + value) / stats.count;
     }
     
@@ -644,7 +645,7 @@ ErrorCode SystemPerformanceMonitor::collectCpuUsage() {
     
     if (!initialized) {
         PdhOpenQuery(NULL, NULL, &cpuQuery);
-        PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
+        PdhAddEnglishCounterA(cpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
         PdhCollectQueryData(cpuQuery);
         initialized = true;
     }

+ 1 - 1
AV/code/utils/utils_performance_monitor.h

@@ -13,7 +13,7 @@
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // 性能指标类型
 enum class MetricType {

+ 37 - 37
AV/code/utils/utils_synchronizer.cpp

@@ -1,5 +1,5 @@
 #include "utils_synchronizer.h"
-#include "../base/base_logger.h"
+#include "../base/logger.h"
 #include <algorithm>
 #include <cmath>
 #include <shared_mutex>
@@ -7,7 +7,7 @@
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 Synchronizer::Synchronizer(const SyncConfig& config)
     : config_(config)
@@ -27,12 +27,12 @@ Synchronizer::Synchronizer(const SyncConfig& config)
     videoClockHistory_.reserve(config_.smoothingWindow);
     syncErrorHistory_.reserve(config_.smoothingWindow);
     
-    Logger::debug("Synchronizer created with strategy: {}", static_cast<int>(config_.strategy));
+    Logger::instance().debugf("Synchronizer created with strategy: {}", static_cast<int>(config_.strategy));
 }
 
 Synchronizer::~Synchronizer() {
     close();
-    Logger::debug("Synchronizer destroyed");
+    Logger::instance().debug("Synchronizer destroyed");
 }
 
 ErrorCode Synchronizer::initialize() {
@@ -60,7 +60,7 @@ ErrorCode Synchronizer::initialize() {
     state_ = SyncState::IDLE;
     initialized_ = true;
     
-    Logger::info("Synchronizer initialized");
+    Logger::instance().info("Synchronizer initialized");
     return ErrorCode::SUCCESS;
 }
 
@@ -79,7 +79,7 @@ ErrorCode Synchronizer::start() {
     
     startTime_ = std::chrono::steady_clock::now();
     
-    Logger::info("Synchronizer started");
+    Logger::instance().info("Synchronizer started");
     return ErrorCode::SUCCESS;
 }
 
@@ -92,7 +92,7 @@ ErrorCode Synchronizer::stop() {
     paused_ = false;
     state_ = SyncState::IDLE;
     
-    Logger::info("Synchronizer stopped");
+    Logger::instance().info("Synchronizer stopped");
     return ErrorCode::SUCCESS;
 }
 
@@ -114,7 +114,7 @@ ErrorCode Synchronizer::pause() {
     pauseClock(ClockType::VIDEO, true);
     pauseClock(ClockType::EXTERNAL, true);
     
-    Logger::info("Synchronizer paused");
+    Logger::instance().info("Synchronizer paused");
     return ErrorCode::SUCCESS;
 }
 
@@ -138,7 +138,7 @@ ErrorCode Synchronizer::resume() {
     
     state_ = SyncState::SYNCING;
     
-    Logger::info("Synchronizer resumed");
+    Logger::instance().info("Synchronizer resumed");
     return ErrorCode::SUCCESS;
 }
 
@@ -165,7 +165,7 @@ ErrorCode Synchronizer::reset() {
     // 重新选择主时钟
     selectMasterClock();
     
-    Logger::info("Synchronizer reset");
+    Logger::instance().info("Synchronizer reset");
     return ErrorCode::SUCCESS;
 }
 
@@ -176,7 +176,7 @@ ErrorCode Synchronizer::close() {
     
     initialized_ = false;
     
-    Logger::info("Synchronizer closed");
+    Logger::instance().info("Synchronizer closed");
     return ErrorCode::SUCCESS;
 }
 
@@ -413,7 +413,7 @@ void Synchronizer::setConfig(const SyncConfig& config) {
     // 重新选择主时钟
     selectMasterClock();
     
-    Logger::debug("Synchronizer config updated");
+    Logger::instance().debug("Synchronizer config updated");
 }
 
 SyncConfig Synchronizer::getConfig() const {
@@ -426,7 +426,7 @@ void Synchronizer::setSyncStrategy(SyncStrategy strategy) {
     config_.strategy = strategy;
     selectMasterClock();
     
-    Logger::debug("Sync strategy set to: {}", static_cast<int>(strategy));
+    Logger::instance().debugf("Sync strategy set to: {}", static_cast<int>(strategy));
 }
 
 SyncStrategy Synchronizer::getSyncStrategy() const {
@@ -438,14 +438,14 @@ void Synchronizer::setSyncThreshold(double threshold) {
     std::lock_guard<std::mutex> lock(configMutex_);
     config_.syncThreshold = threshold;
     
-    Logger::debug("Sync threshold set to: {}ms", threshold * 1000);
+    Logger::instance().debugf("Sync threshold set to: {}ms", threshold * 1000);
 }
 
 void Synchronizer::setMaxSyncError(double maxError) {
     std::lock_guard<std::mutex> lock(configMutex_);
     config_.maxSyncError = maxError;
     
-    Logger::debug("Max sync error set to: {}ms", maxError * 1000);
+    Logger::instance().debugf("Max sync error set to: {}ms", maxError * 1000);
 }
 
 void Synchronizer::setPlaybackSpeed(double speed) {
@@ -455,7 +455,7 @@ void Synchronizer::setPlaybackSpeed(double speed) {
     videoClock_.speed = speed;
     externalClock_.speed = speed;
     
-    Logger::debug("Playback speed set to: {}x", speed);
+    Logger::instance().debugf("Playback speed set to: {}x", speed);
 }
 
 double Synchronizer::getPlaybackSpeed() const {
@@ -502,7 +502,7 @@ void Synchronizer::resetStats() {
     stats_ = SyncStats();
     stats_.lastUpdateTime = std::chrono::steady_clock::now();
     
-    Logger::debug("Synchronizer stats reset");
+    Logger::instance().debug("Synchronizer stats reset");
 }
 
 void Synchronizer::setSyncEventCallback(SyncEventCallback callback) {
@@ -521,14 +521,14 @@ void Synchronizer::enableAdaptiveSync(bool enable) {
     std::lock_guard<std::mutex> lock(configMutex_);
     config_.enableAdaptiveSync = enable;
     
-    Logger::debug("Adaptive sync {}", enable ? "enabled" : "disabled");
+    Logger::instance().debugf("Adaptive sync {}", enable ? "enabled" : "disabled");
 }
 
 void Synchronizer::setClockUpdateInterval(double interval) {
     std::lock_guard<std::mutex> lock(configMutex_);
     config_.clockUpdateInterval = interval;
     
-    Logger::debug("Clock update interval set to: {}ms", interval * 1000);
+    Logger::instance().debugf("Clock update interval set to: {}ms", interval * 1000);
 }
 
 void Synchronizer::setSmoothingWindow(int window) {
@@ -540,7 +540,7 @@ void Synchronizer::setSmoothingWindow(int window) {
     videoClockHistory_.reserve(window);
     syncErrorHistory_.reserve(window);
     
-    Logger::debug("Smoothing window set to: {}", window);
+    Logger::instance().debugf("Smoothing window set to: {}", window);
 }
 
 // 内部方法实现
@@ -690,7 +690,7 @@ void Synchronizer::handleSyncDrift() {
     
     if (syncError > config_.maxSyncError) {
         // 重置时钟
-        Logger::warning("Sync drift detected, resetting clocks");
+        Logger::instance().warning("Sync drift detected, resetting clocks");
         reset();
     }
 }
@@ -704,7 +704,7 @@ void Synchronizer::notifyStateChange(SyncState newState) {
             syncEventCallback_(newState, calculateSyncError());
         }
         
-        Logger::debug("Sync state changed from {} to {}", 
+        Logger::instance().debugf("Sync state changed from {} to {}", 
                      static_cast<int>(oldState), static_cast<int>(newState));
     }
 }
@@ -867,7 +867,7 @@ void Synchronizer::adjustPlaybackSpeed() {
             audioClock_.speed = newSpeed;
         }
         
-        Logger::debug("Adjusted playback speed to: {}x", newSpeed);
+        Logger::instance().debugf("Adjusted playback speed to: {}x", newSpeed);
     }
 }
 
@@ -894,19 +894,19 @@ MultiStreamSynchronizer::MultiStreamSynchronizer(const SyncConfig& config)
     : defaultConfig_(config)
     , masterStreamIndex_(-1)
     , globalState_(SyncState::IDLE) {
-    Logger::debug("MultiStreamSynchronizer created");
+    Logger::instance().debug("MultiStreamSynchronizer created");
 }
 
 MultiStreamSynchronizer::~MultiStreamSynchronizer() {
     streamSynchronizers_.clear();
-    Logger::debug("MultiStreamSynchronizer destroyed");
+    Logger::instance().debug("MultiStreamSynchronizer destroyed");
 }
 
 ErrorCode MultiStreamSynchronizer::addStream(int streamIndex, ClockType type) {
     std::unique_lock<std::shared_mutex> lock(streamsMutex_);
     
     if (streamSynchronizers_.find(streamIndex) != streamSynchronizers_.end()) {
-        Logger::warning("Stream {} already exists", streamIndex);
+        Logger::instance().warningf("Stream {} already exists", streamIndex);
         return ErrorCode::ALREADY_EXISTS;
     }
     
@@ -921,7 +921,7 @@ ErrorCode MultiStreamSynchronizer::addStream(int streamIndex, ClockType type) {
         masterStreamIndex_ = streamIndex;
     }
     
-    Logger::debug("Added stream: {} with type: {}", streamIndex, static_cast<int>(type));
+    Logger::instance().debugf("Added stream: {} with type: {}", streamIndex, static_cast<int>(type));
     return ErrorCode::SUCCESS;
 }
 
@@ -930,7 +930,7 @@ ErrorCode MultiStreamSynchronizer::removeStream(int streamIndex) {
     
     auto it = streamSynchronizers_.find(streamIndex);
     if (it == streamSynchronizers_.end()) {
-        Logger::warning("Stream {} not found", streamIndex);
+        Logger::instance().warningf("Stream {} not found", streamIndex);
         return ErrorCode::NOT_FOUND;
     }
     
@@ -942,7 +942,7 @@ ErrorCode MultiStreamSynchronizer::removeStream(int streamIndex) {
         updateMasterStream();
     }
     
-    Logger::debug("Removed stream: {}", streamIndex);
+    Logger::instance().debugf("Removed stream: {}", streamIndex);
     return ErrorCode::SUCCESS;
 }
 
@@ -1086,7 +1086,7 @@ void MultiStreamSynchronizer::setConfig(const SyncConfig& config) {
         pair.second->setConfig(config);
     }
     
-    Logger::debug("MultiStreamSynchronizer config updated");
+    Logger::instance().debug("MultiStreamSynchronizer config updated");
 }
 
 SyncConfig MultiStreamSynchronizer::getConfig() const {
@@ -1126,7 +1126,7 @@ void MultiStreamSynchronizer::resetStats() {
         pair.second->resetStats();
     }
     
-    Logger::debug("All stream synchronizer stats reset");
+    Logger::instance().debug("All stream synchronizer stats reset");
 }
 
 void MultiStreamSynchronizer::resetStats(int streamIndex) {
@@ -1135,7 +1135,7 @@ void MultiStreamSynchronizer::resetStats(int streamIndex) {
     auto it = streamSynchronizers_.find(streamIndex);
     if (it != streamSynchronizers_.end()) {
         it->second->resetStats();
-        Logger::debug("Stream {} synchronizer stats reset", streamIndex);
+        Logger::instance().debugf("Stream {} synchronizer stats reset", streamIndex);
     }
 }
 
@@ -1153,7 +1153,7 @@ ErrorCode MultiStreamSynchronizer::start() {
     
     globalState_ = SyncState::SYNCING;
     
-    Logger::info("MultiStreamSynchronizer started");
+    Logger::instance().info("MultiStreamSynchronizer started");
     return result;
 }
 
@@ -1171,7 +1171,7 @@ ErrorCode MultiStreamSynchronizer::stop() {
     
     globalState_ = SyncState::IDLE;
     
-    Logger::info("MultiStreamSynchronizer stopped");
+    Logger::instance().info("MultiStreamSynchronizer stopped");
     return result;
 }
 
@@ -1187,7 +1187,7 @@ ErrorCode MultiStreamSynchronizer::pause() {
         }
     }
     
-    Logger::info("MultiStreamSynchronizer paused");
+    Logger::instance().info("MultiStreamSynchronizer paused");
     return result;
 }
 
@@ -1205,7 +1205,7 @@ ErrorCode MultiStreamSynchronizer::resume() {
     
     globalState_ = SyncState::SYNCING;
     
-    Logger::info("MultiStreamSynchronizer resumed");
+    Logger::instance().info("MultiStreamSynchronizer resumed");
     return result;
 }
 
@@ -1221,7 +1221,7 @@ ErrorCode MultiStreamSynchronizer::reset() {
         }
     }
     
-    Logger::info("MultiStreamSynchronizer reset");
+    Logger::instance().info("MultiStreamSynchronizer reset");
     return result;
 }
 

+ 4 - 2
AV/code/utils/utils_synchronizer.h

@@ -6,6 +6,7 @@
 #include <functional>
 #include <atomic>
 #include <mutex>
+#include <shared_mutex>
 #include <condition_variable>
 #include <map>
 #include <vector>
@@ -18,7 +19,7 @@ extern "C" {
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // 同步策略
 enum class SyncStrategy {
@@ -30,6 +31,7 @@ enum class SyncStrategy {
 
 // 同步状态
 enum class SyncState {
+    NOT_STARTED,    // 未开始
     IDLE,           // 空闲
     SYNCING,        // 同步中
     SYNCHRONIZED,   // 已同步
@@ -276,7 +278,7 @@ private:
     std::atomic<SyncState> globalState_;
     
     mutable std::shared_mutex streamsMutex_;
-    std::mutex masterMutex_;
+    mutable std::mutex masterMutex_;
     
     void updateMasterStream();
     void syncToMaster();

+ 22 - 22
AV/code/utils/utils_thread_pool.cpp

@@ -1,5 +1,5 @@
 #include "utils_thread_pool.h"
-#include "../base/base_logger.h"
+#include "../base/logger.h"
 #include <algorithm>
 #include <sstream>
 #include <thread>
@@ -15,7 +15,7 @@
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // ThreadPool 实现
 ThreadPool::ThreadPool(const ThreadPoolConfig& config)
@@ -57,12 +57,12 @@ ErrorCode ThreadPool::initialize() {
         // 预分配线程容器
         workers_.reserve(config_.maxThreads);
         
-        LOG_INFO("Thread pool initialized with {} min threads, {} max threads", 
+        Logger::instance().infof("Thread pool initialized with {} min threads, {} max threads", 
                 config_.minThreads, config_.maxThreads);
         
         return ErrorCode::SUCCESS;
     } catch (const std::exception& e) {
-        LOG_ERROR("Failed to initialize thread pool: {}", e.what());
+        Logger::instance().errorf("Failed to initialize thread pool: %s", e.what());
         return ErrorCode::INITIALIZATION_FAILED;
     }
 }
@@ -94,11 +94,11 @@ ErrorCode ThreadPool::start() {
         startTime_ = std::chrono::steady_clock::now();
         stats_.startTime = startTime_;
         
-        LOG_INFO("Thread pool started with {} threads", config_.minThreads);
+        Logger::instance().infof("Thread pool started with {} threads", config_.minThreads);
         
         return ErrorCode::SUCCESS;
     } catch (const std::exception& e) {
-        LOG_ERROR("Failed to start thread pool: {}", e.what());
+        Logger::instance().errorf("Failed to start thread pool: %s", e.what());
         state_.store(ThreadPoolState::STOPPED);
         return ErrorCode::OPERATION_FAILED;
     }
@@ -136,7 +136,7 @@ ErrorCode ThreadPool::stop(bool waitForCompletion) {
     idleThreads_.store(0);
     state_.store(ThreadPoolState::STOPPED);
     
-    LOG_INFO("Thread pool stopped");
+    Logger::instance().info("Thread pool stopped");
     return ErrorCode::SUCCESS;
 }
 
@@ -146,7 +146,7 @@ ErrorCode ThreadPool::pause() {
     }
     
     state_.store(ThreadPoolState::PAUSED);
-    LOG_INFO("Thread pool paused");
+    Logger::instance().info("Thread pool paused");
     
     return ErrorCode::SUCCESS;
 }
@@ -159,7 +159,7 @@ ErrorCode ThreadPool::resume() {
     state_.store(ThreadPoolState::RUNNING);
     pauseCondition_.notify_all();
     
-    LOG_INFO("Thread pool resumed");
+    Logger::instance().info("Thread pool resumed");
     return ErrorCode::SUCCESS;
 }
 
@@ -176,7 +176,7 @@ ErrorCode ThreadPool::shutdown(std::chrono::milliseconds timeout) {
     }
     
     if (state_.load() != ThreadPoolState::STOPPED) {
-        LOG_WARNING("Thread pool shutdown timeout, forcing termination");
+        Logger::instance().info("Thread pool shutdown timeout, forcing termination");
         // 强制终止(在实际实现中可能需要更复杂的逻辑)
         state_.store(ThreadPoolState::STOPPED);
     }
@@ -393,7 +393,7 @@ ErrorCode ThreadPool::resizeThreadPool(size_t newSize) {
     
     adjustThreadPoolSize();
     
-    LOG_INFO("Thread pool resized to {} threads", newSize);
+    Logger::instance().infof("Thread pool resized to {} threads", newSize);
     return ErrorCode::SUCCESS;
 }
 
@@ -453,7 +453,7 @@ void ThreadPool::clearPendingTasks() {
     
     totalCancelledTasks_ += cancelledCount;
     
-    LOG_INFO("Cleared {} pending tasks", cancelledCount);
+    Logger::instance().infof("Cleared {} pending tasks", cancelledCount);
 }
 
 // 私有方法实现
@@ -463,7 +463,7 @@ void ThreadPool::workerThread(size_t threadIndex) {
     oss << config_.threadNamePrefix << "-" << threadIndex;
     setThreadName(oss.str());
     
-    LOG_DEBUG("Worker thread {} started", threadIndex);
+    Logger::instance().debugf("Worker thread %zu started", threadIndex);
     
     while (!shutdown_.load()) {
         // 处理暂停状态
@@ -489,10 +489,10 @@ void ThreadPool::workerThread(size_t threadIndex) {
             task->execute();
             totalCompletedTasks_++;
         } catch (const std::exception& e) {
-            LOG_ERROR("Task execution failed: {}", e.what());
+            Logger::instance().errorf("Task execution failed: %s", e.what());
             totalFailedTasks_++;
         } catch (...) {
-            LOG_ERROR("Task execution failed with unknown exception");
+            Logger::instance().error("Task execution failed with unknown exception");
             totalFailedTasks_++;
         }
         
@@ -516,7 +516,7 @@ void ThreadPool::workerThread(size_t threadIndex) {
         cleanupCompletedTasks();
     }
     
-    LOG_DEBUG("Worker thread {} stopped", threadIndex);
+    Logger::instance().debugf("Worker thread %zu stopped", threadIndex);
 }
 
 std::shared_ptr<Task> ThreadPool::getNextTask() {
@@ -557,9 +557,9 @@ void ThreadPool::adjustThreadPoolSize() {
             activeThreads_++;
             idleThreads_++;
             
-            LOG_DEBUG("Created new worker thread, total: {}", workers_.size());
+            Logger::instance().debugf("Created new worker thread, total: %zu", workers_.size());
         } catch (const std::exception& e) {
-            LOG_ERROR("Failed to create new worker thread: {}", e.what());
+            Logger::instance().errorf("Failed to create new worker thread: %s", e.what());
         }
     }
     
@@ -732,7 +732,7 @@ std::unique_ptr<ThreadPool> ThreadPoolFactory::createCustomPool(const ThreadPool
 }
 
 size_t ThreadPoolFactory::getRecommendedThreadCount() {
-    return std::max(2u, std::thread::hardware_concurrency());
+    return (std::max)(2u, std::thread::hardware_concurrency());
 }
 
 size_t ThreadPoolFactory::getCpuCoreCount() {
@@ -784,7 +784,7 @@ ErrorCode ThreadPoolManager::createPool(const std::string& name, const ThreadPoo
     
     namedPools_[name] = std::move(pool);
     
-    LOG_INFO("Created thread pool: {}", name);
+    Logger::instance().infof("Created thread pool: {}", name);
     return ErrorCode::SUCCESS;
 }
 
@@ -810,7 +810,7 @@ ErrorCode ThreadPoolManager::destroyPool(const std::string& name) {
     it->second->shutdown();
     namedPools_.erase(it);
     
-    LOG_INFO("Destroyed thread pool: {}", name);
+    Logger::instance().infof("Destroyed thread pool: {}", name);
     return ErrorCode::SUCCESS;
 }
 
@@ -842,7 +842,7 @@ void ThreadPoolManager::shutdownAll() {
         defaultPool_.reset();
     }
     
-    LOG_INFO("All thread pools shutdown");
+    Logger::instance().info("All thread pools shutdown");
 }
 
 } // namespace utils

+ 1 - 1
AV/code/utils/utils_thread_pool.h

@@ -17,7 +17,7 @@
 namespace av {
 namespace utils {
 
-using namespace av::base;
+using namespace av;
 
 // 任务优先级
 enum class TaskPriority {

+ 574 - 0
AV/test_utils.cpp

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

+ 29 - 14
AV/xmake.lua

@@ -89,21 +89,21 @@ target("av_capture")
 --         add_links("avdevice", "avfilter", "postproc")
 --     end
 
--- -- 工具库
--- target("av_utils")
---     set_kind("static")
---     add_files("code/utils/*.cpp")
---     add_headerfiles("code/utils/*.h")
---     add_includedirs(".", {public = true})
---     add_deps("av_base")
+-- 工具库
+target("av_utils")
+    set_kind("static")
+    add_files("code/utils/*.cpp")
+    add_headerfiles("code/utils/*.h")
+    add_includedirs(".", {public = true})
+    add_deps("av_base")
     
---     -- FFmpeg库链接
---     if is_plat("windows") then
---         add_includedirs("E:/AAA/ffmpeg-7.0.2-full_build-shared/include")
---         add_linkdirs("E:/AAA/ffmpeg-7.0.2-full_build-shared/lib")
---         add_links("avcodec", "avformat", "avutil", "swscale", "swresample")
---         add_links("avdevice", "avfilter", "postproc")
---     end
+    -- FFmpeg库链接
+    if is_plat("windows") then
+        add_includedirs("E:/AAA/ffmpeg-7.0.2-full_build-shared/include")
+        add_linkdirs("E:/AAA/ffmpeg-7.0.2-full_build-shared/lib")
+        add_links("avcodec", "avformat", "avutil", "swscale", "swresample")
+        add_links("avdevice", "avfilter", "postproc")
+    end
 
 -- -- 完整的AV框架库
 -- target("av_framework")
@@ -244,4 +244,19 @@ target("test_window_capture")
         add_links("avdevice", "avfilter", "postproc")
     end
 
+-- 工具类测试程序
+target("test_utils")
+    set_kind("binary")
+    add_files("test_utils.cpp")
+    add_deps("av_utils")
+    set_targetdir("$(buildir)/bin")
+    
+    -- FFmpeg库链接
+    if is_plat("windows") then
+        add_includedirs("E:/AAA/ffmpeg-7.0.2-full_build-shared/include")
+        add_linkdirs("E:/AAA/ffmpeg-7.0.2-full_build-shared/lib")
+        add_links("avcodec", "avformat", "avutil", "swscale", "swresample")
+        add_links("avdevice", "avfilter", "postproc")
+    end
+    
 

部分文件因为文件数量过多而无法显示