av_player.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. #include "av_player.h"
  2. #include <QDebug>
  3. #include <QImage>
  4. #include <QThread>
  5. #include "threadpool.h"
  6. #include "vframe.h"
  7. #include "low_latency_config.h"
  8. // 同步阈值定义已移至配置文件(low_latency_config.h)
  9. //单帧视频时长阈值上限,用于适配低帧时同步,
  10. //帧率过低视频帧超前不适合翻倍延迟,应特殊
  11. //处理,这里设置上限一秒10帧
  12. //同步操作摆烂阈值上限,此时同步已无意义
  13. AVPlayer::AVPlayer()
  14. : m_decoder(new Decoder)
  15. , m_fmtCtx(nullptr)
  16. , m_audioFrame(av_frame_alloc())
  17. , m_imageWidth(300)
  18. , m_imageHeight(300)
  19. , m_swrCtx(nullptr)
  20. , m_swsCtx(nullptr)
  21. , m_buffer(nullptr)
  22. , m_audioBuf(nullptr)
  23. , m_duration(0)
  24. , m_volume(30)
  25. , m_exit(0)
  26. , m_pause(0)
  27. , m_playSpeed(1.0)
  28. , m_baseTimeUs(0)
  29. , m_performanceFrameCount(0)
  30. , m_lastDelayValue(0.0)
  31. {
  32. m_sonicStream = nullptr;
  33. // 初始化高精度时间基准
  34. m_baseTimeUs = av_gettime_relative();
  35. }
  36. AVPlayer::~AVPlayer()
  37. {
  38. av_frame_free(&m_audioFrame);
  39. clearPlayer();
  40. delete m_decoder;
  41. if (m_swrCtx)
  42. swr_free(&m_swrCtx);
  43. if (m_swsCtx)
  44. sws_freeContext(m_swsCtx);
  45. if (m_audioBuf)
  46. av_free(m_audioBuf);
  47. if (m_buffer)
  48. av_free(m_buffer);
  49. }
  50. int AVPlayer::play(const QString& url)
  51. {
  52. clearPlayer();
  53. if (!m_decoder->decode(url)) {
  54. qDebug() << "decode failed";
  55. return 0;
  56. }
  57. //解码成功可获取流时长
  58. m_duration = m_decoder->avDuration();
  59. emit AVDurationChanged(m_duration);
  60. m_pause = 0;
  61. m_clockInitFlag = -1;
  62. // 判断是否存在音/视频流
  63. m_audioIndex = m_decoder->audioIndex();
  64. m_videoIndex = m_decoder->videoIndex();
  65. m_hasAudio = (m_audioIndex >= 0);
  66. m_hasVideo = (m_videoIndex >= 0);
  67. bool ok = false;
  68. if (m_hasAudio) {
  69. if (initSDL()) {
  70. ok = true;
  71. } else {
  72. qDebug() << "init sdl failed!";
  73. }
  74. }
  75. if (m_hasVideo) {
  76. if (initVideo()) {
  77. ok = true;
  78. } else {
  79. qDebug() << "init video failed!";
  80. }
  81. }
  82. // 仅音频时,主动初始化时钟
  83. if (!m_hasVideo && m_hasAudio) {
  84. initAVClock();
  85. }
  86. return ok ? 1 : 0;
  87. }
  88. void fillAStreamCallback(void* userdata, uint8_t* stream, int len)
  89. {
  90. memset(stream, 0, len);
  91. AVPlayer* is = (AVPlayer*) userdata;
  92. static double audioPts = 0.00;
  93. while (len > 0) {
  94. if (is->m_exit)
  95. return;
  96. if (is->m_audioBufIndex >= is->m_audioBufSize) { /*index到缓冲区末尾,重新填充数据*/
  97. int ret = is->m_decoder->getAFrame(is->m_audioFrame);
  98. if (ret) {
  99. is->m_audioBufIndex = 0;
  100. if ((is->m_targetSampleFmt != is->m_audioFrame->format
  101. || is->m_targetChannelLayout != (int64_t)ffmpeg_get_frame_channel_layout(is->m_audioFrame)
  102. || is->m_targetFreq != is->m_audioFrame->sample_rate
  103. || is->m_targetNbSamples != is->m_audioFrame->nb_samples)
  104. && !is->m_swrCtx) {
  105. is->m_swrCtx = ffmpeg_swr_alloc_set_opts(nullptr,
  106. is->m_targetChannelLayout,
  107. is->m_targetSampleFmt,
  108. is->m_targetFreq,
  109. (int64_t)ffmpeg_get_frame_channel_layout(is->m_audioFrame),
  110. (enum AVSampleFormat) is->m_audioFrame->format,
  111. is->m_audioFrame->sample_rate,
  112. 0,
  113. nullptr);
  114. if (!is->m_swrCtx || swr_init(is->m_swrCtx) < 0) {
  115. qDebug() << "swr_init failed";
  116. return;
  117. }
  118. }
  119. if (is->m_swrCtx) {
  120. const uint8_t** in = (const uint8_t**) is->m_audioFrame->extended_data;
  121. int out_count = (uint64_t) is->m_audioFrame->nb_samples * is->m_targetFreq
  122. / is->m_audioFrame->sample_rate
  123. + 256;
  124. int out_size = ffmpeg_get_buffer_size(is->m_targetSampleFmt,
  125. is->m_targetChannels,
  126. out_count,
  127. 0);
  128. if (out_size < 0) {
  129. qDebug() << "av_samples_get_buffer_size failed";
  130. return;
  131. }
  132. av_fast_malloc(&is->m_audioBuf, &is->m_audioBufSize, out_size);
  133. if (!is->m_audioBuf) {
  134. qDebug() << "av_fast_malloc failed";
  135. return;
  136. }
  137. int len2 = swr_convert(is->m_swrCtx,
  138. &is->m_audioBuf,
  139. out_count,
  140. in,
  141. is->m_audioFrame->nb_samples);
  142. if (len2 < 0) {
  143. qDebug() << "swr_convert failed";
  144. return;
  145. }
  146. if (is->m_playSpeed != 1.0) {
  147. sonicSetSpeed(is->m_sonicStream, is->m_playSpeed);
  148. int ret = sonicWriteShortToStream(is->m_sonicStream,
  149. (short*) is->m_audioBuf,
  150. len2);
  151. int availSamples = sonicSamplesAvailable(is->m_sonicStream);
  152. if (!availSamples) {
  153. is->m_audioBufSize = is->m_audioBufIndex;
  154. continue;
  155. }
  156. int numSamples = availSamples;
  157. int bytes = numSamples * is->m_targetChannels
  158. * av_get_bytes_per_sample(is->m_targetSampleFmt);
  159. if (bytes > out_size) {
  160. av_fast_malloc(&is->m_audioBuf, &is->m_audioBufSize, bytes);
  161. }
  162. len2 = sonicReadShortFromStream(is->m_sonicStream,
  163. (short*) is->m_audioBuf,
  164. numSamples);
  165. }
  166. is->m_audioBufSize = len2 * is->m_targetChannels
  167. * av_get_bytes_per_sample(is->m_targetSampleFmt);
  168. } else {
  169. is->m_audioBufSize = ffmpeg_get_buffer_size(is->m_targetSampleFmt,
  170. is->m_targetChannels,
  171. is->m_audioFrame->nb_samples,
  172. 0);
  173. av_fast_malloc(&is->m_audioBuf, &is->m_audioBufSize, is->m_audioBufSize + 256);
  174. if (!is->m_audioBuf) {
  175. qDebug() << "av_fast_malloc failed";
  176. return;
  177. }
  178. memcpy(is->m_audioBuf, is->m_audioFrame->data[0], is->m_audioBufSize);
  179. }
  180. audioPts = is->m_audioFrame->pts
  181. * av_q2d(is->m_fmtCtx->streams[is->m_audioIndex]->time_base);
  182. //qDebug()<<is->m_audioPts;
  183. av_frame_unref(is->m_audioFrame);
  184. } else {
  185. //判断是否真正播放到文件末尾
  186. if (is->m_decoder->isExit()) {
  187. emit is->AVTerminate();
  188. }
  189. return;
  190. }
  191. }
  192. int len1 = is->m_audioBufSize - is->m_audioBufIndex;
  193. len1 = (len1 > len ? len : len1);
  194. SDL_MixAudio(stream, is->m_audioBuf + is->m_audioBufIndex, len1, is->m_volume);
  195. len -= len1;
  196. is->m_audioBufIndex += len1;
  197. stream += len1;
  198. }
  199. //记录音频时钟,转换为微秒时间戳
  200. int64_t audioPtsUs = static_cast<int64_t>(audioPts * 1000000.0);
  201. is->m_audioClock.setClock(audioPtsUs);
  202. //发送时间戳变化信号,因为进度以整数秒单位变化展示,
  203. //所以大于一秒才发送,避免过于频繁的信号槽通信消耗性能
  204. uint32_t _pts = (uint32_t) audioPts;
  205. if (is->m_lastAudPts != _pts) {
  206. emit is->AVPtsChanged(_pts);
  207. is->m_lastAudPts = _pts;
  208. }
  209. }
  210. int AVPlayer::initSDL()
  211. {
  212. // 无音频流直接返回失败,调用方根据 m_hasAudio 控制
  213. if (m_decoder->audioIndex() < 0)
  214. return 0;
  215. // 性能优化:使用更快的SDL初始化方式
  216. if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
  217. if (SDL_Init(SDL_INIT_AUDIO) != 0) {
  218. qDebug() << "SDL_Init failed";
  219. return 0;
  220. }
  221. }
  222. m_exit = 0;
  223. m_audioBufSize = 0;
  224. m_audioBufIndex = 0;
  225. m_lastAudPts = -1;
  226. m_audioCodecPar = m_decoder->audioCodecPar();
  227. m_audioIndex = m_decoder->audioIndex();
  228. m_fmtCtx = m_decoder->formatContext();
  229. // 性能优化:使用更小的音频缓冲区减少延迟
  230. SDL_AudioSpec wanted_spec;
  231. wanted_spec.channels = ffmpeg_get_codec_channels(m_fmtCtx->streams[m_audioIndex]);
  232. wanted_spec.freq = m_audioCodecPar->sample_rate;
  233. wanted_spec.format = AUDIO_S16SYS;
  234. wanted_spec.silence = 0;
  235. wanted_spec.callback = fillAStreamCallback;
  236. wanted_spec.userdata = this;
  237. // 使用配置文件中的音频样本数减少延迟
  238. wanted_spec.samples = LowLatencyConfig::MIN_AUDIO_SAMPLES; // 使用配置文件中的最小音频样本数
  239. if (SDL_OpenAudio(&wanted_spec, nullptr) < 0) {
  240. qDebug() << "SDL_OpenAudio failed";
  241. return 0;
  242. }
  243. m_targetSampleFmt = AV_SAMPLE_FMT_S16;
  244. m_targetChannels = ffmpeg_get_codec_channels(m_fmtCtx->streams[m_audioIndex]);
  245. m_targetFreq = m_audioCodecPar->sample_rate;
  246. m_targetChannelLayout = (int64_t)ffmpeg_get_default_channel_layout(m_targetChannels);
  247. m_targetNbSamples = m_audioCodecPar->frame_size;
  248. m_audioIndex = m_decoder->audioIndex();
  249. m_fmtCtx = m_decoder->formatContext();
  250. m_sonicStream = sonicCreateStream(m_targetFreq, m_targetChannels);
  251. sonicSetQuality(m_sonicStream, 1);
  252. SDL_PauseAudio(0);
  253. return 1;
  254. }
  255. int AVPlayer::initVideo()
  256. {
  257. m_frameTimerUs = 0; // 使用高精度微秒时间戳
  258. m_videoCodecPar = m_decoder->videoCodecPar();
  259. m_videoIndex = m_decoder->videoIndex();
  260. m_fmtCtx = m_decoder->formatContext();
  261. m_imageWidth = m_videoCodecPar ? m_videoCodecPar->width : 0;
  262. m_imageHeight = m_videoCodecPar ? m_videoCodecPar->height : 0;
  263. m_dstPixFmt = AV_PIX_FMT_YUV422P;
  264. // 改用快速缩放算法以降低转换时延
  265. m_swsFlags = SWS_FAST_BILINEAR;
  266. // 仅当分辨率有效时分配缓存,否则延迟到首帧分配
  267. if (m_imageWidth > 0 && m_imageHeight > 0) {
  268. int bufSize = av_image_get_buffer_size(m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  269. m_buffer = (uint8_t*) av_realloc(m_buffer, bufSize * sizeof(uint8_t));
  270. av_image_fill_arrays(m_pixels, m_pitch, m_buffer, m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  271. }
  272. //视频帧播放回调递插入线程池任务队列
  273. if (!ThreadPool::addTask(std::bind(&AVPlayer::videoCallback, this, std::placeholders::_1),
  274. std::make_shared<int>(0))) {
  275. qDebug() << "videoCallback add task failed!";
  276. }
  277. return 1;
  278. }
  279. void AVPlayer::pause(bool isPause)
  280. {
  281. if (m_hasAudio) {
  282. if (SDL_GetAudioStatus() == SDL_AUDIO_STOPPED)
  283. return;
  284. if (isPause) {
  285. if (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING) {
  286. SDL_PauseAudio(1);
  287. // 优化:直接使用高精度时间戳,避免除法运算
  288. int64_t pauseTimeUs = av_gettime_relative();
  289. m_pauseTimeUs = pauseTimeUs - (m_baseTimeUs ? m_baseTimeUs : pauseTimeUs);
  290. m_pause = 1;
  291. }
  292. } else {
  293. if (SDL_GetAudioStatus() == SDL_AUDIO_PAUSED) {
  294. SDL_PauseAudio(0);
  295. // 优化:直接使用高精度时间戳计算暂停时长,避免除法运算
  296. int64_t resumeTimeUs = av_gettime_relative();
  297. int64_t resumeElapsedUs = resumeTimeUs - (m_baseTimeUs ? m_baseTimeUs : resumeTimeUs);
  298. m_frameTimerUs += resumeElapsedUs - m_pauseTimeUs;
  299. m_pause = 0;
  300. }
  301. }
  302. } else if (m_hasVideo) {
  303. // 仅视频:通过标志控制回放线程
  304. if (isPause) {
  305. if (!m_pause) {
  306. // 优化:直接使用高精度时间戳,避免除法运算
  307. int64_t pauseTimeUs = av_gettime_relative();
  308. m_pauseTimeUs = pauseTimeUs - (m_baseTimeUs ? m_baseTimeUs : pauseTimeUs);
  309. m_pause = 1;
  310. }
  311. } else {
  312. if (m_pause) {
  313. // 优化:直接使用高精度时间戳计算暂停时长,避免除法运算
  314. int64_t resumeTimeUs = av_gettime_relative();
  315. int64_t resumeElapsedUs = resumeTimeUs - (m_baseTimeUs ? m_baseTimeUs : resumeTimeUs);
  316. m_frameTimerUs += resumeElapsedUs - m_pauseTimeUs;
  317. m_pause = 0;
  318. }
  319. }
  320. }
  321. }
  322. void AVPlayer::clearPlayer()
  323. {
  324. if (playState() != AV_STOPPED) {
  325. m_exit = 1;
  326. if (m_hasAudio && playState() == AV_PLAYING)
  327. SDL_PauseAudio(1);
  328. m_decoder->exit();
  329. if (m_hasAudio)
  330. SDL_CloseAudio();
  331. if (m_swrCtx)
  332. swr_free(&m_swrCtx);
  333. if (m_swsCtx)
  334. sws_freeContext(m_swsCtx);
  335. m_swrCtx = nullptr;
  336. m_swsCtx = nullptr;
  337. if (m_sonicStream)
  338. sonicDestroyStream(m_sonicStream);
  339. m_sonicStream = nullptr;
  340. }
  341. }
  342. AVTool::MediaInfo* AVPlayer::detectMediaInfo(const QString& url)
  343. {
  344. return m_decoder->detectMediaInfo(url);
  345. }
  346. AVPlayer::PlayState AVPlayer::playState()
  347. {
  348. if (m_hasAudio) {
  349. AVPlayer::PlayState state;
  350. switch (SDL_GetAudioStatus()) {
  351. case SDL_AUDIO_PLAYING:
  352. state = AVPlayer::AV_PLAYING;
  353. break;
  354. case SDL_AUDIO_PAUSED:
  355. state = AVPlayer::AV_PAUSED;
  356. break;
  357. case SDL_AUDIO_STOPPED:
  358. state = AVPlayer::AV_STOPPED;
  359. break;
  360. default:
  361. state = AVPlayer::AV_STOPPED;
  362. break;
  363. }
  364. return state;
  365. }
  366. if (m_hasVideo) {
  367. if (m_exit)
  368. return AV_STOPPED;
  369. if (m_pause)
  370. return AV_PAUSED;
  371. return AV_PLAYING;
  372. }
  373. return AV_STOPPED;
  374. }
  375. void AVPlayer::initAVClock()
  376. {
  377. m_audioClock.setClock(0);
  378. m_videoClock.setClock(0);
  379. m_clockInitFlag = 1;
  380. }
  381. void AVPlayer::displayImage(AVFrame* frame)
  382. {
  383. if (frame) {
  384. // 首帧兜底:探测不到分辨率时,用首帧尺寸初始化并分配缓存
  385. if (m_imageWidth <= 0 || m_imageHeight <= 0) {
  386. m_imageWidth = frame->width;
  387. m_imageHeight = frame->height;
  388. int bufSize = av_image_get_buffer_size(m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  389. m_buffer = (uint8_t*) av_realloc(m_buffer, bufSize * sizeof(uint8_t));
  390. av_image_fill_arrays(m_pixels, m_pitch, m_buffer, m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  391. }
  392. // 判断是否需要像素格式/分辨率转换
  393. bool needConvert =
  394. (frame->format != m_dstPixFmt) ||
  395. (frame->width != m_imageWidth) ||
  396. (frame->height != m_imageHeight);
  397. if (needConvert) {
  398. m_swsCtx = sws_getCachedContext(m_swsCtx,
  399. frame->width,
  400. frame->height,
  401. (enum AVPixelFormat) frame->format,
  402. m_imageWidth,
  403. m_imageHeight,
  404. m_dstPixFmt,
  405. m_swsFlags,
  406. nullptr,
  407. nullptr,
  408. nullptr);
  409. if (m_swsCtx) {
  410. // 确保输出缓存已按当前目标尺寸分配
  411. int bufSize = av_image_get_buffer_size(m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  412. m_buffer = (uint8_t*) av_realloc(m_buffer, bufSize * sizeof(uint8_t));
  413. av_image_fill_arrays(m_pixels, m_pitch, m_buffer, m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  414. sws_scale(m_swsCtx, frame->data, frame->linesize, 0, frame->height, m_pixels, m_pitch);
  415. uint8_t* planes[4] = { m_pixels[0], m_pixels[1], m_pixels[2], m_pixels[3] };
  416. int lines[4] = { m_pitch[0], m_pitch[1], m_pitch[2], m_pitch[3] };
  417. emit frameChanged(QSharedPointer<VideoFrame>::create(m_dstPixFmt,
  418. m_imageWidth,
  419. m_imageHeight,
  420. planes,
  421. lines));
  422. } else {
  423. // 回退:直接透传
  424. emit frameChanged(QSharedPointer<VideoFrame>::create((AVPixelFormat) frame->format,
  425. frame->width,
  426. frame->height,
  427. frame->data,
  428. frame->linesize));
  429. }
  430. } else {
  431. // 无需转换,直接透传
  432. emit frameChanged(QSharedPointer<VideoFrame>::create((AVPixelFormat) frame->format,
  433. frame->width,
  434. frame->height,
  435. frame->data,
  436. frame->linesize));
  437. }
  438. //记录视频时钟,转换为微秒时间戳
  439. double videoPtsSeconds = frame->pts * av_q2d(m_fmtCtx->streams[m_videoIndex]->time_base);
  440. int64_t videoPtsUs = static_cast<int64_t>(videoPtsSeconds * 1000000.0);
  441. m_videoClock.setClock(videoPtsUs);
  442. }
  443. }
  444. void AVPlayer::videoCallback(std::shared_ptr<void> par)
  445. {
  446. double time = 0.00;
  447. double duration = 0.00;
  448. double delay = 0.00;
  449. if (m_clockInitFlag == -1) {
  450. initAVClock();
  451. }
  452. do {
  453. if (m_exit)
  454. break;
  455. if (m_pause) {
  456. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  457. continue;
  458. }
  459. if (m_decoder->getRemainingVFrame()) {
  460. MyFrame* lastFrame = m_decoder->peekLastVFrame();
  461. MyFrame* frame = m_decoder->peekVFrame();
  462. //qDebug()<<"video pts:"<<frame->pts;
  463. if (frame->serial != m_decoder->vidPktSerial()) {
  464. m_decoder->setNextVFrame();
  465. continue;
  466. }
  467. if (frame->serial != lastFrame->serial) {
  468. // 优化:直接使用高精度时间戳重置帧定时器,避免除法运算
  469. int64_t currentTimeUs = av_gettime_relative();
  470. m_frameTimerUs = currentTimeUs - m_baseTimeUs;
  471. }
  472. duration = vpDuration(lastFrame, frame);
  473. delay = computeTargetDelay(duration);
  474. // 优化:直接使用高精度时间戳计算当前时间,避免除法运算
  475. int64_t currentTimeUs = av_gettime_relative();
  476. int64_t timeUs = currentTimeUs - m_baseTimeUs;
  477. // 性能监控:检测延迟累积
  478. m_performanceFrameCount++;
  479. if (m_performanceFrameCount % LowLatencyConfig::DELAY_MONITOR_INTERVAL == 0) {
  480. if (delay > m_lastDelayValue + LowLatencyConfig::DELAY_ACCUMULATION_THRESHOLD) {
  481. // 检测到延迟累积,进行校正
  482. delay *= LowLatencyConfig::DELAY_RESET_FACTOR;
  483. qDebug() << "Delay accumulation detected, correcting delay from" << m_lastDelayValue << "to" << delay;
  484. }
  485. m_lastDelayValue = delay;
  486. }
  487. //qDebug()<<"delay:"<<delay<<endl;
  488. //显示时长未到
  489. int64_t delayUs = static_cast<int64_t>(delay * 1000000.0);
  490. if (timeUs < m_frameTimerUs + delayUs) {
  491. // 优化:使用更精确的睡眠时间计算
  492. int64_t sleepTimeUs = m_frameTimerUs + delayUs - timeUs;
  493. int64_t maxSleepUs = LowLatencyConfig::BALANCED_SYNC_REJUDGE_THRESHOLD_US;
  494. if (sleepTimeUs > maxSleepUs) {
  495. sleepTimeUs = maxSleepUs;
  496. }
  497. QThread::msleep(static_cast<uint32_t>(sleepTimeUs / 1000));
  498. continue;
  499. }
  500. m_frameTimerUs += delayUs;
  501. int64_t maxThresholdUs = LowLatencyConfig::BALANCED_SYNC_THRESHOLD_MAX_US;
  502. if (timeUs - m_frameTimerUs > maxThresholdUs) {
  503. m_frameTimerUs = timeUs;
  504. // 帧定时器校正时重置性能计数器
  505. int64_t correctionThresholdUs = LowLatencyConfig::FRAME_TIMER_CORRECTION_THRESHOLD_US;
  506. if (timeUs - m_frameTimerUs > correctionThresholdUs) {
  507. m_performanceFrameCount = 0;
  508. }
  509. }
  510. //队列中未显示帧一帧以上执行逻辑丢帧判断,倍速播放和逐帧播放
  511. //都不跑进此逻辑,倍速易造成丢帧过多导致界面不流畅
  512. // 平衡:温和的丢帧策略,保证稳定性
  513. if (m_playSpeed == 1.0 && m_decoder->getRemainingVFrame() > 1) { // 恢复为>1,更稳定
  514. MyFrame* nextFrame = m_decoder->peekNextVFrame();
  515. if (nextFrame) {
  516. duration = nextFrame->pts - frame->pts;
  517. //若主时钟超前到大于当前帧理论显示应持续的时间了,则当前帧立即丢弃
  518. // 平衡:使用原始duration阈值,避免过度丢帧
  519. int64_t durationUs = static_cast<int64_t>(duration * 1000000.0);
  520. if (timeUs > m_frameTimerUs + durationUs) {
  521. m_decoder->setNextVFrame();
  522. qDebug() << "abandon vframe (balanced mode)" << Qt::endl;
  523. continue;
  524. }
  525. }
  526. // 温和:基于延迟的丢帧阈值使用配置文件参数
  527. if (delay > LowLatencyConfig::FRAME_DROP_THRESHOLD) { // 使用配置文件中的丢帧阈值
  528. m_decoder->setNextVFrame();
  529. qDebug() << "drop frame due to high delay:" << delay << Qt::endl;
  530. continue;
  531. }
  532. }
  533. displayImage(&frame->frame);
  534. // 无音频时,基于视频时钟更新对外进度
  535. if (!m_hasAudio) {
  536. uint32_t _pts = (uint32_t) m_videoClock.getClock();
  537. if (m_lastAudPts != _pts) {
  538. emit AVPtsChanged(_pts);
  539. m_lastAudPts = _pts;
  540. }
  541. }
  542. //读索引后移
  543. m_decoder->setNextVFrame();
  544. } else {
  545. QThread::msleep(10);
  546. }
  547. } while (true);
  548. //qDebug()<<"videoCallBack exit"<<endl;
  549. if (m_decoder->isExit()) {
  550. emit AVTerminate();
  551. }
  552. }
  553. double AVPlayer::computeTargetDelay(double delay)
  554. {
  555. // 无音频流时,不进行音视频同步,直接按视频节奏播放
  556. if (!m_hasAudio)
  557. return delay;
  558. //视频当前显示帧与当前播放音频帧时间戳差值
  559. double diff = m_videoClock.getClock() - m_audioClock.getClock();
  560. //计算同步阈值
  561. double sync = FFMAX(LowLatencyConfig::BALANCED_SYNC_THRESHOLD_MIN, FFMIN(LowLatencyConfig::BALANCED_SYNC_THRESHOLD_MAX, delay));
  562. //不同步时间超过阈值直接放弃同步
  563. if (!isnan(diff) && fabs(diff) < LowLatencyConfig::BALANCED_NOSYNC_THRESHOLD) {
  564. if (diff
  565. <= -sync) { //视频已落后音频大于一帧的显示时长,delay值应为0,立马将当前帧显示追赶音频
  566. delay = FFMAX(0, diff + delay);
  567. } else if (diff >= sync
  568. && delay
  569. > LowLatencyConfig::BALANCED_SYNC_FRAMEDUP_THRESHOLD) { //视频超前音频大于一个视频帧的时间,延时一个视频帧时间+已超时时间,下次判定将至少被延时到下个将要显示的视频帧pts
  570. delay = diff + delay;
  571. } else if (diff >= sync) { //高帧率视频直接延时两个视频帧时间;;;;
  572. delay = 2 * delay;
  573. }
  574. }
  575. return delay;
  576. }
  577. double AVPlayer::vpDuration(MyFrame* lastFrame, MyFrame* curFrame)
  578. {
  579. if (curFrame->serial == lastFrame->serial) {
  580. double duration = curFrame->pts - lastFrame->pts;
  581. if (isnan(duration) || duration > LowLatencyConfig::BALANCED_NOSYNC_THRESHOLD)
  582. return lastFrame->duration;
  583. else
  584. return duration;
  585. } else {
  586. return 0.00;
  587. }
  588. }