4.0音頻系統HAL初探

轉載自:

昨天(2011-11-15)發佈了Android4.0的源碼,今天download下來,開始挺進4.0時代。簡單看了一下,發現音頻系統方面與2.3的有較多地方不同,下面逐一描述。


一、代碼模塊位置


1、AudioFlinger


  1. frameworks/base/services/audioflinger/  
  2. +-- Android.mk  
  3. +-- AudioBufferProvider.h  
  4. +-- AudioFlinger.cpp  
  5. +-- AudioFlinger.h  
  6. +-- AudioMixer.cpp  
  7. +-- AudioMixer.h  
  8. +-- AudioPolicyService.cpp  
  9. +-- AudioPolicyService.h  
  10. +-- AudioResampler.cpp  
  11. +-- AudioResamplerCubic.cpp  
  12. +-- AudioResamplerCubic.h  
  13. +-- AudioResampler.h  
  14. +-- AudioResamplerSinc.cpp  
  15. +-- AudioResamplerSinc.h  
AudioFlinger相關代碼,好像這部分與2.3相差不大,至少接口是兼容的。值得注意的是:2.3位於這裏的還有AudioHardwareGeneric、AudioHardwareInterface、A2dpAudioInterface等一系列接口代碼,現在都移除了。實際上,這些接口變更爲legacy(有另外更好的實現方式,但也兼容之前的方法),取而代之的是要實現hardware/libhardware/include/hardware/audio.h提供的接口,這是一個較大的變化。

兩種Audio Hardware HAL接口定義:
1/ legacy:hardware/libhardware_legacy/include/hardware_legacy/AudioHardwareInterface.h
2/ current:hardware/libhardware/include/hardware/audio.h

2、audio_hw


  1. hardware/libhardware_legacy/audio/  
  2. +-- A2dpAudioInterface.cpp  
  3. +-- A2dpAudioInterface.h  
  4. +-- Android.mk  
  5. +-- AudioDumpInterface.cpp  
  6. +-- AudioDumpInterface.h  
  7. +-- AudioHardwareGeneric.cpp  
  8. +-- AudioHardwareGeneric.h  
  9. +-- AudioHardwareInterface.cpp  
  10. +-- AudioHardwareStub.cpp  
  11. +-- AudioHardwareStub.h  
  12. +-- audio_hw_hal.cpp  
  13. +-- AudioPolicyCompatClient.cpp  
  14. +-- AudioPolicyCompatClient.h  
  15. +-- audio_policy_hal.cpp  
  16. +-- AudioPolicyManagerBase.cpp  
  17. +-- AudioPolicyManagerDefault.cpp  
  18. +-- AudioPolicyManagerDefault.h  
上面提及的AudioHardwareGeneric、AudioHardwareInterface、A2dpAudioInterface等都放到libhardware_legacy裏。
事實上legacy也要封裝成current中的audio.h,確切的說需要一個聯繫legacy interface和not legacy interface的中間層,這裏的audio_hw_hal.cpp就充當這樣的一個角色了。因此,我們其實也可以把2.3之前的alsa_sound這一套東西也搬過來。

  1. hardware/libhardware/modules/audio/  
  2. +-- Android.mk  
  3. +-- audio_hw.c  
  4. +-- audio_policy.c  
這是一個stub(類似於2.3中的AudioHardwareStub),大多數函數只是簡單的返回一個值,並沒有實際操作,只是保證Android能得到一個audio hardware hal實例,從而啓動運行,當然聲音沒有輸出到外設的。在底層音頻驅動或audio hardware hal還沒有實現好的情況下,可以使用這個stub device,先讓Android跑起來。

  1. device/samsung/tuna/audio/  
  2. +-- Android.mk  
  3. +-- audio_hw.c  
  4. +-- ril_interface.c  
  5. +-- ril_interface.h  
這是Samsung Tuna的音頻設備抽象層,很有參考價值,計劃以後就在它的基礎上進行移植。它調用tinyalsa的接口,可見這個方案的底層音頻驅動是alsa。

3、tinyalsa


  1. external/tinyalsa/  
  2. +-- Android.mk  
  3. +-- include  
  4. |   +-- tinyalsa  
  5. |       +-- asoundlib.h  
  6. +-- mixer.c      ##類alsa-lib的control,作用音頻部件開關、音量調節等  
  7. +-- pcm.c        ##類alsa-lib的pcm,作用音頻pcm數據回放錄製  
  8. +-- README  
  9. +-- tinycap.c    ##類alsa_arecord  
  10. +-- tinymix.c    ##類alsa_amixer  
  11. +-- tinyplay.c   ##類alsa_aplay  
在2.3時代,Android還隱晦把它放在android2.3.1-gingerbread/device/samsung/crespo/libaudio,現在終於把alsa-lib一腳踢開,小三變正室了,正名tinyalsa。
這其實是歷史的必然了,alsa-lib太過複雜繁瑣了,我看得也很不爽;更重要的商業上面的考慮,必須移除被GNU GPL授權證所約束的部份,alsa-lib並不是個例。

注意:上面的hardware/libhardware_legacy/audio/、hardware/libhardware/modules/audio/、device/samsung/tuna/audio/是同層的。之一是legacy audio,用於兼容2.2時代的alsa_sound;之二是stub audio接口;之三是Samsung Tuna的音頻抽象層實現。調用層次:AudioFlinger -> audio_hw -> tinyalsa。

二、Audio Hardware HAL加載


1、AudioFlinger


  1. //加載audio hardware hal  
  2. static int load_audio_interface(const char *if_name, const hw_module_t **mod,  
  3.                                 audio_hw_device_t **dev)  
  4. {  
  5.     int rc;  
  6.       
  7.     //根據classid和if_name找到指定的動態庫並加載,這裏加載的是音頻動態庫,如libaudio.primary.tuna.so  
  8.     rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);  
  9.     if (rc)  
  10.         goto out;  
  11.   
  12.     //加載好的動態庫模塊必有個open方法,調用open方法打開音頻設備模塊  
  13.     rc = audio_hw_device_open(*mod, dev);  
  14.     LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",  
  15.             AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));  
  16.     if (rc)  
  17.         goto out;  
  18.   
  19.     return 0;  
  20.   
  21. out:  
  22.     *mod = NULL;  
  23.     *dev = NULL;  
  24.     return rc;  
  25. }  
  26.   
  27. //音頻設備接口,hw_get_module_by_class需要根據這些字符串找到相關的音頻模塊庫  
  28. static const char *audio_interfaces[] = {  
  29.     "primary"//主音頻設備,一般爲本機codec  
  30.     "a2dp",    //a2dp設備,藍牙高保真音頻  
  31.     "usb",     //usb-audio設備,這個東東我2.3就考慮要實現了,現在終於支持了  
  32. };  
  33. #define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))  
  34.   
  35. // ----------------------------------------------------------------------------  
  36.   
  37. AudioFlinger::AudioFlinger()  
  38.     : BnAudioFlinger(),  
  39.         mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),  
  40.         mBtNrecIsOff(false)  
  41. {  
  42. }  
  43.   
  44. void AudioFlinger::onFirstRef()  
  45. {  
  46.     int rc = 0;  
  47.   
  48.     Mutex::Autolock _l(mLock);  
  49.   
  50.     /* TODO: move all this work into an Init() function */  
  51.     mHardwareStatus = AUDIO_HW_IDLE;  
  52.   
  53.     //打開audio_interfaces數組定義的所有音頻設備  
  54.     for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {  
  55.         const hw_module_t *mod;  
  56.         audio_hw_device_t *dev;  
  57.   
  58.         rc = load_audio_interface(audio_interfaces[i], &mod, &dev);  
  59.         if (rc)  
  60.             continue;  
  61.   
  62.         LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],  
  63.              mod->name, mod->id);  
  64.         mAudioHwDevs.push(dev); //mAudioHwDevs是一個Vector,存儲已打開的audio hw devices  
  65.   
  66.         if (!mPrimaryHardwareDev) {  
  67.             mPrimaryHardwareDev = dev;  
  68.             LOGI("Using '%s' (%s.%s) as the primary audio interface",  
  69.                  mod->name, mod->id, audio_interfaces[i]);  
  70.         }  
  71.     }  
  72.   
  73.     mHardwareStatus = AUDIO_HW_INIT;  
  74.   
  75.     if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {  
  76.         LOGE("Primary audio interface not found");  
  77.         return;  
  78.     }  
  79.   
  80.     //對audio hw devices進行一些初始化,如mode、master volume的設置  
  81.     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {  
  82.         audio_hw_device_t *dev = mAudioHwDevs[i];  
  83.   
  84.         mHardwareStatus = AUDIO_HW_INIT;  
  85.         rc = dev->init_check(dev);  
  86.         if (rc == 0) {  
  87.             AutoMutex lock(mHardwareLock);  
  88.   
  89.             mMode = AUDIO_MODE_NORMAL;  
  90.             mHardwareStatus = AUDIO_HW_SET_MODE;  
  91.             dev->set_mode(dev, mMode);  
  92.             mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;  
  93.             dev->set_master_volume(dev, 1.0f);  
  94.             mHardwareStatus = AUDIO_HW_IDLE;  
  95.         }  
  96.     }  
  97. }  

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

