android audio module a2dp analysis

http://blog.csdn.net/uyiwfn/article/details/8808131

\external\bluetooth\bluedroid\audio_a2dp_hw\audio_a2dp_hw.cpp

编译生成audio.a2dp.default.so,主要实现a2dp做为设备的功能

[cpp]  view plain copy
  1. struct audio_module HAL_MODULE_INFO_SYM = {  
  2.     .common = {  
  3.         .tag = HARDWARE_MODULE_TAG,  
  4.         .version_major = 1,  
  5.         .version_minor = 0,  
  6.         .id = AUDIO_HARDWARE_MODULE_ID,  
  7.         .name = "A2DP Audio HW HAL",  
  8.         .author = "The Android Open Source Project",  
  9.         .methods = &hal_module_methods,  
  10.     },  
  11. };  

\hardware\libhardware_legacy\audio\audio_policy_hal.cpp

编译生成libaudiohw_legacy.so,是audio_policy的HAL层,不同厂商可以有自己的audio_policy。

[cpp]  view plain copy
  1. struct legacy_ap_module HAL_MODULE_INFO_SYM = {  
  2.     module: {  
  3.         common: {  
  4.             tag: HARDWARE_MODULE_TAG,  
  5.             version_major: 1,  
  6.             version_minor: 0,  
  7.             id: AUDIO_POLICY_HARDWARE_MODULE_ID,  
  8.             name: "LEGACY Audio Policy HAL",  
  9.             author: "The Android Open Source Project",  
  10.             methods: &legacy_ap_module_methods,  
  11.             dso : NULL,  
  12.             reserved : {0},  
  13.         },  
  14.     },  
  15. };  

audio_policy.conf

该文件最后放在/system/etc/ 下,其定义了系统的音频设备,其中AUDIO_HARDWARE_MODULE_ID =“a2dp”,AudioPolicyService中的load_audio_interface根据AUDIO_HARDWARE_MODULE_ID来加载对应的audio库。

[html]  view plain copy
  1. audio_hw_modules {  
  2.   primary {  
  3.     outputs {  
  4.       primary {  
  5.         sampling_rates 44100  
  6.         channel_masks AUDIO_CHANNEL_OUT_STEREO  
  7.         formats AUDIO_FORMAT_PCM_16_BIT  
  8.         devices  AUDIO_DEVICE_OUT_EARPIECE|AUDIO_DEVICE_OUT_SPEAKER|AUDIO_DEVICE_OUT_WIRED_HEADSET|AUDIO_DEVICE_OUT_WIRED_HEADPHONE|AUDIO_DEVICE_OUT_ALL_SCO|AUDIO_DEVICE_OUT_AUX_DIGITAL|AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET  
  9.         flags AUDIO_OUTPUT_FLAG_PRIMARY  
  10.       }  
  11.     }  
  12.     inputs {  
  13.       primary {  
  14.         sampling_rates 8000|11025|16000|22050|32000|44100|48000  
  15.         channel_masks AUDIO_CHANNEL_IN_MONO|AUDIO_CHANNEL_IN_STEREO  
  16.         formats AUDIO_FORMAT_PCM_16_BIT  
  17.         devices AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET|AUDIO_DEVICE_IN_WIRED_HEADSET  
  18.       }  
  19.     }  
  20.   }  
  21.   a2dp {  
  22.     outputs {  
  23.       a2dp {  
  24.         sampling_rates 44100  
  25.         channel_masks AUDIO_CHANNEL_OUT_STEREO  
  26.         formats AUDIO_FORMAT_PCM_16_BIT  
  27.         devices AUDIO_DEVICE_OUT_ALL_A2DP  
  28.       }  
  29.     }  
  30.   }    
  31. }  

 

下图是一张a2dp模块初始化的流程,其主要是加载了a2dp的audio库,并audio policy中注册了一个a2dp音频设备:

 

 

BluetoothManagerService绑定IBluetooth过程

[cpp]  view plain copy
  1. public void getNameAndAddress() {  
  2.     if (DBG) {  
  3.         Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +  
  4.               " mBinding = " + mBinding);  
  5.     }  
  6.     Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);  
  7.     mHandler.sendMessage(msg);  
  8. }  

BluetoothHandler::handleMessage

