zhuizhu 8 сар өмнө
parent
commit
d4f383fa5e
50 өөрчлөгдсөн 14813 нэмэгдсэн , 17 устгасан
  1. 1 0
      .gitignore
  2. 0 0
      .xmake/windows/x64/project.lock
  3. 7 0
      AV/.xmake/windows/x64/cache/config
  4. 1 0
      AV/.xmake/windows/x64/cache/cxxmodules
  5. 29 0
      AV/.xmake/windows/x64/cache/detect
  6. 40 0
      AV/.xmake/windows/x64/cache/history
  7. 1 0
      AV/.xmake/windows/x64/cache/option
  8. 1 0
      AV/.xmake/windows/x64/cache/package
  9. 1 0
      AV/.xmake/windows/x64/cache/project
  10. 94 0
      AV/.xmake/windows/x64/cache/toolchain
  11. 0 0
      AV/.xmake/windows/x64/project.lock
  12. 32 0
      AV/.xmake/windows/x64/xmake.conf
  13. 6 1
      AV/AV.pri
  14. 87 0
      AV/build.txt
  15. 67 0
      AV/build_and_test.bat
  16. 2 16
      AV/code/base/logger.cpp
  17. 2 0
      AV/code/base/logger.h
  18. 10 0
      AV/code/base/types.h
  19. 172 0
      AV/code/capture/capture_abstract_capturer.cpp
  20. 237 0
      AV/code/capture/capture_abstract_capturer.h
  21. 897 0
      AV/code/capture/capture_audio_capturer.cpp
  22. 257 0
      AV/code/capture/capture_audio_capturer.h
  23. 729 0
      AV/code/capture/capture_video_capturer.cpp
  24. 207 0
      AV/code/capture/capture_video_capturer.h
  25. 581 0
      AV/code/codec/codec_audio_decoder.cpp
  26. 208 0
      AV/code/codec/codec_audio_decoder.h
  27. 633 0
      AV/code/codec/codec_video_decoder.cpp
  28. 153 0
      AV/code/codec/codec_video_decoder.h
  29. 398 0
      AV/code/muxer/muxer_abstract_muxer.cpp
  30. 246 0
      AV/code/muxer/muxer_abstract_muxer.h
  31. 855 0
      AV/code/muxer/muxer_file_muxer.cpp
  32. 196 0
      AV/code/muxer/muxer_file_muxer.h
  33. 864 0
      AV/code/muxer/muxer_stream_muxer.cpp
  34. 257 0
      AV/code/muxer/muxer_stream_muxer.h
  35. 698 0
      AV/code/utils/utils_frame_queue.cpp
  36. 275 0
      AV/code/utils/utils_frame_queue.h
  37. 1098 0
      AV/code/utils/utils_packet_queue.cpp
  38. 356 0
      AV/code/utils/utils_packet_queue.h
  39. 835 0
      AV/code/utils/utils_performance_monitor.cpp
  40. 289 0
      AV/code/utils/utils_performance_monitor.h
  41. 1330 0
      AV/code/utils/utils_synchronizer.cpp
  42. 305 0
      AV/code/utils/utils_synchronizer.h
  43. 849 0
      AV/code/utils/utils_thread_pool.cpp
  44. 390 0
      AV/code/utils/utils_thread_pool.h
  45. 130 0
      AV/codec_test_log.txt
  46. 133 0
      AV/output.txt
  47. 353 0
      AV/test_decoder.cpp
  48. 64 0
      AV/test_log.txt
  49. 188 0
      AV/xmake.lua
  50. 249 0
      AV_REFACTOR_PLAN.md

+ 1 - 0
.gitignore