留意AudioFlinger的構造函數只有簡單的私有變量的初始化操作了,把音頻設備初始化放到onFirstRef(),Android終於改進了這一點,好的設計根本不應該把可能會失敗的操作放到構造函數中。onFirstRef是RefBase類的一個虛函數,在構造sp的時候就會被調用。因此,在構造sp<AudioFlinger>的時候就會觸發onFirstRef方法,從而完成音頻設備模塊初始化。

2、hw_get_module_by_class


我們接下來看看hw_get_module_by_class,實現在hardware/libhardware/ hardware.c中,它作用加載指定名字的模塊庫(.so文件),這個應該是用於加載所有硬件設備相關的庫文件,並不只是音頻設備。
  1. int hw_get_module_by_class(const char *class_id, const char *inst,  
  2.                            const struct hw_module_t **module)  
  3. {  
  4.     int status;  
  5.     int i;  
  6.     const struct hw_module_t *hmi = NULL;  
  7.     char prop[PATH_MAX];  
  8.     char path[PATH_MAX];  
  9.     char name[PATH_MAX];  
  10.   
  11.     if (inst)  
  12.         snprintf(name, PATH_MAX, "%s.%s", class_id, inst);  
  13.     else  
  14.         strlcpy(name, class_id, PATH_MAX);  
  15.           
  16.     //這裏我們以音頻庫爲例,AudioFlinger調用到這個函數時,  
  17.     //class_id=AUDIO_HARDWARE_MODULE_ID="audio",inst="primary"(或"a2dp"或"usb")  
  18.     //那麼此時name="audio.primary"  
  19.   
  20.     /* 
  21.      * Here we rely on the fact that calling dlopen multiple times on 
  22.      * the same .so will simply increment a refcount (and not load 
  23.      * a new copy of the library). 
  24.      * We also assume that dlopen() is thread-safe. 
  25.      */  
  26.   
  27.     /* Loop through the configuration variants looking for a module */  
  28.     for (i=0 ; i<HAL_VARIANT_KEYS_COUNT+1 ; i++) {  
  29.         if (i < HAL_VARIANT_KEYS_COUNT) {  
  30.               //通過property_get找到廠家標記如"ro.product.board=tuna",這時prop="tuna"  
  31.             if (property_get(variant_keys[i], prop, NULL) == 0) {  
  32.                 continue;  
  33.             }  
  34.             snprintf(path, sizeof(path), "%s/%s.%s.so",  
  35.                      HAL_LIBRARY_PATH2, name, prop); //#define HAL_LIBRARY_PATH2 "/vendor/lib/hw"  
  36.             if (access(path, R_OK) == 0) break;  
  37.   
  38.             snprintf(path, sizeof(path), "%s/%s.%s.so",  
  39.                      HAL_LIBRARY_PATH1, name, prop); //#define HAL_LIBRARY_PATH1 "/system/lib/hw"  
  40.             if (access(path, R_OK) == 0) break;  
  41.         } else {  
  42.             snprintf(path, sizeof(path), "%s/%s.default.so"//如沒有指定的庫文件,則加載default.so,即stub-device  
  43.                      HAL_LIBRARY_PATH1, name);  
  44.             if (access(path, R_OK) == 0) break;  
  45.         }  
  46.     }  
  47.     //到這裏,完成一個模塊庫的完整路徑名稱,如path="/system/lib/hw/audio.primary.tuna.so"  
  48.     //如何生成audio.primary.tuna.so?請看相關的Android.mk文件,其中有定義LOCAL_MODULE := audio.primary.tuna  
  49.   
  50.     status = -ENOENT;  
  51.     if (i < HAL_VARIANT_KEYS_COUNT+1) {  
  52.         /* load the module, if this fails, we're doomed, and we should not try 
  53.          * to load a different variant. */  
  54.         status = load(class_id, path, module); //加載模塊庫  
  55.     }  
  56.   
  57.     return status;  
  58. }  