[cpp]  view plain copy
  1. case MESSAGE_GET_NAME_AND_ADDRESS: {  
  2.     if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");  
  3.     synchronized(mConnection) {  
  4.         //Start bind request  
  5.         if ((mBluetooth == null) && (!mBinding)) {  
  6.             if (DBG) Log.d(TAG, "Binding to service to get name and address");  
  7.             mConnection.setGetNameAddressOnly(true);  
  8.             //Start bind timeout and bind  
  9.             Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);  
  10.             mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);  
  11.             Intent i = new Intent(IBluetooth.class.getName());  
  12.             if (!mContext.bindService(i, mConnection,  
  13.                   Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {  
  14.                 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);  
  15.                 Log.e(TAG, "fail to bind to: " + IBluetooth.class.getName());  
  16.             } else {  
  17.                 mBinding = true;  
  18.             }  
  19.         }  

在这里调用了bindService来绑定服务,成功后调用mConnection的onServiceConnected

[cpp]  view plain copy
  1. private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();  
[cpp]  view plain copy
  1. private class BluetoothServiceConnection implements ServiceConnection {  
  2.   
  3.         private boolean mGetNameAddressOnly;  
  4.   
  5.         public void setGetNameAddressOnly(boolean getOnly) {  
  6.             mGetNameAddressOnly = getOnly;  
  7.         }  
  8.   
  9.         public boolean isGetNameAddressOnly() {  
  10.             return mGetNameAddressOnly;  
  11.         }  
  12.   
  13.         public void onServiceConnected(ComponentName className, IBinder service) {  
  14.             if (DBG) Log.d(TAG, "BluetoothServiceConnection: connected to AdapterService className:"+className+" service:",service);  
  15.             Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);  
  16.             msg.obj = service;  
  17.             mHandler.sendMessage(msg);  
  18.         }  
  19.   
  20.         public void onServiceDisconnected(ComponentName className) {  
  21.             // Called if we unexpected disconnected.  
  22.             if (DBG) Log.d(TAG, "BluetoothServiceConnection: disconnected from AdapterService");  
  23.             Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);  
  24.             mHandler.sendMessage(msg);  
  25.         }  
  26.       


onServiceConnected调用完成后再次到

BluetoothHandler::handleMessage,处理打开BT的消息


 

以下是BluetoothAdapter的构造过程,向RemoteCallbackList中注册了一个IBluetoothManagerCallback,用来与BluetoothManagerService通信。

E:\BOX_4.2\frameworks\base\core\java\android\bluetooth\BluetoothAdapter.cpp

[cpp]  view plain copy
  1. BluetoothAdapter(IBluetoothManager managerService) {  
  2.   
  3.     if (managerService == null) {  
  4.         throw new IllegalArgumentException("bluetooth manager service is null");  
  5.     }  
  6.     try {  
  7.         mService = managerService.registerAdapter(mManagerCallback);  
  8.     } catch (RemoteException e) {Log.e(TAG, "", e);}  
  9.     mManagerService = managerService;  
  10.     mServiceRecordHandler = null;  
  11.     if (DBG) Log.d(TAG, "BluetoothAdapter" +  ": mService ="+mService+  ": mManagerService ="+mManagerService+  
  12.         ": mManagerCallback ="+mManagerCallback);  
  13. }  
[cpp]  view plain copy
  1. <p>    final private IBluetoothManagerCallback mManagerCallback =  
  2.         new IBluetoothManagerCallback.Stub() {  
  3.             public void onBluetoothServiceUp(IBluetooth bluetoothService) {  
  4.                 if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);  
  5.                 synchronized (mManagerCallback) {  
  6.                     mService = bluetoothService;  
  7.                     for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){  
  8.                         try {  
  9.                             if (cb != null) {  
  10.                                 cb.onBluetoothServiceUp(bluetoothService);  
  11.                             } else {  
  12.                                 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");  
  13.                             }  
  14.                         } catch (Exception e)  { Log.e(TAG,"",e);}  
  15.                     }  
  16.                 }  
  17.             }</p><p>            public void onBluetoothServiceDown() {  
  18.                 if (VDBG) Log.d(TAG, "onBluetoothServiceDown: " + mService);  
  19.                 synchronized (mManagerCallback) {  
  20.                     mService = null;  
  21.                     for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){  
  22.                         try {  
  23.                             if (cb != null) {  
  24.                                 cb.onBluetoothServiceDown();  
  25.                             } else {  
  26.                                 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");  
  27.                             }  
  28.                         } catch (Exception e)  { Log.e(TAG,"",e);}  
  29.                     }  
  30.                 }  
  31.             }  
  32.     }</p>  

