Android Audio System 之一:AudioTrack如何与AudioFlinger交换音频数据

Android Framework的音频子系统中,每一个音频流对应着一个AudioTrack类的一个实例,每个AudioTrack会在创建时注册到AudioFlinger中,由AudioFlinger把所有的AudioTrack进行混合(Mixer),然后输送到AudioHardware中进行播放,目前Android的Froyo版本设定了同时最多可以创建32个音频流,也就是说,Mixer最多会同时处理32个AudioTrack的数据流。

如何使用AudioTrack
AudioTrack的主要代码位于 frameworks/base/media/libmedia/audiotrack.cpp中。现在先通过一个例子来了解一下如何使用AudioTrack,ToneGenerator是android中产生电话拨号音和其他音调波形的一个实现,我们就以它为例子:

ToneGenerator的初始化函数:

view plaincopy to clipboardprint?
bool ToneGenerator::initAudioTrack() {  
   // Open audio track in mono, PCM 16bit, default sampling rate, default buffer size  
    mpAudioTrack = new AudioTrack();  
    mpAudioTrack->set(mStreamType,  
                      0,  
                      AudioSystem::PCM_16_BIT,  
                      AudioSystem::CHANNEL_OUT_MONO,  
                      0,  
                      0,  
                      audioCallback,  
                      this,  
                      0,  
                      0,  
                      mThreadCanCallJava);  
    if (mpAudioTrack->initCheck() != NO_ERROR) {  
        LOGE("AudioTrack->initCheck failed");  
        goto initAudioTrack_exit;  
    }  
    mpAudioTrack->setVolume(mVolume, mVolume);  
    mState = TONE_INIT;  
    ......  
 } 
bool ToneGenerator::initAudioTrack() {
   // Open audio track in mono, PCM 16bit, default sampling rate, default buffer size
    mpAudioTrack = new AudioTrack();
    mpAudioTrack->set(mStreamType,
                      0,
                      AudioSystem::PCM_16_BIT,
                      AudioSystem::CHANNEL_OUT_MONO,
                      0,
                      0,
                      audioCallback,
                      this,
                      0,
                      0,
                      mThreadCanCallJava);
    if (mpAudioTrack->initCheck() != NO_ERROR) {
        LOGE("AudioTrack->initCheck failed");
        goto initAudioTrack_exit;
    }
    mpAudioTrack->setVolume(mVolume, mVolume);
    mState = TONE_INIT;
    ......
 }
 

可见,创建步骤很简单,先new一个AudioTrack的实例,然后调用set成员函数完成参数的设置并注册到AudioFlinger中,然后可以调用其他诸如设置音量等函数进一步设置音频参数。其中,一个重要的参数是audioCallback,audioCallback是一个回调函数,负责响应AudioTrack的通知,例如填充数据、循环播放、播放位置触发等等。回调函数的写法通常像这样:

view plaincopy to clipboardprint?
void ToneGenerator::audioCallback(int event, void* user, void *info) {  
    if (event != AudioTrack::EVENT_MORE_DATA) return;  
    AudioTrack::Buffer *buffer = static_cast<AudioTrack::Buffer *>(info);  
    ToneGenerator *lpToneGen = static_cast<ToneGenerator *>(user);  
    short *lpOut = buffer->i16;  
    unsigned int lNumSmp = buffer->size/sizeof(short);  
    const ToneDescriptor *lpToneDesc = lpToneGen->mpToneDesc;  
    if (buffer->size == 0) return;  
 
    // Clear output buffer: WaveGenerator accumulates into lpOut buffer  
    memset(lpOut, 0, buffer->size);  
    ......  
    // 以下是产生音调数据的代码,略....  

void ToneGenerator::audioCallback(int event, void* user, void *info) {
    if (event != AudioTrack::EVENT_MORE_DATA) return;
    AudioTrack::Buffer *buffer = static_cast<AudioTrack::Buffer *>(info);
    ToneGenerator *lpToneGen = static_cast<ToneGenerator *>(user);
    short *lpOut = buffer->i16;
    unsigned int lNumSmp = buffer->size/sizeof(short);
    const ToneDescriptor *lpToneDesc = lpToneGen->mpToneDesc;
    if (buffer->size == 0) return;

    // Clear output buffer: WaveGenerator accumulates into lpOut buffer
    memset(lpOut, 0, buffer->size);
    ......
    // 以下是产生音调数据的代码,略....
}

该函数首先判断事件的类型是否是EVENT_MORE_DATA,如果是,则后续的代码会填充相应的音频数据后返回,当然你可以处理其他事件,以下是可用的事件类型:

view plaincopy to clipboardprint?
enum event_type {  
        EVENT_MORE_DATA = 0,        // Request to write more data to PCM buffer.  
        EVENT_UNDERRUN = 1,         // PCM buffer underrun occured.  
        EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from loop start if loop count was not 0.  
        EVENT_MARKER = 3,           // Playback head is at the specified marker position (See setMarkerPosition()).  
        EVENT_NEW_POS = 4,          // Playback head is at a new position (See setPositionUpdatePeriod()).  
        EVENT_BUFFER_END = 5        // Playback head is at the end of the buffer.  
    }; 
enum event_type {
        EVENT_MORE_DATA = 0,        // Request to write more data to PCM buffer.
        EVENT_UNDERRUN = 1,         // PCM buffer underrun occured.
        EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from loop start if loop count was not 0.
        EVENT_MARKER = 3,           // Playback head is at the specified marker position (See setMarkerPosition()).
        EVENT_NEW_POS = 4,          // Playback head is at a new position (See setPositionUpdatePeriod()).
        EVENT_BUFFER_END = 5        // Playback head is at the end of the buffer.
    };

开始播放:

view plaincopy to clipboardprint?
mpAudioTrack->start(); 
mpAudioTrack->start();

停止播放:

view plaincopy to clipboardprint?
mpAudioTrack->stop(); 
mpAudioTrack->stop();

只要简单地调用成员函数start()和stop()即可。

AudioTrack和AudioFlinger的通信机制
通常,AudioTrack和AudioFlinger并不在同一个进程中,它们通过android中的binder机制建立联系。

AudioFlinger是android中的一个service,在android启动时就已经被加载。下面这张图展示了他们两个的关系:

Android Audio System 之一:AudioTrack如何与AudioFlinger交换音频数据_第1张图片

                                                                              图一 AudioTrack和AudioFlinger的关系

我们可以这样理解这张图的含义:

audio_track_cblk_t实现了一个环形FIFO;
AudioTrack是FIFO的数据生产者;
AudioFlinger是FIFO的数据消费者。
建立联系的过程
下面的序列图展示了AudioTrack和AudioFlinger建立联系的过程:

Android Audio System 之一:AudioTrack如何与AudioFlinger交换音频数据_第2张图片

                                                              图二 AudioTrack和AudioFlinger建立联系

解释一下过程:

Framework或者Java层通过JNI,new AudioTrack();
根据StreamType等参数,通过一系列的调用getOutput();
如有必要,AudioFlinger根据StreamType打开不同硬件设备;
AudioFlinger为该输出设备创建混音线程: MixerThread(),并把该线程的id作为getOutput()的返回值返回给AudioTrack;
AudioTrack通过binder机制调用AudioFlinger的createTrack();
AudioFlinger注册该AudioTrack到MixerThread中;
AudioFlinger创建一个用于控制的TrackHandle,并以IAudioTrack这一接口作为createTrack()的返回值;
AudioTrack通过IAudioTrack接口,得到在AudioFlinger中创建的FIFO(audio_track_cblk_t);
AudioTrack创建自己的监控线程:AudioTrackThread;
自此,AudioTrack建立了和AudioFlinger的全部联系工作,接下来,AudioTrack可以:

通过IAudioTrack接口控制该音轨的状态,例如start,stop,pause等等;
通过对FIFO的写入,实现连续的音频播放;
监控线程监控事件的发生,并通过audioCallback回调函数与用户程序进行交互;
FIFO的管理
 audio_track_cblk_t
audio_track_cblk_t这个结构是FIFO实现的关键,该结构是在createTrack的时候,由AudioFlinger申请相应的内存,然后通过IMemory接口返回AudioTrack的,这样AudioTrack和AudioFlinger管理着同一个audio_track_cblk_t,通过它实现了环形FIFO,AudioTrack向FIFO中写入音频数据,AudioFlinger从FIFO中读取音频数据,经Mixer后送给AudioHardware进行播放。

audio_track_cblk_t的主要数据成员:

    user             -- AudioTrack当前的写位置的偏移
    userBase     -- AudioTrack写偏移的基准位置,结合user的值方可确定真实的FIFO地址指针
    server          -- AudioFlinger当前的读位置的偏移
    serverBase  -- AudioFlinger读偏移的基准位置,结合server的值方可确定真实的FIFO地址指针

    frameCount -- FIFO的大小,以音频数据的帧为单位,16bit的音频每帧的大小是2字节

    buffers         -- 指向FIFO的起始地址

    out               -- 音频流的方向,对于AudioTrack,out=1,对于AudioRecord,out=0

audio_track_cblk_t的主要成员函数:

framesAvailable_l()和framesAvailable()用于获取FIFO中可写的空闲空间的大小,只是加锁和不加锁的区别。

view plaincopy to clipboardprint?
uint32_t audio_track_cblk_t::framesAvailable_l()  
{  
    uint32_t u = this->user;  
    uint32_t s = this->server;  
    if (out) {  
        uint32_t limit = (s < loopStart) ? s : loopStart;  
        return limit + frameCount - u;  
    } else {  
        return frameCount + u - s;  
    }  

uint32_t audio_track_cblk_t::framesAvailable_l()
{
    uint32_t u = this->user;
    uint32_t s = this->server;
    if (out) {
        uint32_t limit = (s < loopStart) ? s : loopStart;
        return limit + frameCount - u;
    } else {
        return frameCount + u - s;
    }
}    

framesReady()用于获取FIFO中可读取的空间大小。

view plaincopy to clipboardprint?
uint32_t audio_track_cblk_t::framesReady()  
{  
    uint32_t u = this->user;  
    uint32_t s = this->server;  
    if (out) {  
        if (u < loopEnd) {  
            return u - s;  
        } else {  
            Mutex::Autolock _l(lock);  
            if (loopCount >= 0) {  
                return (loopEnd - loopStart)*loopCount + u - s;  
            } else {  
                return UINT_MAX;  
            }  
        }  
    } else {  
        return s - u;  
    }  

uint32_t audio_track_cblk_t::framesReady()
{
    uint32_t u = this->user;
    uint32_t s = this->server;
    if (out) {
        if (u < loopEnd) {
            return u - s;
        } else {
            Mutex::Autolock _l(lock);
            if (loopCount >= 0) {
                return (loopEnd - loopStart)*loopCount + u - s;
            } else {
                return UINT_MAX;
            }
        }
    } else {
        return s - u;
    }
}
 

我们看看下面的示意图:

               _____________________________________________

               ^                          ^                             ^                           ^

        buffer_start              server(s)                 user(u)                  buffer_end

 很明显,frameReady = u - s,frameAvalible = frameCount - frameReady = frameCount - u + s

 可能有人会问,应为这是一个环形的buffer,一旦user越过了buffer_end以后,应该会发生下面的情况:

                _____________________________________________

               ^                ^             ^                                                     ^

        buffer_start     user(u)     server(s)                                   buffer_end

这时候u在s的前面,用上面的公式计算就会错误,但是android使用了一些技巧,保证了上述公式一直成立。我们先看完下面三个函数的代码再分析:

view plaincopy to clipboardprint?
uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)  
{  
    uint32_t u = this->user;  
    u += frameCount;  
    ......  
    if (u >= userBase + this->frameCount) {  
        userBase += this->frameCount;  
    }  
    this->user = u;  
    ......  
    return u;  

uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
{
    uint32_t u = this->user;
    u += frameCount;
    ......
    if (u >= userBase + this->frameCount) {
        userBase += this->frameCount;
    }
    this->user = u;
    ......
    return u;
}
 

view plaincopy to clipboardprint?
bool audio_track_cblk_t::stepServer(uint32_t frameCount)  
{  
    // the code below simulates lock-with-timeout  
    // we MUST do this to protect the AudioFlinger server  
    // as this lock is shared with the client.  
    status_t err;  
    err = lock.tryLock();  
    if (err == -EBUSY) { // just wait a bit  
        usleep(1000);  
        err = lock.tryLock();  
    }  
    if (err != NO_ERROR) {  
        // probably, the client just died.  
        return false;  
    }  
    uint32_t s = this->server;  
    s += frameCount;  
    // 省略部分代码  
     // ......  
    if (s >= serverBase + this->frameCount) {  
        serverBase += this->frameCount;  
    }  
    this->server = s;  
    cv.signal();  
    lock.unlock();  
    return true;  

bool audio_track_cblk_t::stepServer(uint32_t frameCount)
{
    // the code below simulates lock-with-timeout
    // we MUST do this to protect the AudioFlinger server
    // as this lock is shared with the client.
    status_t err;
    err = lock.tryLock();
    if (err == -EBUSY) { // just wait a bit
        usleep(1000);
        err = lock.tryLock();
    }
    if (err != NO_ERROR) {
        // probably, the client just died.
        return false;
    }
    uint32_t s = this->server;
    s += frameCount;
    // 省略部分代码
     // ......
    if (s >= serverBase + this->frameCount) {
        serverBase += this->frameCount;
    }
    this->server = s;
    cv.signal();
    lock.unlock();
    return true;
}

view plaincopy to clipboardprint?
void* audio_track_cblk_t::buffer(uint32_t offset) const 
{  
    return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;  

void* audio_track_cblk_t::buffer(uint32_t offset) const
{
    return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
}

stepUser()和stepServer的作用是调整当前偏移的位置,可以看到,他们仅仅是把成员变量user或server的值加上需要移动的数量,user和server的值并不考虑FIFO的边界问题,随着数据的不停写入和读出,user和server的值不断增加,只要处理得当,user总是出现在server的后面,因此frameAvalible()和frameReady()中的算法才会一直成立。根据这种算法,user和server的值都可能大于FIFO的大小:framCount,那么,如何确定真正的写指针的位置呢?这里需要用到userBase这一成员变量,在stepUser()中,每当user的值越过(userBase+frameCount),userBase就会增加frameCount,这样,映射到FIFO中的偏移总是可以通过(user-userBase)获得。因此,获得当前FIFO的写地址指针可以通过成员函数buffer()返回:

p = mClbk->buffer(mclbk->user);

在AudioTrack中,封装了两个函数:obtainBuffer()和releaseBuffer()操作FIFO,obtainBuffer()获得当前可写的数量和写指针的位置,releaseBuffer()则在写入数据后被调用,它其实就是简单地调用stepUser()来调整偏移的位置。

IMemory接口
在createTrack的过程中,AudioFlinger会根据传入的frameCount参数,申请一块内存,AudioTrack可以通过IAudioTrack接口的getCblk()函数获得指向该内存块的IMemory接口,然后AudioTrack通过该IMemory接口的pointer()函数获得指向该内存块的指针,这块内存的开始部分就是audio_track_cblk_t结构,紧接着是大小为frameSize的FIFO内存。

IMemory->pointer() ---->|_______________________________________________________

                                     |__audio_track_cblk_t__|_______buffer of FIFO(size==frameCount)____|

看看AudioTrack的createTrack()的代码就明白了:

view plaincopy to clipboardprint?
sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),  
                                                      streamType,  
                                                      sampleRate,  
                                                      format,  
                                                      channelCount,  
                                                      frameCount,  
                                                      ((uint16_t)flags) << 16,  
                                                      sharedBuffer,  
                                                      output,  
                                                      &status);  
    // 得到IMemory接口  
    sp<IMemory> cblk = track->getCblk();                         
    mAudioTrack.clear();  
    mAudioTrack = track;  
    mCblkMemory.clear();  
    mCblkMemory = cblk;  
    // 得到audio_track_cblk_t结构  
    mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());   
    // 该FIFO用于输出      
    mCblk->out = 1;                                              
    // Update buffer size in case it has been limited by AudioFlinger during track creation  
    mFrameCount = mCblk->frameCount;  
    if (sharedBuffer == 0) {  
       // 给FIFO的起始地址赋值  
        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);  
    } else {  
        ..........          
    } 


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/DroidPhone/archive/2010/10/14/5941344.aspx

你可能感兴趣的:(android,server,System,buffer,audio,playback)