load()函數不詳細分析了,它通過dlopen加載庫文件,然後dlsym找到hal_module_info的首地址。我們先看看hal_module_info的定義:
  1. /** 
  2.  * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM 
  3.  * and the fields of this data structure must begin with hw_module_t 
  4.  * followed by module specific information. 
  5.  */  
  6. typedef struct hw_module_t {  
  7.     /** tag must be initialized to HARDWARE_MODULE_TAG */  
  8.     uint32_t tag;  
  9.   
  10.     /** major version number for the module */  
  11.     uint16_t version_major;  
  12.   
  13.     /** minor version number of the module */  
  14.     uint16_t version_minor;  
  15.   
  16.     /** Identifier of module */  
  17.     const char *id;  
  18.   
  19.     /** Name of this module */  
  20.     const char *name;  
  21.   
  22.     /** Author/owner/implementor of the module */  
  23.     const char *author;  
  24.   
  25.     /** Modules methods */  
  26.     struct hw_module_methods_t* methods;  
  27.   
  28.     /** module's dso */  
  29.     void* dso;  
  30.   
  31.     /** padding to 128 bytes, reserved for future use */  
  32.     uint32_t reserved[32-7];  
  33.   
  34. } hw_module_t;  
  35.   
  36. typedef struct hw_module_methods_t {  
  37.     /** Open a specific device */  
  38.     int (*open)(const struct hw_module_t* module, const char* id,  
  39.             struct hw_device_t** device);  
  40.   
  41. } hw_module_methods_t;  
這個結構體很重要,註釋很詳細。dlsym拿到這個結構體的首地址後,就可以調用Modules methods進行設備模塊的初始化了。設備模塊中,都應該按照這個格式初始化好這個結構體,否則dlsym找不到它,也就無法調用Modules methods進行初始化了。

例如,在audio_hw.c中,它是這樣定義的:
  1. static struct hw_module_methods_t hal_module_methods = {  
  2.     .open = adev_open,  
  3. };  
  4.   
  5. struct audio_module HAL_MODULE_INFO_SYM = {  
  6.     .common = {  
  7.         .tag = HARDWARE_MODULE_TAG,  
  8.         .version_major = 1,  
  9.         .version_minor = 0,  
  10.         .id = AUDIO_HARDWARE_MODULE_ID,  
  11.         .name = "Tuna audio HW HAL",  
  12.         .author = "The Android Open Source Project",  
  13.         .methods = &hal_module_methods,  
  14.     },  
  15. };  

3、audio_hw


好了,經過一番周折,又dlopen又dlsym的,終於進入我們的audio_hw。這部分沒什麼好說的,按照hardware/libhardware/include/hardware/audio.h定義的接口實現就行了。這些接口全扔到一個結構體裏面的,這樣做的好處是:不必用大量的dlsym來獲取各個接口函數的地址,只需找到這個結構體即可,從易用性和可擴充性來說,都是首選方式。

