audio_encoder.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "audio_encoder.h"
  2. #include <QDebug>
  3. bool Encoder<MediaType::AUDIO>::Open(const Param& audioParam, AVFormatContext* fmtCtx)
  4. {
  5. Close();
  6. _isOpen = false;
  7. qDebug() << "AudioEncoder::Open: Initializing audio encoder with bitrate" << audioParam.bitRate;
  8. if (!_Init(audioParam, fmtCtx)) {
  9. qDebug() << "AudioEncoder::Open failed: Audio encoder initialization failed";
  10. return false;
  11. }
  12. int ret = avcodec_open2(_codecCtx, _codec, nullptr);
  13. if (ret < 0) {
  14. char errbuf[AV_ERROR_MAX_STRING_SIZE];
  15. av_strerror(ret, errbuf, AV_ERROR_MAX_STRING_SIZE);
  16. qDebug() << "AudioEncoder::Open failed: Cannot open audio codec. Error:" << errbuf << "(" << ret << ")";
  17. qDebug() << "Codec name:" << _codec->name << "ID:" << _codec->id;
  18. qDebug() << "Sample rate:" << _codecCtx->sample_rate << "Channels:" << _codecCtx->ch_layout.nb_channels;
  19. return false;
  20. }
  21. _isOpen = true;
  22. qDebug() << "AudioEncoder::Open: Audio encoder opened successfully";
  23. return true;
  24. }
  25. void Encoder<MediaType::AUDIO>::Close()
  26. {
  27. if (_codecCtx != nullptr) {
  28. avcodec_free_context(&_codecCtx);
  29. }
  30. Free(_codecCtx, [this] { avcodec_free_context(&_codecCtx); });
  31. }
  32. bool Encoder<MediaType::AUDIO>::_Init(const Param& audioParam, AVFormatContext* fmtCtx)
  33. {
  34. // codec
  35. __CheckBool(_codec = avcodec_find_encoder(AV_CODEC_ID_AAC));
  36. // codeccontext
  37. __CheckBool(_codecCtx = avcodec_alloc_context3(_codec));
  38. _codecCtx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  39. _codecCtx->bit_rate = audioParam.bitRate;
  40. _codecCtx->sample_rate = AUDIO_SAMPLE_RATE;
  41. AVChannelLayout layout;
  42. layout.order = AV_CHANNEL_ORDER_NATIVE;
  43. layout.nb_channels = 1;
  44. layout.u.mask = AV_CH_LAYOUT_MONO;
  45. av_channel_layout_copy(&_codecCtx->ch_layout, &layout);
  46. if (fmtCtx->oformat->flags & AVFMT_GLOBALHEADER) {
  47. _codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  48. }
  49. return true;
  50. }
  51. bool Encoder<MediaType::AUDIO>::PushFrame(AVFrame* frame, bool isEnd, uint64_t pts)
  52. {
  53. if (!isEnd) {
  54. __CheckBool(frame);
  55. } else {
  56. frame = nullptr;
  57. }
  58. if (frame != nullptr) {
  59. frame->pts = pts;
  60. }
  61. __CheckBool(avcodec_send_frame(_codecCtx, frame) >= 0);
  62. return true;
  63. }