1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <string.h>
18 #include <set>
19 
20 #define LOG_TAG "DevicesFactoryHalHidl"
21 //#define LOG_NDEBUG 0
22 
23 #include <android/hidl/manager/1.0/IServiceManager.h>
24 #include <android/hidl/manager/1.0/IServiceNotification.h>
25 #include PATH(android/hardware/audio/FILE_VERSION/IDevice.h)
26 #include <media/audiohal/hidl/HalDeathHandler.h>
27 #include <utils/Log.h>
28 
29 #include "DeviceHalHidl.h"
30 #include "DevicesFactoryHalHidl.h"
31 
32 using ::android::detail::AudioHalVersionInfo;
33 using ::android::hardware::audio::CPP_VERSION::IDevice;
34 using ::android::hardware::audio::CORE_TYPES_CPP_VERSION::Result;
35 using ::android::hardware::Return;
36 using ::android::hardware::Void;
37 using ::android::hidl::manager::V1_0::IServiceManager;
38 using ::android::hidl::manager::V1_0::IServiceNotification;
39 
40 namespace android {
41 
42 class ServiceNotificationListener : public IServiceNotification {
43   public:
ServiceNotificationListener(sp<DevicesFactoryHalHidl> factory)44     explicit ServiceNotificationListener(sp<DevicesFactoryHalHidl> factory)
45             : mFactory(factory) {}
46 
onRegistration(const hidl_string &,const hidl_string & instance_name,bool)47     Return<void> onRegistration(const hidl_string& /*fully_qualified_name*/,
48             const hidl_string& instance_name,
49             bool /*pre_existing*/) override {
50         if (static_cast<std::string>(instance_name) == "default") return Void();
51         sp<DevicesFactoryHalHidl> factory = mFactory.promote();
52         if (!factory) return Void();
53         sp<IDevicesFactory> halFactory = IDevicesFactory::getService(instance_name);
54         if (halFactory) {
55             factory->addDeviceFactory(halFactory, true /*needToNotify*/);
56         }
57         return Void();
58     }
59 
60   private:
61     wp<DevicesFactoryHalHidl> mFactory;
62 };
63 
DevicesFactoryHalHidl(sp<IDevicesFactory> devicesFactory)64 DevicesFactoryHalHidl::DevicesFactoryHalHidl(sp<IDevicesFactory> devicesFactory) {
65     ALOG_ASSERT(devicesFactory != nullptr, "Provided default IDevicesFactory service is NULL");
66     addDeviceFactory(devicesFactory, false /*needToNotify*/);
67 }
68 
onFirstRef()69 void DevicesFactoryHalHidl::onFirstRef() {
70     sp<IServiceManager> sm = IServiceManager::getService();
71     ALOG_ASSERT(sm != nullptr, "Hardware service manager is not running");
72     sp<ServiceNotificationListener> listener = new ServiceNotificationListener(this);
73     Return<bool> result = sm->registerForNotifications(
74             IDevicesFactory::descriptor, "", listener);
75     if (result.isOk()) {
76         ALOGE_IF(!static_cast<bool>(result),
77                 "Hardware service manager refused to register listener");
78     } else {
79         ALOGE("Failed to register for hardware service manager notifications: %s",
80                 result.description().c_str());
81     }
82 }
83 
84 #if MAJOR_VERSION == 2
idFromHal(const char * name,status_t * status)85 static IDevicesFactory::Device idFromHal(const char *name, status_t* status) {
86     *status = OK;
87     if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
88         return IDevicesFactory::Device::PRIMARY;
89     } else if(strcmp(name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
90         return IDevicesFactory::Device::A2DP;
91     } else if(strcmp(name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
92         return IDevicesFactory::Device::USB;
93     } else if(strcmp(name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
94         return IDevicesFactory::Device::R_SUBMIX;
95     } else if(strcmp(name, AUDIO_HARDWARE_MODULE_ID_STUB) == 0) {
96         return IDevicesFactory::Device::STUB;
97     }
98     ALOGE("Invalid device name %s", name);
99     *status = BAD_VALUE;
100     return {};
101 }
102 #elif MAJOR_VERSION >= 4
idFromHal(const char * name,status_t * status)103 static const char* idFromHal(const char *name, status_t* status) {
104     *status = OK;
105     return name;
106 }
107 #endif
108 
getDeviceNames(std::vector<std::string> * names __unused)109 status_t DevicesFactoryHalHidl::getDeviceNames(std::vector<std::string> *names __unused) {
110     return INVALID_OPERATION;
111 }
112 
openDevice(const char * name,sp<DeviceHalInterface> * device)113 status_t DevicesFactoryHalHidl::openDevice(const char *name, sp<DeviceHalInterface> *device) {
114     auto factories = copyDeviceFactories();
115     if (factories.empty()) return NO_INIT;
116     status_t status;
117     auto hidlId = idFromHal(name, &status);
118     if (status != OK) return status;
119     Result retval = Result::NOT_INITIALIZED;
120     for (const auto& factory : factories) {
121         Return<void> ret;
122         if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
123             // In V7.1 it's not possible to cast IDevice back to IPrimaryDevice,
124             // thus openPrimaryDevice must be used.
125 #if MAJOR_VERSION == 7 && MINOR_VERSION == 1
126             ret = factory->openPrimaryDevice_7_1(
127 #else
128             ret = factory->openPrimaryDevice(
129 #endif
130                     [&](Result r,
131                         const sp<::android::hardware::audio::CPP_VERSION::IPrimaryDevice>& result) {
132                         retval = r;
133                         if (retval == Result::OK) {
134                             *device = new DeviceHalHidl(result);
135                         }
136                     });
137         } else {
138 #if MAJOR_VERSION == 7 && MINOR_VERSION == 1
139             ret = factory->openDevice_7_1(
140 #else
141             ret = factory->openDevice(
142 #endif
143                     hidlId,
144                     [&](Result r,
145                         const sp<::android::hardware::audio::CPP_VERSION::IDevice>& result) {
146                         retval = r;
147                         if (retval == Result::OK) {
148                             *device = new DeviceHalHidl(result);
149                         }
150                     });
151         }
152         if (!ret.isOk()) return FAILED_TRANSACTION;
153         switch (retval) {
154             // Device was found and was initialized successfully.
155             case Result::OK: return OK;
156             // Device was found but failed to initalize.
157             case Result::NOT_INITIALIZED: return NO_INIT;
158             // Otherwise continue iterating.
159             default: ;
160         }
161     }
162     ALOGW("The specified device name is not recognized: \"%s\"", name);
163     return BAD_VALUE;
164 }
165 
setCallbackOnce(sp<DevicesFactoryHalCallback> callback)166 status_t DevicesFactoryHalHidl::setCallbackOnce(sp<DevicesFactoryHalCallback> callback) {
167     ALOG_ASSERT(callback != nullptr);
168     bool needToCallCallback = false;
169     {
170         std::lock_guard<std::mutex> lock(mLock);
171         if (mCallback.unsafe_get()) return INVALID_OPERATION;
172         mCallback = callback;
173         if (mHaveUndeliveredNotifications) {
174             needToCallCallback = true;
175             mHaveUndeliveredNotifications = false;
176         }
177     }
178     if (needToCallCallback) {
179         callback->onNewDevicesAvailable();
180     }
181     return NO_ERROR;
182 }
183 
addDeviceFactory(sp<::android::hardware::audio::CPP_VERSION::IDevicesFactory> factory,bool needToNotify)184 void DevicesFactoryHalHidl::addDeviceFactory(
185         sp<::android::hardware::audio::CPP_VERSION::IDevicesFactory> factory, bool needToNotify) {
186     // It is assumed that the DevicesFactoryHalInterface instance is owned
187     // by AudioFlinger and thus have the same lifespan.
188     factory->linkToDeath(HalDeathHandler::getInstance(), 0 /*cookie*/);
189     sp<DevicesFactoryHalCallback> callback;
190     {
191         std::lock_guard<std::mutex> lock(mLock);
192         mDeviceFactories.push_back(factory);
193         if (needToNotify) {
194             callback = mCallback.promote();
195             if (!callback) {
196                 mHaveUndeliveredNotifications = true;
197             }
198         }
199     }
200     if (callback) {
201         callback->onNewDevicesAvailable();
202     }
203 }
204 
205 std::vector<sp<::android::hardware::audio::CPP_VERSION::IDevicesFactory>>
copyDeviceFactories()206         DevicesFactoryHalHidl::copyDeviceFactories() {
207     std::lock_guard<std::mutex> lock(mLock);
208     return mDeviceFactories;
209 }
210 
211 
getHalVersion() const212 AudioHalVersionInfo DevicesFactoryHalHidl::getHalVersion() const {
213     return AudioHalVersionInfo(AudioHalVersionInfo::Type::HIDL, MAJOR_VERSION, MINOR_VERSION);
214 }
215 
getSurroundSoundConfig(media::SurroundSoundConfig * config __unused)216 status_t DevicesFactoryHalHidl::getSurroundSoundConfig(
217         media::SurroundSoundConfig *config __unused) {
218     return INVALID_OPERATION;
219 }
220 
getEngineConfig(media::audio::common::AudioHalEngineConfig * config __unused)221 status_t DevicesFactoryHalHidl::getEngineConfig(
222         media::audio::common::AudioHalEngineConfig *config __unused) {
223     return INVALID_OPERATION;
224 }
225 
226 // Main entry-point to the shared library.
createIDevicesFactoryImpl()227 extern "C" __attribute__((visibility("default"))) void* createIDevicesFactoryImpl() {
228     auto service = hardware::audio::CPP_VERSION::IDevicesFactory::getService();
229     return service ? new DevicesFactoryHalHidl(service) : nullptr;
230 }
231 
232 } // namespace android
233