\frameworks\base\services\java\com\android\server\BluetoothManagerService.cpp

[cpp]  view plain copy
  1. public IBluetooth registerAdapter(IBluetoothManagerCallback callback){  
  2.     Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);  
  3.     msg.obj = callback;  
  4.     mHandler.sendMessage(msg);  
  5.     if (DBG) Log.d(TAG,"registerAdapter start");  
  6.     synchronized(mConnection) {  
  7.         if (DBG) Log.d(TAG,"registerAdapter end");  
  8.         return mBluetooth;  
  9.     }  
  10. }  

BluetoothHandler-->handleMessage-->

[cpp]  view plain copy
  1. case MESSAGE_REGISTER_ADAPTER:  
  2. {  
  3.     IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;  
  4.     boolean added = mCallbacks.register(callback);  
  5. }  


最后注册到RemoteCallbackList中。

 

BT使能

BluetoothManagerService::

  

[cpp]  view plain copy
  1. enable-->sendEnableMsg-->mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,quietMode ? 1 : 0, 0));  
  2.   
  3. uetoothHandler  
  4.   
  5.  handleMessage-->handleEnable(true)-->mBluetooth.registerCallback(mBluetoothCallback);  
[cpp]  view plain copy
  1. sendBluetoothServiceUpCallback();  
[cpp]  view plain copy
  1.                                 mBluetooth.enable()  
  2.   
  3. ate final IBluetoothCallback mBluetoothCallback =  new IBluetoothCallback.Stub() {  
  4. @Override  
  5. public void onBluetoothStateChange(int prevState, int newState) throws RemoteException  {  
  6.     Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);  
  7.     mHandler.sendMessage(msg);  
  8. }  


mBluetoothCallback将消息交给BluetoothHandler的sendMessage来处理。

[cpp]  view plain copy
  1. private void sendBluetoothServiceUpCallback() {  
  2.      if (!mConnection.isGetNameAddressOnly()) {  
  3.           
  4.         int n = mCallbacks.beginBroadcast();  
  5.           for (int i=0; i <n;i++) {  
  6.             try {  
  7.                 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);  
  8.             }  catch (RemoteException e) {  
  9.               }  
  10.         }  
  11.         mCallbacks.finishBroadcast();  
  12.     }  
  13. }  



        通知BluetoothAdapter,Adapter service is up

[cpp]  view plain copy
  1. private void sendBluetoothServiceUpCallback() {  
  2.     if (!mConnection.isGetNameAddressOnly()) {  
  3.           
  4.         int n = mCallbacks.beginBroadcast();  
  5.            for (int i=0; i <n;i++) {  
  6.             try {  
  7.                 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);  
  8.             }  catch (RemoteException e) {  
  9.                 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);  
  10.             }  
  11.         }  
  12.         mCallbacks.finishBroadcast();  
  13.     }  
  14. }  

mCallbacks.getBroadcastItem(i)用来获取对对应IBluetoothManagerCallback,这是是指BluetoothAdapter::mManagerCallback,因此调用的是BluetoothAdapter的onBluetoothServiceUp:

[cpp]  view plain copy
  1. public void onBluetoothServiceUp(IBluetooth bluetoothService) {  
  2.     if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);  
  3.     synchronized (mManagerCallback) {  
  4.         mService = bluetoothService;  
  5.         for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){  
  6.             try {  
  7.                 if (cb != null) {  
  8.                     cb.onBluetoothServiceUp(bluetoothService);  
  9.                 } else {  
  10.                     Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");  
  11.                 }  
  12.             } catch (Exception e)  { Log.e(TAG,"",e);}  
  13.         }  
  14.     }  
  15. }  


到此为止,还没有对BT硬件的操作,现在回到BluetoothManagerService的handleEnable,下一步调用了mBluetooth.enable(),最终是调用IBluetooth的enable。

 

