av_player.cpp 20 KB

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