"how do i use coreaudio's audioconverter to encode aac in real-time?" Code Answer


audioconverterfillcomplexbuffer does not actually mean "fill the encoder with my input buffer that i have here". it means "fill this output buffer here with encoded data from the encoder". with this perspective, the callback suddenly makes sense -- it is used to fetch source data to satisfy the "fill this output buffer for me" request. maybe this is obvious to others, but it took me a long time to understand this (and from all the audioconverter sample code i see floating around where people send input data through ininputdataprocuserdata, i'm guessing i'm not the only one).

the audioconverterfillcomplexbuffer call is blocking, and is expecting you to deliver data to it synchronously from the callback. if you are encoding in real time, you will thus need to call fillcomplexbuffer on a separate thread that you set up yourself. in the callback, you can then check for available input data, and if it is not available, you need to block on a semaphore. using an nscondition, the encoder thread would then look something like this:

- (void)startencoder
    osstatus creationstatus = audioconverternew(&_fromformat, &_toformat, &_converter);

    _running = yes;
    _condition = [[nscondition alloc] init];
    [self performselectorinbackground:@selector(_encoderthread) withobject:nil];

- (void)_encoderthread
    while(_running) {
        // make quarter-second buffers.
        size_t buffersize = (_outputbitrate/8) * 0.25;
        nsmutabledata *outaudiobuffer = [nsmutabledata datawithlength:buffersize];
        audiobufferlist outaudiobufferlist;
        outaudiobufferlist.mnumberbuffers = 1;
        outaudiobufferlist.mbuffers[0].mnumberchannels = _toformat.mchannelsperframe;
        outaudiobufferlist.mbuffers[0].mdatabytesize = (uint32)buffersize;
        outaudiobufferlist.mbuffers[0].mdata = [outaudiobuffer mutablebytes];

        uint32 iooutputdatapacketsize = 1;

        _currentpresentationtime = kcmtimeinvalid; // you need to fill this in during fillcomplexbuffer
        const osstatus conversionresult = audioconverterfillcomplexbuffer(_converter, fillbuffertrampoline, (__bridge void*)self, &iooutputdatapacketsize, &outaudiobufferlist, null);

        // here i convert the audiobufferlist into a cmsamplebuffer, which i've omitted for brevity.
        // ping me if you need it.
        [self.delegate encoder:self encodedsamplebuffer:outsamplebuffer];

and the callback could look like this: (note that i normally use this trampoline to immediately forward to a method on my instance (by forwarding my instance in inuserdata; this step is omitted for brevity)):

static osstatus fillbuffertrampoline(audioconverterref               inaudioconverter,
                                        uint32*                         ionumberdatapackets,
                                        audiobufferlist*                iodata,
                                        audiostreampacketdescription**  outdatapacketdescription,
                                        void*                           inuserdata)
    [_condition lock];

    uint32 countofpacketswritten = 0;

    while (true) {
        // if the condition fires and we have shut down the encoder, just pretend like we have written 0 bytes and are done.
        if(!_running) break;

        // out of input data? wait on the condition.
        if(_inputbuffer.length == 0) {
            [_condition wait];

        // we have data! fill iodata from your _inputbuffer here.
        // also save the input buffer's start presentationtime here.

        // exit out of the loop, since we're done waiting for data

    [_condition unlock];

        // 2. set ionumberdatapackets to the amount of data remaining

    // if running is false, this will be 0, indicating endofstream
    *ionumberdatapackets = countofpacketswritten;

    return noerr;

and for completeness, here's how you would then feed this encoder with data, and how to shut it down properly:

- (void)appendsamplebuffer:(cmsamplebufferref)samplebuffer
    [_condition lock];
    // convert samplebuffer and put it into _inputbuffer here
    [_condition broadcast];
    [_condition unlock];

- (void)stopencoding
    [_condition lock];
    _running = no;
    [_condition broadcast];
    [_condition unlock];
By ndd on January 27 2022

Answers related to “how do i use coreaudio's audioconverter to encode aac in real-time?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.