| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- #include "audio_encoder.h"
- #include <QDebug>
- bool Encoder<MediaType::AUDIO>::Open(const Param& audioParam, AVFormatContext* fmtCtx)
- {
- Close();
- _isOpen = false;
-
- qDebug() << "AudioEncoder::Open: Initializing audio encoder with bitrate" << audioParam.bitRate;
-
- if (!_Init(audioParam, fmtCtx)) {
- qDebug() << "AudioEncoder::Open failed: Audio encoder initialization failed";
- return false;
- }
-
- int ret = avcodec_open2(_codecCtx, _codec, nullptr);
- if (ret < 0) {
- char errbuf[AV_ERROR_MAX_STRING_SIZE];
- av_strerror(ret, errbuf, AV_ERROR_MAX_STRING_SIZE);
- qDebug() << "AudioEncoder::Open failed: Cannot open audio codec. Error:" << errbuf << "(" << ret << ")";
- qDebug() << "Codec name:" << _codec->name << "ID:" << _codec->id;
- qDebug() << "Sample rate:" << _codecCtx->sample_rate << "Channels:" << _codecCtx->ch_layout.nb_channels;
- return false;
- }
-
- _isOpen = true;
- qDebug() << "AudioEncoder::Open: Audio encoder opened successfully";
- return true;
- }
- void Encoder<MediaType::AUDIO>::Close()
- {
- if (_codecCtx != nullptr) {
- avcodec_free_context(&_codecCtx);
- }
- Free(_codecCtx, [this] { avcodec_free_context(&_codecCtx); });
- }
- bool Encoder<MediaType::AUDIO>::_Init(const Param& audioParam, AVFormatContext* fmtCtx)
- {
- // codec
- __CheckBool(_codec = avcodec_find_encoder(AV_CODEC_ID_AAC));
- // codeccontext
- __CheckBool(_codecCtx = avcodec_alloc_context3(_codec));
- _codecCtx->sample_fmt = AV_SAMPLE_FMT_FLTP;
- _codecCtx->bit_rate = audioParam.bitRate;
- _codecCtx->sample_rate = AUDIO_SAMPLE_RATE;
- AVChannelLayout layout;
- layout.order = AV_CHANNEL_ORDER_NATIVE;
- layout.nb_channels = 1;
- layout.u.mask = AV_CH_LAYOUT_MONO;
- av_channel_layout_copy(&_codecCtx->ch_layout, &layout);
- if (fmtCtx->oformat->flags & AVFMT_GLOBALHEADER) {
- _codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
- }
- return true;
- }
- bool Encoder<MediaType::AUDIO>::PushFrame(AVFrame* frame, bool isEnd, uint64_t pts)
- {
- if (!isEnd) {
- __CheckBool(frame);
- } else {
- frame = nullptr;
- }
- if (frame != nullptr) {
- frame->pts = pts;
- }
- __CheckBool(avcodec_send_frame(_codecCtx, frame) >= 0);
- return true;
- }
|