Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

藍牙耳機播放流程源碼剖析:從 AudioFlinger 到 A2DP

編輯:關於 Android 程式設計

近來在關注藍牙耳機的相關議題,於是簡單梳理了一下音訊資料從解碼到送出的整條流程。資料完成解碼之後,會在 AudioFlinger 中寫入對應的輸出設備。本文重點放在 AudioFlinger、AudioPolicyManager,以及 external/bluetooth/bluez/audio 底下負責底層操作的 android_audio_hw.c 與 liba2dp.c。

一、設備連接的判斷

在 AudioPolicyManager 裡,設備的連接狀態由 setDeviceConnectionState 負責處理,其中會判斷是否為 A2DP 裝置並轉交給 handleA2dpConnection:

status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
        AudioSystem::device_connection_state state,
        const char *device_address)
{
#ifdef WITH_A2DP
    // handle A2DP device connection
    if (AudioSystem::isA2dpDevice(device)) {
        status_t status = handleA2dpConnection(device, device_address);// 執行藍牙連接
        if (status != NO_ERROR) {
            mAvailableOutputDevices &= ~device;
            return status;
        }
    } else
#endif
}

二、開啟 A2DP 輸出

接著在 handleA2dpConnection 中實際開啟 A2DP 輸出通道:

status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
        const char *device_address)
{
    ...............
    mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
                                                 &outputDesc->mSamplingRate,
                                                 &outputDesc->mFormat,
                                                 &outputDesc->mChannels,
                                                 &outputDesc->mLatency,
                                                 outputDesc->mFlags);
    if (mA2dpOutput) {
        // add A2DP output descriptor
        addOutput(mA2dpOutput, outputDesc);

        // TODO: configure audio effect output stage here

        // set initial stream volume for A2DP device
        applyStreamVolumes(mA2dpOutput, device);
        if (a2dpUsedForSonification()) {
            mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
        }
        if (mDuplicatedOutput != 0 ||
            !a2dpUsedForSonification()) {
            // 若 A2DP 與複製輸出皆已開啟,則把裝置位址送給 A2DP 硬體介面
            AudioParameter param;
            param.add(String8("a2dp_sink_address"), String8(device_address));
            mpClientInterface->setParameters(mA2dpOutput, param.toString());
            mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN;

            if (a2dpUsedForSonification()) {
                // add duplicated output descriptor
                AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
                dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
                dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
                dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
                dupOutputDesc->mFormat = outputDesc->mFormat;
                dupOutputDesc->mChannels = outputDesc->mChannels;
                dupOutputDesc->mLatency = outputDesc->mLatency;
                addOutput(mDuplicatedOutput, dupOutputDesc);
                applyStreamVolumes(mDuplicatedOutput, device);
            }
        } else {
        .........
}

這裡有兩種情況值得區分。若只是單純用藍牙播放音樂,那麼 mDuplicatedOutput 與 a2dpUsedForSonification() 都為 0,僅執行 addOutput(mA2dpOutput, outputDesc),流程與一般喇叭、麥克風類似。

但如果是藍牙與喇叭、麥克風需要同時發聲(例如來電、簡訊、鬧鐘提示音),就會走 mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput) 這條路。要留意參數順序:第一個是藍牙的 mA2dpOutput,第二個才是 mHardwareOutput,也就是喇叭或麥克風等其他輸出設備。

三、openDuplicateOutput 的實作

我們接著看 openDuplicateOutput 在 AudioFlinger.cpp 中的定義:

int AudioFlinger::openDuplicateOutput(int output1, int output2)
{
    Mutex::Autolock _l(mLock);
    MixerThread *thread1 = checkMixerThread_l(output1);
    MixerThread *thread2 = checkMixerThread_l(output2);

    if (thread1 == NULL || thread2 == NULL) {
        LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
        return 0;
    }

    int id = nextUniqueId();
    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
    thread->addOutputTrack(thread2);
    mPlaybackThreads.add(id, thread);
    // notify client processes of the new output creation
    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
    return id;
}

