[Libav-user] AAC encoding question

alex b. abalk at avail-tvn.com
Mon Jul 18 00:53:33 CEST 2011



Hi,

I am trying to encode audio using the AAC audio encoder with the program 
below. It seems to work fine (runs without issues) but the resulting AAC 
audio is not playable with anything like ffplay or mplayer. If anyone 
can point out what I'm doing wrong that would be really appreciated.

The input.wav file is made up of 2 channel 6144 byte samples, 5 to each 
frame (for a frame size of 30720 byes) and it plays fine in mplayer with 
a command like

$ mplayer -demuxer rawaudio -rawaudio rate=48000 input.wav

there is no header in the .wav file, but that's ok. also, encoding this 
input using ffmpeg and the "-strict experimental" option for AAC audio 
works fine as well


thanks, alez...


-----------------------------------------------------------

/* test audio encoder */
#define _XOPEN_SOURCE 600

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdio.h>
#include <avcodec.h>
#include <libavcodec/opt.h>
#include <libavutil/log.h>

#define FRM_SZ  30720
#define SMPL_SZ 6144

int main(void)
{
     AVCodec *codec;
     AVCodecContext *context;
     int bytes_read;
     FILE* in_pcm = fopen("input.wav", "rb");
     FILE* out_aac = fopen("output.aac", "wb");

     uint8_t* inbuff = malloc(FRM_SZ*sizeof(uint8_t));
     uint8_t* smallbuff;

     avcodec_init();
     avcodec_register_all();

     codec = avcodec_find_encoder(CODEC_ID_AAC);

     context = avcodec_alloc_context3(codec);

     context->bit_rate = 128000;
     context->sample_rate = 48000;
     context->channels = 2;
     context->frame_size = 30720;
     context->sample_fmt = AV_SAMPLE_FMT_S16;

     if (avcodec_open2(context, codec, NULL) < 0)
     {
         fprintf(stderr, "ERROR: could not initialize encoder\n");
         exit(1);
     }

     while ( ( bytes_read = fread( inbuff, FRM_SZ, 1, in_pcm ) ) > 0 )
     {
         // there are 5 audio samples per frame (4620 frames total = 
28385280 bytes in the file)
         for ( int i = 0; i < 5; i++ )
         {
             smallbuff = malloc(SMPL_SZ*sizeof(uint8_t));

             memcpy(smallbuff, &inbuff[i*SMPL_SZ], SMPL_SZ);

             int frame_bytes = context->frame_size * context->sample_fmt 
* context->channels;
             int outbuf_size;

             uint8_t* outbuf;
             posix_memalign( (void**)&outbuf, (size_t)16, 
(size_t)frame_bytes );

             outbuf_size = avcodec_encode_audio(context, outbuf, 
frame_bytes, (short*)smallbuff);

             fwrite(outbuf, outbuf_size, 1, out_aac);

             free(outbuf);
             free(smallbuff);
         }
     }

     free(inbuff);
     return 0;
}





More information about the Libav-user mailing list