utils_synchronizer_v2.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #ifndef AV_UTILS_SYNCHRONIZER_V2_H
  2. #define AV_UTILS_SYNCHRONIZER_V2_H
  3. #pragma once
  4. #include "../base/types.h"
  5. #include "../base/logger.h"
  6. #include <memory>
  7. #include <atomic>
  8. #include <mutex>
  9. #include <chrono>
  10. #include <deque>
  11. #include <functional>
  12. #include <limits>
  13. extern "C" {
  14. #include <libavutil/avutil.h>
  15. #include <libavutil/time.h>
  16. }
  17. namespace av {
  18. namespace utils {
  19. // 同步错误常量
  20. const ErrorCode SYNC_ERROR = ErrorCode::PROCESSING_ERROR;
  21. /**
  22. * 改进的时钟类型
  23. */
  24. enum class ClockType {
  25. AUDIO,
  26. VIDEO,
  27. EXTERNAL,
  28. SYSTEM
  29. };
  30. /**
  31. * 同步策略
  32. */
  33. enum class SyncStrategy {
  34. AUDIO_MASTER, // 音频为主时钟
  35. VIDEO_MASTER, // 视频为主时钟
  36. EXTERNAL_MASTER, // 外部时钟为主
  37. ADAPTIVE // 自适应选择
  38. };
  39. /**
  40. * 同步状态
  41. */
  42. enum class SyncState {
  43. IDLE, // 空闲
  44. INITIALIZING, // 初始化中
  45. SYNCING, // 同步中
  46. SYNCHRONIZED, // 已同步
  47. DRIFT, // 轻微漂移
  48. ERROR, // 同步错误
  49. RECOVERING // 恢复中
  50. };
  51. /**
  52. * 时钟信息结构 - 与packets_sync.cpp的Clock结构保持一致
  53. */
  54. struct ClockInfo {
  55. double pts = std::numeric_limits<double>::quiet_NaN(); // 当前PTS,以秒为单位(与packets_sync.cpp一致)
  56. double pts_drift = 0.0; // clock base minus time at which we updated the clock
  57. double lastUpdate = 0.0; // 最后更新时间
  58. double speed = 1.0; // 播放速度
  59. int serial = 0; // 序列号 clock is based on a packet with this serial
  60. bool paused = false; // 是否暂停
  61. // SynchronizerV2特有的扩展字段(保持向后兼容)
  62. double time = 0.0; // 系统时间
  63. double drift = 0.0; // 时钟漂移(兼容字段)
  64. int64_t smoothedPts = AV_NOPTS_VALUE; // 平滑后的PTS
  65. ClockInfo() {
  66. double currentTime = av_gettime_relative() / 1000000.0;
  67. lastUpdate = currentTime;
  68. time = currentTime;
  69. }
  70. };
  71. /**
  72. * 同步配置 - 基于AVPlayer2的packets_sync.cpp优化
  73. */
  74. struct SyncConfigV2 {
  75. SyncStrategy syncStrategy = SyncStrategy::ADAPTIVE; // 同步策略
  76. // 同步阈值 - 参考packets_sync.h的定义
  77. double syncThreshold = 0.04; // AV_SYNC_THRESHOLD_MIN - 40ms
  78. double audioSyncThreshold = 0.04; // 40ms - 音频同步阈值
  79. double videoSyncThreshold = 0.04; // 40ms - 视频同步阈值
  80. double maxSyncError = 0.1; // AV_SYNC_THRESHOLD_MAX - 100ms
  81. double frameDropThreshold = 0.05; // 50ms - 丢帧阈值
  82. double frameDupThreshold = 0.1; // AV_SYNC_FRAMEDUP_THRESHOLD - 100ms
  83. double noSyncThreshold = 10.0; // AV_NOSYNC_THRESHOLD - 10s,超过此值不进行同步
  84. // 帧控制
  85. bool enableFrameDrop = true; // 启用丢帧
  86. bool enableFrameDuplicate = true; // 启用重复帧
  87. // 时钟更新参数
  88. double clockUpdateInterval = 0.01; // 10ms - 时钟更新间隔
  89. int smoothingWindow = 10; // 平滑窗口大小
  90. double smoothingFactor = 0.1; // 平滑因子
  91. // 自适应参数
  92. bool enableAdaptiveSync = true;
  93. double adaptiveThreshold = 0.02; // 20ms - 自适应阈值
  94. int adaptiveWindow = 30; // 自适应窗口
  95. // 恢复参数
  96. double recoveryThreshold = 0.2; // 200ms - 恢复阈值
  97. int maxRecoveryAttempts = 5; // 最大恢复尝试次数
  98. bool enableErrorRecovery = true; // 启用错误恢复
  99. // 性能参数
  100. bool enablePrediction = true; // 启用预测
  101. double predictionWindow = 0.1; // 100ms - 预测窗口
  102. // 兼容性字段 (保持向后兼容)
  103. SyncStrategy strategy = SyncStrategy::ADAPTIVE; // 与syncStrategy相同
  104. };
  105. /**
  106. * 同步统计信息
  107. */
  108. struct SyncStatsV2 {
  109. // 时钟值
  110. double audioClock = 0.0;
  111. double videoClock = 0.0;
  112. double externalClock = 0.0;
  113. double masterClock = 0.0;
  114. // 延迟信息
  115. double audioDelay = 0.0;
  116. double videoDelay = 0.0;
  117. double syncError = 0.0;
  118. double avgSyncError = 0.0;
  119. double maxSyncError = 0.0;
  120. // 帧处理统计
  121. uint64_t totalFrames = 0;
  122. uint64_t droppedFrames = 0;
  123. uint64_t duplicatedFrames = 0;
  124. uint64_t syncAdjustments = 0;
  125. // 状态信息
  126. SyncState state = SyncState::IDLE;
  127. ClockType masterClockType = ClockType::AUDIO;
  128. std::chrono::steady_clock::time_point lastUpdateTime;
  129. // 性能指标
  130. double cpuUsage = 0.0;
  131. double memoryUsage = 0.0;
  132. };
  133. /**
  134. * 帧决策结果
  135. */
  136. enum class FrameAction {
  137. DISPLAY, // 正常显示
  138. DROP, // 丢弃帧
  139. Frame_DUPLICATE, // 重复帧
  140. DELAY // 延迟显示
  141. };
  142. /**
  143. * 帧决策信息
  144. */
  145. struct FrameDecision {
  146. FrameAction action = FrameAction::DISPLAY;
  147. double delay = 0.0; // 延迟时间
  148. int64_t targetPts = AV_NOPTS_VALUE; // 目标PTS (FFmpeg原生格式)
  149. int64_t actualPts = AV_NOPTS_VALUE; // 实际PTS (FFmpeg原生格式)
  150. double syncError = 0.0; // 同步误差
  151. std::string reason; // 决策原因
  152. };
  153. /**
  154. * 回调函数类型
  155. */
  156. using SyncEventCallback = std::function<void(SyncState oldState, SyncState newState)>;
  157. using FrameDropCallback = std::function<void(ClockType clockType, int64_t pts)>;
  158. using FrameDuplicateCallback = std::function<void(ClockType clockType, int64_t pts)>;
  159. using SyncErrorCallback = std::function<void(double error, const std::string& reason)>;
  160. /**
  161. * 改进的同步器类 - 基于AVPlayer2的经验重新设计
  162. *
  163. * 主要改进:
  164. * 1. 更精确的时钟管理和同步算法
  165. * 2. 自适应同步策略
  166. * 3. 更好的错误恢复机制
  167. * 4. 性能优化和预测算法
  168. * 5. 详细的统计和监控
  169. */
  170. class SynchronizerV2 {
  171. public:
  172. explicit SynchronizerV2(const SyncConfigV2& config = SyncConfigV2());
  173. ~SynchronizerV2();
  174. // 生命周期管理
  175. ErrorCode initialize();
  176. ErrorCode start();
  177. ErrorCode stop();
  178. ErrorCode pause();
  179. ErrorCode resume();
  180. ErrorCode reset();
  181. // 设置流信息
  182. void setStreamInfo(bool hasAudio, bool hasVideo);
  183. ErrorCode close();
  184. // 时钟设置与获取
  185. ErrorCode setAudioClock(int64_t pts, double timeBase, int serial = 0);
  186. ErrorCode setVideoClock(int64_t pts, double timeBase, int serial = 0);
  187. ErrorCode setExternalClock(int64_t pts, double timeBase, int serial = 0);
  188. // 时钟获取 - 支持预测
  189. int64_t getAudioClock(bool predict = false) const;
  190. int64_t getVideoClock(bool predict = false) const;
  191. int64_t getExternalClock(bool predict = false) const;
  192. int64_t getMasterClock(bool predict = false) const;
  193. ClockType getMasterClockType() const { return masterClockType_; }
  194. // 同步决策 - 核心功能 (需要传入时间基准进行转换)
  195. FrameDecision shouldDisplayVideoFrame(int64_t pts, double timeBase, double duration = 0.0);
  196. FrameDecision shouldPlayAudioFrame(int64_t pts, double timeBase, double duration = 0.0);
  197. double calculateTargetDelay(int64_t pts, double timeBase, ClockType clockType);
  198. // 同步控制
  199. bool shouldDropFrame(int64_t pts, double timeBase, ClockType clockType);
  200. bool shouldDuplicateFrame(int64_t pts, double timeBase, ClockType clockType);
  201. double calculateSyncError() const;
  202. double calculateAudioDelay(int64_t pts, double timeBase) const;
  203. double calculateVideoDelay(int64_t pts, double timeBase) const;
  204. // 配置管理
  205. void setConfig(const SyncConfigV2& config);
  206. SyncConfigV2 getConfig() const;
  207. void setSyncStrategy(SyncStrategy strategy);
  208. SyncStrategy getSyncStrategy() const;
  209. void setPlaybackSpeed(double speed);
  210. double getPlaybackSpeed() const;
  211. // 状态查询
  212. SyncState getState() const { return state_; }
  213. bool isSynchronized() const;
  214. bool isRunning() const { return running_; }
  215. bool isPaused() const { return paused_; }
  216. // 统计信息
  217. SyncStatsV2 getStats() const;
  218. void resetStats();
  219. // 回调设置
  220. void setSyncEventCallback(SyncEventCallback callback);
  221. void setFrameDropCallback(FrameDropCallback callback);
  222. void setFrameDuplicateCallback(FrameDuplicateCallback callback);
  223. void setSyncErrorCallback(SyncErrorCallback callback);
  224. // 高级功能
  225. void enableAdaptiveSync(bool enable);
  226. void enablePrediction(bool enable);
  227. void setClockUpdateInterval(double interval);
  228. void setSmoothingWindow(int window);
  229. // 调试和监控
  230. std::string getDebugInfo() const;
  231. void dumpClockInfo() const;
  232. private:
  233. // 内部时钟管理
  234. ErrorCode updateClock(ClockType type, int64_t pts, double timeBase, int serial);
  235. int64_t getClock(ClockType type, bool predict = false) const;
  236. void resetClock(ClockType type);
  237. void pauseClock(ClockType type, bool pause);
  238. void syncClockToSlave(ClockInfo* slave, const ClockInfo* master);
  239. // PTS转换辅助方法
  240. double ptsToSeconds(int64_t pts, double timeBase) const;
  241. int64_t secondsToPts(double seconds, double timeBase) const;
  242. // 同步算法
  243. void updateMasterClock();
  244. void selectMasterClock();
  245. void updateSyncState();
  246. void updateStats();
  247. // 平滑和预测
  248. int64_t smoothClock(ClockType type, int64_t newPts);
  249. int64_t predictClock(ClockType type, double futureTime) const;
  250. void updateClockHistory(ClockType type, int64_t pts);
  251. // 自适应算法
  252. void adaptiveSyncUpdate();
  253. bool shouldSwitchMasterClock();
  254. void handleSyncError(double error);
  255. // 错误恢复
  256. void attemptRecovery();
  257. void performDelayedRecovery();
  258. void resetSyncState();
  259. // 工具函数
  260. double getCurrentTime() const;
  261. double getSystemTime() const;
  262. void notifyStateChange(SyncState newState);
  263. void notifyFrameDrop(ClockType type, int64_t pts);
  264. void notifyFrameDuplicate(ClockType type, int64_t pts);
  265. void notifySyncError(double error, const std::string& reason);
  266. // 内部版本,假设调用者已经持有clockMutex_锁
  267. double calculateSyncErrorInternal() const;
  268. private:
  269. // 配置
  270. SyncConfigV2 config_;
  271. mutable std::mutex configMutex_;
  272. // 状态
  273. std::atomic<SyncState> state_{SyncState::IDLE};
  274. std::atomic<ClockType> masterClockType_{ClockType::AUDIO};
  275. std::atomic<bool> initialized_{false};
  276. std::atomic<bool> running_{false};
  277. std::atomic<bool> paused_{false};
  278. // 时钟
  279. ClockInfo audioClock_;
  280. ClockInfo videoClock_;
  281. ClockInfo externalClock_;
  282. mutable std::mutex clockMutex_;
  283. // 历史记录
  284. std::deque<int64_t> audioClockHistory_;
  285. std::deque<int64_t> videoClockHistory_;
  286. std::deque<double> syncErrorHistory_;
  287. mutable std::mutex historyMutex_;
  288. // 统计信息
  289. SyncStatsV2 stats_;
  290. mutable std::mutex statsMutex_;
  291. // 时间记录
  292. std::chrono::steady_clock::time_point startTime_;
  293. std::chrono::steady_clock::time_point lastClockUpdate_;
  294. std::chrono::steady_clock::time_point lastStatsUpdate_;
  295. // 自适应参数
  296. int recoveryAttempts_ = 0;
  297. double lastSyncError_ = 0.0;
  298. double recoveryStartTime_ = 0.0;
  299. std::chrono::steady_clock::time_point lastRecoveryTime_;
  300. // 状态变化回调
  301. std::function<void(SyncState, ClockType)> stateChangeCallback_;
  302. // 回调函数
  303. SyncEventCallback syncEventCallback_;
  304. FrameDropCallback frameDropCallback_;
  305. FrameDuplicateCallback frameDuplicateCallback_;
  306. SyncErrorCallback syncErrorCallback_;
  307. // 流信息
  308. std::atomic<bool> hasAudioStream_{false};
  309. std::atomic<bool> hasVideoStream_{false};
  310. };
  311. } // namespace utils
  312. } // namespace av
  313. #endif // AV_UTILS_SYNCHRONIZER_V2_H