av_muxer.cpp 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #include "av_muxer.h"
  2. bool AvMuxer::Open(std::string_view filePath, std::string_view format)
  3. {
  4. Close();
  5. _isOpenFile = false;
  6. _filePath = filePath;
  7. __CheckBool(avformat_alloc_output_context2(&_fmtCtx, nullptr, format.data(), _filePath.c_str()) >= 0);
  8. __CheckBool(_fmtCtx);
  9. return true;
  10. }
  11. bool AvMuxer::WriteHeader()
  12. {
  13. av_dump_format(_fmtCtx, 0, _filePath.data(), 1);
  14. // 打开输出文件
  15. if (!(_fmtCtx->oformat->flags & AVFMT_NOFILE)) {
  16. __CheckBool(avio_open(&_fmtCtx->pb, _filePath.c_str(), AVIO_FLAG_WRITE) >= 0);
  17. }
  18. // 写入文件头
  19. __CheckBool(avformat_write_header(_fmtCtx, nullptr) >= 0);
  20. _isOpenFile = true;
  21. return true;
  22. }
  23. int AvMuxer::AddVideoStream(const Encoder<MediaType::VIDEO>::Param& param)
  24. {
  25. __Check(-1, _fmtCtx->oformat->video_codec != AV_CODEC_ID_NONE);
  26. Info info;
  27. info.pts = 0;
  28. info.fps = param.fps;
  29. auto encoder = new Encoder<MediaType::VIDEO>;
  30. __Check(-1, encoder->Open(param, _fmtCtx));
  31. info.type = MediaType::VIDEO;
  32. info.encoder = encoder;
  33. __Check(-1, _AddStream(info));
  34. _infos.back().stream->time_base = {1, info.fps};
  35. return info.streamIndex;
  36. }
  37. int AvMuxer::AddAudioStream(const Encoder<MediaType::AUDIO>::Param& param)
  38. {
  39. __Check(-1, _fmtCtx->oformat->audio_codec != AV_CODEC_ID_NONE);
  40. Info info;
  41. info.pts = 0;
  42. info.fps = AUDIO_SAMPLE_RATE;
  43. auto encoder = new Encoder<MediaType::AUDIO>;
  44. info.type = MediaType::AUDIO;
  45. info.encoder = encoder;
  46. __Check(-1, encoder->Open(param, _fmtCtx));
  47. __Check(-1, _AddStream(info));
  48. _infos.back().stream->time_base = {1, AUDIO_SAMPLE_RATE};
  49. return info.streamIndex;
  50. }
  51. bool AvMuxer::Write(AVFrame* frame, int streamIndex, bool isEnd)
  52. {
  53. // 此函数不能被多个流同时调用
  54. std::lock_guard<std::mutex> lk(_mtx);
  55. __CheckBool(_infos.size() > streamIndex);
  56. auto&& info = _infos[streamIndex];
  57. if (info.isEnd) {
  58. return true;
  59. }
  60. if (isEnd) {
  61. info.isEnd = isEnd;
  62. frame = nullptr;
  63. }
  64. __CheckBool(info.encoder);
  65. // 检测流之间时间是不是差的太多,如果差的太多,直接弃掉数据多的流数据
  66. if (!_CheckTime(double(info.pts) / info.fps)) {
  67. info.isEncodeOverload = true;
  68. return false;
  69. }
  70. info.isEncodeOverload = false;
  71. __CheckBool(info.encoder->PushFrame(frame, isEnd, info.pts));
  72. info.pts += info.type == MediaType::AUDIO ? info.encoder->GetCtx()->frame_size : 1; // 更新 pts
  73. AVPacket* packet = nullptr;
  74. while ((packet = info.encoder->Encode())) {
  75. av_packet_rescale_ts(packet, info.encoder->GetCtx()->time_base, info.stream->time_base);
  76. packet->stream_index = info.stream->index;
  77. __CheckBool(av_interleaved_write_frame(_fmtCtx, packet) >= 0);
  78. }
  79. info.encoder->AfterEncode();
  80. return true;
  81. }
  82. bool AvMuxer::_CheckTime(double time)
  83. {
  84. auto minTime = double(_infos.front().pts) / _infos.front().fps;
  85. for (int idx = 1; idx < _infos.size(); ++idx) {
  86. minTime = std::min(double(_infos[idx].pts) / _infos[idx].fps, minTime);
  87. }
  88. if (time - minTime > 0.1) { // 说明相差的太多了,下一帧不能再送往编码器
  89. return false;
  90. }
  91. return true;
  92. }
  93. void AvMuxer::Close()
  94. {
  95. if (_fmtCtx == nullptr) {
  96. return;
  97. }
  98. // 清空编码器缓存
  99. for (int index = 0; index < _infos.size(); ++index) {
  100. __DebugPrint("stream: %d, time:%f", index, double(_infos[index].pts) / _infos[index].fps);
  101. }
  102. if (_isOpenFile) {
  103. __CheckNo(av_write_trailer(_fmtCtx) >= 0);
  104. Free(_fmtCtx->pb, [this] { avio_closep(&_fmtCtx->pb); });
  105. }
  106. _isOpenFile = false;
  107. for (auto&& info : _infos) {
  108. info.encoder->Close();
  109. Free(info.encoder, [&info] {info.encoder->Close(); delete info.encoder; });
  110. }
  111. _infos.clear();
  112. Free(_fmtCtx, [this] { avformat_free_context(_fmtCtx); });
  113. }
  114. bool AvMuxer::_AddStream(Info& info)
  115. {
  116. __CheckBool(info.stream = avformat_new_stream(_fmtCtx, nullptr));
  117. info.stream->id = _fmtCtx->nb_streams - 1;
  118. __CheckBool(avcodec_parameters_from_context(info.stream->codecpar, info.encoder->GetCtx()) >= 0);
  119. info.streamIndex = _fmtCtx->nb_streams - 1;
  120. info.pts = 0;
  121. info.isEnd = false;
  122. _infos.push_back(info);
  123. return true;
  124. }
  125. AVCodecContext* AvMuxer::GetCodecCtx(int streamIndex)
  126. {
  127. __CheckNullptr(streamIndex >= 0 && _infos.size() > streamIndex);
  128. return _infos[streamIndex].encoder->GetCtx();
  129. }
  130. bool AvMuxer::IsEncodeOverload() const
  131. {
  132. for (auto&& info : _infos) {
  133. if (info.isEncodeOverload) {
  134. return true;
  135. }
  136. }
  137. return false;
  138. }