這個函式會啟動兩個播放線程,一個對應藍牙、另一個對應 mHardwareOutput,藉此實現兩者同時播放,例如來電鈴聲、簡訊提示音、鬧鐘等情境。

四、音訊介面的加載

先暫停一下,我們來看看 4.0 版本支援的三種音訊介面:

static const char *audio_interfaces[] = {
    "primary",
    "a2dp",
    "usb",
};

分別是:primary(對應 codec,也就是我們常用的喇叭、麥克風)、a2dp(藍牙)以及 usb 介面。在 onFirstRef 中會逐一走訪並加載這些介面:

void AudioFlinger::onFirstRef()
{
    int rc = 0;
    Mutex::Autolock _l(mLock);
    /* TODO: move all this work into an Init() function */
    mHardwareStatus = AUDIO_HW_IDLE;

    for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
        const hw_module_t *mod;
        audio_hw_device_t *dev;

        rc = load_audio_interface(audio_interfaces[i], &mod, &dev);// 加載介面的 .so 檔
        if (rc)
            continue;

        LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
             mod->name, mod->id);
        mAudioHwDevs.push(dev);
    .........
}

而在 openOutput 中,則會先找出可用的音訊硬體裝置,再呼叫介面裡的 open_output_stream 取得各項參數:

int AudioFlinger::openOutput(uint32_t *pDevices,
                             uint32_t *pSamplingRate,
                             uint32_t *pFormat,
                             uint32_t *pChannels,
                             uint32_t *pLatencyMs,
                             uint32_t flags){
    ......
    outHwDev = findSuitableHwDev_l(*pDevices);// 取得有效的音訊介面設備
    if (outHwDev == NULL)
        return 0;
    // 取得介面 .so 裡的參數資訊
    status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
                                          &channels, &samplingRate, &outStream);
    LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
         outStream, samplingRate, format, channels, status);

    mHardwareStatus = AUDIO_HW_IDLE;
    if (outStream != NULL) {
        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);// 建立該設備的輸出
    ........
}

其中的 outHwDev->open_output_stream 正是藍牙音訊模組所提供的介面函式。

五、藍牙音訊模組的初始化

再看 android_audio_hw.c 中的 adev_open:

static int adev_open(const hw_module_t* module, const char* name,
                     hw_device_t** device)
{
    struct adev_a2dp *adev;
    int ret;

    if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
        return -EINVAL;

    adev = calloc(1, sizeof(struct adev_a2dp));
    if (!adev)
        return -ENOMEM;

    adev->bt_enabled = true;
    adev->suspended = false;
    pthread_mutex_init(&adev->lock, NULL);
    adev->output = NULL;

    adev->device.common.tag = HARDWARE_DEVICE_TAG;
    adev->device.common.version = 0;
    adev->device.common.module = (struct hw_module_t *) module;
    adev->device.common.close = adev_close;

    adev->device.get_supported_devices = adev_get_supported_devices;
    adev->device.init_check = adev_init_check;
    adev->device.set_voice_volume = adev_set_voice_volume;
    adev->device.set_master_volume = adev_set_master_volume;
    adev->device.set_mode = adev_set_mode;
    adev->device.set_mic_mute = adev_set_mic_mute;
    adev->device.get_mic_mute = adev_get_mic_mute;
    adev->device.set_parameters = adev_set_parameters;
    adev->device.get_parameters = adev_get_parameters;
    adev->device.get_input_buffer_size = adev_get_input_buffer_size;
    adev->device.open_output_stream = adev_open_output_stream;
    adev->device.close_output_stream = adev_close_output_stream;
    adev->device.open_input_stream = adev_open_input_stream;
    adev->device.close_input_stream = adev_close_input_stream;
    adev->device.dump = adev_dump;

    *device = &adev->device.common;
    return 0;

err_str_parms_create:
    free(adev);
    return ret;
}

AudioFlinger 所需的各項參數,正是透過這裡完成註冊。之後藍牙音訊模組就會進行一連串的 init、config、start、stop 等狀態操作,其中自然也包括藍牙資料的讀寫。整體看下來,這條從策略管理到硬體抽象層的呼叫鏈,就是藍牙耳機能夠順利出聲的關鍵所在。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved