Search code examples
audioffmpeglibavcodectranscodinglibav

How to encode audio in AAC-LC, AAC-HE-V1, AAC-HE-V2 using libavcodec?


I am trying to encode audio in AAC-LC,AAC-HE-V1, AAC-HE-V2 using libavcodec/ffmpeg APIs.

But when I am using the following configuration and API calls.It says "invalid AAC profile."

AVCodecContext *encoder_ctx;
encoder_ctx->codec_id           =   AV_CODEC_ID_AAC;
encoder_ctx->sample_fmt         =   AV_SAMPLE_FMT_S16; 
encoder_ctx->profile            =   FF_PROFILE_AAC_HE;

encoder = avcodec_find_encoder(encoder_ctx->codec_id);
avcodec_open2(encoder_ctx, encoder, NULL);

Could you please explain what is wrong with this?


Solution

  • First of all have a look at this document:

    Dolby Digital: ac3

    Dolby Digital Plus: eac3

    MP2: libtwolame, mp2

    Windows Media Audio 1: wmav1

    Windows Media Audio 2: wmav2

    LC-AAC: libfdk_aac, libfaac, aac, libvo_aacenc

    HE-AAC: libfdk_aac, libaacplus

    Vorbis: libvorbis, vorbis

    MP3: libmp3lame, libshine

    Opus: libopus

    from the above reading it will be clear to you that in order to encode audio in HE-AAC/ HE-AAC-V2 you have to use libfdk_aac or libaacplus.

    I will explain how you can do it using libfdk_aac:

    first make sure you configure ffmpeg along with following options:

    --enable-libfdk_aac --enable-nonfree
    

    now build ffmpeg and try to run the following command and see if it works:

    ffmpeg -i <input file> -vcodec copy -acodec libfdk_aac -profile:a aac_he <output file>
    

    if this works it means libav is linked with libfdk_aac.

    now in order to use it in the code:

    open the encoder using the following instructions:

    AVCodecContext *encoder_ctx;
    encoder_ctx->codec_id           =   AV_CODEC_ID_AAC;
    encoder_ctx->sample_fmt         =   AV_SAMPLE_FMT_S16; 
    encoder_ctx->profile            =   FF_PROFILE_AAC_HE;
    
    encoder = avcodec_find_encoder_by_name("libfdk_aac");
    // if you still try to open it using avcodec_find_encoder it will open libfaac only.
    avcodec_open2(encoder_ctx, encoder, NULL);
    

    Here we go, you have libfdk_aac encoder open ! The profiles which you can use are as given in this source