av_decoder.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. #include "av_decoder.h"
  2. #include <QDebug>
  3. #include <QThread>
  4. #include "threadpool.h"
  5. #include "low_latency_config.h"
  6. using AVTool::Decoder;
  7. Decoder::Decoder()
  8. : m_fmtCtx(nullptr)
  9. , m_maxFrameQueueSize(LowLatencyConfig::BALANCED_FRAME_QUEUE_SIZE) // 使用配置文件中的帧队列大小
  10. , m_maxPacketQueueSize(LowLatencyConfig::BALANCED_PACKET_QUEUE_SIZE) // 使用配置文件中的包队列大小
  11. , m_audioIndex(-1)
  12. , m_videoIndex(-1)
  13. , m_exit(0)
  14. , m_duration(0)
  15. {
  16. if (!init())
  17. qDebug() << "Decoder init failed!\n";
  18. setInitVal();
  19. }
  20. Decoder::~Decoder()
  21. {
  22. exit();
  23. }
  24. AVTool::MediaInfo* Decoder::detectMediaInfo(const QString& url)
  25. {
  26. int ret = 0;
  27. int duration = 0;
  28. //解封装初始化
  29. AVFormatContext* fmtCtx = avformat_alloc_context();
  30. //用于获取流时长
  31. AVDictionary* formatOpts = nullptr;
  32. av_dict_set(&formatOpts, "probesize", LowLatencyConfig::PROBE_SIZE, 0); // 使用配置文件中的探测大小
  33. av_dict_set(&formatOpts, "analyzeduration", LowLatencyConfig::ANALYZE_DURATION, 0); // 使用配置文件中的分析时长
  34. av_dict_set(&formatOpts, "rtsp_transport", LowLatencyConfig::RTSP_TRANSPORT, 0);
  35. av_dict_set(&formatOpts, "fflags", LowLatencyConfig::FFLAGS, 0); // 使用配置文件中的标志
  36. av_dict_set(&formatOpts, "max_delay", LowLatencyConfig::MAX_DELAY, 0); // 使用配置文件中的最大延迟
  37. av_dict_set(&formatOpts, "buffer_size", LowLatencyConfig::BUFFER_SIZE, 0); // 使用配置文件中的缓冲区大小
  38. ret = avformat_open_input(&fmtCtx, url.toUtf8().constData(), nullptr, &formatOpts);
  39. if (ret < 0) {
  40. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  41. qDebug() << "avformat_open_input error:" << m_errBuf;
  42. av_dict_free(&formatOpts);
  43. //打开失败释放分配的AVFormatContext内存
  44. avformat_free_context(fmtCtx);
  45. return Q_NULLPTR;
  46. }
  47. // 低延迟:关闭内部缓冲,但保持稳定性
  48. if (fmtCtx) {
  49. fmtCtx->flags |= AVFMT_FLAG_NOBUFFER;
  50. fmtCtx->max_delay = 500000; // 500ms,类似VLC
  51. fmtCtx->probesize = 32768; // 32KB
  52. fmtCtx->max_analyze_duration = 1000000; // 1秒
  53. }
  54. ret = avformat_find_stream_info(fmtCtx, nullptr);
  55. if (ret < 0) {
  56. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  57. qDebug() << "avformat_find_stream_info error:" << m_errBuf;
  58. av_dict_free(&formatOpts);
  59. return Q_NULLPTR;
  60. }
  61. //记录流时长
  62. AVRational q = {1, AV_TIME_BASE};
  63. duration = (uint32_t) (fmtCtx->duration * av_q2d(q));
  64. av_dict_free(&formatOpts);
  65. int videoIndex = av_find_best_stream(fmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
  66. if (videoIndex < 0) {
  67. // 仅音频:返回时长和占位图
  68. AVTool::MediaInfo* info = new AVTool::MediaInfo;
  69. info->duration = duration;
  70. info->tipImg = QImage(300, 300, QImage::Format_RGB888);
  71. info->tipImg.fill(Qt::black);
  72. avformat_close_input(&fmtCtx);
  73. return info;
  74. }
  75. //视频解码初始化
  76. AVCodecParameters* videoCodecPar = fmtCtx->streams[videoIndex]->codecpar;
  77. if (!videoCodecPar) {
  78. qDebug() << "videocodecpar is nullptr!";
  79. return Q_NULLPTR;
  80. }
  81. AVCodecContext* codecCtx = avcodec_alloc_context3(nullptr);
  82. ret = avcodec_parameters_to_context(codecCtx, videoCodecPar);
  83. if (ret < 0) {
  84. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  85. qDebug() << "error info_avcodec_parameters_to_context:" << m_errBuf;
  86. return Q_NULLPTR;
  87. }
  88. const AVCodec* videoCodec = avcodec_find_decoder(codecCtx->codec_id);
  89. if (!videoCodec) {
  90. qDebug() << "avcodec_find_decoder failed!";
  91. return Q_NULLPTR;
  92. }
  93. codecCtx->codec_id = videoCodec->id;
  94. ret = avcodec_open2(codecCtx, videoCodec, nullptr);
  95. if (ret < 0) {
  96. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  97. qDebug() << "error info_avcodec_open2:" << m_errBuf;
  98. return Q_NULLPTR;
  99. }
  100. AVPacket* pkt = av_packet_alloc();
  101. AVFrame* frame = av_frame_alloc();
  102. bool flag = false;
  103. while (1) {
  104. ret = av_read_frame(fmtCtx, pkt);
  105. if (ret != 0) {
  106. return Q_NULLPTR;
  107. }
  108. if (pkt->stream_index == videoIndex) {
  109. ret = avcodec_send_packet(codecCtx, pkt);
  110. av_packet_unref(pkt);
  111. if (ret < 0 || ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  112. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  113. qDebug() << "avcodec_send_packet error:" << m_errBuf;
  114. continue;
  115. }
  116. while (1) {
  117. ret = avcodec_receive_frame(codecCtx, frame);
  118. if (ret == 0) {
  119. flag = true;
  120. break;
  121. } else if (ret == AVERROR(EAGAIN)) {
  122. break;
  123. } else {
  124. return Q_NULLPTR;
  125. }
  126. }
  127. if (flag)
  128. break;
  129. } else {
  130. av_packet_unref(pkt);
  131. }
  132. }
  133. int imageWidth = videoCodecPar->width;
  134. int imageHeight = videoCodecPar->height;
  135. enum AVPixelFormat dstPixFmt = AV_PIX_FMT_RGB24;
  136. int swsFlags = SWS_BICUBIC;
  137. uint8_t* pixels[4];
  138. int pitch[4];
  139. //分配存储转换后帧数据的buffer内存
  140. int bufSize = av_image_get_buffer_size(dstPixFmt, imageWidth, imageHeight, 1);
  141. uint8_t* buffer = (uint8_t*) av_malloc(bufSize * sizeof(uint8_t));
  142. av_image_fill_arrays(pixels, pitch, buffer, dstPixFmt, imageWidth, imageHeight, 1);
  143. SwsContext* swsCtx = sws_getCachedContext(nullptr,
  144. frame->width,
  145. frame->height,
  146. (enum AVPixelFormat) frame->format,
  147. imageWidth,
  148. imageHeight,
  149. dstPixFmt,
  150. swsFlags,
  151. nullptr,
  152. nullptr,
  153. nullptr);
  154. if (swsCtx)
  155. sws_scale(swsCtx, frame->data, frame->linesize, 0, frame->height, pixels, pitch);
  156. av_frame_unref(frame);
  157. AVTool::MediaInfo* info = new AVTool::MediaInfo;
  158. info->duration = duration;
  159. info->tipImg = QImage(pixels[0], imageWidth, imageHeight, pitch[0], QImage::Format_RGB888);
  160. av_packet_free(&pkt);
  161. av_frame_free(&frame);
  162. avformat_close_input(&fmtCtx);
  163. avcodec_free_context(&codecCtx);
  164. return info;
  165. }
  166. bool Decoder::init()
  167. {
  168. if (!ThreadPool::init()) {
  169. qDebug() << "threadpool init failed!\n";
  170. return false;
  171. }
  172. m_audioPacketQueue.pktVec.resize(m_maxPacketQueueSize);
  173. m_videoPacketQueue.pktVec.resize(m_maxPacketQueueSize);
  174. m_audioFrameQueue.frameVec.resize(m_maxFrameQueueSize);
  175. m_videoFrameQueue.frameVec.resize(m_maxFrameQueueSize);
  176. m_audioPktDecoder.codecCtx = nullptr;
  177. m_videoPktDecoder.codecCtx = nullptr;
  178. return true;
  179. }
  180. void Decoder::setInitVal()
  181. {
  182. m_audioPacketQueue.size = 0;
  183. m_audioPacketQueue.pushIndex = 0;
  184. m_audioPacketQueue.readIndex = 0;
  185. m_audioPacketQueue.serial = 0;
  186. m_videoPacketQueue.size = 0;
  187. m_videoPacketQueue.pushIndex = 0;
  188. m_videoPacketQueue.readIndex = 0;
  189. m_videoPacketQueue.serial = 0;
  190. m_audioFrameQueue.size = 0;
  191. m_audioFrameQueue.readIndex = 0;
  192. m_audioFrameQueue.pushIndex = 0;
  193. m_audioFrameQueue.shown = 0;
  194. m_videoFrameQueue.size = 0;
  195. m_videoFrameQueue.readIndex = 0;
  196. m_videoFrameQueue.pushIndex = 0;
  197. m_videoFrameQueue.shown = 0;
  198. m_exit = 0;
  199. m_isSeek = 0;
  200. m_audSeek = 0;
  201. m_vidSeek = 0;
  202. m_audioPktDecoder.serial = 0;
  203. m_videoPktDecoder.serial = 0;
  204. }
  205. int Decoder::decode(const QString& url)
  206. {
  207. int ret = 0;
  208. //解封装初始化
  209. m_fmtCtx = avformat_alloc_context();
  210. //用于获取流时长
  211. AVDictionary* formatOpts = nullptr;
  212. av_dict_set(&formatOpts, "probesize", LowLatencyConfig::PROBE_SIZE, 0);
  213. av_dict_set(&formatOpts, "analyzeduration", LowLatencyConfig::ANALYZE_DURATION, 0);
  214. av_dict_set(&formatOpts, "rtsp_transport", LowLatencyConfig::RTSP_TRANSPORT, 0);
  215. av_dict_set(&formatOpts, "fflags", LowLatencyConfig::FFLAGS, 0);
  216. av_dict_set(&formatOpts, "max_delay", LowLatencyConfig::MAX_DELAY, 0);
  217. ret = avformat_open_input(&m_fmtCtx, url.toUtf8().constData(), nullptr, &formatOpts);
  218. if (ret < 0) {
  219. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  220. qDebug() << "avformat_open_input error:" << m_errBuf;
  221. av_dict_free(&formatOpts);
  222. //打开失败释放分配的AVFormatContext内存
  223. avformat_free_context(m_fmtCtx);
  224. return 0;
  225. }
  226. // 低延迟:关闭内部缓冲
  227. if (m_fmtCtx) {
  228. m_fmtCtx->flags |= AVFMT_FLAG_NOBUFFER;
  229. m_fmtCtx->max_delay = 0;
  230. }
  231. ret = avformat_find_stream_info(m_fmtCtx, nullptr);
  232. if (ret < 0) {
  233. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  234. qDebug() << "avformat_find_stream_info error:" << m_errBuf;
  235. av_dict_free(&formatOpts);
  236. return 0;
  237. }
  238. //记录流时长
  239. AVRational q = {1, AV_TIME_BASE};
  240. m_duration = (uint32_t) (m_fmtCtx->duration * av_q2d(q));
  241. av_dict_free(&formatOpts);
  242. // 查找音频/视频流,允许缺失
  243. m_audioIndex = av_find_best_stream(m_fmtCtx, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
  244. if (m_audioIndex < 0) {
  245. qDebug() << "no audio stream!";
  246. }
  247. m_videoIndex = av_find_best_stream(m_fmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
  248. if (m_videoIndex < 0) {
  249. qDebug() << "no video stream!";
  250. }
  251. if (m_audioIndex < 0 && m_videoIndex < 0) {
  252. qDebug() << "no audio and video stream!";
  253. return 0;
  254. }
  255. // 音频解码初始化(可选)
  256. if (m_audioIndex >= 0) {
  257. AVCodecParameters* audioCodecPar = m_fmtCtx->streams[m_audioIndex]->codecpar;
  258. if (!audioCodecPar) {
  259. qDebug() << "audio par is nullptr!";
  260. return 0;
  261. }
  262. m_audioPktDecoder.codecCtx = avcodec_alloc_context3(nullptr);
  263. ret = avcodec_parameters_to_context(m_audioPktDecoder.codecCtx, audioCodecPar);
  264. if (ret < 0) {
  265. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  266. qDebug() << "error info_avcodec_parameters_to_context:" << m_errBuf;
  267. return 0;
  268. }
  269. const AVCodec* audioCodec = avcodec_find_decoder(m_audioPktDecoder.codecCtx->codec_id);
  270. if (!audioCodec) {
  271. qDebug() << "avcodec_find_decoder failed!";
  272. return 0;
  273. }
  274. m_audioPktDecoder.codecCtx->codec_id = audioCodec->id;
  275. // 平衡的解码设置(音频)
  276. m_audioPktDecoder.codecCtx->flags |= AV_CODEC_FLAG_LOW_DELAY;
  277. m_audioPktDecoder.codecCtx->flags2 |= AV_CODEC_FLAG2_FAST;
  278. m_audioPktDecoder.codecCtx->thread_count = LowLatencyConfig::DECODER_THREAD_COUNT; // 使用配置文件中的线程数
  279. m_audioPktDecoder.codecCtx->thread_type = FF_THREAD_SLICE;
  280. // H.264平衡优化
  281. AVDictionary* codecOpts = nullptr;
  282. av_dict_set(&codecOpts, "preset", LowLatencyConfig::CODEC_PRESET, 0); // 使用配置文件中的预设
  283. av_dict_set(&codecOpts, "tune", LowLatencyConfig::CODEC_TUNE, 0);
  284. ret = avcodec_open2(m_audioPktDecoder.codecCtx, audioCodec, &codecOpts);
  285. av_dict_free(&codecOpts);
  286. if (ret < 0) {
  287. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  288. qDebug() << "error info_avcodec_open2:" << m_errBuf;
  289. return 0;
  290. }
  291. }
  292. // 视频解码初始化(可选)
  293. if (m_videoIndex >= 0) {
  294. AVCodecParameters* videoCodecPar = m_fmtCtx->streams[m_videoIndex]->codecpar;
  295. if (!videoCodecPar) {
  296. qDebug() << "videocodecpar is nullptr!";
  297. return 0;
  298. }
  299. m_videoPktDecoder.codecCtx = avcodec_alloc_context3(nullptr);
  300. ret = avcodec_parameters_to_context(m_videoPktDecoder.codecCtx, videoCodecPar);
  301. if (ret < 0) {
  302. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  303. qDebug() << "error info_avcodec_parameters_to_context:" << m_errBuf;
  304. return 0;
  305. }
  306. const AVCodec* videoCodec = avcodec_find_decoder(m_videoPktDecoder.codecCtx->codec_id);
  307. if (!videoCodec) {
  308. qDebug() << "avcodec_find_decoder failed!";
  309. return 0;
  310. }
  311. m_videoPktDecoder.codecCtx->codec_id = videoCodec->id;
  312. // 平衡的解码设置(视频)
  313. m_videoPktDecoder.codecCtx->flags |= AV_CODEC_FLAG_LOW_DELAY;
  314. m_videoPktDecoder.codecCtx->flags2 |= AV_CODEC_FLAG2_FAST;
  315. m_videoPktDecoder.codecCtx->thread_count = LowLatencyConfig::DECODER_THREAD_COUNT; // 使用配置文件中的线程数
  316. m_videoPktDecoder.codecCtx->thread_type = FF_THREAD_SLICE;
  317. // H.264平衡优化
  318. AVDictionary* videoCodecOpts = nullptr;
  319. av_dict_set(&videoCodecOpts, "preset", LowLatencyConfig::CODEC_PRESET, 0); // 使用配置文件中的预设
  320. av_dict_set(&videoCodecOpts, "tune", LowLatencyConfig::CODEC_TUNE, 0);
  321. ret = avcodec_open2(m_videoPktDecoder.codecCtx, videoCodec, &videoCodecOpts);
  322. av_dict_free(&videoCodecOpts);
  323. if (ret < 0) {
  324. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  325. qDebug() << "error info_avcodec_open2:" << m_errBuf;
  326. return 0;
  327. }
  328. //记录视频帧率
  329. m_vidFrameRate = av_guess_frame_rate(m_fmtCtx, m_fmtCtx->streams[m_videoIndex], nullptr);
  330. }
  331. // 启动解复用/解码线程
  332. setInitVal();
  333. ThreadPool::addTask(std::bind(&Decoder::demux, this, std::placeholders::_1),
  334. std::make_shared<int>(1));
  335. if (m_audioIndex >= 0) {
  336. ThreadPool::addTask(std::bind(&Decoder::audioDecode, this, std::placeholders::_1),
  337. std::make_shared<int>(2));
  338. }
  339. if (m_videoIndex >= 0) {
  340. ThreadPool::addTask(std::bind(&Decoder::videoDecode, this, std::placeholders::_1),
  341. std::make_shared<int>(3));
  342. }
  343. return 1;
  344. }
  345. void Decoder::exit()
  346. {
  347. m_exit = 1;
  348. QThread::msleep(200);
  349. clearQueueCache();
  350. if (m_fmtCtx) {
  351. avformat_close_input(&m_fmtCtx);
  352. m_fmtCtx = nullptr;
  353. }
  354. if (m_audioPktDecoder.codecCtx) {
  355. avcodec_free_context(&m_audioPktDecoder.codecCtx);
  356. m_audioPktDecoder.codecCtx = nullptr;
  357. }
  358. if (m_videoPktDecoder.codecCtx) {
  359. avcodec_free_context(&m_videoPktDecoder.codecCtx);
  360. m_videoPktDecoder.codecCtx = nullptr;
  361. }
  362. }
  363. void Decoder::clearQueueCache()
  364. {
  365. std::lock_guard<std::mutex> lockAP(m_audioPacketQueue.mutex);
  366. std::lock_guard<std::mutex> lockVP(m_videoPacketQueue.mutex);
  367. while (m_audioPacketQueue.size) {
  368. av_packet_unref(&m_audioPacketQueue.pktVec[m_audioPacketQueue.readIndex].pkt);
  369. m_audioPacketQueue.readIndex = (m_audioPacketQueue.readIndex + 1) % m_maxPacketQueueSize;
  370. m_audioPacketQueue.size--;
  371. }
  372. while (m_videoPacketQueue.size) {
  373. av_packet_unref(&m_videoPacketQueue.pktVec[m_videoPacketQueue.readIndex].pkt);
  374. m_videoPacketQueue.readIndex = (m_videoPacketQueue.readIndex + 1) % m_maxPacketQueueSize;
  375. m_videoPacketQueue.size--;
  376. }
  377. std::lock_guard<std::mutex> lockAF(m_audioFrameQueue.mutex);
  378. std::lock_guard<std::mutex> lockVF(m_videoFrameQueue.mutex);
  379. while (m_audioFrameQueue.size) {
  380. av_frame_unref(&m_audioFrameQueue.frameVec[m_audioFrameQueue.readIndex].frame);
  381. m_audioFrameQueue.readIndex = (m_audioFrameQueue.readIndex + 1) % m_maxFrameQueueSize;
  382. m_audioFrameQueue.size--;
  383. }
  384. while (m_videoFrameQueue.size) {
  385. av_frame_unref(&m_videoFrameQueue.frameVec[m_videoFrameQueue.readIndex].frame);
  386. m_videoFrameQueue.readIndex = (m_videoFrameQueue.readIndex + 1) % m_maxFrameQueueSize;
  387. m_videoFrameQueue.size--;
  388. }
  389. }
  390. void Decoder::packetQueueFlush(PacketQueue* queue)
  391. {
  392. std::lock_guard<std::mutex> lockAP(queue->mutex);
  393. while (queue->size) {
  394. av_packet_unref(&queue->pktVec[queue->readIndex].pkt);
  395. queue->readIndex = (queue->readIndex + 1) % m_maxPacketQueueSize;
  396. queue->size--;
  397. }
  398. queue->serial++;
  399. }
  400. void Decoder::seekTo(int32_t target, int32_t seekRel)
  401. {
  402. //上次跳转未完成不处理跳转请求
  403. if (m_isSeek == 1)
  404. return;
  405. if (target < 0)
  406. target = 0;
  407. m_seekTarget = target;
  408. m_seekRel = seekRel;
  409. m_isSeek = 1;
  410. }
  411. void Decoder::demux(std::shared_ptr<void> par)
  412. {
  413. int ret = -1;
  414. AVPacket* pkt = av_packet_alloc();
  415. while (1) {
  416. if (m_exit) {
  417. break;
  418. }
  419. if (m_audioPacketQueue.size >= m_maxPacketQueueSize
  420. || m_videoPacketQueue.size >= m_maxPacketQueueSize) {
  421. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  422. continue;
  423. }
  424. if (m_isSeek) {
  425. //AVRational sq={1,AV_TIME_BASE};
  426. //int64_t seekMin = m_seekRel > 0 ? m_seekTarget-m_seekRel+2 : INT64_MIN;
  427. //int64_t seekMax = m_seekRel < 0 ? m_seekTarget-m_seekRel-2 : INT64_MAX;
  428. //qDebug()<<"seekMin:"<<seekMin<<" seekMax:"<<seekMax<<" seekTarget:"<<m_seekTarget<<endl;
  429. //ret=avformat_seek_file(m_fmtCtx,m_audioIndex,seekMin,m_seekTarget,seekMax,AVSEEK_FLAG_BACKWARD);
  430. int64_t seekTarget = m_seekTarget * AV_TIME_BASE;
  431. ret = av_seek_frame(m_fmtCtx, -1, seekTarget, AVSEEK_FLAG_BACKWARD);
  432. if (ret < 0) {
  433. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  434. qDebug() << "avformat_seek_file error:" << m_errBuf;
  435. } else {
  436. packetQueueFlush(&m_audioPacketQueue);
  437. packetQueueFlush(&m_videoPacketQueue);
  438. m_audSeek = 1;
  439. m_vidSeek = 1;
  440. }
  441. m_isSeek = 0;
  442. }
  443. ret = av_read_frame(m_fmtCtx, pkt);
  444. if (ret != 0) {
  445. // 仅清理内部引用,避免与循环末尾的 av_packet_free 重复释放
  446. av_packet_unref(pkt);
  447. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  448. qDebug() << "av_read_frame error:" << m_errBuf;
  449. break;
  450. }
  451. if (pkt->stream_index == m_audioIndex) {
  452. //插入音频包队列
  453. //qDebug()<<pkt->pts*av_q2d(m_fmtCtx->streams[m_audioIndex]->time_base)<<endl;
  454. pushPacket(&m_audioPacketQueue, pkt);
  455. } else if (pkt->stream_index == m_videoIndex) {
  456. //插入视频包队列
  457. pushPacket(&m_videoPacketQueue, pkt);
  458. //av_packet_unref(pkt);
  459. } else {
  460. av_packet_unref(pkt);
  461. }
  462. }
  463. av_packet_free(&pkt);
  464. //是读到文件末尾退出的才清空,强制退出不重复此操作
  465. if (!m_exit) {
  466. // 根据实际存在的流等待对应帧队列清空
  467. if (m_audioIndex >= 0) {
  468. while (m_audioFrameQueue.size)
  469. QThread::msleep(50);
  470. }
  471. if (m_videoIndex >= 0) {
  472. while (m_videoFrameQueue.size)
  473. QThread::msleep(50);
  474. }
  475. exit();
  476. }
  477. //qDebug() << "demuxthread exit";
  478. }
  479. void Decoder::audioDecode(std::shared_ptr<void> par)
  480. {
  481. AVPacket* pkt = av_packet_alloc();
  482. AVFrame* frame = av_frame_alloc();
  483. while (1) {
  484. if (m_exit) {
  485. break;
  486. }
  487. //音频帧队列长度控制
  488. if (m_audioFrameQueue.size >= m_maxFrameQueueSize) {
  489. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  490. continue;
  491. }
  492. //从音频包队列取音频包
  493. int ret = getPacket(&m_audioPacketQueue, pkt, &m_audioPktDecoder);
  494. if (ret) {
  495. ret = avcodec_send_packet(m_audioPktDecoder.codecCtx, pkt);
  496. av_packet_unref(pkt);
  497. if (ret < 0) {
  498. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  499. qDebug() << "avcodec_send_packet error:" << m_errBuf;
  500. continue;
  501. }
  502. while (1) {
  503. ret = avcodec_receive_frame(m_audioPktDecoder.codecCtx, frame);
  504. if (ret == 0) {
  505. if (m_audSeek) {
  506. int pts = (int) frame->pts
  507. * av_q2d(m_fmtCtx->streams[m_audioIndex]->time_base);
  508. //qDebug()<<"audFrame pts:"<<pts<<endl;
  509. if (pts < m_seekTarget) {
  510. av_frame_unref(frame);
  511. continue;
  512. } else {
  513. m_audSeek = 0;
  514. }
  515. }
  516. //添加到待播放音频帧队列
  517. pushAFrame(frame);
  518. } else {
  519. break;
  520. }
  521. }
  522. } else {
  523. //qDebug() << "audio packetQueue is empty for decoding!";
  524. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  525. }
  526. }
  527. av_packet_free(&pkt);
  528. av_frame_free(&frame);
  529. //qDebug() << "audioDecode exit";
  530. }
  531. void Decoder::videoDecode(std::shared_ptr<void> par)
  532. {
  533. AVPacket* pkt = av_packet_alloc();
  534. AVFrame* frame = av_frame_alloc();
  535. while (1) {
  536. if (m_exit) {
  537. break;
  538. }
  539. if (m_videoFrameQueue.size >= m_maxFrameQueueSize) { //视频帧队列长度控制
  540. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  541. continue;
  542. }
  543. int ret = getPacket(&m_videoPacketQueue, pkt, &m_videoPktDecoder);
  544. if (ret) {
  545. ret = avcodec_send_packet(m_videoPktDecoder.codecCtx, pkt);
  546. av_packet_unref(pkt);
  547. if (ret < 0 || ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  548. av_strerror(ret, m_errBuf, sizeof(m_errBuf));
  549. qDebug() << "avcodec_send_packet error:" << m_errBuf;
  550. continue;
  551. }
  552. while (1) {
  553. ret = avcodec_receive_frame(m_videoPktDecoder.codecCtx, frame);
  554. if (ret == 0) {
  555. if (m_vidSeek) {
  556. int pts = (int) frame->pts
  557. * av_q2d(m_fmtCtx->streams[m_videoIndex]->time_base);
  558. if (pts < m_seekTarget) {
  559. av_frame_unref(frame);
  560. continue;
  561. } else {
  562. m_vidSeek = 0;
  563. }
  564. }
  565. //AVRational vidRational=av_guess_frame_rate(m_fmtCtx,
  566. // m_fmtCtx->streams[m_videoIndex],frame);
  567. //添加到待播放视频帧队列
  568. pushVFrame(frame);
  569. } else {
  570. break;
  571. }
  572. }
  573. } else {
  574. //qDebug() << "video packetQueue is empty for decoding!";
  575. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  576. }
  577. }
  578. av_packet_free(&pkt);
  579. av_frame_free(&frame);
  580. //qDebug() << "videoDecode exit";
  581. }
  582. int Decoder::getPacket(PacketQueue* queue, AVPacket* pkt, PktDecoder* decoder)
  583. {
  584. std::unique_lock<std::mutex> lock(queue->mutex);
  585. while (!queue->size) {
  586. bool ret = queue->cond.wait_for(lock, std::chrono::milliseconds(100), [&]() {
  587. return queue->size && !m_exit;
  588. });
  589. if (!ret)
  590. return 0;
  591. }
  592. if (queue->serial != decoder->serial) {
  593. //序列号不连续的帧证明发生了跳转操作则直接丢弃
  594. //并清空解码器缓存
  595. avcodec_flush_buffers(decoder->codecCtx);
  596. decoder->serial = queue->pktVec[queue->readIndex].serial;
  597. return 0;
  598. }
  599. av_packet_move_ref(pkt, &queue->pktVec[queue->readIndex].pkt);
  600. decoder->serial = queue->pktVec[queue->readIndex].serial;
  601. queue->readIndex = (queue->readIndex + 1) % m_maxPacketQueueSize;
  602. queue->size--;
  603. return 1;
  604. }
  605. void Decoder::pushPacket(PacketQueue* queue, AVPacket* pkt)
  606. {
  607. std::lock_guard<std::mutex> lock(queue->mutex);
  608. av_packet_move_ref(&queue->pktVec[queue->pushIndex].pkt, pkt);
  609. queue->pktVec[queue->pushIndex].serial = queue->serial;
  610. if (queue->serial == 1)
  611. qDebug() << "";
  612. queue->pushIndex = (queue->pushIndex + 1) % m_maxPacketQueueSize;
  613. queue->size++;
  614. }
  615. void Decoder::pushAFrame(AVFrame* frame)
  616. {
  617. std::lock_guard<std::mutex> lock(m_audioFrameQueue.mutex);
  618. av_frame_move_ref(&m_audioFrameQueue.frameVec[m_audioFrameQueue.pushIndex].frame, frame);
  619. m_audioFrameQueue.frameVec[m_audioFrameQueue.pushIndex].serial = m_audioPktDecoder.serial;
  620. m_audioFrameQueue.pushIndex = (m_audioFrameQueue.pushIndex + 1) % m_maxFrameQueueSize;
  621. m_audioFrameQueue.size++;
  622. }
  623. int Decoder::getAFrame(AVFrame* frame)
  624. {
  625. if (!frame)
  626. return 0;
  627. std::unique_lock<std::mutex> lock(m_audioFrameQueue.mutex);
  628. while (!m_audioFrameQueue.size) {
  629. bool ret = m_audioFrameQueue.cond.wait_for(lock, std::chrono::milliseconds(100), [&]() {
  630. return !m_exit && m_audioFrameQueue.size;
  631. });
  632. if (!ret)
  633. return 0;
  634. }
  635. if (m_audioFrameQueue.frameVec[m_audioFrameQueue.readIndex].serial
  636. != m_audioPacketQueue.serial) {
  637. av_frame_unref(&m_audioFrameQueue.frameVec[m_audioFrameQueue.readIndex].frame);
  638. m_audioFrameQueue.readIndex = (m_audioFrameQueue.readIndex + 1) % m_maxFrameQueueSize;
  639. m_audioFrameQueue.size--;
  640. return 0;
  641. }
  642. av_frame_move_ref(frame, &m_audioFrameQueue.frameVec[m_audioFrameQueue.readIndex].frame);
  643. m_audioFrameQueue.readIndex = (m_audioFrameQueue.readIndex + 1) % m_maxFrameQueueSize;
  644. m_audioFrameQueue.size--;
  645. return 1;
  646. }
  647. void Decoder::pushVFrame(AVFrame* frame)
  648. {
  649. std::lock_guard<std::mutex> lock(m_videoFrameQueue.mutex);
  650. m_videoFrameQueue.frameVec[m_videoFrameQueue.pushIndex].serial = m_videoPktDecoder.serial;
  651. m_videoFrameQueue.frameVec[m_videoFrameQueue.pushIndex].duration
  652. = (m_vidFrameRate.den && m_vidFrameRate.den)
  653. ? av_q2d(AVRational{m_vidFrameRate.den, m_vidFrameRate.num})
  654. : 0.00;
  655. m_videoFrameQueue.frameVec[m_videoFrameQueue.pushIndex].pts
  656. = frame->pts * av_q2d(m_fmtCtx->streams[m_videoIndex]->time_base);
  657. av_frame_move_ref(&m_videoFrameQueue.frameVec[m_videoFrameQueue.pushIndex].frame, frame);
  658. m_videoFrameQueue.pushIndex = (m_videoFrameQueue.pushIndex + 1) % m_maxFrameQueueSize;
  659. m_videoFrameQueue.size++;
  660. //qDebug()<<"RemainingVFrame:"<<m_videoFrameQueue.size-m_videoFrameQueue.shown;
  661. }
  662. Decoder::MyFrame* Decoder::peekLastVFrame()
  663. {
  664. Decoder::MyFrame* frame = &m_videoFrameQueue.frameVec[m_videoFrameQueue.readIndex];
  665. return frame;
  666. }
  667. Decoder::MyFrame* Decoder::peekVFrame()
  668. {
  669. while (!m_videoFrameQueue.size) {
  670. std::unique_lock<std::mutex> lock(m_videoFrameQueue.mutex);
  671. bool ret = m_videoFrameQueue.cond.wait_for(lock, std::chrono::milliseconds(100), [&]() {
  672. return !m_exit && m_videoFrameQueue.size;
  673. });
  674. if (!ret)
  675. return nullptr;
  676. }
  677. int index = (m_videoFrameQueue.readIndex + m_videoFrameQueue.shown) % m_maxFrameQueueSize;
  678. Decoder::MyFrame* frame = &m_videoFrameQueue.frameVec[index];
  679. return frame;
  680. }
  681. Decoder::MyFrame* Decoder::peekNextVFrame()
  682. {
  683. while (m_videoFrameQueue.size < 2) {
  684. std::unique_lock<std::mutex> lock(m_videoFrameQueue.mutex);
  685. bool ret = m_videoFrameQueue.cond.wait_for(lock, std::chrono::milliseconds(100), [&]() {
  686. return !m_exit && m_videoFrameQueue.size;
  687. });
  688. if (!ret)
  689. return nullptr;
  690. }
  691. int index = (m_videoFrameQueue.readIndex + m_videoFrameQueue.shown + 1) % m_maxFrameQueueSize;
  692. Decoder::MyFrame* frame = &m_videoFrameQueue.frameVec[index];
  693. return frame;
  694. }
  695. void Decoder::setNextVFrame()
  696. {
  697. std::unique_lock<std::mutex> lock(m_videoFrameQueue.mutex);
  698. if (!m_videoFrameQueue.size)
  699. return;
  700. if (!m_videoFrameQueue.shown) {
  701. m_videoFrameQueue.shown = 1;
  702. return;
  703. }
  704. av_frame_unref(&m_videoFrameQueue.frameVec[m_videoFrameQueue.readIndex].frame);
  705. m_videoFrameQueue.readIndex = (m_videoFrameQueue.readIndex + 1) % m_maxFrameQueueSize;
  706. m_videoFrameQueue.size--;
  707. }
  708. int Decoder::getRemainingVFrame()
  709. {
  710. if (!m_videoFrameQueue.size)
  711. return 0;
  712. return m_videoFrameQueue.size - m_videoFrameQueue.shown;
  713. }