@@ -14,3 +14,4 @@
 /bin/styles/*.dll
 /bin/translations/*.qm
 /bin_debug
+/AV/build

+ 0 - 0
.xmake/windows/x64/project.lock


+ 7 - 0
AV/.xmake/windows/x64/cache/config

@@ -0,0 +1,7 @@
+{
+    options = { },
+    mtimes = {
+        ["xmake.lua"] = 1753537297
+    },
+    recheck = false
+}

+ 1 - 0
AV/.xmake/windows/x64/cache/cxxmodules

@@ -0,0 +1 @@
+{ }

+ 29 - 0
AV/.xmake/windows/x64/cache/detect

@@ -0,0 +1,29 @@
+{
+    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]]
+    },
+    ["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__-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_/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_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,
+        ["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
+    },
+    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]]
+    },
+    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_checktoolld = {
+        ["link.exe"] = [[C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.39.33519\bin\HostX64\x64\link.exe]]
+    },
+    find_programver = {
+        ["C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX64\\x64\\cl.exe"] = "19.39.33523"
+    },
+    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
+    }
+}

+ 40 - 0
AV/.xmake/windows/x64/cache/history

@@ -0,0 +1,40 @@
+{
+    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 ",
+        "xmake run test_decoder",
+        "xmake build test_decoder",
+        "xmake run test_decoder",
+        "xmake build test_decoder",
+        "xmake run test_decoder"
+    }
+}

+ 1 - 0
AV/.xmake/windows/x64/cache/option

@@ -0,0 +1 @@
+{ }

+ 1 - 0
AV/.xmake/windows/x64/cache/package

@@ -0,0 +1 @@
+{ }

+ 1 - 0
AV/.xmake/windows/x64/cache/project

@@ -0,0 +1 @@
+{ }

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 94 - 0
AV/.xmake/windows/x64/cache/toolchain


+ 0 - 0
AV/.xmake/windows/x64/project.lock


+ 32 - 0
AV/.xmake/windows/x64/xmake.conf

@@ -0,0 +1,32 @@
+{
+    __toolchains_windows_x64 = {
+        "msvc",
+        "yasm",
+        "nasm",
+        "cuda",
+        "rust",
+        "swift",
+        "go",
+        "gfortran",
+        "fpc"
+    },
+    arch = "x64",
+    buildir = "build",
+    ccache = true,
+    clean = true,
+    enable_examples = false,
+    enable_tests = true,
+    host = "windows",
+    kind = "static",
+    mode = "release",
+    ndk_stdcxx = true,
+    network = "public",
+    pkg_cachedir = "H:/.xmake/cache",
+    pkg_installdir = "H:/.xmake/packages",
+    pkg_searchdirs = "H:/.xmake/packages",
+    plat = "windows",
+    proxy = "http://192.168.3.28:20171",
+    proxy_pac = "pac.lua",
+    theme = "default",
+    vs = "2022"
+}

+ 6 - 1
AV/AV.pri

@@ -4,7 +4,9 @@ HEADERS += \
     $$PWD/code/base/media_thread_base.h \
     $$PWD/code/base/types.h \
     $$PWD/code/codec/codec_abstract_codec.h \
+    $$PWD/code/codec/codec_audio_decoder.h \
     $$PWD/code/codec/codec_audio_encoder.h \
+    $$PWD/code/codec/codec_video_decoder.h \
     $$PWD/code/codec/codec_video_encoder.h
 
 SOURCES += \
@@ -12,12 +14,15 @@ SOURCES += \
     $$PWD/code/base/logger.cpp \
     $$PWD/code/base/media_thread_base.cpp \
     $$PWD/code/codec/codec_abstract_codec.cpp \
+    $$PWD/code/codec/codec_audio_decoder.cpp \
     $$PWD/code/codec/codec_audio_encoder.cpp \
+    $$PWD/code/codec/codec_video_decoder.cpp \
     $$PWD/code/codec/codec_video_encoder.cpp
 
 
 # SOURCES += $$PWD/test_basic.cpp
-SOURCES += $$PWD/test_codec.cpp
+# SOURCES += $$PWD/test_codec.cpp
+SOURCES += $$PWD/test_decoder.cpp
 
 
 

+ 87 - 0
AV/build.txt

@@ -0,0 +1,87 @@
+21:13:00: 为项目LearningSmartClient执行步骤 ...
+21:13:00: 配置没有改变, 跳过 qmake 步骤。
+21:13:01: 正在启动 "D:\Qt\Tools\QtCreator\bin\jom\jom.exe" 
+
+	D:\Qt\Tools\QtCreator\bin\jom\jom.exe -f Makefile.Debug
+	cl -c -nologo -Zc:wchar_t -FS -Zc:rvalueCast -Zc:inline -Zc:strictStrings -Zc:throwingNew -Zc:referenceBinding -Zc:__cplusplus /utf-8 -Zi -MDd -std:c++17 -W3 -w34100 -w34189 -w44996 -w44456 -w44457 -w44458 -wd4577 -wd4467 -EHsc /Fddebug\LearningSmartClientd.vc.pdb -DUNICODE -D_UNICODE -DWIN32 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -DWIN64 -D_SILENCE_CLANG_COROUTINE_MESSAGE -DQWK_CORE_STATIC -DQWK_WIDGETS_STATIC -DQWK_CORE_STATIC -DQWK_WIDGETS_STATIC -DQT_QML_DEBUG -DQT_SVG_LIB -DQT_OPENGL_LIB -DQT_WIDGETS_LIB -DQT_MULTIMEDIA_LIB -DQT_GUI_LIB -DQT_WEBSOCKETS_LIB -DQT_NETWORK_LIB -DQT_CONCURRENT_LIB -DQT_CORE_LIB -I..\..\..\LearningSmartClient -I. -I..\..\AvRecorder -I..\..\qwindowkit\src -I..\..\qwindowkit\src\core -I..\..\qwindowkit\examples\shared -I..\..\fmt\include -I..\..\qtpromise\include -I..\..\qtpromise\src -I..\..\jsonserializer -IE:\AAA\ffmpeg-7.0.2-full_build-shared\include -ID:\Qt\5.15.2\msvc2019_64\include -ID:\Qt\5.15.2\msvc2019_64\include\QtSvg -ID:\Qt\5.15.2\msvc2019_64\include\QtOpenGL -ID:\Qt\5.15.2\msvc2019_64\include\QtWidgets -ID:\Qt\5.15.2\msvc2019_64\include\QtMultimedia -ID:\Qt\5.15.2\msvc2019_64\include\QtGui\5.15.2 -ID:\Qt\5.15.2\msvc2019_64\include\QtGui\5.15.2\QtGui -ID:\Qt\5.15.2\msvc2019_64\include\QtGui -ID:\Qt\5.15.2\msvc2019_64\include\QtANGLE -ID:\Qt\5.15.2\msvc2019_64\include\QtWebSockets -ID:\Qt\5.15.2\msvc2019_64\include\QtNetwork -ID:\Qt\5.15.2\msvc2019_64\include\QtConcurrent -ID:\Qt\5.15.2\msvc2019_64\include\QtCore\5.15.2 -ID:\Qt\5.15.2\msvc2019_64\include\QtCore\5.15.2\QtCore -ID:\Qt\5.15.2\msvc2019_64\include\QtCore -Idebug -I. -ID:\VulkanSDK\1.3.250.1\include -ID:\Qt\5.15.2\msvc2019_64\mkspecs\win32-msvc -Fodebug\ @C:\Windows\TEMP\codec_audio_decoder.obj.12360.532.jom
+codec_audio_decoder.cpp
+..\..\AV\code\codec\codec_audio_decoder.cpp(21): error C2512: “av::codec::AbstractDecoder”: 没有合适的默认构造函数可用
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_abstract_codec.h(168): note: 参见“av::codec::AbstractDecoder”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(30): error C2039: "initialize": 不是 "av::codec::AudioDecoder" 的成员
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_audio_decoder.h(42): note: 参见“av::codec::AudioDecoder”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(36): error C2065: “audioParams_”: 未声明的标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(38): error C2065: “audioParams_”: 未声明的标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(38): error C3861: “validateParams”: 找不到标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(42): error C3861: “setState”: 找不到标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(43): error C2065: “audioParams_”: 未声明的标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(70): error C2039: "channels": 不是 "AVCodecContext" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavcodec/avcodec.h(445): note: 参见“AVCodecContext”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(79): error C2556: “av::ErrorCode av::codec::AudioDecoder::close(void)”: 重载函数与“void av::codec::AudioDecoder::close(void)”只是在返回类型上不同
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_audio_decoder.h(68): note: 参见“av::codec::AudioDecoder::close”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(79): error C2371: “av::codec::AudioDecoder::close”: 重定义;不同的基类型
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_audio_decoder.h(68): note: 参见“av::codec::AudioDecoder::close”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(191): error C2084: 函数“bool av::codec::AudioDecoder::isResamplingEnabled(void) const”已有主体
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_audio_decoder.h(95): note: 参见“isResamplingEnabled”的前一个定义
+..\..\AV\code\codec\codec_audio_decoder.cpp(223): error C2039: "channels": 不是 "AVCodecContext" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavcodec/avcodec.h(445): note: 参见“AVCodecContext”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(257): error C3861: “av_cpu_count”: 找不到标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(267): error C2039: "channels": 不是 "AVCodecContext" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavcodec/avcodec.h(445): note: 参见“AVCodecContext”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(268): error C2039: "channel_layout": 不是 "AVCodecContext" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavcodec/avcodec.h(445): note: 参见“AVCodecContext”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(268): error C3861: “av_get_default_channel_layout”: 找不到标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(350): error C2039: "channels": 不是 "AVFrame" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavformat/avformat.h(332): note: 参见“AVFrame”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(371): error C2039: "channels": 不是 "AVFrame" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavformat/avformat.h(332): note: 参见“AVFrame”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(372): error C2039: "channel_layout": 不是 "AVFrame" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavformat/avformat.h(332): note: 参见“AVFrame”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(372): error C3861: “av_get_default_channel_layout”: 找不到标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(412): error C2039: "channels": 不是 "AVFrame" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavformat/avformat.h(332): note: 参见“AVFrame”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(412): error C2039: "channels": 不是 "AVCodecContext" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavcodec/avcodec.h(445): note: 参见“AVCodecContext”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(429): error C2039: "channel_layout": 不是 "AVFrame" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavformat/avformat.h(332): note: 参见“AVFrame”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(429): error C2660: “av_opt_set_int”: 函数不接受 3 个参数
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavutil/opt.h(781): note: 参见“av_opt_set_int”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(434): error C3861: “av_get_default_channel_layout”: 找不到标识符
+..\..\AV\code\codec\codec_audio_decoder.cpp(448): error C2039: "channels": 不是 "AVFrame" 的成员
+E:\AAA\ffmpeg-7.0.2-full_build-shared\include\libavformat/avformat.h(332): note: 参见“AVFrame”的声明
+..\..\AV\code\codec\codec_audio_decoder.cpp(475): error C2065: “isResamplingEnabled”: 未声明的标识符
+jom: F:\A_QT\im\LearningSmartClient\build\Desktop_Qt_5_15_2_MSVC2019_64bit-Debug\Makefile.Debug [debug\codec_audio_decoder.obj] Error 2
+	cl -c -nologo -Zc:wchar_t -FS -Zc:rvalueCast -Zc:inline -Zc:strictStrings -Zc:throwingNew -Zc:referenceBinding -Zc:__cplusplus /utf-8 -Zi -MDd -std:c++17 -W3 -w34100 -w34189 -w44996 -w44456 -w44457 -w44458 -wd4577 -wd4467 -EHsc /Fddebug\LearningSmartClientd.vc.pdb -DUNICODE -D_UNICODE -DWIN32 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -DWIN64 -D_SILENCE_CLANG_COROUTINE_MESSAGE -DQWK_CORE_STATIC -DQWK_WIDGETS_STATIC -DQWK_CORE_STATIC -DQWK_WIDGETS_STATIC -DQT_QML_DEBUG -DQT_SVG_LIB -DQT_OPENGL_LIB -DQT_WIDGETS_LIB -DQT_MULTIMEDIA_LIB -DQT_GUI_LIB -DQT_WEBSOCKETS_LIB -DQT_NETWORK_LIB -DQT_CONCURRENT_LIB -DQT_CORE_LIB -I..\..\..\LearningSmartClient -I. -I..\..\AvRecorder -I..\..\qwindowkit\src -I..\..\qwindowkit\src\core -I..\..\qwindowkit\examples\shared -I..\..\fmt\include -I..\..\qtpromise\include -I..\..\qtpromise\src -I..\..\jsonserializer -IE:\AAA\ffmpeg-7.0.2-full_build-shared\include -ID:\Qt\5.15.2\msvc2019_64\include -ID:\Qt\5.15.2\msvc2019_64\include\QtSvg -ID:\Qt\5.15.2\msvc2019_64\include\QtOpenGL -ID:\Qt\5.15.2\msvc2019_64\include\QtWidgets -ID:\Qt\5.15.2\msvc2019_64\include\QtMultimedia -ID:\Qt\5.15.2\msvc2019_64\include\QtGui\5.15.2 -ID:\Qt\5.15.2\msvc2019_64\include\QtGui\5.15.2\QtGui -ID:\Qt\5.15.2\msvc2019_64\include\QtGui -ID:\Qt\5.15.2\msvc2019_64\include\QtANGLE -ID:\Qt\5.15.2\msvc2019_64\include\QtWebSockets -ID:\Qt\5.15.2\msvc2019_64\include\QtNetwork -ID:\Qt\5.15.2\msvc2019_64\include\QtConcurrent -ID:\Qt\5.15.2\msvc2019_64\include\QtCore\5.15.2 -ID:\Qt\5.15.2\msvc2019_64\include\QtCore\5.15.2\QtCore -ID:\Qt\5.15.2\msvc2019_64\include\QtCore -Idebug -I. -ID:\VulkanSDK\1.3.250.1\include -ID:\Qt\5.15.2\msvc2019_64\mkspecs\win32-msvc -Fodebug\ @C:\Windows\TEMP\codec_video_decoder.obj.12360.625.jom
+codec_video_decoder.cpp
+..\..\AV\code\codec\codec_video_decoder.cpp(21): error C2512: “av::codec::AbstractDecoder”: 没有合适的默认构造函数可用
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_abstract_codec.h(168): note: 参见“av::codec::AbstractDecoder”的声明
+..\..\AV\code\codec\codec_video_decoder.cpp(30): error C2039: "initialize": 不是 "av::codec::VideoDecoder" 的成员
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_video_decoder.h(28): note: 参见“av::codec::VideoDecoder”的声明
+..\..\AV\code\codec\codec_video_decoder.cpp(36): error C2065: “videoParams_”: 未声明的标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(38): error C2065: “videoParams_”: 未声明的标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(38): error C3861: “validateParams”: 找不到标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(42): error C3861: “setState”: 找不到标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(43): error C2065: “videoParams_”: 未声明的标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(77): error C2556: “av::ErrorCode av::codec::VideoDecoder::close(void)”: 重载函数与“void av::codec::VideoDecoder::close(void)”只是在返回类型上不同
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_video_decoder.h(35): note: 参见“av::codec::VideoDecoder::close”的声明
+..\..\AV\code\codec\codec_video_decoder.cpp(77): error C2371: “av::codec::VideoDecoder::close”: 重定义;不同的基类型
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_video_decoder.h(35): note: 参见“av::codec::VideoDecoder::close”的声明
+..\..\AV\code\codec\codec_video_decoder.cpp(154): error C2509: “validateParams”: 成员函数没有在“av::codec::VideoDecoder”中声明
+F:\A_QT\im\LearningSmartClient\AV\code\codec\codec_video_decoder.h(28): note: 参见“av::codec::VideoDecoder”的声明
+..\..\AV\code\codec\codec_video_decoder.cpp(253): error C3861: “av_cpu_count”: 找不到标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(270): error C3861: “av_opt_set_int”: 找不到标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(273): error C3861: “av_opt_set_int”: 找不到标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(278): error C3861: “av_opt_set”: 找不到标识符
+..\..\AV\code\codec\codec_video_decoder.cpp(367): error C2280: “std::unique_ptr<AVFrame,av::AVFrameDeleter> &std::unique_ptr<AVFrame,av::AVFrameDeleter>::operator =(const std::unique_ptr<AVFrame,av::AVFrameDeleter> &)”: 尝试引用已删除的函数
+C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.29.30133\include\memory(3270): note: 参见“std::unique_ptr<AVFrame,av::AVFrameDeleter>::operator =”的声明
+C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.29.30133\include\memory(3270): note: “std::unique_ptr<AVFrame,av::AVFrameDeleter> &std::unique_ptr<AVFrame,av::AVFrameDeleter>::operator =(const std::unique_ptr<AVFrame,av::AVFrameDeleter> &)”: 已隐式删除函数
+	cl -c -nologo -Zc:wchar_t -FS -Zc:rvalueCast -Zc:inline -Zc:strictStrings -Zc:throwingNew -Zc:referenceBinding -Zc:__cplusplus /utf-8 -Zi -MDd -std:c++17 -W3 -w34100 -w34189 -w44996 -w44456 -w44457 -w44458 -wd4577 -wd4467 -EHsc /Fddebug\LearningSmartClientd.vc.pdb -DUNICODE -D_UNICODE -DWIN32 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -DWIN64 -D_SILENCE_CLANG_COROUTINE_MESSAGE -DQWK_CORE_STATIC -DQWK_WIDGETS_STATIC -DQWK_CORE_STATIC -DQWK_WIDGETS_STATIC -DQT_QML_DEBUG -DQT_SVG_LIB -DQT_OPENGL_LIB -DQT_WIDGETS_LIB -DQT_MULTIMEDIA_LIB -DQT_GUI_LIB -DQT_WEBSOCKETS_LIB -DQT_NETWORK_LIB -DQT_CONCURRENT_LIB -DQT_CORE_LIB -I..\..\..\LearningSmartClient -I. -I..\..\AvRecorder -I..\..\qwindowkit\src -I..\..\qwindowkit\src\core -I..\..\qwindowkit\examples\shared -I..\..\fmt\include -I..\..\qtpromise\include -I..\..\qtpromise\src -I..\..\jsonserializer -IE:\AAA\ffmpeg-7.0.2-full_build-shared\include -ID:\Qt\5.15.2\msvc2019_64\include -ID:\Qt\5.15.2\msvc2019_64\include\QtSvg -ID:\Qt\5.15.2\msvc2019_64\include\QtOpenGL -ID:\Qt\5.15.2\msvc2019_64\include\QtWidgets -ID:\Qt\5.15.2\msvc2019_64\include\QtMultimedia -ID:\Qt\5.15.2\msvc2019_64\include\QtGui\5.15.2 -ID:\Qt\5.15.2\msvc2019_64\include\QtGui\5.15.2\QtGui -ID:\Qt\5.15.2\msvc2019_64\include\QtGui -ID:\Qt\5.15.2\msvc2019_64\include\QtANGLE -ID:\Qt\5.15.2\msvc2019_64\include\QtWebSockets -ID:\Qt\5.15.2\msvc2019_64\include\QtNetwork -ID:\Qt\5.15.2\msvc2019_64\include\QtConcurrent -ID:\Qt\5.15.2\msvc2019_64\include\QtCore\5.15.2 -ID:\Qt\5.15.2\msvc2019_64\include\QtCore\5.15.2\QtCore -ID:\Qt\5.15.2\msvc2019_64\include\QtCore -Idebug -I. -ID:\VulkanSDK\1.3.250.1\include -ID:\Qt\5.15.2\msvc2019_64\mkspecs\win32-msvc -Fodebug\ @C:\Windows\TEMP\test_decoder.obj.12360.719.jom
+test_decoder.cpp
+..\..\AV\test_decoder.cpp(256): error C2440: “=”: 无法从“void”转换为“av::ErrorCode”
+..\..\AV\test_decoder.cpp(256): note: void 类型的表达式不能转换为其他类型
+jom: F:\A_QT\im\LearningSmartClient\build\Desktop_Qt_5_15_2_MSVC2019_64bit-Debug\Makefile.Debug [debug\codec_video_decoder.obj] Error 2
+jom: F:\A_QT\im\LearningSmartClient\build\Desktop_Qt_5_15_2_MSVC2019_64bit-Debug\Makefile.Debug [debug\test_decoder.obj] Error 2
+jom: F:\A_QT\im\LearningSmartClient\build\Desktop_Qt_5_15_2_MSVC2019_64bit-Debug\Makefile [debug] Error 2
+21:13:02: The command "D:\Qt\Tools\QtCreator\bin\jom\jom.exe" terminated with exit code 2.
+21:13:02: Error while building/deploying project LearningSmartClient (kit: Desktop Qt 5.15.2 MSVC2019 64bit)
+21:13:02: When executing step "Make"
+21:13:02: Elapsed time: 00:02.

+ 67 - 0
AV/build_and_test.bat

@@ -0,0 +1,67 @@
+@echo off
+echo ===== AV解码器测试构建脚本 =====
+
+:: 设置编码为UTF-8
+chcp 65001 > nul
+
+:: 检查CMake是否存在
+cmake --version > nul 2>&1
+if %errorlevel% neq 0 (
+    echo 错误: 未找到CMake,请先安装CMake
+    pause
+    exit /b 1
+)
+
+:: 创建构建目录
+if not exist "build_test" (
+    mkdir build_test
+)
+
+cd build_test
+
+echo.
+echo 正在配置CMake项目...
+:: 使用CMakeLists_test.txt作为CMakeLists.txt
+copy /Y "..\CMakeLists_test.txt" "CMakeLists.txt" > nul
+
+:: 配置项目
+cmake .. -G "Visual Studio 16 2019" -A x64
+if %errorlevel% neq 0 (
+    echo 错误: CMake配置失败
+    echo 请检查:
+    echo 1. FFmpeg是否正确安装
+    echo 2. 环境变量FFMPEG_ROOT是否设置
+    echo 3. Visual Studio是否正确安装
+    pause
+    exit /b 1
+)
+
+echo.
+echo 正在编译项目...
+:: 编译项目
+cmake --build . --config Release
+if %errorlevel% neq 0 (
+    echo 错误: 编译失败
+    echo 请检查编译错误信息
+    pause
+    exit /b 1
+)
+
+echo.
+echo 编译成功!正在运行测试...
+echo.
+
+:: 运行测试
+if exist "bin\Release\test_decoder.exe" (
+    bin\Release\test_decoder.exe
+) else if exist "Release\test_decoder.exe" (
+    Release\test_decoder.exe
+) else (
+    echo 错误: 找不到测试可执行文件
+    pause
+    exit /b 1
+)
+
+echo.
+echo 测试完成!
+pause

+ 2 - 16
AV/code/base/logger.cpp

@@ -115,37 +115,23 @@ void Logger::error(const std::string& message) {
     }
 }
 
-void Logger::qtDebug(const QString& message) {
 #ifdef QT_CORE_LIB
+void Logger::qtDebug(const QString& message) {
     debug(message.toUtf8().toStdString());
-#else
-    debug("[Qt Debug] " + std::string(message.toUtf8().constData()));
-#endif
 }
 
 void Logger::qtInfo(const QString& message) {
-#ifdef QT_CORE_LIB
     info(message.toUtf8().toStdString());
-#else
-    info("[Qt Info] " + std::string(message.toUtf8().constData()));
-#endif
 }
 
 void Logger::qtWarning(const QString& message) {
-#ifdef QT_CORE_LIB
     warning(message.toUtf8().toStdString());
-#else
-    warning("[Qt Warning] " + std::string(message.toUtf8().constData()));
-#endif
 }
 
 void Logger::qtError(const QString& message) {
-#ifdef QT_CORE_LIB
     error(message.toUtf8().toStdString());
-#else
-    error("[Qt Error] " + std::string(message.toUtf8().constData()));
-#endif
 }
+#endif
 
 void Logger::initialize(const std::string& logFile, 
                        LogLevel level,

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

@@ -102,11 +102,13 @@ public:
         }
     }
     
+#ifdef QT_CORE_LIB
     // Qt兼容接口
     void qtDebug(const QString& message);
     void qtInfo(const QString& message);
     void qtWarning(const QString& message);
     void qtError(const QString& message);
+#endif
     
     // 初始化方法(全局初始化时调用)
     static void initialize(const std::string& logFile = "av_log.txt", 

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

@@ -22,6 +22,7 @@ namespace av {
 
 // 媒体类型枚举
 enum class MediaType {
+    UNKNOWN,
     AUDIO,
     VIDEO
 };
@@ -82,6 +83,15 @@ enum class ErrorCode {
     CONVERSION_FAILED,
     NOT_SUPPORTED,
     HARDWARE_ERROR,
+    STREAM_NOT_FOUND,
+    PROCESSING_ERROR,
+    STREAM_EXISTS,
+    FORMAT_NOT_SUPPORTED,
+    FILE_EXISTS,
+    STREAM_CREATE_FAILED,
+    INVALID_PATH,
+    THREAD_ERROR,
+    QUEUE_FULL,
     UNKNOWN_ERROR
 };
 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 1330 - 0
AV/code/utils/utils_synchronizer.cpp

@@ -0,0 +1,1330 @@
+#include "utils_synchronizer.h"
+#include "../base/base_logger.h"
+#include <algorithm>
+#include <cmath>
+#include <shared_mutex>
+
+namespace av {
+namespace utils {
+
+using namespace av::base;
+
+Synchronizer::Synchronizer(const SyncConfig& config)
+    : config_(config)
+    , masterClockType_(ClockType::AUDIO)
+    , state_(SyncState::IDLE)
+    , initialized_(false)
+    , running_(false)
+    , paused_(false) {
+    
+    // 初始化时钟
+    audioClock_ = ClockInfo();
+    videoClock_ = ClockInfo();
+    externalClock_ = ClockInfo();
+    
+    // 初始化历史记录
+    audioClockHistory_.reserve(config_.smoothingWindow);
+    videoClockHistory_.reserve(config_.smoothingWindow);
+    syncErrorHistory_.reserve(config_.smoothingWindow);
+    
+    Logger::debug("Synchronizer created with strategy: {}", static_cast<int>(config_.strategy));
+}
+
+Synchronizer::~Synchronizer() {
+    close();
+    Logger::debug("Synchronizer destroyed");
+}
+
+ErrorCode Synchronizer::initialize() {
+    if (initialized_) {
+        return ErrorCode::ALREADY_INITIALIZED;
+    }
+    
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    // 重置所有时钟
+    resetClock(ClockType::AUDIO);
+    resetClock(ClockType::VIDEO);
+    resetClock(ClockType::EXTERNAL);
+    
+    // 选择主时钟
+    selectMasterClock();
+    
+    // 重置统计信息
+    resetStats();
+    
+    // 设置开始时间
+    startTime_ = std::chrono::steady_clock::now();
+    lastClockUpdate_ = startTime_;
+    
+    state_ = SyncState::IDLE;
+    initialized_ = true;
+    
+    Logger::info("Synchronizer initialized");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::start() {
+    if (!initialized_) {
+        return ErrorCode::NOT_INITIALIZED;
+    }
+    
+    if (running_) {
+        return ErrorCode::ALREADY_STARTED;
+    }
+    
+    running_ = true;
+    paused_ = false;
+    state_ = SyncState::SYNCING;
+    
+    startTime_ = std::chrono::steady_clock::now();
+    
+    Logger::info("Synchronizer started");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::stop() {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    running_ = false;
+    paused_ = false;
+    state_ = SyncState::IDLE;
+    
+    Logger::info("Synchronizer stopped");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::pause() {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    if (paused_) {
+        return ErrorCode::ALREADY_PAUSED;
+    }
+    
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    paused_ = true;
+    
+    // 暂停所有时钟
+    pauseClock(ClockType::AUDIO, true);
+    pauseClock(ClockType::VIDEO, true);
+    pauseClock(ClockType::EXTERNAL, true);
+    
+    Logger::info("Synchronizer paused");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::resume() {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    if (!paused_) {
+        return ErrorCode::NOT_PAUSED;
+    }
+    
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    paused_ = false;
+    
+    // 恢复所有时钟
+    pauseClock(ClockType::AUDIO, false);
+    pauseClock(ClockType::VIDEO, false);
+    pauseClock(ClockType::EXTERNAL, false);
+    
+    state_ = SyncState::SYNCING;
+    
+    Logger::info("Synchronizer resumed");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::reset() {
+    std::lock_guard<std::mutex> clockLock(clockMutex_);
+    std::lock_guard<std::mutex> statsLock(statsMutex_);
+    
+    // 重置时钟
+    resetClock(ClockType::AUDIO);
+    resetClock(ClockType::VIDEO);
+    resetClock(ClockType::EXTERNAL);
+    
+    // 重置统计信息
+    stats_ = SyncStats();
+    
+    // 清空历史记录
+    audioClockHistory_.clear();
+    videoClockHistory_.clear();
+    syncErrorHistory_.clear();
+    
+    // 重置状态
+    state_ = running_ ? SyncState::SYNCING : SyncState::IDLE;
+    
+    // 重新选择主时钟
+    selectMasterClock();
+    
+    Logger::info("Synchronizer reset");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::close() {
+    if (running_) {
+        stop();
+    }
+    
+    initialized_ = false;
+    
+    Logger::info("Synchronizer closed");
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::setAudioClock(double pts, double time) {
+    return updateClock(ClockType::AUDIO, pts, time);
+}
+
+ErrorCode Synchronizer::setVideoClock(double pts, double time) {
+    return updateClock(ClockType::VIDEO, pts, time);
+}
+
+ErrorCode Synchronizer::setExternalClock(double time) {
+    if (time < 0) {
+        time = getCurrentTime();
+    }
+    
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    externalClock_.pts = time;
+    externalClock_.time = time;
+    externalClock_.lastUpdate = std::chrono::steady_clock::now();
+    
+    if (config_.enableStats) {
+        updateStats();
+    }
+    
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::updateClock(ClockType type, double pts, double time) {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    if (time < 0) {
+        time = getCurrentTime();
+    }
+    
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    ClockInfo* clock = nullptr;
+    switch (type) {
+        case ClockType::AUDIO:
+            clock = &audioClock_;
+            break;
+        case ClockType::VIDEO:
+            clock = &videoClock_;
+            break;
+        case ClockType::EXTERNAL:
+            clock = &externalClock_;
+            break;
+    }
+    
+    if (!clock) {
+        return ErrorCode::INVALID_PARAMETER;
+    }
+    
+    // 平滑处理
+    double smoothedPts = config_.enableAdaptiveSync ? smoothClock(type, pts) : pts;
+    
+    clock->pts = smoothedPts;
+    clock->time = time;
+    clock->lastUpdate = std::chrono::steady_clock::now();
+    
+    // 更新主时钟
+    updateMasterClock();
+    
+    // 更新同步状态
+    updateSyncState();
+    
+    // 更新统计信息
+    if (config_.enableStats) {
+        updateStats();
+    }
+    
+    return ErrorCode::SUCCESS;
+}
+
+double Synchronizer::getAudioClock() const {
+    return getClockValue(ClockType::AUDIO);
+}
+
+double Synchronizer::getVideoClock() const {
+    return getClockValue(ClockType::VIDEO);
+}
+
+double Synchronizer::getExternalClock() const {
+    return getClockValue(ClockType::EXTERNAL);
+}
+
+double Synchronizer::getMasterClock() const {
+    return getClockValue(masterClockType_);
+}
+
+ClockType Synchronizer::getMasterClockType() const {
+    return masterClockType_;
+}
+
+ErrorCode Synchronizer::synchronize() {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    // 更新主时钟
+    updateMasterClock();
+    
+    // 计算同步误差
+    double syncError = calculateSyncError();
+    
+    // 检查是否需要调整
+    if (std::abs(syncError) > config_.syncThreshold) {
+        // 调整播放速度
+        if (config_.enableAdaptiveSync) {
+            adjustPlaybackSpeed();
+        }
+        
+        // 更新状态
+        if (std::abs(syncError) > config_.maxSyncError) {
+            state_ = SyncState::ERROR;
+        } else {
+            state_ = SyncState::DRIFT;
+        }
+    } else {
+        state_ = SyncState::SYNCHRONIZED;
+    }
+    
+    // 更新统计信息
+    if (config_.enableStats) {
+        updateSyncError(syncError);
+    }
+    
+    // 通知状态变化
+    if (syncEventCallback_) {
+        syncEventCallback_(state_, syncError);
+    }
+    
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::synchronizeAudio(double audioPts, double& delay) {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    // 更新音频时钟
+    updateClock(ClockType::AUDIO, audioPts);
+    
+    // 计算延迟
+    delay = calculateAudioDelay(audioPts);
+    
+    // 检查是否需要丢帧
+    if (config_.enableFrameDrop && shouldDropFrame(ClockType::AUDIO, audioPts)) {
+        if (frameDropCallback_) {
+            frameDropCallback_(ClockType::AUDIO, audioPts);
+        }
+        updateDropCount();
+    }
+    
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode Synchronizer::synchronizeVideo(double videoPts, double& delay) {
+    if (!running_) {
+        return ErrorCode::NOT_STARTED;
+    }
+    
+    // 更新视频时钟
+    updateClock(ClockType::VIDEO, videoPts);
+    
+    // 计算延迟
+    delay = calculateVideoDelay(videoPts);
+    
+    // 检查是否需要丢帧或重复帧
+    if (config_.enableFrameDrop && shouldDropFrame(ClockType::VIDEO, videoPts)) {
+        if (frameDropCallback_) {
+            frameDropCallback_(ClockType::VIDEO, videoPts);
+        }
+        updateDropCount();
+    } else if (config_.enableFrameDuplicate && shouldDuplicateFrame(ClockType::VIDEO, videoPts)) {
+        if (frameDuplicateCallback_) {
+            frameDuplicateCallback_(ClockType::VIDEO, videoPts);
+        }
+        updateDuplicateCount();
+    }
+    
+    return ErrorCode::SUCCESS;
+}
+
+bool Synchronizer::shouldDropFrame(ClockType type, double pts) {
+    return needFrameDrop(type, pts);
+}
+
+bool Synchronizer::shouldDuplicateFrame(ClockType type, double pts) {
+    return needFrameDuplicate(type, pts);
+}
+
+double Synchronizer::calculateAudioDelay(double audioPts) const {
+    double masterClock = getMasterClock();
+    double delay = audioPts - masterClock;
+    
+    // 限制延迟范围
+    delay = std::max(-config_.maxAudioDelay, std::min(config_.maxAudioDelay, delay));
+    
+    return delay;
+}
+
+double Synchronizer::calculateVideoDelay(double videoPts) const {
+    double masterClock = getMasterClock();
+    double delay = videoPts - masterClock;
+    
+    // 限制延迟范围
+    delay = std::max(-config_.maxVideoDelay, std::min(config_.maxVideoDelay, delay));
+    
+    return delay;
+}
+
+double Synchronizer::calculateSyncError() const {
+    double audioClock = getAudioClock();
+    double videoClock = getVideoClock();
+    
+    if (audioClock <= 0 || videoClock <= 0) {
+        return 0.0;
+    }
+    
+    return std::abs(audioClock - videoClock);
+}
+
+void Synchronizer::setConfig(const SyncConfig& config) {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    config_ = config;
+    
+    // 重新选择主时钟
+    selectMasterClock();
+    
+    Logger::debug("Synchronizer config updated");
+}
+
+SyncConfig Synchronizer::getConfig() const {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    return config_;
+}
+
+void Synchronizer::setSyncStrategy(SyncStrategy strategy) {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    config_.strategy = strategy;
+    selectMasterClock();
+    
+    Logger::debug("Sync strategy set to: {}", static_cast<int>(strategy));
+}
+
+SyncStrategy Synchronizer::getSyncStrategy() const {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    return config_.strategy;
+}
+
+void Synchronizer::setSyncThreshold(double threshold) {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    config_.syncThreshold = threshold;
+    
+    Logger::debug("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);
+}
+
+void Synchronizer::setPlaybackSpeed(double speed) {
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    audioClock_.speed = speed;
+    videoClock_.speed = speed;
+    externalClock_.speed = speed;
+    
+    Logger::debug("Playback speed set to: {}x", speed);
+}
+
+double Synchronizer::getPlaybackSpeed() const {
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    return audioClock_.speed;
+}
+
+void Synchronizer::setPaused(bool paused) {
+    if (paused) {
+        pause();
+    } else {
+        resume();
+    }
+}
+
+bool Synchronizer::isPaused() const {
+    return paused_;
+}
+
+SyncState Synchronizer::getState() const {
+    return state_;
+}
+
+bool Synchronizer::isSynchronized() const {
+    return state_ == SyncState::SYNCHRONIZED;
+}
+
+SyncStats Synchronizer::getStats() const {
+    std::lock_guard<std::mutex> lock(statsMutex_);
+    SyncStats stats = stats_;
+    
+    // 更新当前时钟值
+    stats.audioClock = getAudioClock();
+    stats.videoClock = getVideoClock();
+    stats.externalClock = getExternalClock();
+    stats.masterClock = getMasterClock();
+    stats.state = state_;
+    
+    return stats;
+}
+
+void Synchronizer::resetStats() {
+    std::lock_guard<std::mutex> lock(statsMutex_);
+    stats_ = SyncStats();
+    stats_.lastUpdateTime = std::chrono::steady_clock::now();
+    
+    Logger::debug("Synchronizer stats reset");
+}
+
+void Synchronizer::setSyncEventCallback(SyncEventCallback callback) {
+    syncEventCallback_ = callback;
+}
+
+void Synchronizer::setFrameDropCallback(FrameDropCallback callback) {
+    frameDropCallback_ = callback;
+}
+
+void Synchronizer::setFrameDuplicateCallback(FrameDuplicateCallback callback) {
+    frameDuplicateCallback_ = callback;
+}
+
+void Synchronizer::enableAdaptiveSync(bool enable) {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    config_.enableAdaptiveSync = enable;
+    
+    Logger::debug("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);
+}
+
+void Synchronizer::setSmoothingWindow(int window) {
+    std::lock_guard<std::mutex> lock(configMutex_);
+    config_.smoothingWindow = window;
+    
+    // 调整历史记录大小
+    audioClockHistory_.reserve(window);
+    videoClockHistory_.reserve(window);
+    syncErrorHistory_.reserve(window);
+    
+    Logger::debug("Smoothing window set to: {}", window);
+}
+
+// 内部方法实现
+void Synchronizer::updateMasterClock() {
+    // 根据策略选择主时钟
+    switch (config_.strategy) {
+        case SyncStrategy::AUDIO_MASTER:
+            masterClockType_ = ClockType::AUDIO;
+            break;
+        case SyncStrategy::VIDEO_MASTER:
+            masterClockType_ = ClockType::VIDEO;
+            break;
+        case SyncStrategy::EXTERNAL_CLOCK:
+            masterClockType_ = ClockType::EXTERNAL;
+            break;
+        case SyncStrategy::AUTO_SELECT:
+            selectMasterClock();
+            break;
+    }
+}
+
+void Synchronizer::updateSyncState() {
+    if (!running_) {
+        state_ = SyncState::IDLE;
+        return;
+    }
+    
+    if (paused_) {
+        return;
+    }
+    
+    double syncError = calculateSyncError();
+    
+    if (syncError <= config_.syncThreshold) {
+        state_ = SyncState::SYNCHRONIZED;
+    } else if (syncError <= config_.maxSyncError) {
+        state_ = SyncState::DRIFT;
+    } else {
+        state_ = SyncState::ERROR;
+    }
+}
+
+void Synchronizer::updateStats() {
+    std::lock_guard<std::mutex> lock(statsMutex_);
+    
+    stats_.audioClock = getAudioClock();
+    stats_.videoClock = getVideoClock();
+    stats_.externalClock = getExternalClock();
+    stats_.masterClock = getMasterClock();
+    stats_.audioDelay = calculateAudioDelay(stats_.audioClock);
+    stats_.videoDelay = calculateVideoDelay(stats_.videoClock);
+    stats_.syncError = calculateSyncError();
+    stats_.state = state_;
+    stats_.lastUpdateTime = std::chrono::steady_clock::now();
+    
+    // 更新最大同步误差
+    stats_.maxSyncError = std::max(stats_.maxSyncError, stats_.syncError);
+    
+    // 更新同步次数
+    stats_.syncCount++;
+    
+    // 更新平均同步误差
+    if (stats_.syncCount == 1) {
+        stats_.avgSyncError = stats_.syncError;
+    } else {
+        stats_.avgSyncError = (stats_.avgSyncError * (stats_.syncCount - 1) + stats_.syncError) / stats_.syncCount;
+    }
+}
+
+double Synchronizer::getCurrentTime() const {
+    auto now = std::chrono::steady_clock::now();
+    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now - startTime_);
+    return duration.count() / 1000000.0; // 转换为秒
+}
+
+double Synchronizer::smoothClock(ClockType type, double newValue) {
+    std::vector<double>* history = nullptr;
+    
+    switch (type) {
+        case ClockType::AUDIO:
+            history = &audioClockHistory_;
+            break;
+        case ClockType::VIDEO:
+            history = &videoClockHistory_;
+            break;
+        default:
+            return newValue;
+    }
+    
+    // 添加新值到历史记录
+    history->push_back(newValue);
+    
+    // 保持历史记录大小
+    if (history->size() > static_cast<size_t>(config_.smoothingWindow)) {
+        history->erase(history->begin());
+    }
+    
+    // 计算平均值
+    double sum = 0.0;
+    for (double value : *history) {
+        sum += value;
+    }
+    
+    return sum / history->size();
+}
+
+bool Synchronizer::isClockValid(ClockType type) const {
+    const ClockInfo* clock = nullptr;
+    
+    switch (type) {
+        case ClockType::AUDIO:
+            clock = &audioClock_;
+            break;
+        case ClockType::VIDEO:
+            clock = &videoClock_;
+            break;
+        case ClockType::EXTERNAL:
+            clock = &externalClock_;
+            break;
+    }
+    
+    if (!clock) {
+        return false;
+    }
+    
+    // 检查时钟是否有效(最近更新过)
+    auto now = std::chrono::steady_clock::now();
+    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - clock->lastUpdate);
+    
+    return elapsed.count() < 1000; // 1秒内更新过认为有效
+}
+
+void Synchronizer::selectMasterClock() {
+    // 自动选择最稳定的时钟作为主时钟
+    if (isClockValid(ClockType::AUDIO)) {
+        masterClockType_ = ClockType::AUDIO;
+    } else if (isClockValid(ClockType::VIDEO)) {
+        masterClockType_ = ClockType::VIDEO;
+    } else {
+        masterClockType_ = ClockType::EXTERNAL;
+    }
+}
+
+void Synchronizer::handleSyncDrift() {
+    // 处理时钟漂移
+    double syncError = calculateSyncError();
+    
+    if (syncError > config_.maxSyncError) {
+        // 重置时钟
+        Logger::warning("Sync drift detected, resetting clocks");
+        reset();
+    }
+}
+
+void Synchronizer::notifyStateChange(SyncState newState) {
+    if (state_ != newState) {
+        SyncState oldState = state_;
+        state_ = newState;
+        
+        if (syncEventCallback_) {
+            syncEventCallback_(newState, calculateSyncError());
+        }
+        
+        Logger::debug("Sync state changed from {} to {}", 
+                     static_cast<int>(oldState), static_cast<int>(newState));
+    }
+}
+
+double Synchronizer::getClockValue(ClockType type) const {
+    std::lock_guard<std::mutex> lock(clockMutex_);
+    
+    const ClockInfo* clock = nullptr;
+    
+    switch (type) {
+        case ClockType::AUDIO:
+            clock = &audioClock_;
+            break;
+        case ClockType::VIDEO:
+            clock = &videoClock_;
+            break;
+        case ClockType::EXTERNAL:
+            clock = &externalClock_;
+            break;
+    }
+    
+    if (!clock || clock->paused) {
+        return clock ? clock->pts : 0.0;
+    }
+    
+    // 计算当前时钟值
+    auto now = std::chrono::steady_clock::now();
+    auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now - clock->lastUpdate);
+    double elapsedSeconds = elapsed.count() / 1000000.0;
+    
+    return clock->pts + elapsedSeconds * clock->speed;
+}
+
+void Synchronizer::setClockValue(ClockType type, double value, double time) {
+    ClockInfo* clock = nullptr;
+    
+    switch (type) {
+        case ClockType::AUDIO:
+            clock = &audioClock_;
+            break;
+        case ClockType::VIDEO:
+            clock = &videoClock_;
+            break;
+        case ClockType::EXTERNAL:
+            clock = &externalClock_;
+            break;
+    }
+    
+    if (clock) {
+        clock->pts = value;
+        clock->time = (time >= 0) ? time : getCurrentTime();
+        clock->lastUpdate = std::chrono::steady_clock::now();
+    }
+}
+
+void Synchronizer::resetClock(ClockType type) {
+    ClockInfo* clock = nullptr;
+    
+    switch (type) {
+        case ClockType::AUDIO:
+            clock = &audioClock_;
+            break;
+        case ClockType::VIDEO:
+            clock = &videoClock_;
+            break;
+        case ClockType::EXTERNAL:
+            clock = &externalClock_;
+            break;
+    }
+    
+    if (clock) {
+        *clock = ClockInfo();
+        clock->lastUpdate = std::chrono::steady_clock::now();
+    }
+}
+
+void Synchronizer::pauseClock(ClockType type, bool pause) {
+    ClockInfo* clock = nullptr;
+    
+    switch (type) {
+        case ClockType::AUDIO:
+            clock = &audioClock_;
+            break;
+        case ClockType::VIDEO:
+            clock = &videoClock_;
+            break;
+        case ClockType::EXTERNAL:
+            clock = &externalClock_;
+            break;
+    }
+    
+    if (clock) {
+        clock->paused = pause;
+        if (!pause) {
+            clock->lastUpdate = std::chrono::steady_clock::now();
+        }
+    }
+}
+
+double Synchronizer::calculateOptimalDelay(ClockType type, double pts) {
+    double masterClock = getMasterClock();
+    double delay = pts - masterClock;
+    
+    // 根据类型调整延迟
+    if (type == ClockType::AUDIO) {
+        delay = std::max(-config_.maxAudioDelay, std::min(config_.maxAudioDelay, delay));
+    } else if (type == ClockType::VIDEO) {
+        delay = std::max(-config_.maxVideoDelay, std::min(config_.maxVideoDelay, delay));
+    }
+    
+    return delay;
+}
+
+bool Synchronizer::needFrameDrop(ClockType type, double pts) {
+    double delay = calculateOptimalDelay(type, pts);
+    
+    // 如果延迟太大(帧太晚),需要丢帧
+    if (type == ClockType::AUDIO) {
+        return delay < -config_.maxAudioDelay / 2;
+    } else if (type == ClockType::VIDEO) {
+        return delay < -config_.maxVideoDelay / 2;
+    }
+    
+    return false;
+}
+
+bool Synchronizer::needFrameDuplicate(ClockType type, double pts) {
+    double delay = calculateOptimalDelay(type, pts);
+    
+    // 如果延迟太小(帧太早),需要重复帧
+    if (type == ClockType::VIDEO) {
+        return delay > config_.maxVideoDelay / 2;
+    }
+    
+    return false;
+}
+
+void Synchronizer::adjustPlaybackSpeed() {
+    double syncError = calculateSyncError();
+    
+    if (syncError > config_.syncThreshold) {
+        // 根据同步误差调整播放速度
+        double speedAdjustment = std::min(0.1, syncError / 10.0);
+        
+        double newSpeed = 1.0;
+        if (masterClockType_ == ClockType::AUDIO) {
+            // 音频为主,调整视频速度
+            newSpeed = videoClock_.speed + speedAdjustment;
+        } else if (masterClockType_ == ClockType::VIDEO) {
+            // 视频为主,调整音频速度
+            newSpeed = audioClock_.speed + speedAdjustment;
+        }
+        
+        // 限制速度范围
+        newSpeed = std::max(0.5, std::min(2.0, newSpeed));
+        
+        if (masterClockType_ == ClockType::AUDIO) {
+            videoClock_.speed = newSpeed;
+        } else if (masterClockType_ == ClockType::VIDEO) {
+            audioClock_.speed = newSpeed;
+        }
+        
+        Logger::debug("Adjusted playback speed to: {}x", newSpeed);
+    }
+}
+
+void Synchronizer::updateSyncError(double error) {
+    syncErrorHistory_.push_back(error);
+    
+    if (syncErrorHistory_.size() > static_cast<size_t>(config_.smoothingWindow)) {
+        syncErrorHistory_.erase(syncErrorHistory_.begin());
+    }
+}
+
+void Synchronizer::updateDropCount() {
+    std::lock_guard<std::mutex> lock(statsMutex_);
+    stats_.dropCount++;
+}
+
+void Synchronizer::updateDuplicateCount() {
+    std::lock_guard<std::mutex> lock(statsMutex_);
+    stats_.duplicateCount++;
+}
+
+// 多流同步器实现
+MultiStreamSynchronizer::MultiStreamSynchronizer(const SyncConfig& config)
+    : defaultConfig_(config)
+    , masterStreamIndex_(-1)
+    , globalState_(SyncState::IDLE) {
+    Logger::debug("MultiStreamSynchronizer created");
+}
+
+MultiStreamSynchronizer::~MultiStreamSynchronizer() {
+    streamSynchronizers_.clear();
+    Logger::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);
+        return ErrorCode::ALREADY_EXISTS;
+    }
+    
+    auto synchronizer = std::make_unique<Synchronizer>(defaultConfig_);
+    synchronizer->initialize();
+    
+    streamSynchronizers_[streamIndex] = std::move(synchronizer);
+    streamTypes_[streamIndex] = type;
+    
+    // 如果是第一个流,设为主流
+    if (masterStreamIndex_ == -1) {
+        masterStreamIndex_ = streamIndex;
+    }
+    
+    Logger::debug("Added stream: {} with type: {}", streamIndex, static_cast<int>(type));
+    return ErrorCode::SUCCESS;
+}
+
+ErrorCode MultiStreamSynchronizer::removeStream(int streamIndex) {
+    std::unique_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it == streamSynchronizers_.end()) {
+        Logger::warning("Stream {} not found", streamIndex);
+        return ErrorCode::NOT_FOUND;
+    }
+    
+    streamSynchronizers_.erase(it);
+    streamTypes_.erase(streamIndex);
+    
+    // 如果删除的是主流,重新选择主流
+    if (masterStreamIndex_ == streamIndex) {
+        updateMasterStream();
+    }
+    
+    Logger::debug("Removed stream: {}", streamIndex);
+    return ErrorCode::SUCCESS;
+}
+
+bool MultiStreamSynchronizer::hasStream(int streamIndex) const {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    return streamSynchronizers_.find(streamIndex) != streamSynchronizers_.end();
+}
+
+std::vector<int> MultiStreamSynchronizer::getStreamIndices() const {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    std::vector<int> indices;
+    for (const auto& pair : streamSynchronizers_) {
+        indices.push_back(pair.first);
+    }
+    
+    return indices;
+}
+
+ErrorCode MultiStreamSynchronizer::synchronizeStream(int streamIndex, double pts, double& delay) {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it == streamSynchronizers_.end()) {
+        return ErrorCode::NOT_FOUND;
+    }
+    
+    auto typeIt = streamTypes_.find(streamIndex);
+    if (typeIt == streamTypes_.end()) {
+        return ErrorCode::NOT_FOUND;
+    }
+    
+    ClockType type = typeIt->second;
+    
+    if (type == ClockType::AUDIO) {
+        return it->second->synchronizeAudio(pts, delay);
+    } else if (type == ClockType::VIDEO) {
+        return it->second->synchronizeVideo(pts, delay);
+    }
+    
+    return ErrorCode::INVALID_PARAMETER;
+}
+
+ErrorCode MultiStreamSynchronizer::synchronizeAllStreams() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    ErrorCode result = ErrorCode::SUCCESS;
+    
+    for (auto& pair : streamSynchronizers_) {
+        ErrorCode syncResult = pair.second->synchronize();
+        if (syncResult != ErrorCode::SUCCESS) {
+            result = syncResult;
+        }
+    }
+    
+    // 同步到主流
+    syncToMaster();
+    
+    return result;
+}
+
+bool MultiStreamSynchronizer::shouldDropFrame(int streamIndex, double pts) {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it == streamSynchronizers_.end()) {
+        return false;
+    }
+    
+    auto typeIt = streamTypes_.find(streamIndex);
+    if (typeIt == streamTypes_.end()) {
+        return false;
+    }
+    
+    return it->second->shouldDropFrame(typeIt->second, pts);
+}
+
+bool MultiStreamSynchronizer::shouldDuplicateFrame(int streamIndex, double pts) {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it == streamSynchronizers_.end()) {
+        return false;
+    }
+    
+    auto typeIt = streamTypes_.find(streamIndex);
+    if (typeIt == streamTypes_.end()) {
+        return false;
+    }
+    
+    return it->second->shouldDuplicateFrame(typeIt->second, pts);
+}
+
+ErrorCode MultiStreamSynchronizer::updateStreamClock(int streamIndex, double pts, double time) {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it == streamSynchronizers_.end()) {
+        return ErrorCode::NOT_FOUND;
+    }
+    
+    auto typeIt = streamTypes_.find(streamIndex);
+    if (typeIt == streamTypes_.end()) {
+        return ErrorCode::NOT_FOUND;
+    }
+    
+    return it->second->updateClock(typeIt->second, pts, time);
+}
+
+double MultiStreamSynchronizer::getStreamClock(int streamIndex) const {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it == streamSynchronizers_.end()) {
+        return 0.0;
+    }
+    
+    return it->second->getMasterClock();
+}
+
+double MultiStreamSynchronizer::getMasterClock() const {
+    std::lock_guard<std::mutex> lock(masterMutex_);
+    
+    if (masterStreamIndex_ == -1) {
+        return 0.0;
+    }
+    
+    return getStreamClock(masterStreamIndex_);
+}
+
+int MultiStreamSynchronizer::getMasterStreamIndex() const {
+    std::lock_guard<std::mutex> lock(masterMutex_);
+    return masterStreamIndex_;
+}
+
+void MultiStreamSynchronizer::setConfig(const SyncConfig& config) {
+    defaultConfig_ = config;
+    
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    for (auto& pair : streamSynchronizers_) {
+        pair.second->setConfig(config);
+    }
+    
+    Logger::debug("MultiStreamSynchronizer config updated");
+}
+
+SyncConfig MultiStreamSynchronizer::getConfig() const {
+    return defaultConfig_;
+}
+
+SyncState MultiStreamSynchronizer::getState() const {
+    return globalState_;
+}
+
+std::map<int, SyncStats> MultiStreamSynchronizer::getAllStats() const {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    std::map<int, SyncStats> allStats;
+    for (const auto& pair : streamSynchronizers_) {
+        allStats[pair.first] = pair.second->getStats();
+    }
+    
+    return allStats;
+}
+
+SyncStats MultiStreamSynchronizer::getStats(int streamIndex) const {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it != streamSynchronizers_.end()) {
+        return it->second->getStats();
+    }
+    
+    return SyncStats();
+}
+
+void MultiStreamSynchronizer::resetStats() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    for (auto& pair : streamSynchronizers_) {
+        pair.second->resetStats();
+    }
+    
+    Logger::debug("All stream synchronizer stats reset");
+}
+
+void MultiStreamSynchronizer::resetStats(int streamIndex) {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    auto it = streamSynchronizers_.find(streamIndex);
+    if (it != streamSynchronizers_.end()) {
+        it->second->resetStats();
+        Logger::debug("Stream {} synchronizer stats reset", streamIndex);
+    }
+}
+
+ErrorCode MultiStreamSynchronizer::start() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    ErrorCode result = ErrorCode::SUCCESS;
+    
+    for (auto& pair : streamSynchronizers_) {
+        ErrorCode startResult = pair.second->start();
+        if (startResult != ErrorCode::SUCCESS) {
+            result = startResult;
+        }
+    }
+    
+    globalState_ = SyncState::SYNCING;
+    
+    Logger::info("MultiStreamSynchronizer started");
+    return result;
+}
+
+ErrorCode MultiStreamSynchronizer::stop() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    ErrorCode result = ErrorCode::SUCCESS;
+    
+    for (auto& pair : streamSynchronizers_) {
+        ErrorCode stopResult = pair.second->stop();
+        if (stopResult != ErrorCode::SUCCESS) {
+            result = stopResult;
+        }
+    }
+    
+    globalState_ = SyncState::IDLE;
+    
+    Logger::info("MultiStreamSynchronizer stopped");
+    return result;
+}
+
+ErrorCode MultiStreamSynchronizer::pause() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    ErrorCode result = ErrorCode::SUCCESS;
+    
+    for (auto& pair : streamSynchronizers_) {
+        ErrorCode pauseResult = pair.second->pause();
+        if (pauseResult != ErrorCode::SUCCESS) {
+            result = pauseResult;
+        }
+    }
+    
+    Logger::info("MultiStreamSynchronizer paused");
+    return result;
+}
+
+ErrorCode MultiStreamSynchronizer::resume() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    ErrorCode result = ErrorCode::SUCCESS;
+    
+    for (auto& pair : streamSynchronizers_) {
+        ErrorCode resumeResult = pair.second->resume();
+        if (resumeResult != ErrorCode::SUCCESS) {
+            result = resumeResult;
+        }
+    }
+    
+    globalState_ = SyncState::SYNCING;
+    
+    Logger::info("MultiStreamSynchronizer resumed");
+    return result;
+}
+
+ErrorCode MultiStreamSynchronizer::reset() {
+    std::shared_lock<std::shared_mutex> lock(streamsMutex_);
+    
+    ErrorCode result = ErrorCode::SUCCESS;
+    
+    for (auto& pair : streamSynchronizers_) {
+        ErrorCode resetResult = pair.second->reset();
+        if (resetResult != ErrorCode::SUCCESS) {
+            result = resetResult;
+        }
+    }
+    
+    Logger::info("MultiStreamSynchronizer reset");
+    return result;
+}
+
+void MultiStreamSynchronizer::updateMasterStream() {
+    std::lock_guard<std::mutex> lock(masterMutex_);
+    
+    if (streamSynchronizers_.empty()) {
+        masterStreamIndex_ = -1;
+        return;
+    }
+    
+    // 选择第一个音频流作为主流,如果没有音频流则选择第一个视频流
+    for (const auto& pair : streamTypes_) {
+        if (pair.second == ClockType::AUDIO) {
+            masterStreamIndex_ = pair.first;
+            return;
+        }
+    }
+    
+    // 如果没有音频流,选择第一个流
+    masterStreamIndex_ = streamSynchronizers_.begin()->first;
+}
+
+void MultiStreamSynchronizer::syncToMaster() {
+    if (masterStreamIndex_ == -1) {
+        return;
+    }
+    
+    double masterClock = getMasterClock();
+    
+    // 将其他流同步到主流
+    for (auto& pair : streamSynchronizers_) {
+        if (pair.first != masterStreamIndex_) {
+            // 这里可以实现更复杂的同步逻辑
+            // 暂时简化处理
+        }
+    }
+}
+
+// 工厂类实现
+std::unique_ptr<Synchronizer> SynchronizerFactory::createStandardSynchronizer() {
+    SyncConfig config;
+    config.strategy = SyncStrategy::AUDIO_MASTER;
+    config.maxAudioDelay = 0.1;
+    config.maxVideoDelay = 0.04;
+    config.syncThreshold = 0.01;
+    config.enableFrameDrop = true;
+    config.enableFrameDuplicate = true;
+    config.enableAdaptiveSync = true;
+    
+    return std::make_unique<Synchronizer>(config);
+}
+
+std::unique_ptr<Synchronizer> SynchronizerFactory::createLowLatencySynchronizer() {
+    SyncConfig config;
+    config.strategy = SyncStrategy::AUTO_SELECT;
+    config.maxAudioDelay = 0.05;
+    config.maxVideoDelay = 0.02;
+    config.syncThreshold = 0.005;
+    config.maxSyncError = 0.1;
+    config.enableFrameDrop = true;
+    config.enableFrameDuplicate = false;
+    config.enableAdaptiveSync = true;
+    config.smoothingWindow = 5;
+    
+    return std::make_unique<Synchronizer>(config);
+}
+
+std::unique_ptr<Synchronizer> SynchronizerFactory::createHighPrecisionSynchronizer() {
+    SyncConfig config;
+    config.strategy = SyncStrategy::EXTERNAL_CLOCK;
+    config.maxAudioDelay = 0.2;
+    config.maxVideoDelay = 0.08;
+    config.syncThreshold = 0.001;
+    config.maxSyncError = 0.01;
+    config.enableFrameDrop = true;
+    config.enableFrameDuplicate = true;
+    config.enableAdaptiveSync = true;
+    config.smoothingWindow = 20;
+    config.clockUpdateInterval = 0.01;
+    
+    return std::make_unique<Synchronizer>(config);
+}
+
+std::unique_ptr<Synchronizer> SynchronizerFactory::createRealtimeSynchronizer() {
+    SyncConfig config;
+    config.strategy = SyncStrategy::VIDEO_MASTER;
+    config.maxAudioDelay = 0.03;
+    config.maxVideoDelay = 0.016;
+    config.syncThreshold = 0.008;
+    config.maxSyncError = 0.05;
+    config.enableFrameDrop = true;
+    config.enableFrameDuplicate = false;
+    config.enableAdaptiveSync = true;
+    config.smoothingWindow = 3;
+    config.clockUpdateInterval = 0.016;
+    
+    return std::make_unique<Synchronizer>(config);
+}
+
+std::unique_ptr<MultiStreamSynchronizer> SynchronizerFactory::createMultiStreamSynchronizer(const SyncConfig& config) {
+    return std::make_unique<MultiStreamSynchronizer>(config);
+}
+
+} // namespace utils
+} // namespace av

+ 305 - 0
AV/code/utils/utils_synchronizer.h

@@ -0,0 +1,305 @@
+#pragma once
+
+#include "../base/types.h"
+#include <memory>
+#include <chrono>
+#include <functional>
+#include <atomic>
+#include <mutex>
+#include <condition_variable>
+#include <map>
+#include <vector>
+
+extern "C" {
+#include <libavformat/avformat.h>
+#include <libavutil/time.h>
+}
+
+namespace av {
+namespace utils {
+
+using namespace av::base;
+
+// 同步策略
+enum class SyncStrategy {
+    AUDIO_MASTER,    // 以音频为主
+    VIDEO_MASTER,    // 以视频为主
+    EXTERNAL_CLOCK,  // 外部时钟
+    AUTO_SELECT      // 自动选择
+};
+
+// 同步状态
+enum class SyncState {
+    IDLE,           // 空闲
+    SYNCING,        // 同步中
+    SYNCHRONIZED,   // 已同步
+    DRIFT,          // 时钟漂移
+    ERROR           // 错误
+};
+
+// 时钟类型
+enum class ClockType {
+    AUDIO,
+    VIDEO,
+    EXTERNAL
+};
+
+// 同步统计信息
+struct SyncStats {
+    double audioClock = 0.0;           // 音频时钟
+    double videoClock = 0.0;           // 视频时钟
+    double externalClock = 0.0;        // 外部时钟
+    double masterClock = 0.0;          // 主时钟
+    double audioDelay = 0.0;           // 音频延迟
+    double videoDelay = 0.0;           // 视频延迟
+    double syncError = 0.0;            // 同步误差
+    double maxSyncError = 0.0;         // 最大同步误差
+    double avgSyncError = 0.0;         // 平均同步误差
+    uint64_t syncCount = 0;            // 同步次数
+    uint64_t dropCount = 0;            // 丢帧次数
+    uint64_t duplicateCount = 0;       // 重复帧次数
+    SyncState state = SyncState::IDLE; // 同步状态
+    std::chrono::steady_clock::time_point lastUpdateTime; // 最后更新时间
+};
+
+// 同步配置
+struct SyncConfig {
+    SyncStrategy strategy = SyncStrategy::AUDIO_MASTER;  // 同步策略
+    double maxAudioDelay = 0.1;        // 最大音频延迟(秒)
+    double maxVideoDelay = 0.04;       // 最大视频延迟(秒)
+    double syncThreshold = 0.01;       // 同步阈值(秒)
+    double maxSyncError = 1.0;         // 最大同步误差(秒)
+    bool enableFrameDrop = true;       // 启用丢帧
+    bool enableFrameDuplicate = true;  // 启用重复帧
+    bool enableAdaptiveSync = true;    // 启用自适应同步
+    bool enableStats = true;           // 启用统计
+    int smoothingWindow = 10;          // 平滑窗口大小
+    double clockUpdateInterval = 0.1;  // 时钟更新间隔(秒)
+};
+
+// 时钟信息
+struct ClockInfo {
+    double pts = 0.0;                  // 显示时间戳
+    double time = 0.0;                 // 系统时间
+    double speed = 1.0;                // 播放速度
+    bool paused = false;               // 是否暂停
+    std::chrono::steady_clock::time_point lastUpdate; // 最后更新时间
+};
+
+// 同步事件回调
+using SyncEventCallback = std::function<void(SyncState state, double error)>;
+using FrameDropCallback = std::function<void(ClockType type, double pts)>;
+using FrameDuplicateCallback = std::function<void(ClockType type, double pts)>;
+
+// 音视频同步器
+class Synchronizer {
+public:
+    explicit Synchronizer(const SyncConfig& config = SyncConfig());
+    virtual ~Synchronizer();
+
+    // 基本控制
+    ErrorCode initialize();
+    ErrorCode start();
+    ErrorCode stop();
+    ErrorCode pause();
+    ErrorCode resume();
+    ErrorCode reset();
+    ErrorCode close();
+
+    // 时钟管理
+    ErrorCode setAudioClock(double pts, double time = -1);
+    ErrorCode setVideoClock(double pts, double time = -1);
+    ErrorCode setExternalClock(double time);
+    ErrorCode updateClock(ClockType type, double pts, double time = -1);
+    
+    double getAudioClock() const;
+    double getVideoClock() const;
+    double getExternalClock() const;
+    double getMasterClock() const;
+    ClockType getMasterClockType() const;
+    
+    // 同步控制
+    ErrorCode synchronize();
+    ErrorCode synchronizeAudio(double audioPts, double& delay);
+    ErrorCode synchronizeVideo(double videoPts, double& delay);
+    bool shouldDropFrame(ClockType type, double pts);
+    bool shouldDuplicateFrame(ClockType type, double pts);
+    
+    // 延迟计算
+    double calculateAudioDelay(double audioPts) const;
+    double calculateVideoDelay(double videoPts) const;
+    double calculateSyncError() const;
+    
+    // 配置管理
+    void setConfig(const SyncConfig& config);
+    SyncConfig getConfig() const;
+    void setSyncStrategy(SyncStrategy strategy);
+    SyncStrategy getSyncStrategy() const;
+    void setSyncThreshold(double threshold);
+    void setMaxSyncError(double maxError);
+    
+    // 播放控制
+    void setPlaybackSpeed(double speed);
+    double getPlaybackSpeed() const;
+    void setPaused(bool paused);
+    bool isPaused() const;
+    
+    // 状态查询
+    SyncState getState() const;
+    bool isSynchronized() const;
+    SyncStats getStats() const;
+    void resetStats();
+    
+    // 回调设置
+    void setSyncEventCallback(SyncEventCallback callback);
+    void setFrameDropCallback(FrameDropCallback callback);
+    void setFrameDuplicateCallback(FrameDuplicateCallback callback);
+    
+    // 高级功能
+    void enableAdaptiveSync(bool enable);
+    void setClockUpdateInterval(double interval);
+    void setSmoothingWindow(int window);
+    
+private:
+    // 内部方法
+    void updateMasterClock();
+    void updateSyncState();
+    void updateStats();
+    double getCurrentTime() const;
+    double smoothClock(ClockType type, double newValue);
+    bool isClockValid(ClockType type) const;
+    void selectMasterClock();
+    void handleSyncDrift();
+    void notifyStateChange(SyncState newState);
+    
+    // 时钟相关
+    double getClockValue(ClockType type) const;
+    void setClockValue(ClockType type, double value, double time = -1);
+    void resetClock(ClockType type);
+    void pauseClock(ClockType type, bool pause);
+    
+    // 同步算法
+    double calculateOptimalDelay(ClockType type, double pts);
+    bool needFrameDrop(ClockType type, double pts);
+    bool needFrameDuplicate(ClockType type, double pts);
+    void adjustPlaybackSpeed();
+    
+    // 统计更新
+    void updateSyncError(double error);
+    void updateDropCount();
+    void updateDuplicateCount();
+    
+private:
+    SyncConfig config_;
+    
+    // 时钟信息
+    ClockInfo audioClock_;
+    ClockInfo videoClock_;
+    ClockInfo externalClock_;
+    ClockType masterClockType_;
+    
+    // 同步状态
+    std::atomic<SyncState> state_;
+    std::atomic<bool> initialized_;
+    std::atomic<bool> running_;
+    std::atomic<bool> paused_;
+    
+    // 统计信息
+    SyncStats stats_;
+    mutable std::mutex statsMutex_;
+    
+    // 平滑处理
+    std::vector<double> audioClockHistory_;
+    std::vector<double> videoClockHistory_;
+    std::vector<double> syncErrorHistory_;
+    
+    // 回调函数
+    SyncEventCallback syncEventCallback_;
+    FrameDropCallback frameDropCallback_;
+    FrameDuplicateCallback frameDuplicateCallback_;
+    
+    // 线程同步
+    mutable std::mutex clockMutex_;
+    mutable std::mutex configMutex_;
+    
+    // 时间相关
+    std::chrono::steady_clock::time_point startTime_;
+    std::chrono::steady_clock::time_point lastClockUpdate_;
+};
+
+// 多流同步器
+class MultiStreamSynchronizer {
+public:
+    explicit MultiStreamSynchronizer(const SyncConfig& config = SyncConfig());
+    virtual ~MultiStreamSynchronizer();
+
+    // 流管理
+    ErrorCode addStream(int streamIndex, ClockType type);
+    ErrorCode removeStream(int streamIndex);
+    bool hasStream(int streamIndex) const;
+    std::vector<int> getStreamIndices() const;
+    
+    // 同步控制
+    ErrorCode synchronizeStream(int streamIndex, double pts, double& delay);
+    ErrorCode synchronizeAllStreams();
+    bool shouldDropFrame(int streamIndex, double pts);
+    bool shouldDuplicateFrame(int streamIndex, double pts);
+    
+    // 时钟管理
+    ErrorCode updateStreamClock(int streamIndex, double pts, double time = -1);
+    double getStreamClock(int streamIndex) const;
+    double getMasterClock() const;
+    int getMasterStreamIndex() const;
+    
+    // 配置和状态
+    void setConfig(const SyncConfig& config);
+    SyncConfig getConfig() const;
+    SyncState getState() const;
+    std::map<int, SyncStats> getAllStats() const;
+    SyncStats getStats(int streamIndex) const;
+    void resetStats();
+    void resetStats(int streamIndex);
+    
+    // 控制
+    ErrorCode start();
+    ErrorCode stop();
+    ErrorCode pause();
+    ErrorCode resume();
+    ErrorCode reset();
+    
+private:
+    SyncConfig defaultConfig_;
+    std::map<int, std::unique_ptr<Synchronizer>> streamSynchronizers_;
+    std::map<int, ClockType> streamTypes_;
+    
+    int masterStreamIndex_;
+    std::atomic<SyncState> globalState_;
+    
+    mutable std::shared_mutex streamsMutex_;
+    std::mutex masterMutex_;
+    
+    void updateMasterStream();
+    void syncToMaster();
+};
+
+// 同步器工厂
+class SynchronizerFactory {
+public:
+    // 创建标准同步器
+    static std::unique_ptr<Synchronizer> createStandardSynchronizer();
+    
+    // 创建低延迟同步器
+    static std::unique_ptr<Synchronizer> createLowLatencySynchronizer();
+    
+    // 创建高精度同步器
+    static std::unique_ptr<Synchronizer> createHighPrecisionSynchronizer();
+    
+    // 创建实时同步器
+    static std::unique_ptr<Synchronizer> createRealtimeSynchronizer();
+    
+    // 创建多流同步器
+    static std::unique_ptr<MultiStreamSynchronizer> createMultiStreamSynchronizer(const SyncConfig& config = SyncConfig());
+};
+
+} // namespace utils
+} // namespace av

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

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

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

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

+ 130 - 0
AV/codec_test_log.txt

@@ -0,0 +1,130 @@
+2025-07-26 21:45:04.463 [INFO] AV Logger initialized
+2025-07-26 21:45:04.463 [INFO] FFmpeg initialized successfully
+2025-07-26 21:45:04.463 [INFO] 1. 测试视频编码器支持...
+2025-07-26 21:45:04.463 [INFO] 查找可用的视频编码器...
+2025-07-26 21:45:04.464 [INFO] 找到硬件编码器: h264_nvenc
+2025-07-26 21:45:04.464 [INFO] 找到硬件编码器: h264_qsv
+2025-07-26 21:45:04.464 [INFO] 找到硬件编码器: h264_amf
+2025-07-26 21:45:04.464 [INFO] 找到软件编码器: libx264
+2025-07-26 21:45:04.464 [INFO] 找到软件编码器: libx265
+2025-07-26 21:45:04.464 [INFO] 总共找到 5 个可用的视频编码器
+2025-07-26 21:45:04.464 [INFO] 支持的视频编码器数量: 5
+2025-07-26 21:45:04.464 [INFO]   - h264_nvenc (硬件: 是)
+2025-07-26 21:45:04.467 [INFO]   - h264_qsv (硬件: 是)
+2025-07-26 21:45:04.467 [INFO]   - h264_amf (硬件: 是)
+2025-07-26 21:45:04.467 [INFO]   - libx264 (硬件: 否)
+2025-07-26 21:45:04.467 [INFO]   - libx265 (硬件: 否)
+2025-07-26 21:45:04.467 [INFO] 推荐的视频编码器: h264_nvenc
+2025-07-26 21:45:04.467 [INFO] 2. 测试音频编码器支持...
+2025-07-26 21:45:04.467 [INFO] 查找可用的音频编码器...
+2025-07-26 21:45:04.467 [INFO] 找到音频编码器: aac
+2025-07-26 21:45:04.467 [INFO] 找到音频编码器: libmp3lame
+2025-07-26 21:45:04.467 [INFO] 找到音频编码器: opus
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: libopus
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: vorbis
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: libvorbis
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: flac
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: pcm_s16le
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: pcm_s24le
+2025-07-26 21:45:04.468 [INFO] 找到音频编码器: pcm_s32le
+2025-07-26 21:45:04.468 [INFO] 总共找到 10 个可用的音频编码器
+2025-07-26 21:45:04.468 [INFO] 支持的音频编码器数量: 10
+2025-07-26 21:45:04.468 [INFO]   - aac
+2025-07-26 21:45:04.469 [INFO]   - libmp3lame
+2025-07-26 21:45:04.469 [INFO]   - opus
+2025-07-26 21:45:04.469 [INFO]   - libopus
+2025-07-26 21:45:04.469 [INFO]   - vorbis
+2025-07-26 21:45:04.469 [INFO]   - libvorbis
+2025-07-26 21:45:04.469 [INFO]   - flac
+2025-07-26 21:45:04.469 [INFO]   - pcm_s16le
+2025-07-26 21:45:04.469 [INFO]   - pcm_s24le
+2025-07-26 21:45:04.469 [INFO]   - pcm_s32le
+2025-07-26 21:45:04.469 [INFO] 推荐的音频编码器: aac
+2025-07-26 21:45:04.469 [INFO] 3. 测试视频编码器创建...
+2025-07-26 21:45:04.470 [DEBUG] 创建编码编解码器, 媒体类型: 2
+2025-07-26 21:45:04.470 [DEBUG] 创建视频编码器
+2025-07-26 21:45:04.470 [INFO] 视频编码器创建成功
+2025-07-26 21:45:04.470 [INFO] 开始设置硬件加速: 编码器=h264_nvenc, 设备类型=2
+2025-07-26 21:45:04.470 [INFO] 检查CUDA设备可用性...
+2025-07-26 21:45:04.470 [INFO] 创建硬件设备上下文...
+2025-07-26 21:45:04.574 [INFO] 硬件设备上下文创建成功: h264_nvenc
+2025-07-26 21:45:04.574 [INFO] 设置硬件帧上下文: 1280x720, 硬件格式: 117, 软件格式: 23, 池大小: 8
+2025-07-26 21:45:04.575 [INFO] 硬件帧上下文初始化成功
+2025-07-26 21:45:04.575 [INFO] 设置硬件编码器像素格式: 117 (cuda)
+2025-07-26 21:45:04.575 [INFO] 设置NVENC编码器参数...
+2025-07-26 21:45:04.576 [INFO] 设置preset=medium: 成功
+2025-07-26 21:45:04.576 [INFO] 设置profile=main: 成功
+2025-07-26 21:45:04.576 [INFO] 设置rc=vbr: 成功
+2025-07-26 21:45:04.576 [INFO] 设置surfaces=16: 成功
+2025-07-26 21:45:04.576 [INFO] 设置delay=0: 成功
+2025-07-26 21:45:04.576 [INFO] 启用低延迟模式
+2025-07-26 21:45:04.576 [INFO] 设置preset=fast: 成功
+2025-07-26 21:45:04.576 [INFO] 设置tune=ll: 成功
+2025-07-26 21:45:04.576 [INFO] 准备打开编码器: h264_nvenc
+2025-07-26 21:45:04.576 [INFO] 编码器参数: 1280x720, 比特率: 2000000, 帧率: 30, 像素格式: 117
+2025-07-26 21:45:04.576 [INFO] 硬件编码器状态: 设备上下文=已创建, 帧上下文=已设置
+2025-07-26 21:45:04.622 [INFO] 编码器打开成功: h264_nvenc
+2025-07-26 21:45:04.622 [DEBUG] 编解码器状态变更: 0 -> 1
+2025-07-26 21:45:04.622 [INFO] 视频编码器已打开: h264_nvenc (1280x720 @ 30fps)
+2025-07-26 21:45:04.622 [INFO] 视频编码器打开成功
+2025-07-26 21:45:04.622 [INFO] 编码器状态: 1
+2025-07-26 21:45:04.622 [INFO] 是否已打开: 是
+2025-07-26 21:45:04.650 [DEBUG] 编解码器状态变更: 1 -> 4
+2025-07-26 21:45:04.650 [DEBUG] 视频编码器已关闭
+2025-07-26 21:45:04.651 [INFO] 视频编码器已关闭
+2025-07-26 21:45:04.651 [DEBUG] 视频编码器已销毁
+2025-07-26 21:45:04.651 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.651 [INFO] 4. 测试音频编码器创建...
+2025-07-26 21:45:04.651 [DEBUG] 创建编码编解码器, 媒体类型: 1
+2025-07-26 21:45:04.651 [DEBUG] 创建音频编码器
+2025-07-26 21:45:04.651 [INFO] 音频编码器创建成功
+2025-07-26 21:45:04.652 [DEBUG] 编解码器状态变更: 0 -> 1
+2025-07-26 21:45:04.652 [INFO] 音频编码器已打开: aac (44100Hz, 2ch, 128kbps)
+2025-07-26 21:45:04.652 [INFO] 音频编码器打开成功
+2025-07-26 21:45:04.652 [INFO] 编码器状态: 1
+2025-07-26 21:45:04.653 [INFO] 是否已打开: 是
+2025-07-26 21:45:04.653 [DEBUG] 编解码器状态变更: 1 -> 4
+2025-07-26 21:45:04.653 [DEBUG] 音频编码器已关闭
+2025-07-26 21:45:04.653 [INFO] 音频编码器已关闭
+2025-07-26 21:45:04.653 [DEBUG] 音频编码器已销毁
+2025-07-26 21:45:04.653 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.653 [INFO] 5. 测试编码器工厂...
+2025-07-26 21:45:04.653 [DEBUG] 创建编码编解码器, 媒体类型: 2
+2025-07-26 21:45:04.653 [DEBUG] 创建视频编码器
+2025-07-26 21:45:04.654 [INFO] 最佳视频编码器创建成功(硬件优先)
+2025-07-26 21:45:04.654 [DEBUG] 创建编码编解码器, 媒体类型: 2
+2025-07-26 21:45:04.654 [DEBUG] 创建视频编码器
+2025-07-26 21:45:04.654 [INFO] 最佳视频编码器创建成功(软件优先)
+2025-07-26 21:45:04.654 [DEBUG] 创建编码编解码器, 媒体类型: 1
+2025-07-26 21:45:04.654 [DEBUG] 创建音频编码器
+2025-07-26 21:45:04.654 [INFO] 最佳音频编码器创建成功
+2025-07-26 21:45:04.654 [DEBUG] 创建编码编解码器, 媒体类型: 1
+2025-07-26 21:45:04.654 [DEBUG] 创建音频编码器
+2025-07-26 21:45:04.655 [INFO] 无损音频编码器创建成功
+2025-07-26 21:45:04.655 [INFO] 6. 测试编码器能力查询...
+2025-07-26 21:45:04.655 [INFO] 编码器 aac 支持:
+2025-07-26 21:45:04.655 [INFO]   - FLTP格式: 是
+2025-07-26 21:45:04.655 [INFO]   - 44100Hz: 是
+2025-07-26 21:45:04.655 [INFO]   - 立体声: 是
+2025-07-26 21:45:04.655 [INFO] 7. 测试编码器统计信息...
+2025-07-26 21:45:04.655 [DEBUG] 创建编码编解码器, 媒体类型: 2
+2025-07-26 21:45:04.655 [DEBUG] 创建视频编码器
+2025-07-26 21:45:04.655 [INFO] 编码器统计信息:
+2025-07-26 21:45:04.656 [INFO]   - 处理帧数: 0
+2025-07-26 21:45:04.656 [INFO]   - 丢弃帧数: 0
+2025-07-26 21:45:04.656 [INFO]   - 错误次数: 0
+2025-07-26 21:45:04.656 [INFO]   - 平均处理时间: {:.2f}ms
+2025-07-26 21:45:04.656 [INFO]   - 总字节数: 0
+2025-07-26 21:45:04.656 [DEBUG] 视频编码器已销毁
+2025-07-26 21:45:04.656 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.656 [INFO] === 所有编解码测试完成 ===
+2025-07-26 21:45:04.656 [INFO] 测试完成,请查看 codec_test_log.txt 文件
+2025-07-26 21:45:04.656 [DEBUG] 音频编码器已销毁
+2025-07-26 21:45:04.656 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.657 [DEBUG] 音频编码器已销毁
+2025-07-26 21:45:04.657 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.657 [DEBUG] 视频编码器已销毁
+2025-07-26 21:45:04.657 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.657 [DEBUG] 视频编码器已销毁
+2025-07-26 21:45:04.657 [DEBUG] 编解码器已析构
+2025-07-26 21:45:04.657 [INFO] FFmpeg cleanup completed

+ 133 - 0
AV/output.txt

@@ -0,0 +1,133 @@
+
+20:14:48: Starting F:\A_QT\im\LearningSmartClient\bin_debug\LearningSmartClientd.exe...
+"2025-07-26 20:14:49.830 [INFO] AV Logger initialized"
+"2025-07-26 20:14:49.832 [INFO] FFmpeg initialized successfully"
+"2025-07-26 20:14:49.832 [INFO] 1. 测试视频编码器支持..."
+"2025-07-26 20:14:49.832 [INFO] 查找可用的视频编码器..."
+"2025-07-26 20:14:49.832 [INFO] 找到硬件编码器: h264_nvenc"
+"2025-07-26 20:14:49.833 [INFO] 找到硬件编码器: h264_qsv"
+"2025-07-26 20:14:49.833 [INFO] 找到硬件编码器: h264_amf"
+"2025-07-26 20:14:49.833 [INFO] 找到软件编码器: libx264"
+"2025-07-26 20:14:49.833 [INFO] 找到软件编码器: libx265"
+"2025-07-26 20:14:49.833 [INFO] 总共找到 5 个可用的视频编码器"
+"2025-07-26 20:14:49.833 [INFO] 支持的视频编码器数量: 5"
+"2025-07-26 20:14:49.833 [INFO]   - h264_nvenc (硬件: 是)"
+"2025-07-26 20:14:49.833 [INFO]   - h264_qsv (硬件: 是)"
+"2025-07-26 20:14:49.833 [INFO]   - h264_amf (硬件: 是)"
+"2025-07-26 20:14:49.833 [INFO]   - libx264 (硬件: 否)"
+"2025-07-26 20:14:49.833 [INFO]   - libx265 (硬件: 否)"
+"2025-07-26 20:14:49.833 [INFO] 推荐的视频编码器: h264_nvenc"
+"2025-07-26 20:14:49.834 [INFO] 2. 测试音频编码器支持..."
+"2025-07-26 20:14:49.834 [INFO] 查找可用的音频编码器..."
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: aac"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: libmp3lame"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: opus"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: libopus"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: vorbis"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: libvorbis"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: flac"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: pcm_s16le"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: pcm_s24le"
+"2025-07-26 20:14:49.834 [INFO] 找到音频编码器: pcm_s32le"
+"2025-07-26 20:14:49.835 [INFO] 总共找到 10 个可用的音频编码器"
+"2025-07-26 20:14:49.835 [INFO] 支持的音频编码器数量: 10"
+"2025-07-26 20:14:49.835 [INFO]   - aac"
+"2025-07-26 20:14:49.835 [INFO]   - libmp3lame"
+"2025-07-26 20:14:49.835 [INFO]   - opus"
+"2025-07-26 20:14:49.835 [INFO]   - libopus"
+"2025-07-26 20:14:49.835 [INFO]   - vorbis"
+"2025-07-26 20:14:49.835 [INFO]   - libvorbis"
+"2025-07-26 20:14:49.835 [INFO]   - flac"
+"2025-07-26 20:14:49.835 [INFO]   - pcm_s16le"
+"2025-07-26 20:14:49.835 [INFO]   - pcm_s24le"
+"2025-07-26 20:14:49.835 [INFO]   - pcm_s32le"
+"2025-07-26 20:14:49.835 [INFO] 推荐的音频编码器: aac"
+"2025-07-26 20:14:49.836 [INFO] 3. 测试视频编码器创建..."
+"2025-07-26 20:14:49.836 [DEBUG] 创建编码编解码器, 媒体类型: 1"
+"2025-07-26 20:14:49.836 [DEBUG] 创建视频编码器"
+"2025-07-26 20:14:49.836 [INFO] 视频编码器创建成功"
+"2025-07-26 20:14:49.836 [INFO] 开始设置硬件加速: 编码器=h264_nvenc, 设备类型=2"
+"2025-07-26 20:14:49.836 [INFO] 检查CUDA设备可用性..."
+"2025-07-26 20:14:49.836 [INFO] 创建硬件设备上下文..."
+"2025-07-26 20:14:49.941 [INFO] 硬件设备上下文创建成功: h264_nvenc"
+"2025-07-26 20:14:49.941 [INFO] 设置硬件帧上下文: 1280x720, 硬件格式: 117, 软件格式: 23, 池大小: 8"
+"2025-07-26 20:14:49.943 [INFO] 硬件帧上下文初始化成功"
+"2025-07-26 20:14:49.943 [INFO] 设置硬件编码器像素格式: 117 (cuda)"
+"2025-07-26 20:14:49.943 [INFO] 设置NVENC编码器参数..."
+"2025-07-26 20:14:49.943 [INFO] 设置preset=medium: 成功"
+"2025-07-26 20:14:49.943 [INFO] 设置profile=main: 成功"
+"2025-07-26 20:14:49.943 [INFO] 设置rc=vbr: 成功"
+"2025-07-26 20:14:49.943 [INFO] 设置surfaces=16: 成功"
+"2025-07-26 20:14:49.943 [INFO] 设置delay=0: 成功"
+"2025-07-26 20:14:49.943 [INFO] 启用低延迟模式"
+"2025-07-26 20:14:49.943 [INFO] 设置preset=fast: 成功"
+"2025-07-26 20:14:49.943 [INFO] 设置tune=ll: 成功"
+"2025-07-26 20:14:49.943 [INFO] 准备打开编码器: h264_nvenc"
+"2025-07-26 20:14:49.944 [INFO] 编码器参数: 1280x720, 比特率: 2000000, 帧率: 30, 像素格式: 117"
+"2025-07-26 20:14:49.944 [INFO] 硬件编码器状态: 设备上下文=已创建, 帧上下文=已设置"
+"2025-07-26 20:14:49.998 [INFO] 编码器打开成功: h264_nvenc"
+"2025-07-26 20:14:49.998 [DEBUG] 编解码器状态变更: 0 -> 1"
+"2025-07-26 20:14:49.999 [INFO] 视频编码器已打开: h264_nvenc (1280x720 @ 30fps)"
+"2025-07-26 20:14:49.999 [INFO] 视频编码器打开成功"
+"2025-07-26 20:14:49.999 [INFO] 编码器状态: 1"
+"2025-07-26 20:14:49.999 [INFO] 是否已打开: 是"
+"2025-07-26 20:14:50.026 [DEBUG] 编解码器状态变更: 1 -> 4"
+"2025-07-26 20:14:50.026 [DEBUG] 视频编码器已关闭"
+"2025-07-26 20:14:50.026 [INFO] 视频编码器已关闭"
+"2025-07-26 20:14:50.026 [DEBUG] 视频编码器已销毁"
+"2025-07-26 20:14:50.026 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.026 [INFO] 4. 测试音频编码器创建..."
+"2025-07-26 20:14:50.026 [DEBUG] 创建编码编解码器, 媒体类型: 0"
+"2025-07-26 20:14:50.026 [DEBUG] 创建音频编码器"
+"2025-07-26 20:14:50.026 [INFO] 音频编码器创建成功"
+"2025-07-26 20:14:50.027 [DEBUG] 编解码器状态变更: 0 -> 1"
+"2025-07-26 20:14:50.027 [INFO] 音频编码器已打开: aac (44100Hz, 2ch, 128kbps)"
+"2025-07-26 20:14:50.027 [INFO] 音频编码器打开成功"
+"2025-07-26 20:14:50.027 [INFO] 编码器状态: 1"
+"2025-07-26 20:14:50.027 [INFO] 是否已打开: 是"
+"2025-07-26 20:14:50.027 [DEBUG] 编解码器状态变更: 1 -> 4"
+"2025-07-26 20:14:50.028 [DEBUG] 音频编码器已关闭"
+"2025-07-26 20:14:50.028 [INFO] 音频编码器已关闭"
+"2025-07-26 20:14:50.028 [DEBUG] 音频编码器已销毁"
+"2025-07-26 20:14:50.028 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.028 [INFO] 5. 测试编码器工厂..."
+"2025-07-26 20:14:50.028 [DEBUG] 创建编码编解码器, 媒体类型: 1"
+"2025-07-26 20:14:50.028 [DEBUG] 创建视频编码器"
+"2025-07-26 20:14:50.028 [INFO] 最佳视频编码器创建成功(硬件优先)"
+"2025-07-26 20:14:50.028 [DEBUG] 创建编码编解码器, 媒体类型: 1"
+"2025-07-26 20:14:50.029 [DEBUG] 创建视频编码器"
+"2025-07-26 20:14:50.029 [INFO] 最佳视频编码器创建成功(软件优先)"
+"2025-07-26 20:14:50.029 [DEBUG] 创建编码编解码器, 媒体类型: 0"
+"2025-07-26 20:14:50.029 [DEBUG] 创建音频编码器"
+"2025-07-26 20:14:50.029 [INFO] 最佳音频编码器创建成功"
+"2025-07-26 20:14:50.029 [DEBUG] 创建编码编解码器, 媒体类型: 0"
+"2025-07-26 20:14:50.029 [DEBUG] 创建音频编码器"
+"2025-07-26 20:14:50.029 [INFO] 无损音频编码器创建成功"
+"2025-07-26 20:14:50.029 [INFO] 6. 测试编码器能力查询..."
+"2025-07-26 20:14:50.029 [INFO] 编码器 aac 支持:"
+"2025-07-26 20:14:50.029 [INFO]   - FLTP格式: 是"
+"2025-07-26 20:14:50.029 [INFO]   - 44100Hz: 是"
+"2025-07-26 20:14:50.029 [INFO]   - 立体声: 是"
+"2025-07-26 20:14:50.029 [INFO] 7. 测试编码器统计信息..."
+"2025-07-26 20:14:50.030 [DEBUG] 创建编码编解码器, 媒体类型: 1"
+"2025-07-26 20:14:50.030 [DEBUG] 创建视频编码器"
+"2025-07-26 20:14:50.030 [INFO] 编码器统计信息:"
+"2025-07-26 20:14:50.030 [INFO]   - 处理帧数: 0"
+"2025-07-26 20:14:50.030 [INFO]   - 丢弃帧数: 0"
+"2025-07-26 20:14:50.030 [INFO]   - 错误次数: 0"
+"2025-07-26 20:14:50.030 [INFO]   - 平均处理时间: {:.2f}ms"
+"2025-07-26 20:14:50.030 [INFO]   - 总字节数: 0"
+"2025-07-26 20:14:50.030 [DEBUG] 视频编码器已销毁"
+"2025-07-26 20:14:50.030 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.030 [INFO] === 所有编解码测试完成 ==="
+"2025-07-26 20:14:50.030 [INFO] 测试完成,请查看 codec_test_log.txt 文件"
+"2025-07-26 20:14:50.030 [DEBUG] 音频编码器已销毁"
+"2025-07-26 20:14:50.030 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.031 [DEBUG] 音频编码器已销毁"
+"2025-07-26 20:14:50.031 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.031 [DEBUG] 视频编码器已销毁"
+"2025-07-26 20:14:50.031 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.031 [DEBUG] 视频编码器已销毁"
+"2025-07-26 20:14:50.031 [DEBUG] 编解码器已析构"
+"2025-07-26 20:14:50.031 [INFO] FFmpeg cleanup completed"
+20:14:50: The command "F:\A_QT\im\LearningSmartClient\bin_debug\LearningSmartClientd.exe" finished successfully.

+ 353 - 0
AV/test_decoder.cpp

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

+ 64 - 0
AV/test_log.txt

@@ -0,0 +1,64 @@
+2025-07-26 21:44:52.587 [INFO] AV Logger initialized
+2025-07-26 21:44:52.588 [DEBUG] 这是一条调试信息
+2025-07-26 21:44:52.588 [INFO] 这是一条信息
+2025-07-26 21:44:52.588 [WARN] 这是一条警告
+2025-07-26 21:44:52.588 [ERROR] 这是一条错误
+2025-07-26 21:44:52.588 [INFO] 格式化日志测试: 1 + 2 = 3
+2025-07-26 21:44:52.650 [INFO] [Timer] 测试代码块 took 61 ms
+2025-07-26 21:44:52.767 [INFO] 计时器测试: 116 ms
+2025-07-26 21:44:52.767 [INFO] 原始字符串: '  Hello, World!  '
+2025-07-26 21:44:52.767 [INFO] 修剪后: 'Hello, World!'
+2025-07-26 21:44:52.767 [INFO] 转大写: '  HELLO, WORLD!  '
+2025-07-26 21:44:52.767 [INFO] 分割结果数量: 4
+2025-07-26 21:44:52.768 [INFO] 路径: C:/test/file.txt
+2025-07-26 21:44:52.768 [INFO] 目录: C:/test
+2025-07-26 21:44:52.768 [INFO] 文件名: file.txt
+2025-07-26 21:44:52.768 [INFO] 扩展名: .txt
+2025-07-26 21:44:52.768 [DEBUG] ThreadBase created
+2025-07-26 21:44:52.769 [INFO] 启动测试线程...
+2025-07-26 21:44:52.769 [DEBUG] Thread 'TestThread' state changed to 1
+2025-07-26 21:44:52.769 [DEBUG] Thread 'TestThread' state changed to 2
+2025-07-26 21:44:52.769 [INFO] 线程启动回调被调用
+2025-07-26 21:44:52.769 [DEBUG] Thread 'TestThread' entering run loop
+2025-07-26 21:44:52.770 [INFO] Test thread started
+2025-07-26 21:44:52.770 [INFO] Thread 'TestThread' started successfully
+2025-07-26 21:44:52.770 [INFO] 测试线程启动成功
+2025-07-26 21:44:52.770 [INFO] Test thread iteration: 0
+2025-07-26 21:44:52.883 [INFO] Test thread iteration: 1
+2025-07-26 21:44:52.999 [INFO] Test thread iteration: 2
+2025-07-26 21:44:53.083 [INFO] 停止测试线程...
+2025-07-26 21:44:53.084 [DEBUG] Thread 'TestThread' state changed to 3
+2025-07-26 21:44:53.084 [INFO] Thread 'TestThread' stop requested
+2025-07-26 21:44:53.084 [INFO] Test thread finished
+2025-07-26 21:44:53.084 [DEBUG] Thread 'TestThread' exiting run loop
+2025-07-26 21:44:53.084 [INFO] 线程完成回调被调用
+2025-07-26 21:44:53.084 [DEBUG] Thread 'TestThread' state changed to 0
+2025-07-26 21:44:53.084 [INFO] Thread 'TestThread' finished
+2025-07-26 21:44:53.084 [INFO] Thread 'TestThread' joined successfully
+2025-07-26 21:44:53.085 [INFO] 测试线程已停止
+2025-07-26 21:44:53.085 [DEBUG] ThreadBase destroyed
+2025-07-26 21:44:53.085 [DEBUG] ThreadBase created
+2025-07-26 21:44:53.085 [DEBUG] Thread 'WorkerThread' state changed to 1
+2025-07-26 21:44:53.085 [DEBUG] Thread 'WorkerThread' state changed to 2
+2025-07-26 21:44:53.085 [DEBUG] Thread 'WorkerThread' entering run loop
+2025-07-26 21:44:53.085 [INFO] 工作线程计数: 1
+2025-07-26 21:44:53.085 [INFO] Thread 'WorkerThread' started successfully
+2025-07-26 21:44:53.150 [INFO] 工作线程计数: 2
+2025-07-26 21:44:53.203 [INFO] 工作线程计数: 3
+2025-07-26 21:44:53.266 [INFO] 工作线程计数: 4
+2025-07-26 21:44:53.300 [DEBUG] Thread 'WorkerThread' state changed to 3
+2025-07-26 21:44:53.300 [INFO] Thread 'WorkerThread' stop requested
+2025-07-26 21:44:53.301 [DEBUG] Thread 'WorkerThread' exiting run loop
+2025-07-26 21:44:53.301 [DEBUG] Thread 'WorkerThread' state changed to 0
+2025-07-26 21:44:53.301 [INFO] Thread 'WorkerThread' finished
+2025-07-26 21:44:53.301 [INFO] Thread 'WorkerThread' joined successfully
+2025-07-26 21:44:53.301 [INFO] 工作线程最终计数: 4
+2025-07-26 21:44:53.301 [DEBUG] ThreadBase destroyed
+2025-07-26 21:44:53.301 [INFO] 分配内存块 0
+2025-07-26 21:44:53.302 [INFO] 分配内存块 1
+2025-07-26 21:44:53.302 [INFO] 分配内存块 2
+2025-07-26 21:44:53.302 [INFO] 分配内存块 3
+2025-07-26 21:44:53.302 [INFO] 分配内存块 4
+2025-07-26 21:44:53.302 [INFO] 剩余可用块: 5
+2025-07-26 21:44:53.302 [INFO] 释放后可用块: 10
+2025-07-26 21:44:53.302 [INFO] === 所有测试完成 ===

+ 188 - 0
AV/xmake.lua

@@ -0,0 +1,188 @@
+-- xmake.lua for AV Framework
+
+-- 设置项目信息
+set_project("AV_Framework")
+set_version("1.0.0")
+set_languages("c++17")
+
+-- 设置编译模式
+add_rules("mode.debug", "mode.release")
+
+-- 设置编译选项
+if is_plat("windows") then
+    add_cxflags("/W3", "/utf-8")
+    add_defines("_CRT_SECURE_NO_WARNINGS")
+else
+    add_cxflags("-Wall", "-Wextra")
+end
+
+-- 添加包依赖
+-- add_requires("ffmpeg") -- 注释掉,使用本地FFmpeg库
+
+-- 基础库
+target("av_base")
+    set_kind("static")
+    add_files("code/base/*.cpp")
+    add_headerfiles("code/base/*.h")
+    add_includedirs(".", {public = true})
+    
+    -- Windows特定设置
+    if is_plat("windows") then
+        add_syslinks("ws2_32", "winmm")
+        -- FFmpeg库链接
+        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")
+    else
+        add_syslinks("pthread")
+    end
+
+-- 编解码库
+target("av_codec")
+    set_kind("static")
+    add_files("code/codec/*.cpp")
+    add_headerfiles("code/codec/*.h")
+    add_includedirs(".", {public = true})
+    add_deps("av_base")
+    
+    -- FFmpeg库链接
+    if is_plat("windows") then
+        -- Windows下的FFmpeg库路径
+        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")
+    else
+        add_links("avcodec", "avformat", "avutil", "swscale", "swresample")
+    end
+
+-- -- 捕获库
+-- target("av_capture")
+--     set_kind("static")
+--     add_files("code/capture/*.cpp")
+--     add_headerfiles("code/capture/*.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
+
+-- -- 混流库
+-- target("av_muxer")
+--     set_kind("static")
+--     add_files("code/muxer/*.cpp")
+--     add_headerfiles("code/muxer/*.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
+
+-- -- 工具库
+-- 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
+
+-- -- 完整的AV框架库
+-- target("av_framework")
+--     set_kind("static")
+--     add_deps("av_base", "av_codec", "av_capture", "av_muxer", "av_utils")
+--     add_includedirs(".", {public = true})
+
+-- 基础测试程序
+target("test_basic")
+    set_kind("binary")
+    add_files("test_basic.cpp")
+    add_deps("av_base")
+    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
+
+-- 编解码测试程序
+target("test_codec")
+    set_kind("binary")
+    add_files("test_codec.cpp")
+    add_deps("av_codec")
+    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
+
+-- 解码器测试程序
+target("test_decoder")
+    set_kind("binary")
+    add_files("test_decoder.cpp")
+    add_deps("av_codec")
+    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
+    
+    -- Windows下复制FFmpeg DLL
+    if is_plat("windows") then
+        after_build(function (target)
+            local ffmpeg_bin = "E:/AAA/ffmpeg-7.0.2-full_build-shared/bin"
+            local target_dir = target:targetdir()
+            
+            -- 复制FFmpeg DLL文件
+            local dlls = {
+                "avcodec-60.dll",
+                "avformat-60.dll", 
+                "avutil-58.dll",
+                "swscale-7.dll",
+                "swresample-4.dll",
+                "avdevice-60.dll",
+                "avfilter-9.dll",
+                "postproc-57.dll"
+            }
+            
+            for _, dll in ipairs(dlls) do
+                local src = path.join(ffmpeg_bin, dll)
+                local dst = path.join(target_dir, dll)
+                if os.exists(src) then
+                    os.cp(src, dst)
+                    print("Copied: " .. dll)
+                end
+            end
+        end)
+    end
+
+

+ 249 - 0
AV_REFACTOR_PLAN.md

@@ -0,0 +1,249 @@
+# AV项目重构方案
+
+## 项目概述
+
+当前有两个项目:
+- **AVPlayer2**: 音视频播放器,包含解码、播放功能
+- **AvRecorder**: 音视频录制器,包含采集、编码、推流功能
+
+## 重构目标
+
+1. **去Qt化**: 除UI渲染和音频播放外,其他模块不使用Qt
+2. **代码复用**: 提取两个项目的共同部分
+3. **模块化**: 清晰的模块划分,便于维护和扩展
+4. **小范围重构**: 每个步骤都能保证项目正常运行
+5. **统一日志**: 封装统一的日志系统
+
+## 新目录结构
+
+```
+AV/
+├── code/                    # 核心代码库(不依赖Qt)
+│   ├── base/               # 基础设施
+│   │   ├── logger.h/.cpp   # 统一日志系统
+│   │   ├── thread_base.h/.cpp # 线程基类
+│   │   ├── common.h/.cpp   # 通用工具
+│   │   └── types.h         # 类型定义
+│   ├── codec/              # 编解码模块
+│   │   ├── decoder/        # 解码器
+│   │   │   ├── audio_decoder.h/.cpp
+│   │   │   ├── video_decoder.h/.cpp
+│   │   │   └── decoder_base.h/.cpp
+│   │   └── encoder/        # 编码器
+│   │       ├── audio_encoder.h/.cpp
+│   │       ├── video_encoder.h/.cpp
+│   │       └── encoder_base.h/.cpp
+│   ├── capture/            # 采集模块
+│   │   ├── audio_capture.h/.cpp
+│   │   └── video_capture.h/.cpp
+│   ├── muxer/              # 复用器
+│   │   └── av_muxer.h/.cpp
+│   └── utils/              # 工具类
+│       ├── frame_queue.h/.cpp
+│       ├── packet_queue.h/.cpp
+│       └── sync_helper.h/.cpp
+├── AvPlayer/               # 播放器项目
+│   ├── ui/                 # Qt UI相关
+│   ├── player/             # 播放器逻辑
+│   └── main.cpp
+└── AvRecorder/             # 录制器项目
+    ├── ui/                 # Qt UI相关
+    ├── recorder/           # 录制器逻辑
+    └── main.cpp
+```
+
+## 重构步骤(分阶段进行)
+
+### 阶段1: 基础设施搭建(1-3步)
+
+#### 步骤1: 创建新目录结构和基础类
+- 创建 `AV/code/base/` 目录
+- 实现统一的日志系统 `logger.h/.cpp`
+- 实现线程基类 `thread_base.h/.cpp`(基于现有ThreadBase.h改进)
+- 实现通用类型定义 `types.h`
+
+#### 步骤2: 统一日志系统
+- 在两个项目中集成新的日志系统
+- 保持向后兼容,逐步替换现有日志调用
+- 测试日志功能正常
+
+#### 步骤3: 线程基类统一
+- 将AVPlayer2的ThreadBase迁移到新的thread_base
+- 在AvRecorder中也使用统一的线程基类
+- 确保所有线程相关功能正常
+
+### 阶段2: 编解码模块重构(4-8步)
+
+#### 步骤4: 抽象编解码基类
+- 创建 `AV/code/codec/` 目录
+- 基于AvRecorder的abstract_encoder设计统一的编解码基类
+- 定义编码器和解码器的通用接口
+
+#### 步骤5: 音频编码器重构
+- 将AvRecorder的audio_encoder迁移到新目录
+- 去除Qt依赖,使用标准C++
+- 在AvRecorder中使用新的音频编码器
+
+#### 步骤6: 视频编码器重构
+- 将AvRecorder的video_encoder迁移到新目录
+- 去除Qt依赖
+- 在AvRecorder中使用新的视频编码器
+
+#### 步骤7: 音频解码器重构
+- 基于AVPlayer2的audio_decode_thread创建新的audio_decoder
+- 分离解码逻辑和线程逻辑
+- 在AVPlayer2中使用新的音频解码器
+
+#### 步骤8: 视频解码器重构
+- 基于AVPlayer2的video_decode_thread创建新的video_decoder
+- 分离解码逻辑和线程逻辑
+- 在AVPlayer2中使用新的视频解码器
+
+### 阶段3: 采集和复用模块(9-11步)
+
+#### 步骤9: 音视频采集模块
+- 将AvRecorder的capturer模块迁移到 `AV/code/capture/`
+- 去除Qt依赖(除了必要的音频采集部分)
+- 统一采集接口
+
+#### 步骤10: 复用器模块
+- 将AvRecorder的muxer迁移到新目录
+- 确保与新的编码器兼容
+
+#### 步骤11: 工具类模块
+- 创建统一的队列管理(frame_queue, packet_queue)
+- 创建同步辅助类
+- 替换两个项目中的相关实现
+
+### 阶段4: 项目整合和优化(12-15步)
+
+#### 步骤12: AVPlayer2重构
+- 使用新的核心库重构播放器
+- 保持UI部分不变
+- 确保播放功能完整
+
+#### 步骤13: AvRecorder重构
+- 使用新的核心库重构录制器
+- 保持UI部分不变
+- 确保录制和推流功能完整
+
+#### 步骤14: 代码清理
+- 删除重复的旧代码
+- 优化包含路径
+- 统一编码规范
+
+#### 步骤15: 测试和文档
+- 全面测试两个项目的功能
+- 编写使用文档
+- 性能优化
+
+## 技术要点
+
+### 日志系统设计
+```cpp
+// 支持Qt的qDebug等,但封装为独立接口
+class Logger {
+public:
+    static Logger& instance();
+    void debug(const std::string& msg);
+    void info(const std::string& msg);
+    void warning(const std::string& msg);
+    void error(const std::string& msg);
+    
+    // Qt兼容接口
+    void qtDebug(const QString& msg);
+    void qtInfo(const QString& msg);
+};
+
+// 宏定义,便于使用
+#define LOG_DEBUG(msg) Logger::instance().debug(msg)
+#define LOG_INFO(msg) Logger::instance().info(msg)
+```
+
+### 线程基类改进
+- 基于现有ThreadBase.h,但去除Qt依赖
+- 使用std::thread和标准库同步原语
+- 提供更好的异常处理和资源管理
+
+### 编解码接口设计
+```cpp
+class CodecBase {
+public:
+    virtual bool open(const CodecParams& params) = 0;
+    virtual bool process(AVFrame* frame) = 0;
+    virtual void close() = 0;
+    virtual ~CodecBase() = default;
+};
+
+class EncoderBase : public CodecBase {
+public:
+    virtual AVPacket* encode(AVFrame* frame) = 0;
+};
+
+class DecoderBase : public CodecBase {
+public:
+    virtual AVFrame* decode(AVPacket* packet) = 0;
+};
+```
+
+## 风险控制
+
+1. **每个步骤都要测试**: 确保修改后项目能正常编译和运行
+2. **保持向后兼容**: 在过渡期间保留旧接口
+3. **分支开发**: 在独立分支进行重构,主分支保持稳定
+4. **增量迁移**: 逐个模块迁移,不要一次性大改
+5. **回滚机制**: 每个步骤完成后提交代码,便于回滚
+
+## 当前进度
+
+### 第一阶段:基础设施 ✅
+- [x] 创建基础目录结构 (`AV/code/`)
+- [x] 实现统一日志系统 (`logger.h/cpp`)
+- [x] 实现线程基类 (`thread_base.h/cpp`)
+- [x] 实现通用工具类 (`common.h/cpp`, `types.h`)
+- [x] 创建基础测试程序 (`test_basic.cpp`)
+
+### 第二阶段:编解码模块 ✅
+- [x] 编解码抽象基类设计 (`abstract_codec.h/cpp`)
+- [x] 视频编码器实现 (`video_encoder.h/cpp`)
+  - [x] 硬件加速支持 (NVENC, QSV, AMF, VideoToolbox)
+  - [x] 像素格式转换
+  - [x] 编码参数配置
+  - [x] 统计信息收集
+- [x] 音频编码器实现 (`audio_encoder.h/cpp`)
+  - [x] 音频重采样支持
+  - [x] 多种音频格式支持 (AAC, MP3, Opus, FLAC等)
+  - [x] 声道布局处理
+  - [x] 采样率转换
+- [x] 编解码工厂模式
+- [x] 编解码测试程序 (`test_codec.cpp`)
+- [x] CMake构建系统配置
+
+### 第三阶段:解码器模块 🔄
+- [ ] 视频解码器实现
+- [ ] 音频解码器实现
+- [ ] 解码器测试程序
+
+### 第四阶段:采集和复用模块 ⏳
+- [ ] 视频采集模块
+- [ ] 音频采集模块
+- [ ] 媒体复用器模块
+- [ ] 流媒体支持
+
+### 第五阶段:项目整合和优化 ⏳
+- [ ] 原项目迁移适配
+- [ ] 性能优化
+- [ ] 文档完善
+- [ ] 单元测试
+
+## 预期收益
+
+1. **代码复用**: 减少重复代码,提高维护效率
+2. **模块化**: 清晰的模块边界,便于测试和扩展
+3. **跨平台**: 核心逻辑不依赖Qt,便于移植
+4. **性能优化**: 去除不必要的Qt开销
+5. **团队协作**: 统一的代码规范和架构
+
+## 下一步行动
+
+建议从**步骤1**开始,创建基础目录结构和日志系统。每完成一个步骤,都要进行充分测试,确保项目功能正常后再进行下一步。

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно