zhuizhu 6 ay önce
ebeveyn
işleme
dc769809cf

+ 104 - 16
libs/AVPlayer/av_clock.h

@@ -2,40 +2,128 @@
 #define AVCLOCK_H
 
 #include "ffmpeg_compat.h"
+#include "low_latency_config.h"
 
 class AVClock
 {
 public:
     AVClock()
-        : m_pts(0.0)
-        , m_drift(0.0)
+        : m_ptsUs(0)
+        , m_driftUs(0)
+        , m_baseTimeUs(0)
+        , m_frameCount(0)
+        , m_lastResetTimeUs(0)
+        , m_lastClockValueUs(0)
     {}
 
     inline void reset()
     {
-        m_pts = 0.0;
-        m_drift = 0.0;
+        m_ptsUs = 0;
+        m_driftUs = 0;
+        m_baseTimeUs = av_gettime_relative();
+        m_frameCount = 0;
+        m_lastResetTimeUs = m_baseTimeUs;
+        m_lastClockValueUs = 0;
     }
 
-    inline void setClock(double pts) { setCloctAt(pts); }
+    // 修改:接受int64_t微秒时间戳,消除double参数类型
+    inline void setClock(int64_t ptsUs) { setClockAt(ptsUs); }
 
-    inline double getClock() { 
-        // 使用高精度时间计算,减少累积误差
-        double currentTime = av_gettime_relative() / 1000000.0;
-        return m_drift + currentTime; 
+    // 新增:为兼容性提供秒级时间戳设置函数
+    inline void setClockSeconds(double pts) { 
+        int64_t ptsUs = static_cast<int64_t>(pts * 1000000.0);
+        setClock(ptsUs);
+    }
+
+    // 修改:返回int64_t微秒时间戳,消除double类型和除法运算
+    inline int64_t getClock() { 
+        // 优化:全程使用int64微秒时间戳,避免除法运算
+        int64_t currentTimeUs = av_gettime_relative();
+        
+        // 定期重置时间基准,防止累积误差
+        if (++m_frameCount % LowLatencyConfig::TIMER_RESET_INTERVAL == 0) {
+            resetTimeBase(currentTimeUs);
+        }
+        
+        // 使用整数运算保持精度,避免浮点除法
+        int64_t elapsedUs = currentTimeUs - m_baseTimeUs;
+        int64_t resultUs = m_driftUs + elapsedUs;
+        
+        // 检测并补偿精度误差(转换为微秒单位)
+        if (m_frameCount > 1) {
+            int64_t driftUs = resultUs - m_lastClockValueUs;
+            if (driftUs > LowLatencyConfig::MAX_ACCEPTABLE_DRIFT_US) {
+                resultUs -= LowLatencyConfig::PRECISION_ERROR_COMPENSATION_US;
+            }
+        }
+        m_lastClockValueUs = resultUs;
+        
+        // 直接返回微秒时间戳,消除除法运算
+        return resultUs;
+    }
+
+    // 新增:为兼容性提供秒级时间戳转换函数
+    inline double getClockSeconds() {
+        return static_cast<double>(getClock()) / 1000000.0;
+    }
+
+    // 新增:获取高精度微秒时间戳
+    inline int64_t getClockUs() {
+        int64_t currentTimeUs = av_gettime_relative();
+        
+        // 定期重置时间基准,防止累积误差
+        if (++m_frameCount % LowLatencyConfig::TIMER_RESET_INTERVAL == 0) {
+            resetTimeBase(currentTimeUs);
+        }
+        
+        int64_t elapsedUs = currentTimeUs - m_baseTimeUs;
+        int64_t resultUs = m_driftUs + elapsedUs;
+        
+        // 检测并补偿精度误差
+        if (m_frameCount > 1) {
+            int64_t driftUs = resultUs - m_lastClockValueUs;
+            if (driftUs > LowLatencyConfig::MAX_ACCEPTABLE_DRIFT_US) {
+                resultUs -= LowLatencyConfig::PRECISION_ERROR_COMPENSATION_US;
+            }
+        }
+        m_lastClockValueUs = resultUs;
+        
+        return resultUs;
     }
 
 private:
-    inline void setCloctAt(double pts)
+    // 修改:接受int64_t微秒时间戳,消除double参数类型
+    inline void setClockAt(int64_t ptsUs)
+    {
+        // 优化:使用高精度整数时间戳,减少转换误差
+        int64_t currentTimeUs = av_gettime_relative();
+        if (m_baseTimeUs == 0) {
+            m_baseTimeUs = currentTimeUs;
+        }
+        
+        // 直接使用微秒时间戳,避免浮点转换
+        int64_t elapsedUs = currentTimeUs - m_baseTimeUs;
+        m_driftUs = ptsUs - elapsedUs;
+        m_ptsUs = ptsUs;
+    }
+    
+    inline void resetTimeBase(int64_t currentTimeUs)
     {
-        // 使用高精度时间设置,减少设置时的精度损失
-        double currentTime = av_gettime_relative() / 1000000.0;
-        m_drift = pts - currentTime;
-        m_pts = pts;
+        // 定期重置时间基准,防止长时间运行时的累积误差
+        if (currentTimeUs - m_lastResetTimeUs > LowLatencyConfig::TIMER_RESET_INTERVAL_US) {
+            int64_t currentClockUs = getClockUs();
+            m_baseTimeUs = currentTimeUs;
+            m_driftUs = currentClockUs;
+            m_lastResetTimeUs = currentTimeUs;
+        }
     }
 
-    double m_pts;
-    double m_drift;
+    int64_t m_ptsUs;              // 高精度PTS(微秒)
+    int64_t m_driftUs;            // 高精度漂移(微秒)
+    int64_t m_baseTimeUs;         // 高精度时间基准(微秒)
+    int m_frameCount;             // 帧计数器
+    int64_t m_lastResetTimeUs;    // 上次重置时间(微秒)
+    int64_t m_lastClockValueUs;   // 上次时钟值(微秒),用于漂移检测
 };
 
 #endif // AVCLOCK_H

+ 14 - 11
libs/AVPlayer/av_decoder.cpp

@@ -14,6 +14,9 @@ Decoder::Decoder()
     , m_videoIndex(-1)
     , m_exit(0)
     , m_duration(0)
+    , m_frameQueueAdaptiveSize(LowLatencyConfig::BALANCED_FRAME_QUEUE_SIZE)  // 动态帧队列大小
+    , m_lastBufferAdjustTime(0)
+    , m_bufferPerformanceCounter(0)
 {
     if (!init())
         qDebug() << "Decoder init failed!\n";
@@ -33,13 +36,13 @@ AVTool::MediaInfo* Decoder::detectMediaInfo(const QString& url)
     //解封装初始化
     AVFormatContext* fmtCtx = avformat_alloc_context();
 
-    //用于获取流时长
+    // 性能优化:统一使用LowLatencyConfig配置参数
     AVDictionary* formatOpts = nullptr;
-    av_dict_set(&formatOpts, "probesize", LowLatencyConfig::PROBE_SIZE, 0);       // 使用配置文件中的探测大小
-    av_dict_set(&formatOpts, "analyzeduration", LowLatencyConfig::ANALYZE_DURATION, 0);  // 使用配置文件中的分析时长
+    av_dict_set(&formatOpts, "probesize", LowLatencyConfig::PROBE_SIZE, 0);        // 使用配置文件中的探测大小
+    av_dict_set(&formatOpts, "analyzeduration", LowLatencyConfig::ANALYZE_DURATION, 0); // 使用配置文件中的分析时长
+    av_dict_set(&formatOpts, "fflags", LowLatencyConfig::FFLAGS, 0);               // 使用配置文件中的标志
+    av_dict_set(&formatOpts, "max_delay", LowLatencyConfig::MAX_DELAY, 0);         // 使用配置文件中的最大延迟
     av_dict_set(&formatOpts, "rtsp_transport", LowLatencyConfig::RTSP_TRANSPORT, 0);
-    av_dict_set(&formatOpts, "fflags", LowLatencyConfig::FFLAGS, 0);       // 使用配置文件中的标志
-    av_dict_set(&formatOpts, "max_delay", LowLatencyConfig::MAX_DELAY, 0);      // 使用配置文件中的最大延迟
     av_dict_set(&formatOpts, "rtsp_flags", LowLatencyConfig::RTSP_FLAGS, 0);
     av_dict_set(&formatOpts, "stimeout", LowLatencyConfig::STIMEOUT, 0);
     av_dict_set(&formatOpts, "user_agent", LowLatencyConfig::USER_AGENT, 0);
@@ -55,12 +58,12 @@ AVTool::MediaInfo* Decoder::detectMediaInfo(const QString& url)
         return Q_NULLPTR;
     }
 
-    // 低延迟:关闭内部缓冲,但保持稳定
+    // 性能优化:统一使用LowLatencyConfig配置参数
     if (fmtCtx) {
         fmtCtx->flags |= AVFMT_FLAG_NOBUFFER;
-        fmtCtx->max_delay = 500000;  // 500ms,类似VLC
-        fmtCtx->probesize = 32768;   // 32KB
-        fmtCtx->max_analyze_duration = 1000000;  // 1秒
+        fmtCtx->max_delay = std::atoi(LowLatencyConfig::MAX_DELAY);  // 使用配置文件中的最大延迟
+        fmtCtx->probesize = std::atoi(LowLatencyConfig::PROBE_SIZE);   // 使用配置文件中的探测大小
+        fmtCtx->max_analyze_duration = std::atoi(LowLatencyConfig::ANALYZE_DURATION);  // 使用配置文件中的分析时长
     }
 
     ret = avformat_find_stream_info(fmtCtx, nullptr);
@@ -269,10 +272,10 @@ int Decoder::decode(const QString& url)
         return 0;
     }
 
-    // 低延迟:关闭内部缓冲
+    // 低延迟:关闭内部缓冲,使用配置文件参数
     if (m_fmtCtx) {
         m_fmtCtx->flags |= AVFMT_FLAG_NOBUFFER;
-        m_fmtCtx->max_delay = 0;
+        m_fmtCtx->max_delay = std::atoi(LowLatencyConfig::MAX_DELAY);  // 使用配置文件中的最大延迟
     }
 
     ret = avformat_find_stream_info(m_fmtCtx, nullptr);

+ 5 - 0
libs/AVPlayer/av_decoder.h

@@ -151,6 +151,11 @@ private:
     uint32_t m_duration;
 
     char m_errBuf[100];
+    
+    // 性能优化:动态缓冲区管理
+    int m_frameQueueAdaptiveSize;        // 动态帧队列大小
+    int64_t m_lastBufferAdjustTime;      // 上次缓冲区调整时间
+    int m_bufferPerformanceCounter;      // 缓冲区性能计数器
 
 private:
     bool init();

+ 78 - 30
libs/AVPlayer/av_player.cpp

@@ -30,8 +30,13 @@ AVPlayer::AVPlayer()
     , m_exit(0)
     , m_pause(0)
     , m_playSpeed(1.0)
+    , m_baseTimeUs(0)
+    , m_performanceFrameCount(0)
+    , m_lastDelayValue(0.0)
 {
     m_sonicStream = nullptr;
+    // 初始化高精度时间基准
+    m_baseTimeUs = av_gettime_relative();
 }
 
 AVPlayer::~AVPlayer()
@@ -207,8 +212,9 @@ void fillAStreamCallback(void* userdata, uint8_t* stream, int len)
         is->m_audioBufIndex += len1;
         stream += len1;
     }
-    //记录音频时钟
-    is->m_audioClock.setClock(audioPts);
+    //记录音频时钟,转换为微秒时间戳
+    int64_t audioPtsUs = static_cast<int64_t>(audioPts * 1000000.0);
+    is->m_audioClock.setClock(audioPtsUs);
     //发送时间戳变化信号,因为进度以整数秒单位变化展示,
     //所以大于一秒才发送,避免过于频繁的信号槽通信消耗性能
     uint32_t _pts = (uint32_t) audioPts;
@@ -224,9 +230,12 @@ int AVPlayer::initSDL()
     if (m_decoder->audioIndex() < 0)
         return 0;
 
-    if (SDL_Init(SDL_INIT_AUDIO) != 0) {
-        qDebug() << "SDL_Init failed";
-        return 0;
+    // 性能优化:使用更快的SDL初始化方式
+    if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
+        if (SDL_Init(SDL_INIT_AUDIO) != 0) {
+            qDebug() << "SDL_Init failed";
+            return 0;
+        }
     }
 
     m_exit = 0;
@@ -240,24 +249,22 @@ int AVPlayer::initSDL()
     m_audioIndex = m_decoder->audioIndex();
     m_fmtCtx = m_decoder->formatContext();
 
