av_decoder.cpp 29 KB

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