AudioFlinger::MixerThread::threadLoop

1、进程的创建

int AudioFlinger::openOutput(uint32_t *pDevices,

                                uint32_t *pSamplingRate,

                                uint32_t *pFormat,

                                uint32_t *pChannels,

                                uint32_t *pLatencyMs,

                                uint32_t flags)

{
if (output != 0) {

        thread = new MixerThread(this, output, ++mNextThreadId);

        }
}

2、进程的启动

void AudioFlinger::PlaybackThread::onFirstRef()

{

    const size_t SIZE = 256;

    char buffer[SIZE];

 

    snprintf(buffer, SIZE, "Playback Thread %p", this);

    run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);

}

3、进程的运行

bool AudioFlinger::MixerThread::threadLoop()
{
    Vector< sp<Track> > tracksToRemove;
    uint32_t mixerStatus = MIXER_IDLE;
    nsecs_t standbyTime = systemTime();
    size_t mixBufferSize = mFrameCount * mFrameSize;
    // FIXME: Relaxed timing because of a certain device that can't meet latency
    // Should be reduced to 2x after the vendor fixes the driver issue
    nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
    nsecs_t lastWarning = 0;
    bool longStandbyExit = false;
    uint32_t activeSleepTime = activeSleepTimeUs();//当有活跃音轨时需要sleep的时间
    uint32_t idleSleepTime = idleSleepTimeUs();//当mixer处于idle状态,没有活跃音轨时需要sleep的时间
    uint32_t sleepTime = idleSleepTime;//真正需要sleep时候的时间,初始化为idle状态的时间
    Vector< sp<EffectChain> > effectChains;

    while (!exitPending())//exitPending是每个进程的一个开关标志,创建该进程是初始化为false,所以这里while一直条件为真,进程一直运行
    {
        processConfigEvents();//处理广播消息事件

	//初始化mixerStatus, 该变量有三种状态:idle enabled ready 
        mixerStatus = MIXER_IDLE;
        { // scope for mLock

            Mutex::Autolock _l(mLock);
		//如果有新参数,设置相应的变量值
		//新参数包括:采样率、格式、通道数、帧数、路由情况
		//相应的变量值包括:周期大小、缓存大小等
            if (checkForNewParameters_l()) {
                mixBufferSize = mFrameCount * mFrameSize;
                // FIXME: Relaxed timing because of a certain device that can't meet latency
                // Should be reduced to 2x after the vendor fixes the driver issue
                maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
                activeSleepTime = activeSleepTimeUs();
                idleSleepTime = idleSleepTimeUs();
            }
		//找出活跃音轨数组,活跃音轨个数是硬件退出standby的一个条件
            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;

            // put audio hardware into standby after short delay
            if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
                        mSuspended) {
           //两种情况需要硬件进入standby
           //第一:没有活跃音轨而且standbyTime  过期
           //第二:需要Suspend
                if (!mStandby) {//状态为standby
                    LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
                    mOutput->standby();
                    mStandby = true;
                    mBytesWritten = 0;
                }
                //没有活跃音轨并且没有广播消息
                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
                    // we're about to wait, flush the binder command buffer
                    IPCThreadState::self()->flushCommands();

                    if (exitPending()) break;

                    // wait until we have something to do...
                    LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
                    mWaitWorkCV.wait(mLock);//等待广播消息,包括配置参数、活跃音轨添加等消息
                    LOGV("MixerThread %p TID %d waking up\n", this, gettid());

                    if (mMasterMute == false) {
                        char value[PROPERTY_VALUE_MAX];
                        property_get("ro.audio.silent", value, "0");
                        if (atoi(value)) {
                            LOGD("Silence is golden");
                            setMasterMute(true);
                        }
                    }

                    standbyTime = systemTime() + kStandbyTimeInNsecs;
                    sleepTime = idleSleepTime;
                    continue;
                }
            }
            //为音轨混音做准备,返回值作为mixerStatus
            mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);

            // prevent any changes in effect chain list and in each effect chain
            // during mixing and effect process as the audio buffers could be deleted
            // or modified if an effect is created or deleted
            lockEffectChains_l(effectChains);
       }
        //只有当音轨准备就绪,才能进入到混音处理函数process
        if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
            // mix buffers...
            mAudioMixer->process();
            sleepTime = 0;//sleepTime设置为零表示有数据需要写入到硬件层的缓冲中
            standbyTime = systemTime() + kStandbyTimeInNsecs;
            //TODO: delay standby when effects have a tail
        } else {
            // If no tracks are ready, sleep once for the duration of an output
            // buffer size, then write 0s to the output
            if (sleepTime == 0) {//如果音轨还未准备好,但是有数据需要传输,说明需要播放,就sleep一个周期的时间
                if (mixerStatus == MIXER_TRACKS_ENABLED) {
                    sleepTime = activeSleepTime;//这个是硬件延时周期的一半时间,(mOutput->latency() * 1000) / 2;
                } else {
                    sleepTime = idleSleepTime;//这个是半个buffer传输时间,1024帧的44100采样率就是11.7ms
                }
            } else if (mBytesWritten != 0 ||
                       (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
                memset (mMixBuffer, 0, mixBufferSize);
                sleepTime = 0;
                LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
            }
            // TODO add standby time extension fct of effect tail
        }

        if (mSuspended) {
            sleepTime = suspendSleepTimeUs();
        }
        // sleepTime == 0 means we must write to audio hardware
        if (sleepTime == 0) {
             for (size_t i = 0; i < effectChains.size(); i ++) {
                 effectChains[i]->process_l();
             }
             // enable changes in effect chain
             unlockEffectChains(effectChains);

            mLastWriteTime = systemTime();
            mInWrite = true;
            mBytesWritten += mixBufferSize;

            int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);//这里是实际在向硬件抽象层写数据,返回写了多少byte数据
            if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
            mNumWrites++;
            mInWrite = false;
            nsecs_t now = systemTime();
            nsecs_t delta = now - mLastWriteTime;//写数据花了多少时间
            if (delta > maxPeriod) {//写的太慢!maxPeriod是按FramCount和SampleRate算出来的,和硬件延时有关,即I2S播放完DMAbuffer数据需要的时间
                mNumDelayedWrites++;
                if ((now - lastWarning) > kWarningThrottle) {//超过警告时间上限,不能忍受,容易导致断音,必须输出log告知开发者
                    LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
                            ns2ms(delta), mNumDelayedWrites, this);
                    lastWarning = now;
                }
                if (mStandby) {
                    longStandbyExit = true;
                }
            }
            mStandby = false;
        } else {//没有数据需要传输,休眠了
            // enable changes in effect chain
            unlockEffectChains(effectChains);
            usleep(sleepTime);
        }

        // finally let go of all our tracks, without the lock held
        // since we can't guarantee the destructors won't acquire that
        // same lock.
        tracksToRemove.clear();

        // Effect chains will be actually deleted here if they were removed from
        // mEffectChains list during mixing or effects processing
        effectChains.clear();
    }

    if (!mStandby) {
        mOutput->standby();
    }

    LOGV("MixerThread %p exiting", this);
    return false;
}


你可能感兴趣的:(thread,vector,buffer,audio,output,playback)