Android AudioFlinger加載HAL層流程

一、前提

Audio HAL層最終以.so的方式爲Android所用,那這個.so的庫如何被AudioFlinger所使用?

二、Audio Hardware HAL加載

(1)AudioFlinger

AudioFlinger加載HAL層:

static int load_audio_interface(const char *if_name, const hw_module_t **mod,  
                                audio_hw_device_t **dev)  
{  
    int rc;  

    /* 這裏加載的是音頻動態庫,如audio.primary.msm8916.so,如何加載會獨立體現 */
    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);  
    if (rc)  
        goto out;  

    //加載好的動態庫模塊必有個open方法,調用open方法打開音頻設備模塊  
    rc = audio_hw_device_open(*mod, dev);  
    LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",  
            AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));  
    if (rc)  
        goto out;  

    return 0;  

out:  
    *mod = NULL;  
    *dev = NULL;  
    return rc;  
}  

audio_interface:

/* hw_get_module_by_class需要根據這些字符串找到相關的音頻模塊庫 */
static const char *audio_interfaces[] = {  
    "primary",              //指本機中的codec  
    "a2dp",                 //a2dp設備,藍牙高保真音頻  
    "usb",                  //usb-audio設備 
};  

AudioFlinger::onFirstRef:

void AudioFlinger::onFirstRef()  
{  
    int rc = 0;  

    Mutex::Autolock _l(mLock);  

    /* TODO: move all this work into an Init() function */  
    mHardwareStatus = AUDIO_HW_IDLE;  

    //打開audio_interfaces數組定義的所有音頻設備  
    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);  
        if (rc)  
            continue;  

        LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],  
             mod->name, mod->id);  
        mAudioHwDevs.push(dev); //mAudioHwDevs是一個Vector,存儲已打開的audio hw devices  

        if (!mPrimaryHardwareDev) {  
            mPrimaryHardwareDev = dev;  
            LOGI("Using '%s' (%s.%s) as the primary audio interface",  
                 mod->name, mod->id, audio_interfaces[i]);  
        }  
    }  

    mHardwareStatus = AUDIO_HW_INIT;  

    if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {  
        LOGE("Primary audio interface not found");  
        return;  
    }  

    //對audio hw devices進行一些初始化,如mode、master volume的設置  
    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {  
        audio_hw_device_t *dev = mAudioHwDevs[i];  

        mHardwareStatus = AUDIO_HW_INIT;  
        rc = dev->init_check(dev);  
        if (rc == 0) {  
            AutoMutex lock(mHardwareLock);  

            mMode = AUDIO_MODE_NORMAL;  
            mHardwareStatus = AUDIO_HW_SET_MODE;  
            dev->set_mode(dev, mMode);  
            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;  
            dev->set_master_volume(dev, 1.0f);  
            mHardwareStatus = AUDIO_HW_IDLE;  
        }  
    }  
} 

主要是通過hw_get_module_by_class()找到模塊接口名字if_name相匹配的模塊庫,加載之後audio_hw_device_open()調用模塊的open方法,完成音頻設備模塊的初始化。

hw_get_module_by_class:

hw_get_module_by_class實現在hardware/libhardware/ hardware.c中,它作用加載指定名字的模塊庫(.so文件)。

int hw_get_module_by_class(const char *class_id, const char *inst,  
                           const struct hw_module_t **module)  
{  
    int status;  
    int i;  
    const struct hw_module_t *hmi = NULL;  
    char prop[PATH_MAX];  
    char path[PATH_MAX];  
    char name[PATH_MAX];  

    if (inst)  
        snprintf(name, PATH_MAX, "%s.%s", class_id, inst);  
    else  
        strlcpy(name, class_id, PATH_MAX);  

    //這裏我們以音頻庫爲例,AudioFlinger調用到這個函數時,  
    //class_id=AUDIO_HARDWARE_MODULE_ID="audio",inst="primary"(或"a2dp"或"usb")  
    //那麼此時name="audio.primary"  

    /* 
     * Here we rely on the fact that calling dlopen multiple times on 
     * the same .so will simply increment a refcount (and not load 
     * a new copy of the library). 
     * We also assume that dlopen() is thread-safe. 
     */  

    /* Loop through the configuration variants looking for a module */  
    for (i=0 ; i<HAL_VARIANT_KEYS_COUNT+1 ; i++) {  
        if (i < HAL_VARIANT_KEYS_COUNT) {  
            /* 通過property_get找到廠家標記如"ro.product.board=msm8916",這時prop="msm8916" */
            if (property_get(variant_keys[i], prop, NULL) == 0) {  
                continue;  
            }  
            /* #define HAL_LIBRARY_PATH2 "/vendor/lib/hw" */
            snprintf(path, sizeof(path), "%s/%s.%s.so",  
                     HAL_LIBRARY_PATH2, name, prop);  
            if (access(path, R_OK) == 0) break;  

            /* #define HAL_LIBRARY_PATH1 "/system/lib/hw" */
            snprintf(path, sizeof(path), "%s/%s.%s.so",  
                     HAL_LIBRARY_PATH1, name, prop);   
            if (access(path, R_OK) == 0) break;  
        } else {  
            /* 如沒有指定的庫文件,則加載default.so */
            snprintf(path, sizeof(path), "%s/%s.default.so",  
                     HAL_LIBRARY_PATH1, name);  
            if (access(path, R_OK) == 0) break;  
        }  
    }  
    /** 到這裏,完成一個模塊庫的完整路徑名稱,如path="/system/lib/hw/audio.primary.msm8916.so"  */

    status = -ENOENT;  
    if (i < HAL_VARIANT_KEYS_COUNT+1) {  
        /* load the module, if this fails, we're doomed, and we should not try 
         * to load a different variant. */  
         //加載模塊庫:見下面
        status = load(class_id, path, module);   
    }  

    return status;  
} 

