av_decoder.cpp 29 KB

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