Пытаюсь написать encode с помощью библиотеки ffmpeg.
Ошибка заключается в том что при вызове функции avcodec_open2
. Перед этим я выполнил все нужные настройки кодека но все же приведу весь свой код.
Мой класс :
class AudioFileWriter : public soundiocpp::InStream::IReader
{
public:
explicit AudioFileWriter(const std::string filename, enum AVCodecID id, AVSampleFormat format, std::string aformat);
~AudioFileWriter() override;
private:
void encode(enum AVCodecID id, AVSampleFormat f);
int check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt);
bool check_audio_format();
int sample_rate_supported();
int channel_layout();
static void register_if_need();
void openFile();
AVCodec *codec;
AVCodecContext *_format;
std::string namef;
std::string path;
std::string audioFormat;
AVFormatContext *s;
AVOutputFormat *outFmt;
AVFrame *frame;
FILE *f;
AVPacket pkt;
char* output_formats[4] = { "mp3", "wav", "wma", "ogg" };
public:
int availableReadFrames(int min, int max) override;
void readSample(int channel, char *ptr, int size) override;
void overflow() override;
void readError(int err) override;
};
И главная функция в которой я проваливаюсь в ошибку:
void AudioFileWriter::encode( enum AVCodecID id, AVSampleFormat f )
{
codec = avcodec_find_encoder(AV_CODEC_ID_MP3);
if (!codec)
throw std::invalid_argument("This encoder is not available for this system!");
_format = avcodec_alloc_context3(codec);
if (!_format)
throw std::invalid_argument("cannot allocate memory for AVFormatContext");
_format->bit_rate = 128000;
_format->sample_rate = f;
_format->sample_rate = sample_rate_supported();
_format->channel_layout = channel_layout();
_format->channels = av_get_channel_layout_nb_channels(_format->channel_layout);
if (avcodec_open2( _format,codec,NULL ) < 0)
throw std::invalid_argument("cannot open codec");
s = avformat_alloc_context();
if ( !s )
throw std::invalid_argument("cannot allocate media context");
outFmt = av_guess_format(audioFormat.c_str(),NULL,NULL);
if (outFmt->flags & AVFMT_NOFILE)
{
throw std::invalid_argument("format fail");
}
avformat_alloc_output_context2(&s,outFmt,output_formats[1],NULL);
frame = av_frame_alloc();
if (!frame)
throw std::invalid_argument("Could not allocate audio frame");
frame->nb_samples = _format->frame_size;
frame->format = _format->sample_fmt;
frame->channel_layout = _format->channel_layout;
}
Падаю в ошибку при вызове функции : if (avcodec_open2( _format,codec,NULL ) < 0)
Падаю на следующей ошибкой Specified sample format -1 is invalid or not supported
_format->sample_fmt
, а заодно и прочие поля этой структуры, которые могут быть использованы целевым кодеком