接口定義如下:
  1. struct audio_hw_device {  
  2.     struct hw_device_t common;  
  3.   
  4.     /** 
  5.      * used by audio flinger to enumerate what devices are supported by 
  6.      * each audio_hw_device implementation. 
  7.      * 
  8.      * Return value is a bitmask of 1 or more values of audio_devices_t 
  9.      */  
  10.     uint32_t (*get_supported_devices)(const struct audio_hw_device *dev);  
  11.   
  12.     /** 
  13.      * check to see if the audio hardware interface has been initialized. 
  14.      * returns 0 on success, -ENODEV on failure. 
  15.      */  
  16.     int (*init_check)(const struct audio_hw_device *dev);  
  17.   
  18.     /** set the audio volume of a voice call. Range is between 0.0 and 1.0 */  
  19.     int (*set_voice_volume)(struct audio_hw_device *dev, float volume);  
  20.   
  21.     /** 
  22.      * set the audio volume for all audio activities other than voice call. 
  23.      * Range between 0.0 and 1.0. If any value other than 0 is returned, 
  24.      * the software mixer will emulate this capability. 
  25.      */  
  26.     int (*set_master_volume)(struct audio_hw_device *dev, float volume);  
  27.   
  28.     /** 
  29.      * setMode is called when the audio mode changes. AUDIO_MODE_NORMAL mode 
  30.      * is for standard audio playback, AUDIO_MODE_RINGTONE when a ringtone is 
  31.      * playing, and AUDIO_MODE_IN_CALL when a call is in progress. 
  32.      */  
  33.     int (*set_mode)(struct audio_hw_device *dev, int mode);  
  34.   
  35.     /* mic mute */  
  36.     int (*set_mic_mute)(struct audio_hw_device *dev, bool state);  
  37.     int (*get_mic_mute)(const struct audio_hw_device *dev, bool *state);  
  38.   
  39.     /* set/get global audio parameters */  
  40.     int (*set_parameters)(struct audio_hw_device *dev, const char *kv_pairs);  
  41.   
  42.     /* 
  43.      * Returns a pointer to a heap allocated string. The caller is responsible 
  44.      * for freeing the memory for it. 
  45.      */  
  46.     char * (*get_parameters)(const struct audio_hw_device *dev,  
  47.                              const char *keys);  
  48.   
  49.     /* Returns audio input buffer size according to parameters passed or 
  50.      * 0 if one of the parameters is not supported 
  51.      */  
  52.     size_t (*get_input_buffer_size)(const struct audio_hw_device *dev,  
  53.                                     uint32_t sample_rate, int format,  
  54.                                     int channel_count);  
  55.   
  56.     /** This method creates and opens the audio hardware output stream */  
  57.     int (*open_output_stream)(struct audio_hw_device *dev, uint32_t devices,  
  58.                               int *format, uint32_t *channels,  
  59.                               uint32_t *sample_rate,  
  60.                               struct audio_stream_out **out);  
  61.   
  62.     void (*close_output_stream)(struct audio_hw_device *dev,  
  63.                                 struct audio_stream_out* out);  
  64.   
  65.     /** This method creates and opens the audio hardware input stream */  
  66.     int (*open_input_stream)(struct audio_hw_device *dev, uint32_t devices,  
  67.                              int *format, uint32_t *channels,  
  68.                              uint32_t *sample_rate,  
  69.                              audio_in_acoustics_t acoustics,  
  70.                              struct audio_stream_in **stream_in);  
  71.   
  72.     void (*close_input_stream)(struct audio_hw_device *dev,  
  73.                                struct audio_stream_in *in);  
  74.   
  75.     /** This method dumps the state of the audio hardware */  
  76.     int (*dump)(const struct audio_hw_device *dev, int fd);  
  77. };  
  78. typedef struct audio_hw_device audio_hw_device_t;  

注:這是比較標準的C接口設計方法了,但是個人感覺還是用C++比較好,直觀易讀。2.3之前都是用C++實現這些接口設計的,到了4.0,不知道爲何採納用C?不會理由是做底層的不懂C++吧?!

三、Audio Hardware HAL的legacy實現


之前提到兩種Audio Hardware HAL接口定義:
1/ legacy:hardware/libhardware_legacy/include/hardware_legacy/AudioHardwareInterface.h
2/ current:hardware/libhardware/include/hardware/audio.h
前者是2.3及之前的音頻設備接口定義,後者是4.0的接口定義。

爲了兼容以前的設計,4.0實現一箇中間層:hardware/libhardware_legacy/audio/audio_hw_hal.cpp,結構與其他的audio_hw.c大同小異,差別在於open方法:
  1. static int legacy_adev_open(const hw_module_t* module, const char* name,  
  2.                             hw_device_t** device)  
  3. {  
  4.     ......  
  5.   
  6.     ladev->hwif = createAudioHardware();  
  7.     if (!ladev->hwif) {  
  8.         ret = -EIO;  
  9.         goto err_create_audio_hw;  
  10.     }  
  11.   
  12.     ......  
  13. }  
看到那個熟悉的createAudioHardware()沒有?這是以前我提到的Vendor Specific Audio接口,然後新的接口再調用ladev->hwif的函數就是了。
因此老一套的alsa-lib、alsa-utils和alsa_sound也可以照搬過來,這裏的文件被編譯成靜態庫的,因此你需要修改alsa_sound裏面的Android.mk文件,鏈接這個靜態庫。還有alsa_sound的命名空間原來是“android”,現在需要改成“android_audio_legacy”。

四、a2dp Audio HAL的實現


4.0的a2dp audio hal放到bluez裏實現了,我找了好一會才找到:
external/Bluetooth/bluez/audio/android_audio_hw.c
大致與上面提到的audio_hw.c類似,因爲都是基於audio.h定義的接口來實現的。
如果需要編譯這個庫,須在BoardConfig.mk裏定義:
BOARD_HAVE_BLUETOOTH := true

開始還提到現在支持3種audio設備了,分別是primary、a2dp和usb。目前剩下usb audio hal我沒有找到,不知是否需要自己去實現?其實alsa-driver都支持大部分的usb-audio設備了,因此上層也可調用tinyalsa的接口,就像samsung tuna的audio_hw.c那樣。

五、音質改進???


可使用audio echo cancel和更好的resampler(SRC)???

--to be continued…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章