以上我们只看到了IBluetooth的客户端代码,服务端在哪儿呢?看AdapterService的定义。

[cpp]  view plain copy
  1. public class AdapterService extends Service{  
  2.     static {  
  3.         classInitNative();  
  4.     }  
  5.     private static class AdapterServiceBinder extends IBluetooth.Stub  
  6.   
  7. }  

classInitNative被声明成Native方法,直接调用com/android/bluetooth/btservice/AdapterService的classInitNative

\packages\apps\Bluetooth\jni\com_android_bluetooth_btservice_AdapterService.cpp

[cpp]  view plain copy
  1. <p>static void classInitNative(JNIEnv* env, jclass clazz) {  
  2.     int err;  
  3.     hw_module_t* module;</p><p>    jclass jniCallbackClass =  
  4.         env->FindClass("com/android/bluetooth/btservice/JniCallbacks");  
  5.     sJniCallbacksField = env->GetFieldID(clazz, "mJniCallbacks",  
  6.         "Lcom/android/bluetooth/btservice/JniCallbacks;");</p><p>    method_stateChangeCallback = env->GetMethodID(jniCallbackClass, "stateChangeCallback""(I)V");</p><p>    method_adapterPropertyChangedCallback = env->GetMethodID(jniCallbackClass,  
  7.                                                              "adapterPropertyChangedCallback",  
  8.                                                              "([I[[B)V");  
  9.     method_discoveryStateChangeCallback = env->GetMethodID(jniCallbackClass,  
  10.                                                            "discoveryStateChangeCallback""(I)V");</p><p>    method_devicePropertyChangedCallback = env->GetMethodID(jniCallbackClass,  
  11.                                                             "devicePropertyChangedCallback",  
  12.                                                             "([B[I[[B)V");  
  13.     method_deviceFoundCallback = env->GetMethodID(jniCallbackClass, "deviceFoundCallback""([B)V");  
  14.     method_pinRequestCallback = env->GetMethodID(jniCallbackClass, "pinRequestCallback",  
  15.                                                  "([B[BI)V");  
  16.     method_sspRequestCallback = env->GetMethodID(jniCallbackClass, "sspRequestCallback",  
  17.                                                  "([B[BIII)V");</p><p>    method_bondStateChangeCallback = env->GetMethodID(jniCallbackClass,  
  18.                                                      "bondStateChangeCallback""(I[BI)V");</p><p>    method_aclStateChangeCallback = env->GetMethodID(jniCallbackClass,  
  19.                                                     "aclStateChangeCallback""(I[BI)V");  
  20.     char value[PROPERTY_VALUE_MAX];  
  21.     property_get("bluetooth.mock_stack", value, "");</p><p>    const char *id = (strcmp(value, "1")? BT_STACK_MODULE_ID : BT_STACK_TEST_MODULE_ID);</p><p>    err = hw_get_module(id, (hw_module_t const**)&module);</p><p>    if (err == 0) {  
  22.         hw_device_t* abstraction;  
  23.         err = module->methods->open(module, id, &abstraction);  
  24.         if (err == 0) {  
  25.             bluetooth_module_t* btStack = (bluetooth_module_t *)abstraction;  
  26.             sBluetoothInterface = btStack->get_bluetooth_interface();  
  27.         } else {  
  28.            ALOGE("Error while opening Bluetooth library");  
  29.         }  
  30.     } else {  
  31.         ALOGE("No Bluetooth Library found");  
  32.     }  
  33. }</p>这里主要是得到了sBluetoothInterface  

AdapterService继承至Service,有一个内部类继承IBluetooth.Stub,这便是Bluetooth的服务端了。因此在AdapterService中必定有Bluetooth的服务端的具体实现。

[cpp]  view plain copy
  1.   

AdapterServiceBinder::enable

[cpp]  view plain copy
  1. public boolean enable() {  
  2.     if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&  
  3.         (!Utils.checkCaller())) {  
  4.         Log.w(TAG,"enable(): not allowed for non-active user and non system user");  
  5.         return false;  
  6.   
  7.   
  8.     AdapterService service = getService();  
  9.     if (service == null) return false;  
  10.     return service.enable();  
  11. }  

 