load(class_id, path, module):

static int load(const char *id,
        const char *path,
        const struct hw_module_t **pHmi)
{
    int status;
    void *handle;
    struct hw_module_t *hmi;

    /*
     * load the symbols resolving undefined symbols before
     * dlopen returns. Since RTLD_GLOBAL is not or'd in with
     * RTLD_NOW the external symbols will not be global
     */
    handle = dlopen(path, RTLD_NOW);
    if (handle == NULL) {
        char const *err_str = dlerror();
        LOGE("load: module=%s\n%s", path, err_str?err_str:"unknown");
        status = -EINVAL;
        goto done;
    }

    /* Get the address of the struct hal_module_info. */
    const char *sym = HAL_MODULE_INFO_SYM_AS_STR;
    hmi = (struct hw_module_t *)dlsym(handle, sym);
        if (hmi == NULL) {
        LOGE("load: couldn't find symbol %s", sym);
        status = -EINVAL;
        goto done;
    }

    /* Check that the id matches */
    if (strcmp(id, hmi->id) != 0) {
        LOGE("load: id=%s != hmi->id=%s", id, hmi->id);
        status = -EINVAL;
        goto done;
    }

    hmi->dso = handle;

    /* success */
    status = 0;

    done:
    if (status != 0) {
        hmi = NULL;
        if (handle != NULL) {
            dlclose(handle);
            handle = NULL;
        }
    } else {
        LOGV("loaded HAL id=%s path=%s hmi=%p handle=%p",
                id, path, *pHmi, handle);
    }

    *pHmi = hmi;

    return status;
}

在打開的.so(audio.primary.msm8916.so)中查找HMI符號的地址,並保存在hmi中。至此.so中的hw_module_t已經被成功獲取。從而可以根據它獲取HAL層相關接口。

  1. HAL通過hw_get_module函數獲取hw_module_t
  2. HAL通過hw_module_t->methods->open獲取hw_device_t指針,並在此open函數中初始化audio_hw_device_t結構中的函數。
  3. 三個重要的數據結構:
    a) struct hw_device_t: 表示硬件設備,存儲了各種硬件設備的公共屬性和方法
    b)struct hw_module_t: 可用hw_get_module進行加載的module
    c)struct hw_module_methods_t: 用於定義操作設備的方法,其中只定義了一個打開設備的方法open.

hw_module_t定義:

/** 
 * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM 
 * and the fields of this data structure must begin with hw_module_t 
 * followed by module specific information. 
 */  
typedef struct hw_module_t {  
    /** tag must be initialized to HARDWARE_MODULE_TAG */  
    uint32_t tag;  

    /** major version number for the module */  
    uint16_t version_major;  

    /** minor version number of the module */  
    uint16_t version_minor;  

    /** Identifier of module */  
    const char *id;  

    /** Name of this module */  
    const char *name;  

    /** Author/owner/implementor of the module */  
    const char *author;  

    /** Modules methods */  
    struct hw_module_methods_t* methods;  

    /** module's dso */  
    void* dso;  

    /** padding to 128 bytes, reserved for future use */  
    uint32_t reserved[32-7];  

} hw_module_t;  

typedef struct hw_module_methods_t {  
    /** Open a specific device */  
    int (*open)(const struct hw_module_t* module, const char* id,  
            struct hw_device_t** device);  

} hw_module_methods_t;  

