1. 程式人生 > >Android AudioFlinger載入HAL層流程

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。