再看一下AdapterService的onCreate,这里调用了AdapterServiceBinder的构造

    public void onCreate() {
        super.onCreate();
        mBinder = new AdapterServiceBinder(this);
        mAdapterProperties = new AdapterProperties(this);
        mAdapterStateMachine =  AdapterState.make(this, mAdapterProperties);
        mJniCallbacks =  new JniCallbacks(mAdapterStateMachine, mAdapterProperties);
        initNative();
        mNativeAvailable=true;
        mCallbacks = new RemoteCallbackList<IBluetoothCallback>();
        //Load the name and address
        getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDADDR);
        getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDNAME);

    }

 

service.enable()的的service是AdapterService,下一步是AdapterService的enable

[cpp]  view plain copy
  1. public synchronized boolean enable(boolean quietMode) {  
  2.     enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,  
  3.             "Need BLUETOOTH ADMIN permission");  
  4.     if (DBG)debugLog("Enable called with quiet mode status =  " + mQuietmode);  
  5.     mQuietmode  = quietMode;  
  6.     Message m =  
  7.             mAdapterStateMachine.obtainMessage(AdapterState.USER_TURN_ON);  
  8.     mAdapterStateMachine.sendMessage(m);  
  9.     return true;  
  10. }  


 123456789101234567891012345678910

[cpp]  view plain copy
  1. mAdapterStateMachine.sendMessage(m)  
[cpp]  view plain copy
  1. 状态转换:  

OffState::USER_TURN_ON  ---> processMessage::STARTED ---> processMessage::ENABLED_READY

在processMessage::STARTED 状态时调用mAdapterService.enableNative--》调用JNI方法

[html]  view plain copy
  1. static jboolean enableNative(JNIEnv* env, jobject obj) {  
  2.   
  3.     jboolean result = JNI_FALSE;  
  4.     if (!sBluetoothInterface) return result;  
  5.   
  6.     int ret = sBluetoothInterface->enable();  
  7.     result = (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;  
  8.     return result;  
  9. }  


\external\bluetooth\bluedroid\btif\src\bluetooth.c
[html]  view plain copy
  1. struct hw_module_t HAL_MODULE_INFO_SYM = {  
  2.     .tag = HARDWARE_MODULE_TAG,  
  3.     .version_major = 1,  
  4.     .version_minor = 0,  
  5.     .id = BT_HARDWARE_MODULE_ID,  
  6.     .name = "Bluetooth Stack",  
  7.     .author = "The Android Open Source Project",  
  8.     .methods = &bt_stack_module_methods  
  9. };  

[html]  view plain copy
  1. static int enable( void )  
  2. {  
  3.     /* sanity check */  
  4.     if (interface_ready() == FALSE)  
  5.         return BT_STATUS_NOT_READY;  
  6.   
  7.     return btif_enable_bluetooth();  
  8. }  

E:\BOX_4.2\external\bluetooth\bluedroid\btif\src\btif_core.c

[html]  view plain copy
  1. bt_status_t btif_enable_bluetooth(void)  
  2. {  
  3.     BTIF_TRACE_DEBUG0("BTIF ENABLE BLUETOOTH");  
  4.   
  5.     if (btif_core_state != BTIF_CORE_STATE_DISABLED)  
  6.     {  
  7.         ALOGD("not disabled\n");  
  8.         return BT_STATUS_DONE;  
  9.     }  
  10.   
  11.     btif_core_state = BTIF_CORE_STATE_ENABLING;  
  12.   
  13.     /* Create the GKI tasks and run them */  
  14.     bte_main_enable(btif_local_bd_addr.address);  
  15.   
  16.     return BT_STATUS_SUCCESS;  
  17. }  
\external\bluetooth\bluedroid\main\bte_main.c
bte_main_enable-->bt_hc_if->set_power

bt_hc_if是HCI层接口

\external\bluetooth\bluedroid\hci\src\bt_hci_bdroid.c

[html]  view plain copy
  1. static const bt_hc_interface_t bluetoothHCLibInterface = {  
  2.     sizeof(bt_hc_interface_t),  
  3.     init,  
  4.     set_power,  
  5.     lpm,  
  6.     preload,  
  7.     postload,  
  8.     transmit_buf,  
  9.     set_rxflow,  
  10.     logging,  
  11.     cleanup  
  12. };  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值