av_player.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. #include "av_player.h"
  2. #include <QDebug>
  3. #include <QImage>
  4. #include <QThread>
  5. #include "threadpool.h"
  6. #include "vframe.h"
  7. //同步阈值下限
  8. #define AV_SYNC_THRESHOLD_MIN 0.04
  9. //同步阈值上限
  10. #define AV_SYNC_THRESHOLD_MAX 0.1
  11. //单帧视频时长阈值上限,用于适配低帧时同步,
  12. //帧率过低视频帧超前不适合翻倍延迟,应特殊
  13. //处理,这里设置上限一秒10帧
  14. #define AV_SYNC_FRAMEDUP_THRESHOLD 0.1
  15. //同步操作摆烂阈值上限,此时同步已无意义
  16. #define AV_NOSYNC_THRESHOLD 10.0
  17. #define AV_SYNC_REJUDGESHOLD 0.01
  18. AVPlayer::AVPlayer()
  19. : m_decoder(new Decoder)
  20. , m_fmtCtx(nullptr)
  21. , m_audioFrame(av_frame_alloc())
  22. , m_imageWidth(300)
  23. , m_imageHeight(300)
  24. , m_swrCtx(nullptr)
  25. , m_swsCtx(nullptr)
  26. , m_buffer(nullptr)
  27. , m_audioBuf(nullptr)
  28. , m_duration(0)
  29. , m_volume(30)
  30. , m_exit(0)
  31. , m_pause(0)
  32. , m_playSpeed(1.0)
  33. {
  34. m_sonicStream = nullptr;
  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. is->m_audioClock.setClock(audioPts);
  201. //发送时间戳变化信号,因为进度以整数秒单位变化展示,
  202. //所以大于一秒才发送,避免过于频繁的信号槽通信消耗性能
  203. uint32_t _pts = (uint32_t) audioPts;
  204. if (is->m_lastAudPts != _pts) {
  205. emit is->AVPtsChanged(_pts);
  206. is->m_lastAudPts = _pts;
  207. }
  208. }
  209. int AVPlayer::initSDL()
  210. {
  211. // 无音频流直接返回失败,调用方根据 m_hasAudio 控制
  212. if (m_decoder->audioIndex() < 0)
  213. return 0;
  214. if (SDL_Init(SDL_INIT_AUDIO) != 0) {
  215. qDebug() << "SDL_Init failed";
  216. return 0;
  217. }
  218. m_exit = 0;
  219. m_audioBufSize = 0;
  220. m_audioBufIndex = 0;
  221. m_lastAudPts = -1;
  222. m_audioCodecPar = m_decoder->audioCodecPar();
  223. m_audioIndex = m_decoder->audioIndex();
  224. m_fmtCtx = m_decoder->formatContext();
  225. SDL_AudioSpec wanted_spec;
  226. // wanted_spec.channels = m_audioCodecPar->channels;
  227. wanted_spec.channels = ffmpeg_get_codec_channels(m_fmtCtx->streams[m_audioIndex]);
  228. wanted_spec.freq = m_audioCodecPar->sample_rate;
  229. wanted_spec.format = AUDIO_S16SYS;
  230. wanted_spec.silence = 0;
  231. wanted_spec.callback = fillAStreamCallback;
  232. wanted_spec.userdata = this;
  233. // 缩小音频回调缓冲区,降低端到端延迟(需为2的幂)
  234. wanted_spec.samples = 512;
  235. if (SDL_OpenAudio(&wanted_spec, nullptr) < 0) {
  236. qDebug() << "SDL_OpenAudio failed";
  237. return 0;
  238. }
  239. m_targetSampleFmt = AV_SAMPLE_FMT_S16;
  240. // m_targetChannels = m_audioCodecPar->channels;
  241. m_targetChannels = ffmpeg_get_codec_channels(m_fmtCtx->streams[m_audioIndex]);
  242. m_targetFreq = m_audioCodecPar->sample_rate;
  243. m_targetChannelLayout = (int64_t)ffmpeg_get_default_channel_layout(m_targetChannels);
  244. m_targetNbSamples = m_audioCodecPar->frame_size;
  245. m_audioIndex = m_decoder->audioIndex();
  246. m_fmtCtx = m_decoder->formatContext();
  247. m_sonicStream = sonicCreateStream(m_targetFreq, m_targetChannels);
  248. sonicSetQuality(m_sonicStream, 1);
  249. SDL_PauseAudio(0);
  250. return 1;
  251. }
  252. int AVPlayer::initVideo()
  253. {
  254. m_frameTimer = 0.00;
  255. m_videoCodecPar = m_decoder->videoCodecPar();
  256. m_videoIndex = m_decoder->videoIndex();
  257. m_fmtCtx = m_decoder->formatContext();
  258. m_imageWidth = m_videoCodecPar->width;
  259. m_imageHeight = m_videoCodecPar->height;
  260. m_dstPixFmt = AV_PIX_FMT_YUV422P;
  261. // 改用快速缩放算法以降低转换时延
  262. m_swsFlags = SWS_FAST_BILINEAR;
  263. //分配存储转换后帧数据的buffer内存
  264. int bufSize = av_image_get_buffer_size(m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  265. m_buffer = (uint8_t*) av_realloc(m_buffer, bufSize * sizeof(uint8_t));
  266. av_image_fill_arrays(m_pixels, m_pitch, m_buffer, m_dstPixFmt, m_imageWidth, m_imageHeight, 1);
  267. //视频帧播放回调递插入线程池任务队列
  268. if (!ThreadPool::addTask(std::bind(&AVPlayer::videoCallback, this, std::placeholders::_1),
  269. std::make_shared<int>(0))) {
  270. qDebug() << "videoCallback add task failed!";
  271. }
  272. return 1;
  273. }
  274. void AVPlayer::pause(bool isPause)
  275. {
  276. if (m_hasAudio) {
  277. if (SDL_GetAudioStatus() == SDL_AUDIO_STOPPED)
  278. return;
  279. if (isPause) {
  280. if (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING) {
  281. SDL_PauseAudio(1);
  282. m_pauseTime = av_gettime_relative() / 1000000.0;
  283. m_pause = 1;
  284. }
  285. } else {
  286. if (SDL_GetAudioStatus() == SDL_AUDIO_PAUSED) {
  287. SDL_PauseAudio(0);
  288. m_frameTimer += av_gettime_relative() / 1000000.0 - m_pauseTime;
  289. m_pause = 0;
  290. }
  291. }
  292. } else if (m_hasVideo) {
  293. // 仅视频:通过标志控制回放线程
  294. double now = av_gettime_relative() / 1000000.0;
  295. if (isPause) {
  296. if (!m_pause) {
  297. m_pauseTime = now;
  298. m_pause = 1;
  299. }
  300. } else {
  301. if (m_pause) {
  302. m_frameTimer += now - m_pauseTime;
  303. m_pause = 0;
  304. }
  305. }
  306. }
  307. }
  308. void AVPlayer::clearPlayer()
  309. {
  310. if (playState() != AV_STOPPED) {
  311. m_exit = 1;
  312. if (m_hasAudio && playState() == AV_PLAYING)
  313. SDL_PauseAudio(1);
  314. m_decoder->exit();
  315. if (m_hasAudio)
  316. SDL_CloseAudio();
  317. if (m_swrCtx)
  318. swr_free(&m_swrCtx);
  319. if (m_swsCtx)
  320. sws_freeContext(m_swsCtx);
  321. m_swrCtx = nullptr;
  322. m_swsCtx = nullptr;
  323. if (m_sonicStream)
  324. sonicDestroyStream(m_sonicStream);
  325. m_sonicStream = nullptr;
  326. }
  327. }
  328. AVTool::MediaInfo* AVPlayer::detectMediaInfo(const QString& url)
  329. {
  330. return m_decoder->detectMediaInfo(url);
  331. }
  332. AVPlayer::PlayState AVPlayer::playState()
  333. {
  334. if (m_hasAudio) {
  335. AVPlayer::PlayState state;
  336. switch (SDL_GetAudioStatus()) {
  337. case SDL_AUDIO_PLAYING:
  338. state = AVPlayer::AV_PLAYING;
  339. break;
  340. case SDL_AUDIO_PAUSED:
  341. state = AVPlayer::AV_PAUSED;
  342. break;
  343. case SDL_AUDIO_STOPPED:
  344. state = AVPlayer::AV_STOPPED;
  345. break;
  346. default:
  347. state = AVPlayer::AV_STOPPED;
  348. break;
  349. }
  350. return state;
  351. }
  352. if (m_hasVideo) {
  353. if (m_exit)
  354. return AV_STOPPED;
  355. if (m_pause)
  356. return AV_PAUSED;
  357. return AV_PLAYING;
  358. }
  359. return AV_STOPPED;
  360. }
  361. void AVPlayer::initAVClock()
  362. {
  363. m_audioClock.setClock(0.00);
  364. m_videoClock.setClock(0.00);
  365. m_clockInitFlag = 1;
  366. }
  367. void AVPlayer::displayImage(AVFrame* frame)
  368. {
  369. if (frame) {
  370. //判断若是否需要格式转换
  371. if ((m_videoCodecPar->width != m_imageWidth || m_videoCodecPar->height != m_imageHeight
  372. || m_videoCodecPar->format != m_dstPixFmt)
  373. && !m_swsCtx) {
  374. m_swsCtx = sws_getCachedContext(m_swsCtx,
  375. frame->width,
  376. frame->height,
  377. (enum AVPixelFormat) frame->format,
  378. m_imageWidth,
  379. m_imageHeight,
  380. m_dstPixFmt,
  381. m_swsFlags,
  382. nullptr,
  383. nullptr,
  384. nullptr);
  385. }
  386. if (m_swsCtx) {
  387. sws_scale(m_swsCtx, frame->data, frame->linesize, 0, frame->height, m_pixels, m_pitch);
  388. uint8_t* planes[4] = { m_pixels[0], m_pixels[1], m_pixels[2], m_pixels[3] };
  389. int lines[4] = { m_pitch[0], m_pitch[1], m_pitch[2], m_pitch[3] };
  390. emit frameChanged(QSharedPointer<VideoFrame>::create(m_dstPixFmt,
  391. m_imageWidth,
  392. m_imageHeight,
  393. planes,
  394. lines));
  395. } else {
  396. // 直接使用解码帧的平面数据
  397. emit frameChanged(QSharedPointer<VideoFrame>::create((AVPixelFormat)m_videoCodecPar->format,
  398. m_imageWidth,
  399. m_imageHeight,
  400. frame->data,
  401. frame->linesize));
  402. }
  403. //记录视频时钟
  404. m_videoClock.setClock(frame->pts * av_q2d(m_fmtCtx->streams[m_videoIndex]->time_base));
  405. }
  406. }
  407. void AVPlayer::videoCallback(std::shared_ptr<void> par)
  408. {
  409. double time = 0.00;
  410. double duration = 0.00;
  411. double delay = 0.00;
  412. if (m_clockInitFlag == -1) {
  413. initAVClock();
  414. }
  415. do {
  416. if (m_exit)
  417. break;
  418. if (m_pause) {
  419. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  420. continue;
  421. }
  422. if (m_decoder->getRemainingVFrame()) {
  423. MyFrame* lastFrame = m_decoder->peekLastVFrame();
  424. MyFrame* frame = m_decoder->peekVFrame();
  425. //qDebug()<<"video pts:"<<frame->pts;
  426. if (frame->serial != m_decoder->vidPktSerial()) {
  427. m_decoder->setNextVFrame();
  428. continue;
  429. }
  430. if (frame->serial != lastFrame->serial)
  431. m_frameTimer = av_gettime_relative() / 1000000.0;
  432. duration = vpDuration(lastFrame, frame);
  433. delay = computeTargetDelay(duration);
  434. time = av_gettime_relative() / 1000000.0;
  435. //qDebug()<<"delay:"<<delay<<endl;
  436. //显示时长未到
  437. if (time < m_frameTimer + delay) {
  438. QThread::msleep(
  439. (uint32_t) (FFMIN(AV_SYNC_REJUDGESHOLD, m_frameTimer + delay - time) * 1000));
  440. continue;
  441. }
  442. m_frameTimer += delay;
  443. if (time - m_frameTimer > AV_SYNC_THRESHOLD_MAX)
  444. m_frameTimer = time;
  445. //队列中未显示帧一帧以上执行逻辑丢帧判断,倍速播放和逐帧播放
  446. //都不跑进此逻辑,倍速易造成丢帧过多导致界面不流畅
  447. if (m_playSpeed == 1.0 && m_decoder->getRemainingVFrame() > 1) {
  448. MyFrame* nextFrame = m_decoder->peekNextVFrame();
  449. duration = nextFrame->pts - frame->pts;
  450. //若主时钟超前到大于当前帧理论显示应持续的时间了,则当前帧立即丢弃
  451. if (time > m_frameTimer + duration) {
  452. m_decoder->setNextVFrame();
  453. qDebug() << "abandon vframe" << Qt::endl;
  454. continue;
  455. }
  456. }
  457. displayImage(&frame->frame);
  458. // 无音频时,基于视频时钟更新对外进度
  459. if (!m_hasAudio) {
  460. uint32_t _pts = (uint32_t) m_videoClock.getClock();
  461. if (m_lastAudPts != _pts) {
  462. emit AVPtsChanged(_pts);
  463. m_lastAudPts = _pts;
  464. }
  465. }
  466. //读索引后移
  467. m_decoder->setNextVFrame();
  468. } else {
  469. QThread::msleep(10);
  470. }
  471. } while (true);
  472. //qDebug()<<"videoCallBack exit"<<endl;
  473. if (m_decoder->isExit()) {
  474. emit AVTerminate();
  475. }
  476. }
  477. double AVPlayer::computeTargetDelay(double delay)
  478. {
  479. // 无音频流时,不进行音视频同步,直接按视频节奏播放
  480. if (!m_hasAudio)
  481. return delay;
  482. //视频当前显示帧与当前播放音频帧时间戳差值
  483. double diff = m_videoClock.getClock() - m_audioClock.getClock();
  484. //计算同步阈值
  485. double sync = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay));
  486. //不同步时间超过阈值直接放弃同步
  487. if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD) {
  488. if (diff
  489. <= -sync) { //视频已落后音频大于一帧的显示时长,delay值应为0,立马将当前帧显示追赶音频
  490. delay = FFMAX(0, diff + delay);
  491. } else if (diff >= sync
  492. && delay
  493. > AV_SYNC_FRAMEDUP_THRESHOLD) { //视频超前音频大于一个视频帧的时间,延时一个视频帧时间+已超时时间,下次判定将至少被延时到下个将要显示的视频帧pts
  494. delay = diff + delay;
  495. } else if (diff >= sync) { //高帧率视频直接延时两个视频帧时间;;;;
  496. delay = 2 * delay;
  497. }
  498. }
  499. return delay;
  500. }
  501. double AVPlayer::vpDuration(MyFrame* lastFrame, MyFrame* curFrame)
  502. {
  503. if (curFrame->serial == lastFrame->serial) {
  504. double duration = curFrame->pts - lastFrame->pts;
  505. if (isnan(duration) || duration > AV_NOSYNC_THRESHOLD)
  506. return lastFrame->duration;
  507. else
  508. return duration;
  509. } else {
  510. return 0.00;
  511. }
  512. }