Opus严格的旗帜

时间:2017-07-07 19:32:06

标签: c ffmpeg libavcodec opus

我正在使用libavcodec库的库。

我尝试使用opus编解码器编码音频帧但是在avcodec_open2(...)之后我得到了这个日志

[opus @ 0x2335f30] The encoder 'opus' is experimental but experimental codecs are not enabled, add '-strict -2' if you want to use it.

当尝试av_fill_audio_frame(..)时,我也会收到此错误

Invalid argument

我的代码:

#include <libavcodec/avcodec.h>
#include "libavutil/opt.h"
#include <libavformat/avformat.h>
AVFrame *audio_frame = NULL;
AVPacket *audio_packet = NULL;
AVCodecContext *audio_encoder_codec_context = NULL;
AVCodec *audio_encoder_codec = NULL;

void init(){
    audio_frame = av_frame_alloc();
    audio_packet = av_packet_alloc();
    audio_encoder_codec = avcodec_find_encoder(AV_CODEC_ID_OPUS);
    audio_encoder_codec_context = avcodec_alloc_context3(audio_encoder_codec);
    audio_encoder_codec_context->time_base = (AVRational){1,25};
    audio_encoder_codec_context->sample_rate = audio_sample_rate;
    audio_encoder_codec_context->sample_fmt = (enum AVSampleFormat) audio_sample_format == 0 ? AV_SAMPLE_FMT_U8 : AV_SAMPLE_FMT_S16;
    audio_encoder_codec_context->channels = 1;
    audio_encoder_codec_context->channel_layout = AV_CH_LAYOUT_MONO;
    audio_encoder_codec_context->codec_type = AVMEDIA_TYPE_AUDIO;
    audio_encoder_codec_context->extradata = NULL;
    avcodec_open2(audio_encoder_codec_context,audio_encoder_codec,NULL);
    audio_frame_size = av_samples_get_buffer_size(
            NULL,
            audio_encoder_codec_context->channels,
            audio_sample_rate,
            audio_encoder_codec_context->sample_fmt,
            1
    );
    audio_frame_buffer = (uint8_t*) av_malloc((audio_frame_size)*sizeof(uint8_t));
}

void encode(uint8_t *frame,int frame_size,uint8_t **packet, int *packet_size){
    memcpy(audio_frame_buffer, frame, (size_t) frame_size);
    av_init_packet(audio_packet);
    int isFin = 0;
    int r = avcodec_fill_audio_frame(audio_frame,audio_encoder_codec_context->channels,audio_encoder_codec_context->sample_fmt,audio_frame_buffer,audio_frame_size,0);
    printf("ERROR = %s",av_err2str(r));
    avcodec_encode_audio2(audio_encoder_codec_context,audio_packet,audio_frame,&isFin);
    *packet = audio_packet->data;
    *packet_size = audio_packet->size;
}

int main(){
    init();
    uint8_t *packet = NULL;
    int size = 0;
    encode(".....",44100,packet,size);

}

1 个答案:

答案 0 :(得分:2)

可以通过在invalid_argument上设置nb_samples来解决frame错误 - 在我设置之前我也遇到了此错误。示例代码和输出:

AVFrame *frame = av_frame_alloc();
int ret = avcodec_fill_audio_frame(frame, channels, fmt, frame_buffer, frame_size, 0);
if (ret < 0)
{
    printf("ERROR = %s\n", av_err2str(ret));
}
else
{
    printf("Success (%i bytes required to allocate)\n", ret);
}

产量输出:

ERROR = Invalid argument

正确设置nb_samples

AVFrame *frame = av_frame_alloc();
frame->nb_samples = 48000;
int ret = avcodec_fill_audio_frame(frame, channels, fmt, frame_buffer, frame_size, 0);
// etc...

结果:

Success (192000 bytes required to allocate)