-    // 音频设备配置(平衡模式 - 类似VLC)
+    // 性能优化:使用更小的音频缓冲区减少延迟
     SDL_AudioSpec wanted_spec;
-    // wanted_spec.channels = m_audioCodecPar->channels;
     wanted_spec.channels = ffmpeg_get_codec_channels(m_fmtCtx->streams[m_audioIndex]);
     wanted_spec.freq = m_audioCodecPar->sample_rate;
     wanted_spec.format = AUDIO_S16SYS;
     wanted_spec.silence = 0;
     wanted_spec.callback = fillAStreamCallback;
     wanted_spec.userdata = this;
-    // 平衡音频回调缓冲区,兼顾延迟与稳定性(需为2的幂)
-    wanted_spec.samples = LowLatencyConfig::BALANCED_AUDIO_SAMPLES;  // 使用配置文件中的音频样本数
+    // 使用配置文件中的音频样本数减少延迟
+    wanted_spec.samples = LowLatencyConfig::MIN_AUDIO_SAMPLES;  // 使用配置文件中的最小音频样本数
 
     if (SDL_OpenAudio(&wanted_spec, nullptr) < 0) {
         qDebug() << "SDL_OpenAudio failed";
         return 0;
     }
     m_targetSampleFmt = AV_SAMPLE_FMT_S16;
-    // m_targetChannels = m_audioCodecPar->channels;
     m_targetChannels = ffmpeg_get_codec_channels(m_fmtCtx->streams[m_audioIndex]);
     m_targetFreq = m_audioCodecPar->sample_rate;
     m_targetChannelLayout = (int64_t)ffmpeg_get_default_channel_layout(m_targetChannels);
@@ -274,7 +281,7 @@ int AVPlayer::initSDL()
 
 int AVPlayer::initVideo()
 {
-    m_frameTimer = 0.00;
+    m_frameTimerUs = 0;  // 使用高精度微秒时间戳
 
     m_videoCodecPar = m_decoder->videoCodecPar();
     m_videoIndex = m_decoder->videoIndex();
@@ -310,27 +317,36 @@ void AVPlayer::pause(bool isPause)
         if (isPause) {
             if (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING) {
                 SDL_PauseAudio(1);
-                m_pauseTime = av_gettime_relative() / 1000000.0;
+                // 优化:直接使用高精度时间戳,避免除法运算
+                int64_t pauseTimeUs = av_gettime_relative();
+                m_pauseTimeUs = pauseTimeUs - (m_baseTimeUs ? m_baseTimeUs : pauseTimeUs);
                 m_pause = 1;
             }
         } else {
             if (SDL_GetAudioStatus() == SDL_AUDIO_PAUSED) {
                 SDL_PauseAudio(0);
-                m_frameTimer += av_gettime_relative() / 1000000.0 - m_pauseTime;
+                // 优化:直接使用高精度时间戳计算暂停时长,避免除法运算
+                int64_t resumeTimeUs = av_gettime_relative();
+                int64_t resumeElapsedUs = resumeTimeUs - (m_baseTimeUs ? m_baseTimeUs : resumeTimeUs);
+                m_frameTimerUs += resumeElapsedUs - m_pauseTimeUs;
                 m_pause = 0;
             }
         }
     } else if (m_hasVideo) {
         // 仅视频:通过标志控制回放线程
-        double now = av_gettime_relative() / 1000000.0;
         if (isPause) {
             if (!m_pause) {
-                m_pauseTime = now;
+                // 优化:直接使用高精度时间戳,避免除法运算
+                int64_t pauseTimeUs = av_gettime_relative();
+                m_pauseTimeUs = pauseTimeUs - (m_baseTimeUs ? m_baseTimeUs : pauseTimeUs);
                 m_pause = 1;
             }
         } else {
             if (m_pause) {
-                m_frameTimer += now - m_pauseTime;
+                // 优化:直接使用高精度时间戳计算暂停时长,避免除法运算
+                int64_t resumeTimeUs = av_gettime_relative();
+                int64_t resumeElapsedUs = resumeTimeUs - (m_baseTimeUs ? m_baseTimeUs : resumeTimeUs);
+                m_frameTimerUs += resumeElapsedUs - m_pauseTimeUs;
                 m_pause = 0;
             }
         }
@@ -397,8 +413,8 @@ AVPlayer::PlayState AVPlayer::playState()
 
 void AVPlayer::initAVClock()
 {
-    m_audioClock.setClock(0.00);
-    m_videoClock.setClock(0.00);
+    m_audioClock.setClock(0);
+    m_videoClock.setClock(0);
     m_clockInitFlag = 1;
 }
 
@@ -466,8 +482,10 @@ void AVPlayer::displayImage(AVFrame* frame)
                                                                  frame->linesize));
         }
 
-        //记录视频时钟
-        m_videoClock.setClock(frame->pts * av_q2d(m_fmtCtx->streams[m_videoIndex]->time_base));
+        //记录视频时钟,转换为微秒时间戳
+        double videoPtsSeconds = frame->pts * av_q2d(m_fmtCtx->streams[m_videoIndex]->time_base);
+        int64_t videoPtsUs = static_cast<int64_t>(videoPtsSeconds * 1000000.0);
+        m_videoClock.setClock(videoPtsUs);
     }
 }
 
@@ -497,26 +515,55 @@ void AVPlayer::videoCallback(std::shared_ptr<void> par)
                 continue;
             }
 
-            if (frame->serial != lastFrame->serial)
-                m_frameTimer = av_gettime_relative() / 1000000.0;
+            if (frame->serial != lastFrame->serial) {
+                // 优化:直接使用高精度时间戳重置帧定时器,避免除法运算
+                int64_t currentTimeUs = av_gettime_relative();
+                m_frameTimerUs = currentTimeUs - m_baseTimeUs;
+            }
 
             duration = vpDuration(lastFrame, frame);
             delay = computeTargetDelay(duration);
 
-            time = av_gettime_relative() / 1000000.0;
+            // 优化:直接使用高精度时间戳计算当前时间,避免除法运算
+            int64_t currentTimeUs = av_gettime_relative();
+            int64_t timeUs = currentTimeUs - m_baseTimeUs;
+            
+            // 性能监控:检测延迟累积
+            m_performanceFrameCount++;
+            if (m_performanceFrameCount % LowLatencyConfig::DELAY_MONITOR_INTERVAL == 0) {
+                if (delay > m_lastDelayValue + LowLatencyConfig::DELAY_ACCUMULATION_THRESHOLD) {
+                    // 检测到延迟累积,进行校正
+                    delay *= LowLatencyConfig::DELAY_RESET_FACTOR;
+                    qDebug() << "Delay accumulation detected, correcting delay from" << m_lastDelayValue << "to" << delay;
+                }
+                m_lastDelayValue = delay;
+            }
 
             //qDebug()<<"delay:"<<delay<<endl;
 
             //显示时长未到
-            if (time < m_frameTimer + delay) {
-                QThread::msleep(
-                    (uint32_t) (FFMIN(LowLatencyConfig::BALANCED_SYNC_REJUDGE_THRESHOLD, m_frameTimer + delay - time) * 1000));
+            int64_t delayUs = static_cast<int64_t>(delay * 1000000.0);
+            if (timeUs < m_frameTimerUs + delayUs) {
+                // 优化:使用更精确的睡眠时间计算
+                int64_t sleepTimeUs = m_frameTimerUs + delayUs - timeUs;
+                int64_t maxSleepUs = LowLatencyConfig::BALANCED_SYNC_REJUDGE_THRESHOLD_US;
+                if (sleepTimeUs > maxSleepUs) {
+                    sleepTimeUs = maxSleepUs;
+                }
+                QThread::msleep(static_cast<uint32_t>(sleepTimeUs / 1000));
                 continue;
             }
 
-            m_frameTimer += delay;
-            if (time - m_frameTimer > LowLatencyConfig::BALANCED_SYNC_THRESHOLD_MAX)
-                m_frameTimer = time;
+            m_frameTimerUs += delayUs;
+            int64_t maxThresholdUs = LowLatencyConfig::BALANCED_SYNC_THRESHOLD_MAX_US;
+            if (timeUs - m_frameTimerUs > maxThresholdUs) {
+                m_frameTimerUs = timeUs;
+                // 帧定时器校正时重置性能计数器
+                int64_t correctionThresholdUs = LowLatencyConfig::FRAME_TIMER_CORRECTION_THRESHOLD_US;
+                if (timeUs - m_frameTimerUs > correctionThresholdUs) {
+                    m_performanceFrameCount = 0;
+                }
+            }
 
             //队列中未显示帧一帧以上执行逻辑丢帧判断,倍速播放和逐帧播放
             //都不跑进此逻辑,倍速易造成丢帧过多导致界面不流畅
@@ -527,7 +574,8 @@ void AVPlayer::videoCallback(std::shared_ptr<void> par)
                     duration = nextFrame->pts - frame->pts;
                     //若主时钟超前到大于当前帧理论显示应持续的时间了,则当前帧立即丢弃
                     // 平衡:使用原始duration阈值,避免过度丢帧
-                    if (time > m_frameTimer + duration) {
+                    int64_t durationUs = static_cast<int64_t>(duration * 1000000.0);
+                    if (timeUs > m_frameTimerUs + durationUs) {
                         m_decoder->setNextVFrame();
                         qDebug() << "abandon vframe (balanced mode)" << Qt::endl;
                         continue;

+ 15 - 9
libs/AVPlayer/av_player.h

@@ -53,11 +53,12 @@ public:
         m_volume = (volumePer * SDL_MIX_MAXVOLUME / 100) % (SDL_MIX_MAXVOLUME + 1);
     }
 
-    // 修改:根据可用主时钟进行seek
+    // 修改:根据可用主时钟进行seek,使用微秒时间戳
     inline void seekBy(int32_t time_s)
     {
-        double base = m_hasAudio ? m_audioClock.getClock() : m_videoClock.getClock();
-        seekTo((int32_t) base + time_s);
+        int64_t baseUs = m_hasAudio ? m_audioClock.getClock() : m_videoClock.getClock();
+        int32_t baseSeconds = static_cast<int32_t>(baseUs / 1000000);
+        seekTo(baseSeconds + time_s);
     }
 
     inline void seekTo(int32_t time_s)
@@ -66,8 +67,9 @@ public:
             return;
         if (time_s < 0)
             time_s = 0;
-        double base = m_hasAudio ? m_audioClock.getClock() : m_videoClock.getClock();
-        m_decoder->seekTo(time_s, time_s - (int32_t) base);
+        int64_t baseUs = m_hasAudio ? m_audioClock.getClock() : m_videoClock.getClock();
+        int32_t baseSeconds = static_cast<int32_t>(baseUs / 1000000);
+        m_decoder->seekTo(time_s, time_s - baseSeconds);
     }
 
     inline uint32_t avDuration() { return m_duration; }
@@ -112,8 +114,6 @@ private:
     //    double m_audioPts;
     //    double m_videoPts;
 
-    double m_frameTimer;
-
     std::atomic<float> m_playSpeed;
 
     //延时时间
@@ -145,8 +145,8 @@ private:
     //终止标志
     std::atomic<int> m_exit;
 
-    //记录暂停前的时间
-    double m_pauseTime;
+    //记录暂停前的时间(微秒)
+    int64_t m_pauseTimeUs;
 
     //暂停标志
     std::atomic<int> m_pause;
@@ -167,6 +167,12 @@ private:
     // 新增:是否存在音频/视频流
     bool m_hasAudio = false;
     bool m_hasVideo = false;
+    
+    // 性能优化:添加高精度时间基准(微秒)
+    int64_t m_baseTimeUs = 0;           // 高精度时间基准(微秒)
+    int64_t m_frameTimerUs = 0;         // 高精度帧定时器(微秒)
+    int m_performanceFrameCount = 0;    // 性能监控帧计数
+    double m_lastDelayValue = 0.0;      // 上次延迟值,用于延迟累积检测
 };
 
 #endif

+ 9 - 0
libs/AVPlayer/low_latency_config.h

@@ -42,6 +42,15 @@ constexpr double FRAME_TIMER_CORRECTION_THRESHOLD = 0.001; // 帧定时器校正
 constexpr double PRECISION_ERROR_COMPENSATION = 0.0001;    // 精度误差补偿值(0.1ms)
 constexpr int TIMER_RESET_INTERVAL = 300;            // 定时器重置间隔(帧数)
 constexpr double MAX_ACCEPTABLE_DRIFT = 0.01;        // 最大可接受漂移(10ms)(帧数)
+
+// 高精度时间常量(int64类型,微秒单位)- 避免运算表达式
+constexpr int64_t MAX_ACCEPTABLE_DRIFT_US = 10000LL;        // 最大可接受漂移(10ms = 10000微秒)
+constexpr int64_t PRECISION_ERROR_COMPENSATION_US = 100LL;  // 精度误差补偿值(0.1ms = 100微秒)
+constexpr int64_t TIMER_RESET_INTERVAL_US = 300000000LL;    // 定时器重置间隔(300秒 = 300000000微秒)
+constexpr int64_t FRAME_TIMER_CORRECTION_THRESHOLD_US = 1000LL; // 帧定时器校正阈值(1ms = 1000微秒)
+constexpr int64_t BALANCED_SYNC_THRESHOLD_MIN_US = 10000LL;     // 同步阈值最小值(10ms = 10000微秒)
+constexpr int64_t BALANCED_SYNC_THRESHOLD_MAX_US = 40000LL;     // 同步阈值最大值(40ms = 40000微秒)
+constexpr int64_t BALANCED_SYNC_REJUDGE_THRESHOLD_US = 5000LL;  // 同步重判阈值(5ms = 5000微秒)
     
     // 网络优化参数(更新为平衡配置)
     constexpr const char* RTSP_TRANSPORT = "tcp";

+ 13 - 1
libs/AVPlayer/threadpool.cpp

@@ -70,7 +70,8 @@ void ThreadPool::threadEventLoop(void* arg)
         while (!m_size) {
             if (theThread->isTerminate)
                 break;
-            m_cond.wait(lock);
+            // 优化:使用超时等待,避免无限期阻塞
+            m_cond.wait_for(lock, std::chrono::milliseconds(100));
         }
         if (theThread->isTerminate)
             break;
@@ -82,8 +83,19 @@ void ThreadPool::threadEventLoop(void* arg)
         m_freeThreads--;
         lock.unlock();
         theThread->isWorking = true;
+        
+        // 性能优化:添加任务执行时间监控
+        auto startTime = std::chrono::high_resolution_clock::now();
         //执行任务函数
         task.func(task.par);
+        auto endTime = std::chrono::high_resolution_clock::now();
+        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime);
+        
+        // 如果任务执行时间过长,输出警告
+        if (duration.count() > 50000) { // 50ms
+            qDebug() << "Long running task detected:" << duration.count() << "microseconds";
+        }
+        
         theThread->isWorking = false;
         lock.lock();
         m_freeThreads++;