在load(…)中dlsym拿到這個結構體的首地址後,就可以調用Modules methods進行設備模塊的初始化了。設備模塊中,都應該按照這個格式初始化好這個結構體,否則dlsym找不到它,也就無法調用Modules methods進行初始化了。

audio_hw.c中hw_module_methods_t 的實例化:

static struct hw_module_methods_t hal_module_methods = {  
    .open = adev_open,  
};  

struct audio_module HAL_MODULE_INFO_SYM = {  
    .common = {  
        .tag = HARDWARE_MODULE_TAG,  
        .version_major = 1,  
        .version_minor = 0,  
        .id = AUDIO_HARDWARE_MODULE_ID,  
        .name = "Tuna audio HW HAL",  
        .author = "The Android Open Source Project",  
        .methods = &hal_module_methods,  
    },  
};  

audio_module 是我們Audio HAL必須要實現的。

audio_hw_device 接口
接口按照hardware/libhardware/include/hardware/audio.h定義的接口實現就行了。這些接口全扔到一個結構體裏面的,這樣做的好處是:不必用大量的dlsym來獲取各個接口函數的地址,只需找到這個結構體即可,從易用性和可擴充性來說,都是首選方式。

audio_hw_device 接口如下:

struct audio_hw_device {  
    struct hw_device_t common;  

    /** 
     * used by audio flinger to enumerate what devices are supported by 
     * each audio_hw_device implementation. 
     * 
     * Return value is a bitmask of 1 or more values of audio_devices_t 
     */  
    uint32_t (*get_supported_devices)(const struct audio_hw_device *dev);  

    /** 
     * check to see if the audio hardware interface has been initialized. 
     * returns 0 on success, -ENODEV on failure. 
     */  
    int (*init_check)(const struct audio_hw_device *dev);  

    /** set the audio volume of a voice call. Range is between 0.0 and 1.0 */  
    int (*set_voice_volume)(struct audio_hw_device *dev, float volume);  

    /** 
     * set the audio volume for all audio activities other than voice call. 
     * Range between 0.0 and 1.0. If any value other than 0 is returned, 
     * the software mixer will emulate this capability. 
     */  
    int (*set_master_volume)(struct audio_hw_device *dev, float volume);  

    /** 
     * setMode is called when the audio mode changes. AUDIO_MODE_NORMAL mode 
     * is for standard audio playback, AUDIO_MODE_RINGTONE when a ringtone is 
     * playing, and AUDIO_MODE_IN_CALL when a call is in progress. 
     */  
    int (*set_mode)(struct audio_hw_device *dev, int mode);  

    /* mic mute */  
    int (*set_mic_mute)(struct audio_hw_device *dev, bool state);  
    int (*get_mic_mute)(const struct audio_hw_device *dev, bool *state);  

    /* set/get global audio parameters */  
    int (*set_parameters)(struct audio_hw_device *dev, const char *kv_pairs);  

    /* 
     * Returns a pointer to a heap allocated string. The caller is responsible 
     * for freeing the memory for it. 
     */  
    char * (*get_parameters)(const struct audio_hw_device *dev,  
                             const char *keys);  

    /* Returns audio input buffer size according to parameters passed or 
     * 0 if one of the parameters is not supported 
     */  
    size_t (*get_input_buffer_size)(const struct audio_hw_device *dev,  
                                    uint32_t sample_rate, int format,  
                                    int channel_count);  

    /** This method creates and opens the audio hardware output stream */  
    int (*open_output_stream)(struct audio_hw_device *dev, uint32_t devices,  
                              int *format, uint32_t *channels,  
                              uint32_t *sample_rate,  
                              struct audio_stream_out **out);  

    void (*close_output_stream)(struct audio_hw_device *dev,  
                                struct audio_stream_out* out);  

    /** This method creates and opens the audio hardware input stream */  
    int (*open_input_stream)(struct audio_hw_device *dev, uint32_t devices,  
                             int *format, uint32_t *channels,  
                             uint32_t *sample_rate,  
                             audio_in_acoustics_t acoustics,  
                             struct audio_stream_in **stream_in);  

    void (*close_input_stream)(struct audio_hw_device *dev,  
                               struct audio_stream_in *in);  

    /** This method dumps the state of the audio hardware */  
    int (*dump)(const struct audio_hw_device *dev, int fd);  
};  
typedef struct audio_hw_device audio_hw_device_t;  

在HAL層adev_open初始化中要對audio_hw_device 進行賦值初始化,HAL層的重頭戲其實就是對這些函數進行實例化。

HAL層之後就會調用Tinyalsa,接着就是Audio Driver了。
總體順序:AudioFlinger->Audio HAL->Tinyalsa->Audio Driver。

發佈了33 篇原創文章 · 獲贊 18 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章