audio_encoder.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "audio_encoder.h"
  2. bool Encoder<MediaType::AUDIO>::Open(const Param& audioParma, AVFormatContext* fmtCtx)
  3. {
  4. Close();
  5. _isOpen = false;
  6. __CheckBool(_Init(audioParma, fmtCtx));
  7. __CheckBool(avcodec_open2(_codecCtx, _codec, nullptr) >= 0);
  8. _isOpen = true;
  9. return true;
  10. }
  11. void Encoder<MediaType::AUDIO>::Close()
  12. {
  13. if (_codecCtx != nullptr) {
  14. avcodec_free_context(&_codecCtx);
  15. }
  16. Free(_codecCtx, [this] { avcodec_free_context(&_codecCtx); });
  17. }
  18. bool Encoder<MediaType::AUDIO>::_Init(const Param& audioParam, AVFormatContext* fmtCtx)
  19. {
  20. // codec
  21. __CheckBool(_codec = avcodec_find_encoder(AV_CODEC_ID_AAC));
  22. // codeccontext
  23. __CheckBool(_codecCtx = avcodec_alloc_context3(_codec));
  24. _codecCtx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  25. _codecCtx->bit_rate = audioParam.bitRate;
  26. _codecCtx->sample_rate = AUDIO_SAMPLE_RATE;
  27. AVChannelLayout layout;
  28. layout.order = AV_CHANNEL_ORDER_NATIVE;
  29. layout.nb_channels = 1;
  30. layout.u.mask = AV_CH_LAYOUT_MONO;
  31. av_channel_layout_copy(&_codecCtx->ch_layout, &layout);
  32. if (fmtCtx->oformat->flags & AVFMT_GLOBALHEADER) {
  33. _codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  34. }
  35. return true;
  36. }
  37. bool Encoder<MediaType::AUDIO>::PushFrame(AVFrame* frame, bool isEnd, uint64_t pts)
  38. {
  39. if (!isEnd) {
  40. __CheckBool(frame);
  41. } else {
  42. frame = nullptr;
  43. }
  44. if (frame != nullptr) {
  45. frame->pts = pts;
  46. }
  47. __CheckBool(avcodec_send_frame(_codecCtx, frame) >= 0);
  48. return true;
  49. }