• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 <algorithm>
18 #include <set>
19 
20 #define LOG_TAG "AHAL_Module"
21 #include <aidl/android/media/audio/common/AudioInputFlags.h>
22 #include <aidl/android/media/audio/common/AudioOutputFlags.h>
23 #include <android-base/logging.h>
24 #include <android/binder_ibinder_platform.h>
25 #include <error/expected_utils.h>
26 
27 #include "core-impl/Configuration.h"
28 #include "core-impl/Module.h"
29 #include "core-impl/ModuleBluetooth.h"
30 #include "core-impl/ModulePrimary.h"
31 #include "core-impl/ModuleRemoteSubmix.h"
32 #include "core-impl/ModuleStub.h"
33 #include "core-impl/ModuleUsb.h"
34 #include "core-impl/SoundDose.h"
35 #include "core-impl/utils.h"
36 
37 using aidl::android::hardware::audio::common::frameCountFromDurationMs;
38 using aidl::android::hardware::audio::common::getFrameSizeInBytes;
39 using aidl::android::hardware::audio::common::hasMmapFlag;
40 using aidl::android::hardware::audio::common::isBitPositionFlagSet;
41 using aidl::android::hardware::audio::common::isValidAudioMode;
42 using aidl::android::hardware::audio::common::SinkMetadata;
43 using aidl::android::hardware::audio::common::SourceMetadata;
44 using aidl::android::hardware::audio::core::sounddose::ISoundDose;
45 using aidl::android::media::audio::common::AudioChannelLayout;
46 using aidl::android::media::audio::common::AudioDevice;
47 using aidl::android::media::audio::common::AudioDeviceType;
48 using aidl::android::media::audio::common::AudioFormatDescription;
49 using aidl::android::media::audio::common::AudioFormatType;
50 using aidl::android::media::audio::common::AudioGainConfig;
51 using aidl::android::media::audio::common::AudioInputFlags;
52 using aidl::android::media::audio::common::AudioIoFlags;
53 using aidl::android::media::audio::common::AudioMMapPolicy;
54 using aidl::android::media::audio::common::AudioMMapPolicyInfo;
55 using aidl::android::media::audio::common::AudioMMapPolicyType;
56 using aidl::android::media::audio::common::AudioMode;
57 using aidl::android::media::audio::common::AudioOffloadInfo;
58 using aidl::android::media::audio::common::AudioOutputFlags;
59 using aidl::android::media::audio::common::AudioPort;
60 using aidl::android::media::audio::common::AudioPortConfig;
61 using aidl::android::media::audio::common::AudioPortExt;
62 using aidl::android::media::audio::common::AudioProfile;
63 using aidl::android::media::audio::common::Boolean;
64 using aidl::android::media::audio::common::Int;
65 using aidl::android::media::audio::common::MicrophoneInfo;
66 using aidl::android::media::audio::common::PcmType;
67 
68 namespace aidl::android::hardware::audio::core {
69 
70 namespace {
71 
hasDynamicChannelMasks(const std::vector<AudioChannelLayout> & channelMasks)72 inline bool hasDynamicChannelMasks(const std::vector<AudioChannelLayout>& channelMasks) {
73     return channelMasks.empty() ||
74            std::all_of(channelMasks.begin(), channelMasks.end(),
75                        [](const auto& channelMask) { return channelMask == AudioChannelLayout{}; });
76 }
77 
hasDynamicFormat(const AudioFormatDescription & format)78 inline bool hasDynamicFormat(const AudioFormatDescription& format) {
79     return format == AudioFormatDescription{};
80 }
81 
hasDynamicSampleRates(const std::vector<int32_t> & sampleRates)82 inline bool hasDynamicSampleRates(const std::vector<int32_t>& sampleRates) {
83     return sampleRates.empty() ||
84            std::all_of(sampleRates.begin(), sampleRates.end(),
85                        [](const auto& sampleRate) { return sampleRate == 0; });
86 }
87 
isDynamicProfile(const AudioProfile & profile)88 inline bool isDynamicProfile(const AudioProfile& profile) {
89     return hasDynamicFormat(profile.format) || hasDynamicChannelMasks(profile.channelMasks) ||
90            hasDynamicSampleRates(profile.sampleRates);
91 }
92 
hasDynamicProfilesOnly(const std::vector<AudioProfile> & profiles)93 bool hasDynamicProfilesOnly(const std::vector<AudioProfile>& profiles) {
94     if (profiles.empty()) return true;
95     return std::all_of(profiles.begin(), profiles.end(), isDynamicProfile);
96 }
97 
findAudioProfile(const AudioPort & port,const AudioFormatDescription & format,AudioProfile * profile)98 bool findAudioProfile(const AudioPort& port, const AudioFormatDescription& format,
99                       AudioProfile* profile) {
100     if (auto profilesIt =
101                 find_if(port.profiles.begin(), port.profiles.end(),
102                         [&format](const auto& profile) { return profile.format == format; });
103         profilesIt != port.profiles.end()) {
104         *profile = *profilesIt;
105         return true;
106     }
107     return false;
108 }
109 
110 }  // namespace
111 
112 // static
createInstance(Type type,std::unique_ptr<Configuration> && config)113 std::shared_ptr<Module> Module::createInstance(Type type, std::unique_ptr<Configuration>&& config) {
114     switch (type) {
115         case Type::DEFAULT:
116             return ndk::SharedRefBase::make<ModulePrimary>(std::move(config));
117         case Type::R_SUBMIX:
118             return ndk::SharedRefBase::make<ModuleRemoteSubmix>(std::move(config));
119         case Type::STUB:
120             return ndk::SharedRefBase::make<ModuleStub>(std::move(config));
121         case Type::USB:
122             return ndk::SharedRefBase::make<ModuleUsb>(std::move(config));
123         case Type::BLUETOOTH:
124             return ndk::SharedRefBase::make<ModuleBluetooth>(std::move(config));
125     }
126 }
127 
128 // static
typeFromString(const std::string & type)129 std::optional<Module::Type> Module::typeFromString(const std::string& type) {
130     if (type == "default")
131         return Module::Type::DEFAULT;
132     else if (type == "r_submix")
133         return Module::Type::R_SUBMIX;
134     else if (type == "stub")
135         return Module::Type::STUB;
136     else if (type == "usb")
137         return Module::Type::USB;
138     else if (type == "bluetooth")
139         return Module::Type::BLUETOOTH;
140     return {};
141 }
142 
operator <<(std::ostream & os,Module::Type t)143 std::ostream& operator<<(std::ostream& os, Module::Type t) {
144     switch (t) {
145         case Module::Type::DEFAULT:
146             os << "default";
147             break;
148         case Module::Type::R_SUBMIX:
149             os << "r_submix";
150             break;
151         case Module::Type::STUB:
152             os << "stub";
153             break;
154         case Module::Type::USB:
155             os << "usb";
156             break;
157         case Module::Type::BLUETOOTH:
158             os << "bluetooth";
159             break;
160     }
161     return os;
162 }
163 
Module(Type type,std::unique_ptr<Configuration> && config)164 Module::Module(Type type, std::unique_ptr<Configuration>&& config)
165     : mType(type), mConfig(std::move(config)) {
166     populateConnectedProfiles();
167 }
168 
cleanUpPatch(int32_t patchId)169 void Module::cleanUpPatch(int32_t patchId) {
170     erase_all_values(mPatches, std::set<int32_t>{patchId});
171 }
172 
createStreamContext(int32_t in_portConfigId,int64_t in_bufferSizeFrames,std::shared_ptr<IStreamCallback> asyncCallback,std::shared_ptr<IStreamOutEventCallback> outEventCallback,StreamContext * out_context)173 ndk::ScopedAStatus Module::createStreamContext(
174         int32_t in_portConfigId, int64_t in_bufferSizeFrames,
175         std::shared_ptr<IStreamCallback> asyncCallback,
176         std::shared_ptr<IStreamOutEventCallback> outEventCallback, StreamContext* out_context) {
177     if (in_bufferSizeFrames <= 0) {
178         LOG(ERROR) << __func__ << ": " << mType << ": non-positive buffer size "
179                    << in_bufferSizeFrames;
180         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
181     }
182     auto& configs = getConfig().portConfigs;
183     auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
184     const int32_t nominalLatencyMs = getNominalLatencyMs(*portConfigIt);
185     // Since this is a private method, it is assumed that
186     // validity of the portConfigId has already been checked.
187     int32_t minimumStreamBufferSizeFrames = 0;
188     if (!calculateBufferSizeFrames(
189                 portConfigIt->format.value(), nominalLatencyMs,
190                 portConfigIt->sampleRate.value().value, &minimumStreamBufferSizeFrames).isOk()) {
191         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
192     }
193     if (in_bufferSizeFrames < minimumStreamBufferSizeFrames) {
194         LOG(ERROR) << __func__ << ": " << mType << ": insufficient buffer size "
195                    << in_bufferSizeFrames << ", must be at least " << minimumStreamBufferSizeFrames;
196         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
197     }
198     const size_t frameSize =
199             getFrameSizeInBytes(portConfigIt->format.value(), portConfigIt->channelMask.value());
200     if (frameSize == 0) {
201         LOG(ERROR) << __func__ << ": " << mType
202                    << ": could not calculate frame size for port config "
203                    << portConfigIt->toString();
204         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
205     }
206     LOG(DEBUG) << __func__ << ": " << mType << ": frame size " << frameSize << " bytes";
207     if (frameSize > static_cast<size_t>(kMaximumStreamBufferSizeBytes / in_bufferSizeFrames)) {
208         LOG(ERROR) << __func__ << ": " << mType << ": buffer size " << in_bufferSizeFrames
209                    << " frames is too large, maximum size is "
210                    << kMaximumStreamBufferSizeBytes / frameSize;
211         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
212     }
213     const auto& flags = portConfigIt->flags.value();
214     StreamContext::DebugParameters params{mDebug.streamTransientStateDelayMs,
215                                           mVendorDebug.forceTransientBurst,
216                                           mVendorDebug.forceSynchronousDrain};
217     std::shared_ptr<ISoundDose> soundDose;
218     if (!getSoundDose(&soundDose).isOk()) {
219         LOG(ERROR) << __func__ << ": could not create sound dose instance";
220         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
221     }
222     StreamContext temp;
223     if (hasMmapFlag(flags)) {
224         MmapBufferDescriptor mmapDesc;
225         RETURN_STATUS_IF_ERROR(
226                 createMmapBuffer(*portConfigIt, in_bufferSizeFrames, frameSize, &mmapDesc));
227         temp = StreamContext(
228                 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
229                 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
230                 portConfigIt->format.value(), portConfigIt->channelMask.value(),
231                 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
232                 portConfigIt->ext.get<AudioPortExt::mix>().handle, std::move(mmapDesc),
233                 outEventCallback, mSoundDose.getInstance(), params);
234     } else {
235         temp = StreamContext(
236                 std::make_unique<StreamContext::CommandMQ>(1, true /*configureEventFlagWord*/),
237                 std::make_unique<StreamContext::ReplyMQ>(1, true /*configureEventFlagWord*/),
238                 portConfigIt->format.value(), portConfigIt->channelMask.value(),
239                 portConfigIt->sampleRate.value().value, flags, nominalLatencyMs,
240                 portConfigIt->ext.get<AudioPortExt::mix>().handle,
241                 std::make_unique<StreamContext::DataMQ>(frameSize * in_bufferSizeFrames),
242                 asyncCallback, outEventCallback, mSoundDose.getInstance(), params);
243     }
244     if (temp.isValid()) {
245         *out_context = std::move(temp);
246     } else {
247         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
248     }
249     return ndk::ScopedAStatus::ok();
250 }
251 
getDevicesFromDevicePortConfigIds(const std::set<int32_t> & devicePortConfigIds)252 std::vector<AudioDevice> Module::getDevicesFromDevicePortConfigIds(
253         const std::set<int32_t>& devicePortConfigIds) {
254     std::vector<AudioDevice> result;
255     auto& configs = getConfig().portConfigs;
256     for (const auto& id : devicePortConfigIds) {
257         auto it = findById<AudioPortConfig>(configs, id);
258         if (it != configs.end() && it->ext.getTag() == AudioPortExt::Tag::device) {
259             result.push_back(it->ext.template get<AudioPortExt::Tag::device>().device);
260         } else {
261             LOG(FATAL) << __func__ << ": " << mType
262                        << ": failed to find device for id" << id;
263         }
264     }
265     return result;
266 }
267 
findConnectedDevices(int32_t portConfigId)268 std::vector<AudioDevice> Module::findConnectedDevices(int32_t portConfigId) {
269     return getDevicesFromDevicePortConfigIds(findConnectedPortConfigIds(portConfigId));
270 }
271 
findConnectedPortConfigIds(int32_t portConfigId)272 std::set<int32_t> Module::findConnectedPortConfigIds(int32_t portConfigId) {
273     std::set<int32_t> result;
274     auto patchIdsRange = mPatches.equal_range(portConfigId);
275     auto& patches = getConfig().patches;
276     for (auto it = patchIdsRange.first; it != patchIdsRange.second; ++it) {
277         auto patchIt = findById<AudioPatch>(patches, it->second);
278         if (patchIt == patches.end()) {
279             LOG(FATAL) << __func__ << ": " << mType << ": patch with id " << it->second
280                        << " taken from mPatches "
281                        << "not found in the configuration";
282         }
283         if (std::find(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end(),
284                       portConfigId) != patchIt->sourcePortConfigIds.end()) {
285             result.insert(patchIt->sinkPortConfigIds.begin(), patchIt->sinkPortConfigIds.end());
286         } else {
287             result.insert(patchIt->sourcePortConfigIds.begin(), patchIt->sourcePortConfigIds.end());
288         }
289     }
290     return result;
291 }
292 
findPortIdForNewStream(int32_t in_portConfigId,AudioPort ** port)293 ndk::ScopedAStatus Module::findPortIdForNewStream(int32_t in_portConfigId, AudioPort** port) {
294     auto& configs = getConfig().portConfigs;
295     auto portConfigIt = findById<AudioPortConfig>(configs, in_portConfigId);
296     if (portConfigIt == configs.end()) {
297         LOG(ERROR) << __func__ << ": " << mType << ": existing port config id " << in_portConfigId
298                    << " not found";
299         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
300     }
301     const int32_t portId = portConfigIt->portId;
302     // In our implementation, configs of mix ports always have unique IDs.
303     CHECK(portId != in_portConfigId);
304     auto& ports = getConfig().ports;
305     auto portIt = findById<AudioPort>(ports, portId);
306     if (portIt == ports.end()) {
307         LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
308                    << " used by port config id " << in_portConfigId << " not found";
309         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
310     }
311     if (mStreams.count(in_portConfigId) != 0) {
312         LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
313                    << " already has a stream opened on it";
314         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
315     }
316     if (portIt->ext.getTag() != AudioPortExt::Tag::mix) {
317         LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
318                    << " does not correspond to a mix port";
319         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
320     }
321     const size_t maxOpenStreamCount = portIt->ext.get<AudioPortExt::Tag::mix>().maxOpenStreamCount;
322     if (maxOpenStreamCount != 0 && mStreams.count(portId) >= maxOpenStreamCount) {
323         LOG(ERROR) << __func__ << ": " << mType << ": port id " << portId
324                    << " has already reached maximum allowed opened stream count: "
325                    << maxOpenStreamCount;
326         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
327     }
328     *port = &(*portIt);
329     return ndk::ScopedAStatus::ok();
330 }
331 
generateDefaultPortConfig(const AudioPort & port,AudioPortConfig * config)332 bool Module::generateDefaultPortConfig(const AudioPort& port, AudioPortConfig* config) {
333     const bool allowDynamicConfig = port.ext.getTag() == AudioPortExt::device;
334     for (const auto& profile : port.profiles) {
335         if (isDynamicProfile(profile)) continue;
336         config->format = profile.format;
337         config->channelMask = *profile.channelMasks.begin();
338         config->sampleRate = Int{.value = *profile.sampleRates.begin()};
339         config->flags = port.flags;
340         config->ext = port.ext;
341         return true;
342     }
343     if (allowDynamicConfig) {
344         config->format = AudioFormatDescription{};
345         config->channelMask = AudioChannelLayout{};
346         config->sampleRate = Int{.value = 0};
347         config->flags = port.flags;
348         config->ext = port.ext;
349         return true;
350     }
351     LOG(ERROR) << __func__ << ": " << mType << ": port " << port.id << " only has dynamic profiles";
352     return false;
353 }
354 
populateConnectedProfiles()355 void Module::populateConnectedProfiles() {
356     Configuration& config = getConfig();
357     for (const AudioPort& port : config.ports) {
358         if (port.ext.getTag() == AudioPortExt::device) {
359             if (auto devicePort = port.ext.get<AudioPortExt::device>();
360                 !devicePort.device.type.connection.empty() && port.profiles.empty()) {
361                 if (auto connIt = config.connectedProfiles.find(port.id);
362                     connIt == config.connectedProfiles.end()) {
363                     config.connectedProfiles.emplace(
364                             port.id, internal::getStandard16And24BitPcmAudioProfiles());
365                 }
366             }
367         }
368     }
369 }
370 
371 template <typename C>
portIdsFromPortConfigIds(C portConfigIds)372 std::set<int32_t> Module::portIdsFromPortConfigIds(C portConfigIds) {
373     std::set<int32_t> result;
374     auto& portConfigs = getConfig().portConfigs;
375     for (auto it = portConfigIds.begin(); it != portConfigIds.end(); ++it) {
376         auto portConfigIt = findById<AudioPortConfig>(portConfigs, *it);
377         if (portConfigIt != portConfigs.end()) {
378             result.insert(portConfigIt->portId);
379         }
380     }
381     return result;
382 }
383 
initializeConfig()384 std::unique_ptr<Module::Configuration> Module::initializeConfig() {
385     return internal::getConfiguration(getType());
386 }
387 
getNominalLatencyMs(const AudioPortConfig &)388 int32_t Module::getNominalLatencyMs(const AudioPortConfig&) {
389     // Arbitrary value. Implementations must override this method to provide their actual latency.
390     static constexpr int32_t kLatencyMs = 5;
391     return kLatencyMs;
392 }
393 
calculateBufferSizeFrames(const::aidl::android::media::audio::common::AudioFormatDescription & format,int32_t latencyMs,int32_t sampleRateHz,int32_t * bufferSizeFrames)394 ndk::ScopedAStatus Module::calculateBufferSizeFrames(
395         const ::aidl::android::media::audio::common::AudioFormatDescription &format,
396         int32_t latencyMs, int32_t sampleRateHz, int32_t *bufferSizeFrames) {
397     if (format.type == AudioFormatType::PCM) {
398         *bufferSizeFrames = calculateBufferSizeFramesForPcm(latencyMs, sampleRateHz);
399         return ndk::ScopedAStatus::ok();
400     }
401     LOG(ERROR) << __func__ << ": " << mType << ": format " << format.toString()
402         << " is not supported";
403     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
404 }
405 
createMmapBuffer(const AudioPortConfig & portConfig __unused,int32_t bufferSizeFrames __unused,int32_t frameSizeBytes __unused,MmapBufferDescriptor * desc __unused)406 ndk::ScopedAStatus Module::createMmapBuffer(const AudioPortConfig& portConfig __unused,
407                                             int32_t bufferSizeFrames __unused,
408                                             int32_t frameSizeBytes __unused,
409                                             MmapBufferDescriptor* desc __unused) {
410     LOG(ERROR) << __func__ << ": " << mType << ": is not implemented";
411     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
412 }
413 
getAudioRoutesForAudioPortImpl(int32_t portId)414 std::vector<AudioRoute*> Module::getAudioRoutesForAudioPortImpl(int32_t portId) {
415     std::vector<AudioRoute*> result;
416     auto& routes = getConfig().routes;
417     for (auto& r : routes) {
418         const auto& srcs = r.sourcePortIds;
419         if (r.sinkPortId == portId || std::find(srcs.begin(), srcs.end(), portId) != srcs.end()) {
420             result.push_back(&r);
421         }
422     }
423     return result;
424 }
425 
getConfig()426 Module::Configuration& Module::getConfig() {
427     if (!mConfig) {
428         mConfig = initializeConfig();
429     }
430     return *mConfig;
431 }
432 
getRoutableAudioPortIds(int32_t portId,std::vector<AudioRoute * > * routes)433 std::set<int32_t> Module::getRoutableAudioPortIds(int32_t portId,
434                                                   std::vector<AudioRoute*>* routes) {
435     std::vector<AudioRoute*> routesStorage;
436     if (routes == nullptr) {
437         routesStorage = getAudioRoutesForAudioPortImpl(portId);
438         routes = &routesStorage;
439     }
440     std::set<int32_t> result;
441     for (AudioRoute* r : *routes) {
442         if (r->sinkPortId == portId) {
443             result.insert(r->sourcePortIds.begin(), r->sourcePortIds.end());
444         } else {
445             result.insert(r->sinkPortId);
446         }
447     }
448     return result;
449 }
450 
registerPatch(const AudioPatch & patch)451 void Module::registerPatch(const AudioPatch& patch) {
452     auto& configs = getConfig().portConfigs;
453     auto do_insert = [&](const std::vector<int32_t>& portConfigIds) {
454         for (auto portConfigId : portConfigIds) {
455             auto configIt = findById<AudioPortConfig>(configs, portConfigId);
456             if (configIt != configs.end()) {
457                 mPatches.insert(std::pair{portConfigId, patch.id});
458                 if (configIt->portId != portConfigId) {
459                     mPatches.insert(std::pair{configIt->portId, patch.id});
460                 }
461             }
462         };
463     };
464     do_insert(patch.sourcePortConfigIds);
465     do_insert(patch.sinkPortConfigIds);
466 }
467 
updateStreamsConnectedState(const AudioPatch & oldPatch,const AudioPatch & newPatch)468 ndk::ScopedAStatus Module::updateStreamsConnectedState(const AudioPatch& oldPatch,
469                                                        const AudioPatch& newPatch) {
470     // Notify streams about the new set of devices they are connected to.
471     auto maybeFailure = ndk::ScopedAStatus::ok();
472     using Connections =
473             std::map<int32_t /*mixPortConfigId*/, std::set<int32_t /*devicePortConfigId*/>>;
474     Connections oldConnections, newConnections;
475     auto fillConnectionsHelper = [&](Connections& connections,
476                                      const std::vector<int32_t>& mixPortCfgIds,
477                                      const std::vector<int32_t>& devicePortCfgIds) {
478         for (int32_t mixPortCfgId : mixPortCfgIds) {
479             connections[mixPortCfgId].insert(devicePortCfgIds.begin(), devicePortCfgIds.end());
480         }
481     };
482     auto fillConnections = [&](Connections& connections, const AudioPatch& patch) {
483         if (std::find_if(patch.sourcePortConfigIds.begin(), patch.sourcePortConfigIds.end(),
484                          [&](int32_t portConfigId) { return mStreams.count(portConfigId) > 0; }) !=
485             patch.sourcePortConfigIds.end()) {
486             // Sources are mix ports.
487             fillConnectionsHelper(connections, patch.sourcePortConfigIds, patch.sinkPortConfigIds);
488         } else if (std::find_if(patch.sinkPortConfigIds.begin(), patch.sinkPortConfigIds.end(),
489                                 [&](int32_t portConfigId) {
490                                     return mStreams.count(portConfigId) > 0;
491                                 }) != patch.sinkPortConfigIds.end()) {
492             // Sources are device ports.
493             fillConnectionsHelper(connections, patch.sinkPortConfigIds, patch.sourcePortConfigIds);
494         }  // Otherwise, there are no streams to notify.
495     };
496     auto restoreOldConnections = [&](const std::set<int32_t>& mixPortIds,
497                                      const bool continueWithEmptyDevices) {
498         for (const auto mixPort : mixPortIds) {
499             if (auto it = oldConnections.find(mixPort);
500                 continueWithEmptyDevices || it != oldConnections.end()) {
501                 const std::vector<AudioDevice> d =
502                         it != oldConnections.end() ? getDevicesFromDevicePortConfigIds(it->second)
503                                                    : std::vector<AudioDevice>();
504                 if (auto status = mStreams.setStreamConnectedDevices(mixPort, d); status.isOk()) {
505                     LOG(WARNING) << ":updateStreamsConnectedState: rollback: mix port config:"
506                                  << mixPort
507                                  << (d.empty() ? "; not connected"
508                                                : std::string("; connected to ") +
509                                                          ::android::internal::ToString(d));
510                 } else {
511                     // can't do much about rollback failures
512                     LOG(ERROR)
513                             << ":updateStreamsConnectedState: rollback: failed for mix port config:"
514                             << mixPort;
515                 }
516             }
517         }
518     };
519     fillConnections(oldConnections, oldPatch);
520     fillConnections(newConnections, newPatch);
521     /**
522      * Illustration of oldConnections and newConnections
523      *
524      * oldConnections {
525      * a : {A,B,C},
526      * b : {D},
527      * d : {H,I,J},
528      * e : {N,O,P},
529      * f : {Q,R},
530      * g : {T,U,V},
531      * }
532      *
533      * newConnections {
534      * a : {A,B,C},
535      * c : {E,F,G},
536      * d : {K,L,M},
537      * e : {N,P},
538      * f : {Q,R,S},
539      * g : {U,V,W},
540      * }
541      *
542      * Expected routings:
543      *      'a': is ignored both in disconnect step and connect step,
544      *           due to same devices both in oldConnections and newConnections.
545      *      'b': handled only in disconnect step with empty devices because 'b' is only present
546      *           in oldConnections.
547      *      'c': handled only in connect step with {E,F,G} devices because 'c' is only present
548      *           in newConnections.
549      *      'd': handled only in connect step with {K,L,M} devices because 'd' is also present
550      *           in newConnections and it is ignored in disconnected step.
551      *      'e': handled only in connect step with {N,P} devices because 'e' is also present
552      *           in newConnections and it is ignored in disconnect step. please note that there
553      *           is no exclusive disconnection for device {O}.
554      *      'f': handled only in connect step with {Q,R,S} devices because 'f' is also present
555      *           in newConnections and it is ignored in disconnect step. Even though stream is
556      *           already connected with {Q,R} devices and connection happens with {Q,R,S}.
557      *      'g': handled only in connect step with {U,V,W} devices because 'g' is also present
558      *           in newConnections and it is ignored in disconnect step. There is no exclusive
559      *           disconnection with devices {T,U,V}.
560      *
561      *       If, any failure, will lead to restoreOldConnections (rollback).
562      *       The aim of the restoreOldConnections is to make connections back to oldConnections.
563      *       Failures in restoreOldConnections aren't handled.
564      */
565 
566     std::set<int32_t> idsToConnectBackOnFailure;
567     // disconnection step
568     for (const auto& [oldMixPortConfigId, oldDevicePortConfigIds] : oldConnections) {
569         if (auto it = newConnections.find(oldMixPortConfigId); it == newConnections.end()) {
570             idsToConnectBackOnFailure.insert(oldMixPortConfigId);
571             if (auto status = mStreams.setStreamConnectedDevices(oldMixPortConfigId, {});
572                 status.isOk()) {
573                 LOG(DEBUG) << __func__ << ": The stream on port config id " << oldMixPortConfigId
574                            << " has been disconnected";
575             } else {
576                 maybeFailure = std::move(status);
577                 // proceed to rollback even on one failure
578                 break;
579             }
580         }
581     }
582 
583     if (!maybeFailure.isOk()) {
584         restoreOldConnections(idsToConnectBackOnFailure, false /*continueWithEmptyDevices*/);
585         LOG(WARNING) << __func__ << ": failed to disconnect from old patch. attempted rollback";
586         return maybeFailure;
587     }
588 
589     std::set<int32_t> idsToRollbackOnFailure;
590     // connection step
591     for (const auto& [newMixPortConfigId, newDevicePortConfigIds] : newConnections) {
592         if (auto it = oldConnections.find(newMixPortConfigId);
593             it == oldConnections.end() || it->second != newDevicePortConfigIds) {
594             const auto connectedDevices = getDevicesFromDevicePortConfigIds(newDevicePortConfigIds);
595             idsToRollbackOnFailure.insert(newMixPortConfigId);
596             if (connectedDevices.empty()) {
597                 // This is important as workers use the vector size to derive the connection status.
598                 LOG(FATAL) << __func__ << ": No connected devices found for port config id "
599                            << newMixPortConfigId;
600             }
601             if (auto status =
602                         mStreams.setStreamConnectedDevices(newMixPortConfigId, connectedDevices);
603                 status.isOk()) {
604                 LOG(DEBUG) << __func__ << ": The stream on port config id " << newMixPortConfigId
605                            << " has been connected to: "
606                            << ::android::internal::ToString(connectedDevices);
607             } else {
608                 maybeFailure = std::move(status);
609                 // proceed to rollback even on one failure
610                 break;
611             }
612         }
613     }
614 
615     if (!maybeFailure.isOk()) {
616         restoreOldConnections(idsToConnectBackOnFailure, false /*continueWithEmptyDevices*/);
617         restoreOldConnections(idsToRollbackOnFailure, true /*continueWithEmptyDevices*/);
618         LOG(WARNING) << __func__ << ": failed to connect for new patch. attempted rollback";
619         return maybeFailure;
620     }
621 
622     return ndk::ScopedAStatus::ok();
623 }
624 
dump(int fd,const char ** args,uint32_t numArgs)625 binder_status_t Module::dump(int fd, const char** args, uint32_t numArgs) {
626     for (const auto& portConfig : getConfig().portConfigs) {
627         if (portConfig.ext.getTag() == AudioPortExt::Tag::mix) {
628             getStreams().dump(portConfig.id, fd, args, numArgs);
629         }
630     }
631     return STATUS_OK;
632 }
633 
setModuleDebug(const::aidl::android::hardware::audio::core::ModuleDebug & in_debug)634 ndk::ScopedAStatus Module::setModuleDebug(
635         const ::aidl::android::hardware::audio::core::ModuleDebug& in_debug) {
636     LOG(DEBUG) << __func__ << ": " << mType << ": old flags:" << mDebug.toString()
637                << ", new flags: " << in_debug.toString();
638     if (mDebug.simulateDeviceConnections != in_debug.simulateDeviceConnections &&
639         !mConnectedDevicePorts.empty()) {
640         LOG(ERROR) << __func__ << ": " << mType
641                    << ": attempting to change device connections simulation while "
642                       "having external "
643                    << "devices connected";
644         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
645     }
646     if (in_debug.streamTransientStateDelayMs < 0) {
647         LOG(ERROR) << __func__ << ": " << mType << ": streamTransientStateDelayMs is negative: "
648                    << in_debug.streamTransientStateDelayMs;
649         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
650     }
651     mDebug = in_debug;
652     return ndk::ScopedAStatus::ok();
653 }
654 
getTelephony(std::shared_ptr<ITelephony> * _aidl_return)655 ndk::ScopedAStatus Module::getTelephony(std::shared_ptr<ITelephony>* _aidl_return) {
656     *_aidl_return = nullptr;
657     LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
658     return ndk::ScopedAStatus::ok();
659 }
660 
getBluetooth(std::shared_ptr<IBluetooth> * _aidl_return)661 ndk::ScopedAStatus Module::getBluetooth(std::shared_ptr<IBluetooth>* _aidl_return) {
662     *_aidl_return = nullptr;
663     LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
664     return ndk::ScopedAStatus::ok();
665 }
666 
getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp> * _aidl_return)667 ndk::ScopedAStatus Module::getBluetoothA2dp(std::shared_ptr<IBluetoothA2dp>* _aidl_return) {
668     *_aidl_return = nullptr;
669     LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
670     return ndk::ScopedAStatus::ok();
671 }
672 
getBluetoothLe(std::shared_ptr<IBluetoothLe> * _aidl_return)673 ndk::ScopedAStatus Module::getBluetoothLe(std::shared_ptr<IBluetoothLe>* _aidl_return) {
674     *_aidl_return = nullptr;
675     LOG(DEBUG) << __func__ << ": " << mType << ": returning null";
676     return ndk::ScopedAStatus::ok();
677 }
678 
connectExternalDevice(const AudioPort & in_templateIdAndAdditionalData,AudioPort * _aidl_return)679 ndk::ScopedAStatus Module::connectExternalDevice(const AudioPort& in_templateIdAndAdditionalData,
680                                                  AudioPort* _aidl_return) {
681     const int32_t templateId = in_templateIdAndAdditionalData.id;
682     auto& ports = getConfig().ports;
683     AudioPort connectedPort;
684     {  // Scope the template port so that we don't accidentally modify it.
685         auto templateIt = findById<AudioPort>(ports, templateId);
686         if (templateIt == ports.end()) {
687             LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId << " not found";
688             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
689         }
690         if (templateIt->ext.getTag() != AudioPortExt::Tag::device) {
691             LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
692                        << " is not a device port";
693             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
694         }
695         auto& templateDevicePort = templateIt->ext.get<AudioPortExt::Tag::device>();
696         if (templateDevicePort.device.type.connection.empty()) {
697             LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
698                        << " is permanently attached";
699             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
700         }
701         if (mConnectedDevicePorts.find(templateId) != mConnectedDevicePorts.end()) {
702             LOG(ERROR) << __func__ << ": " << mType << ": port id " << templateId
703                        << " is a connected device port";
704             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
705         }
706         // Postpone id allocation until we ensure that there are no client errors.
707         connectedPort = *templateIt;
708         connectedPort.extraAudioDescriptors = in_templateIdAndAdditionalData.extraAudioDescriptors;
709         const auto& inputDevicePort =
710                 in_templateIdAndAdditionalData.ext.get<AudioPortExt::Tag::device>();
711         auto& connectedDevicePort = connectedPort.ext.get<AudioPortExt::Tag::device>();
712         connectedDevicePort.device.address = inputDevicePort.device.address;
713         LOG(DEBUG) << __func__ << ": " << mType << ": device port " << connectedPort.id
714                    << " device set to " << connectedDevicePort.device.toString();
715         // Check if there is already a connected port with for the same external device.
716 
717         for (auto connectedPortPair : mConnectedDevicePorts) {
718             auto connectedPortIt = findById<AudioPort>(ports, connectedPortPair.first);
719             if (connectedPortIt->ext.get<AudioPortExt::Tag::device>().device ==
720                 connectedDevicePort.device) {
721                 LOG(ERROR) << __func__ << ": " << mType << ": device "
722                            << connectedDevicePort.device.toString()
723                            << " is already connected at the device port id "
724                            << connectedPortPair.first;
725                 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
726             }
727         }
728     }
729 
730     // Two main cases are considered with regard to the profiles of the connected device port:
731     //
732     //  1. If the template device port has dynamic profiles, and at least one routable mix
733     //     port also has dynamic profiles, it means that after connecting the device, the
734     //     connected device port must have profiles populated with actual capabilities of
735     //     the connected device, and dynamic of routable mix ports will be filled
736     //     according to these capabilities. An example of this case is connection of an
737     //     HDMI or USB device. For USB handled by ADSP, there can be mix ports with static
738     //     profiles, and one dedicated mix port for "hi-fi" playback. The latter is left with
739     //     dynamic profiles so that they can be populated with actual capabilities of
740     //     the connected device.
741     //
742     //  2. If the template device port has dynamic profiles, while all routable mix ports
743     //     have static profiles, it means that after connecting the device, the connected
744     //     device port can be left with dynamic profiles, and profiles of mix ports are
745     //     left untouched. An example of this case is connection of an analog wired
746     //     headset, it should be treated in the same way as a speaker.
747     //
748     //  Yet another possible case is when both the template device port and all routable
749     //  mix ports have static profiles. This is allowed and handled correctly, however, it
750     //  is not very practical, since these profiles are likely duplicates of each other.
751 
752     std::vector<AudioRoute*> routesToMixPorts = getAudioRoutesForAudioPortImpl(templateId);
753     std::set<int32_t> routableMixPortIds = getRoutableAudioPortIds(templateId, &routesToMixPorts);
754     const int32_t nextPortId = getConfig().nextPortId++;
755     if (!mDebug.simulateDeviceConnections) {
756         // Even if the device port has static profiles, the HAL module might need to update
757         // them, or abort the connection process.
758         RETURN_STATUS_IF_ERROR(populateConnectedDevicePort(&connectedPort, nextPortId));
759     } else if (hasDynamicProfilesOnly(connectedPort.profiles)) {
760         auto& connectedProfiles = getConfig().connectedProfiles;
761         if (auto connectedProfilesIt = connectedProfiles.find(templateId);
762             connectedProfilesIt != connectedProfiles.end()) {
763             connectedPort.profiles = connectedProfilesIt->second;
764         }
765     }
766     if (hasDynamicProfilesOnly(connectedPort.profiles)) {
767         // Possible case 2. Check if all routable mix ports have static profiles.
768         if (auto dynamicMixPortIt = std::find_if(ports.begin(), ports.end(),
769                                                  [&routableMixPortIds](const auto& p) {
770                                                      return routableMixPortIds.count(p.id) > 0 &&
771                                                             hasDynamicProfilesOnly(p.profiles);
772                                                  });
773             dynamicMixPortIt != ports.end()) {
774             LOG(ERROR) << __func__ << ": " << mType
775                        << ": connected port only has dynamic profiles after connecting "
776                        << "external device " << connectedPort.toString() << ", and there exist "
777                        << "a routable mix port with dynamic profiles: "
778                        << dynamicMixPortIt->toString();
779             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
780         }
781     }
782 
783     connectedPort.id = nextPortId;
784     auto [connectedPortsIt, _] =
785             mConnectedDevicePorts.insert(std::pair(connectedPort.id, std::set<int32_t>()));
786     LOG(DEBUG) << __func__ << ": " << mType << ": template port " << templateId
787                << " external device connected, "
788                << "connected port ID " << connectedPort.id;
789     ports.push_back(connectedPort);
790     onExternalDeviceConnectionChanged(connectedPort, true /*connected*/);
791 
792     // For routes where the template port is a source, add the connected port to sources,
793     // otherwise, create a new route by copying from the route for the template port.
794     std::vector<AudioRoute> newRoutes;
795     for (AudioRoute* r : routesToMixPorts) {
796         if (r->sinkPortId == templateId) {
797             newRoutes.push_back(AudioRoute{.sourcePortIds = r->sourcePortIds,
798                                            .sinkPortId = connectedPort.id,
799                                            .isExclusive = r->isExclusive});
800         } else {
801             r->sourcePortIds.push_back(connectedPort.id);
802         }
803     }
804     auto& routes = getConfig().routes;
805     routes.insert(routes.end(), newRoutes.begin(), newRoutes.end());
806 
807     if (!hasDynamicProfilesOnly(connectedPort.profiles) && !routableMixPortIds.empty()) {
808         // Note: this is a simplistic approach assuming that a mix port can only be populated
809         // from a single device port. Implementing support for stuffing dynamic profiles with
810         // a superset of all profiles from all routable dynamic device ports would be more involved.
811         for (auto& port : ports) {
812             if (routableMixPortIds.count(port.id) == 0) continue;
813             if (hasDynamicProfilesOnly(port.profiles)) {
814                 port.profiles = connectedPort.profiles;
815                 connectedPortsIt->second.insert(port.id);
816             } else {
817                 // Check if profiles are not all dynamic because they were populated by
818                 // a previous connection. Otherwise, it means that they are actually static.
819                 for (const auto& cp : mConnectedDevicePorts) {
820                     if (cp.second.count(port.id) > 0) {
821                         connectedPortsIt->second.insert(port.id);
822                         break;
823                     }
824                 }
825             }
826         }
827     }
828     *_aidl_return = std::move(connectedPort);
829 
830     return ndk::ScopedAStatus::ok();
831 }
832 
disconnectExternalDevice(int32_t in_portId)833 ndk::ScopedAStatus Module::disconnectExternalDevice(int32_t in_portId) {
834     auto& ports = getConfig().ports;
835     auto portIt = findById<AudioPort>(ports, in_portId);
836     if (portIt == ports.end()) {
837         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
838         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
839     }
840     if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
841         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
842                    << " is not a device port";
843         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
844     }
845     auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
846     if (connectedPortsIt == mConnectedDevicePorts.end()) {
847         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
848                    << " is not a connected device port";
849         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
850     }
851     auto& configs = getConfig().portConfigs;
852     auto& initials = getConfig().initialConfigs;
853     auto configIt = std::find_if(configs.begin(), configs.end(), [&](const auto& config) {
854         if (config.portId == in_portId) {
855             // Check if the configuration was provided by the client.
856             const auto& initialIt = findById<AudioPortConfig>(initials, config.id);
857             return initialIt == initials.end() || config != *initialIt;
858         }
859         return false;
860     });
861     if (configIt != configs.end()) {
862         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
863                    << " has a non-default config with id " << configIt->id;
864         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
865     }
866     onExternalDeviceConnectionChanged(*portIt, false /*connected*/);
867     ports.erase(portIt);
868     LOG(DEBUG) << __func__ << ": " << mType << ": connected device port " << in_portId
869                << " released";
870 
871     auto& routes = getConfig().routes;
872     for (auto routesIt = routes.begin(); routesIt != routes.end();) {
873         if (routesIt->sinkPortId == in_portId) {
874             routesIt = routes.erase(routesIt);
875         } else {
876             // Note: the list of sourcePortIds can't become empty because there must
877             // be the id of the template port in the route.
878             erase_if(routesIt->sourcePortIds, [in_portId](auto src) { return src == in_portId; });
879             ++routesIt;
880         }
881     }
882 
883     // Clear profiles for mix ports that are not connected to any other ports.
884     std::set<int32_t> mixPortsToClear = std::move(connectedPortsIt->second);
885     mConnectedDevicePorts.erase(connectedPortsIt);
886     for (const auto& connectedPort : mConnectedDevicePorts) {
887         for (int32_t mixPortId : connectedPort.second) {
888             mixPortsToClear.erase(mixPortId);
889         }
890     }
891     for (int32_t mixPortId : mixPortsToClear) {
892         auto mixPortIt = findById<AudioPort>(ports, mixPortId);
893         if (mixPortIt != ports.end()) {
894             mixPortIt->profiles = {};
895         }
896     }
897 
898     return ndk::ScopedAStatus::ok();
899 }
900 
prepareToDisconnectExternalDevice(int32_t in_portId)901 ndk::ScopedAStatus Module::prepareToDisconnectExternalDevice(int32_t in_portId) {
902     auto& ports = getConfig().ports;
903     auto portIt = findById<AudioPort>(ports, in_portId);
904     if (portIt == ports.end()) {
905         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
906         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
907     }
908     if (portIt->ext.getTag() != AudioPortExt::Tag::device) {
909         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
910                    << " is not a device port";
911         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
912     }
913     auto connectedPortsIt = mConnectedDevicePorts.find(in_portId);
914     if (connectedPortsIt == mConnectedDevicePorts.end()) {
915         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId
916                    << " is not a connected device port";
917         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
918     }
919 
920     onPrepareToDisconnectExternalDevice(*portIt);
921 
922     return ndk::ScopedAStatus::ok();
923 }
924 
getAudioPatches(std::vector<AudioPatch> * _aidl_return)925 ndk::ScopedAStatus Module::getAudioPatches(std::vector<AudioPatch>* _aidl_return) {
926     *_aidl_return = getConfig().patches;
927     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " patches";
928     return ndk::ScopedAStatus::ok();
929 }
930 
getAudioPort(int32_t in_portId,AudioPort * _aidl_return)931 ndk::ScopedAStatus Module::getAudioPort(int32_t in_portId, AudioPort* _aidl_return) {
932     auto& ports = getConfig().ports;
933     auto portIt = findById<AudioPort>(ports, in_portId);
934     if (portIt != ports.end()) {
935         *_aidl_return = *portIt;
936         LOG(DEBUG) << __func__ << ": " << mType << ": returning port by id " << in_portId;
937         return ndk::ScopedAStatus::ok();
938     }
939     LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
940     return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
941 }
942 
getAudioPortConfigs(std::vector<AudioPortConfig> * _aidl_return)943 ndk::ScopedAStatus Module::getAudioPortConfigs(std::vector<AudioPortConfig>* _aidl_return) {
944     *_aidl_return = getConfig().portConfigs;
945     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size()
946                << " port configs";
947     return ndk::ScopedAStatus::ok();
948 }
949 
getAudioPorts(std::vector<AudioPort> * _aidl_return)950 ndk::ScopedAStatus Module::getAudioPorts(std::vector<AudioPort>* _aidl_return) {
951     *_aidl_return = getConfig().ports;
952     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " ports";
953     return ndk::ScopedAStatus::ok();
954 }
955 
getAudioRoutes(std::vector<AudioRoute> * _aidl_return)956 ndk::ScopedAStatus Module::getAudioRoutes(std::vector<AudioRoute>* _aidl_return) {
957     *_aidl_return = getConfig().routes;
958     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << _aidl_return->size() << " routes";
959     return ndk::ScopedAStatus::ok();
960 }
961 
getAudioRoutesForAudioPort(int32_t in_portId,std::vector<AudioRoute> * _aidl_return)962 ndk::ScopedAStatus Module::getAudioRoutesForAudioPort(int32_t in_portId,
963                                                       std::vector<AudioRoute>* _aidl_return) {
964     auto& ports = getConfig().ports;
965     if (auto portIt = findById<AudioPort>(ports, in_portId); portIt == ports.end()) {
966         LOG(ERROR) << __func__ << ": " << mType << ": port id " << in_portId << " not found";
967         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
968     }
969     std::vector<AudioRoute*> routes = getAudioRoutesForAudioPortImpl(in_portId);
970     std::transform(routes.begin(), routes.end(), std::back_inserter(*_aidl_return),
971                    [](auto rptr) { return *rptr; });
972     return ndk::ScopedAStatus::ok();
973 }
974 
openInputStream(const OpenInputStreamArguments & in_args,OpenInputStreamReturn * _aidl_return)975 ndk::ScopedAStatus Module::openInputStream(const OpenInputStreamArguments& in_args,
976                                            OpenInputStreamReturn* _aidl_return) {
977     LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
978                << ", buffer size " << in_args.bufferSizeFrames << " frames";
979     AudioPort* port = nullptr;
980     RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
981     if (port->flags.getTag() != AudioIoFlags::Tag::input) {
982         LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
983                    << " does not correspond to an input mix port";
984         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
985     }
986     StreamContext context;
987     RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
988                                                nullptr, nullptr, &context));
989     context.fillDescriptor(&_aidl_return->desc);
990     std::shared_ptr<StreamIn> stream;
991     RETURN_STATUS_IF_ERROR(createInputStream(std::move(context), in_args.sinkMetadata,
992                                              getMicrophoneInfos(), &stream));
993     StreamWrapper streamWrapper(stream);
994     if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
995         RETURN_STATUS_IF_ERROR(
996                 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
997     }
998     auto streamBinder = streamWrapper.getBinder();
999     AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
1000     AIBinder_setInheritRt(streamBinder.get(), true);
1001     mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
1002     _aidl_return->stream = std::move(stream);
1003     return ndk::ScopedAStatus::ok();
1004 }
1005 
openOutputStream(const OpenOutputStreamArguments & in_args,OpenOutputStreamReturn * _aidl_return)1006 ndk::ScopedAStatus Module::openOutputStream(const OpenOutputStreamArguments& in_args,
1007                                             OpenOutputStreamReturn* _aidl_return) {
1008     LOG(DEBUG) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
1009                << ", has offload info? " << (in_args.offloadInfo.has_value()) << ", buffer size "
1010                << in_args.bufferSizeFrames << " frames";
1011     AudioPort* port = nullptr;
1012     RETURN_STATUS_IF_ERROR(findPortIdForNewStream(in_args.portConfigId, &port));
1013     if (port->flags.getTag() != AudioIoFlags::Tag::output) {
1014         LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_args.portConfigId
1015                    << " does not correspond to an output mix port";
1016         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1017     }
1018     const bool isOffload = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
1019                                                 AudioOutputFlags::COMPRESS_OFFLOAD);
1020     if (isOffload && !in_args.offloadInfo.has_value()) {
1021         LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
1022                    << " has COMPRESS_OFFLOAD flag set, requires offload info";
1023         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1024     }
1025     const bool isNonBlocking = isBitPositionFlagSet(port->flags.get<AudioIoFlags::Tag::output>(),
1026                                                     AudioOutputFlags::NON_BLOCKING);
1027     if (isNonBlocking && in_args.callback == nullptr) {
1028         LOG(ERROR) << __func__ << ": " << mType << ": port id " << port->id
1029                    << " has NON_BLOCKING flag set, requires async callback";
1030         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1031     }
1032     StreamContext context;
1033     RETURN_STATUS_IF_ERROR(createStreamContext(in_args.portConfigId, in_args.bufferSizeFrames,
1034                                                isNonBlocking ? in_args.callback : nullptr,
1035                                                in_args.eventCallback, &context));
1036     context.fillDescriptor(&_aidl_return->desc);
1037     std::shared_ptr<StreamOut> stream;
1038     RETURN_STATUS_IF_ERROR(createOutputStream(std::move(context), in_args.sourceMetadata,
1039                                               in_args.offloadInfo, &stream));
1040     StreamWrapper streamWrapper(stream);
1041     if (auto patchIt = mPatches.find(in_args.portConfigId); patchIt != mPatches.end()) {
1042         RETURN_STATUS_IF_ERROR(
1043                 streamWrapper.setConnectedDevices(findConnectedDevices(in_args.portConfigId)));
1044     }
1045     auto streamBinder = streamWrapper.getBinder();
1046     AIBinder_setMinSchedulerPolicy(streamBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
1047     AIBinder_setInheritRt(streamBinder.get(), true);
1048     mStreams.insert(port->id, in_args.portConfigId, std::move(streamWrapper));
1049     _aidl_return->stream = std::move(stream);
1050     return ndk::ScopedAStatus::ok();
1051 }
1052 
getSupportedPlaybackRateFactors(SupportedPlaybackRateFactors * _aidl_return)1053 ndk::ScopedAStatus Module::getSupportedPlaybackRateFactors(
1054         SupportedPlaybackRateFactors* _aidl_return) {
1055     LOG(DEBUG) << __func__ << ": " << mType;
1056     (void)_aidl_return;
1057     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1058 }
1059 
setAudioPatch(const AudioPatch & in_requested,AudioPatch * _aidl_return)1060 ndk::ScopedAStatus Module::setAudioPatch(const AudioPatch& in_requested, AudioPatch* _aidl_return) {
1061     LOG(DEBUG) << __func__ << ": " << mType << ": requested patch " << in_requested.toString();
1062     if (in_requested.sourcePortConfigIds.empty()) {
1063         LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sources list";
1064         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1065     }
1066     if (!all_unique<int32_t>(in_requested.sourcePortConfigIds)) {
1067         LOG(ERROR) << __func__ << ": " << mType
1068                    << ": requested patch has duplicate ids in the sources list";
1069         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1070     }
1071     if (in_requested.sinkPortConfigIds.empty()) {
1072         LOG(ERROR) << __func__ << ": " << mType << ": requested patch has empty sinks list";
1073         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1074     }
1075     if (!all_unique<int32_t>(in_requested.sinkPortConfigIds)) {
1076         LOG(ERROR) << __func__ << ": " << mType
1077                    << ": requested patch has duplicate ids in the sinks list";
1078         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1079     }
1080 
1081     auto& configs = getConfig().portConfigs;
1082     std::vector<int32_t> missingIds;
1083     auto sources =
1084             selectByIds<AudioPortConfig>(configs, in_requested.sourcePortConfigIds, &missingIds);
1085     if (!missingIds.empty()) {
1086         LOG(ERROR) << __func__ << ": " << mType << ": following source port config ids not found: "
1087                    << ::android::internal::ToString(missingIds);
1088         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1089     }
1090     auto sinks = selectByIds<AudioPortConfig>(configs, in_requested.sinkPortConfigIds, &missingIds);
1091     if (!missingIds.empty()) {
1092         LOG(ERROR) << __func__ << ": " << mType << ": following sink port config ids not found: "
1093                    << ::android::internal::ToString(missingIds);
1094         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1095     }
1096     // bool indicates whether a non-exclusive route is available.
1097     // If only an exclusive route is available, that means the patch can not be
1098     // established if there is any other patch which currently uses the sink port.
1099     std::map<int32_t, bool> allowedSinkPorts;
1100     auto& routes = getConfig().routes;
1101     for (auto src : sources) {
1102         for (const auto& r : routes) {
1103             const auto& srcs = r.sourcePortIds;
1104             if (std::find(srcs.begin(), srcs.end(), src->portId) != srcs.end()) {
1105                 if (!allowedSinkPorts[r.sinkPortId]) {  // prefer non-exclusive
1106                     allowedSinkPorts[r.sinkPortId] = !r.isExclusive;
1107                 }
1108             }
1109         }
1110     }
1111     for (auto sink : sinks) {
1112         if (allowedSinkPorts.count(sink->portId) == 0) {
1113             LOG(ERROR) << __func__ << ": " << mType << ": there is no route to the sink port id "
1114                        << sink->portId;
1115             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1116         }
1117     }
1118     RETURN_STATUS_IF_ERROR(checkAudioPatchEndpointsMatch(sources, sinks));
1119 
1120     auto& patches = getConfig().patches;
1121     auto existing = patches.end();
1122     std::optional<decltype(mPatches)> patchesBackup;
1123     if (in_requested.id != 0) {
1124         existing = findById<AudioPatch>(patches, in_requested.id);
1125         if (existing != patches.end()) {
1126             patchesBackup = mPatches;
1127             cleanUpPatch(existing->id);
1128         } else {
1129             LOG(ERROR) << __func__ << ": " << mType << ": not found existing patch id "
1130                        << in_requested.id;
1131             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1132         }
1133     }
1134     // Validate the requested patch.
1135     for (const auto& [sinkPortId, nonExclusive] : allowedSinkPorts) {
1136         if (!nonExclusive && mPatches.count(sinkPortId) != 0) {
1137             LOG(ERROR) << __func__ << ": " << mType << ": sink port id " << sinkPortId
1138                        << "is exclusive and is already used by some other patch";
1139             if (patchesBackup.has_value()) {
1140                 mPatches = std::move(*patchesBackup);
1141             }
1142             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1143         }
1144     }
1145     // Find the highest sample rate among mix port configs.
1146     std::map<int32_t, AudioPortConfig*> sampleRates;
1147     std::vector<AudioPortConfig*>& mixPortConfigs =
1148             sources[0]->ext.getTag() == AudioPortExt::mix ? sources : sinks;
1149     for (auto mix : mixPortConfigs) {
1150         sampleRates.emplace(mix->sampleRate.value().value, mix);
1151     }
1152     *_aidl_return = in_requested;
1153     auto maxSampleRateIt = std::max_element(sampleRates.begin(), sampleRates.end());
1154     const int32_t latencyMs = getNominalLatencyMs(*(maxSampleRateIt->second));
1155     if (!calculateBufferSizeFrames(
1156                 maxSampleRateIt->second->format.value(), latencyMs, maxSampleRateIt->first,
1157                 &_aidl_return->minimumStreamBufferSizeFrames).isOk()) {
1158         if (patchesBackup.has_value()) {
1159             mPatches = std::move(*patchesBackup);
1160         }
1161         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1162     }
1163     _aidl_return->latenciesMs.clear();
1164     _aidl_return->latenciesMs.insert(_aidl_return->latenciesMs.end(),
1165                                      _aidl_return->sinkPortConfigIds.size(), latencyMs);
1166     AudioPatch oldPatch{};
1167     if (existing == patches.end()) {
1168         _aidl_return->id = getConfig().nextPatchId++;
1169         patches.push_back(*_aidl_return);
1170     } else {
1171         oldPatch = *existing;
1172         *existing = *_aidl_return;
1173     }
1174     patchesBackup = mPatches;
1175     registerPatch(*_aidl_return);
1176     if (auto status = updateStreamsConnectedState(oldPatch, *_aidl_return); !status.isOk()) {
1177         mPatches = std::move(*patchesBackup);
1178         if (existing == patches.end()) {
1179             patches.pop_back();
1180         } else {
1181             *existing = oldPatch;
1182         }
1183         return status;
1184     }
1185 
1186     LOG(DEBUG) << __func__ << ": " << mType << ": " << (oldPatch.id == 0 ? "created" : "updated")
1187                << " patch " << _aidl_return->toString();
1188     return ndk::ScopedAStatus::ok();
1189 }
1190 
setAudioPortConfig(const AudioPortConfig & in_requested,AudioPortConfig * out_suggested,bool * _aidl_return)1191 ndk::ScopedAStatus Module::setAudioPortConfig(const AudioPortConfig& in_requested,
1192                                               AudioPortConfig* out_suggested, bool* _aidl_return) {
1193     auto generate = [this](const AudioPort& port, AudioPortConfig* config) {
1194         return generateDefaultPortConfig(port, config);
1195     };
1196     return setAudioPortConfigImpl(in_requested, generate, out_suggested, _aidl_return);
1197 }
1198 
setAudioPortConfigImpl(const AudioPortConfig & in_requested,const std::function<bool (const::aidl::android::media::audio::common::AudioPort & port,::aidl::android::media::audio::common::AudioPortConfig * config)> & fillPortConfig,AudioPortConfig * out_suggested,bool * applied)1199 ndk::ScopedAStatus Module::setAudioPortConfigImpl(
1200         const AudioPortConfig& in_requested,
1201         const std::function<bool(const ::aidl::android::media::audio::common::AudioPort& port,
1202                                  ::aidl::android::media::audio::common::AudioPortConfig* config)>&
1203                 fillPortConfig,
1204         AudioPortConfig* out_suggested, bool* applied) {
1205     LOG(DEBUG) << __func__ << ": " << mType << ": requested " << in_requested.toString();
1206     auto& configs = getConfig().portConfigs;
1207     auto existing = configs.end();
1208     if (in_requested.id != 0) {
1209         if (existing = findById<AudioPortConfig>(configs, in_requested.id);
1210             existing == configs.end()) {
1211             LOG(ERROR) << __func__ << ": " << mType << ": existing port config id "
1212                        << in_requested.id << " not found";
1213             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1214         }
1215     }
1216 
1217     const int portId = existing != configs.end() ? existing->portId : in_requested.portId;
1218     if (portId == 0) {
1219         LOG(ERROR) << __func__ << ": " << mType
1220                    << ": requested port config does not specify portId";
1221         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1222     }
1223     auto& ports = getConfig().ports;
1224     auto portIt = findById<AudioPort>(ports, portId);
1225     if (portIt == ports.end()) {
1226         LOG(ERROR) << __func__ << ": " << mType
1227                    << ": requested port config points to non-existent portId " << portId;
1228         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1229     }
1230     if (existing != configs.end()) {
1231         *out_suggested = *existing;
1232     } else {
1233         AudioPortConfig newConfig;
1234         newConfig.portId = portIt->id;
1235         if (fillPortConfig(*portIt, &newConfig)) {
1236             *out_suggested = newConfig;
1237         } else {
1238             LOG(ERROR) << __func__ << ": " << mType
1239                        << ": unable generate a default config for port " << portId;
1240             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1241         }
1242     }
1243     // From this moment, 'out_suggested' is either an existing port config,
1244     // or a new generated config. Now attempt to update it according to the specified
1245     // fields of 'in_requested'.
1246 
1247     // Device ports with only dynamic profiles are used for devices that are connected via ADSP,
1248     // which takes care of their actual configuration automatically.
1249     const bool allowDynamicConfig = portIt->ext.getTag() == AudioPortExt::device &&
1250                                     hasDynamicProfilesOnly(portIt->profiles);
1251     bool requestedIsValid = true, requestedIsFullySpecified = true;
1252 
1253     AudioIoFlags portFlags = portIt->flags;
1254     if (in_requested.flags.has_value()) {
1255         if (in_requested.flags.value() != portFlags) {
1256             LOG(WARNING) << __func__ << ": " << mType << ": requested flags "
1257                          << in_requested.flags.value().toString() << " do not match port's "
1258                          << portId << " flags " << portFlags.toString();
1259             requestedIsValid = false;
1260         }
1261     } else {
1262         requestedIsFullySpecified = false;
1263     }
1264 
1265     AudioProfile portProfile;
1266     if (in_requested.format.has_value()) {
1267         const auto& format = in_requested.format.value();
1268         if ((format == AudioFormatDescription{} && allowDynamicConfig) ||
1269             findAudioProfile(*portIt, format, &portProfile)) {
1270             out_suggested->format = format;
1271         } else {
1272             LOG(WARNING) << __func__ << ": " << mType << ": requested format " << format.toString()
1273                          << " is not found in the profiles of port " << portId;
1274             requestedIsValid = false;
1275         }
1276     } else {
1277         requestedIsFullySpecified = false;
1278     }
1279     if (!(out_suggested->format.value() == AudioFormatDescription{} && allowDynamicConfig) &&
1280         !findAudioProfile(*portIt, out_suggested->format.value(), &portProfile)) {
1281         LOG(ERROR) << __func__ << ": " << mType << ": port " << portId
1282                    << " does not support format " << out_suggested->format.value().toString()
1283                    << " anymore";
1284         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1285     }
1286 
1287     if (in_requested.channelMask.has_value()) {
1288         const auto& channelMask = in_requested.channelMask.value();
1289         if ((channelMask == AudioChannelLayout{} && allowDynamicConfig) ||
1290             find(portProfile.channelMasks.begin(), portProfile.channelMasks.end(), channelMask) !=
1291                     portProfile.channelMasks.end()) {
1292             out_suggested->channelMask = channelMask;
1293         } else {
1294             LOG(WARNING) << __func__ << ": " << mType << ": requested channel mask "
1295                          << channelMask.toString() << " is not supported for the format "
1296                          << portProfile.format.toString() << " by the port " << portId;
1297             requestedIsValid = false;
1298         }
1299     } else {
1300         requestedIsFullySpecified = false;
1301     }
1302 
1303     if (in_requested.sampleRate.has_value()) {
1304         const auto& sampleRate = in_requested.sampleRate.value();
1305         if ((sampleRate.value == 0 && allowDynamicConfig) ||
1306             find(portProfile.sampleRates.begin(), portProfile.sampleRates.end(),
1307                  sampleRate.value) != portProfile.sampleRates.end()) {
1308             out_suggested->sampleRate = sampleRate;
1309         } else {
1310             LOG(WARNING) << __func__ << ": " << mType << ": requested sample rate "
1311                          << sampleRate.value << " is not supported for the format "
1312                          << portProfile.format.toString() << " by the port " << portId;
1313             requestedIsValid = false;
1314         }
1315     } else {
1316         requestedIsFullySpecified = false;
1317     }
1318 
1319     if (in_requested.gain.has_value()) {
1320         if (!setAudioPortConfigGain(*portIt, in_requested.gain.value())) {
1321             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1322         }
1323         out_suggested->gain = in_requested.gain.value();
1324     }
1325 
1326     if (in_requested.ext.getTag() != AudioPortExt::Tag::unspecified) {
1327         if (in_requested.ext.getTag() == out_suggested->ext.getTag()) {
1328             if (out_suggested->ext.getTag() == AudioPortExt::Tag::mix) {
1329                 // 'AudioMixPortExt.handle' and '.usecase' are set by the client,
1330                 // copy from in_requested.
1331                 const auto& src = in_requested.ext.get<AudioPortExt::Tag::mix>();
1332                 auto& dst = out_suggested->ext.get<AudioPortExt::Tag::mix>();
1333                 dst.handle = src.handle;
1334                 dst.usecase = src.usecase;
1335             }
1336         } else {
1337             LOG(WARNING) << __func__ << ": " << mType << ": requested ext tag "
1338                          << toString(in_requested.ext.getTag()) << " do not match port's tag "
1339                          << toString(out_suggested->ext.getTag());
1340             requestedIsValid = false;
1341         }
1342     }
1343 
1344     if (existing == configs.end() && requestedIsValid && requestedIsFullySpecified) {
1345         out_suggested->id = getConfig().nextPortId++;
1346         configs.push_back(*out_suggested);
1347         *applied = true;
1348         LOG(DEBUG) << __func__ << ": " << mType << ": created new port config "
1349                    << out_suggested->toString();
1350     } else if (existing != configs.end() && requestedIsValid) {
1351         *existing = *out_suggested;
1352         *applied = true;
1353         LOG(DEBUG) << __func__ << ": " << mType << ": updated port config "
1354                    << out_suggested->toString();
1355     } else {
1356         LOG(DEBUG) << __func__ << ": " << mType << ": not applied; existing config ? "
1357                    << (existing != configs.end()) << "; requested is valid? " << requestedIsValid
1358                    << ", fully specified? " << requestedIsFullySpecified;
1359         *applied = false;
1360     }
1361     return ndk::ScopedAStatus::ok();
1362 }
1363 
setAudioPortConfigGain(const AudioPort & port,const AudioGainConfig & gainRequested)1364 bool Module::setAudioPortConfigGain(const AudioPort& port, const AudioGainConfig& gainRequested) {
1365     auto& ports = getConfig().ports;
1366     if (gainRequested.index < 0 || gainRequested.index >= (int)port.gains.size()) {
1367         LOG(ERROR) << __func__ << ": gains for port " << port.id << " is undefined";
1368         return false;
1369     }
1370     int stepValue = port.gains[gainRequested.index].stepValue;
1371     if (stepValue == 0) {
1372         LOG(ERROR) << __func__ << ": port gain step value is 0";
1373         return false;
1374     }
1375     int minValue = port.gains[gainRequested.index].minValue;
1376     int maxValue = port.gains[gainRequested.index].maxValue;
1377     if (gainRequested.values[0] > maxValue || gainRequested.values[0] < minValue) {
1378         LOG(ERROR) << __func__ << ": gain value " << gainRequested.values[0]
1379                    << " out of range of min and max gain config";
1380         return false;
1381     }
1382     int gainIndex = (gainRequested.values[0] - minValue) / stepValue;
1383     int totalSteps = (maxValue - minValue) / stepValue;
1384     if (totalSteps == 0) {
1385         LOG(ERROR) << __func__ << ": difference between port gain min value " << minValue
1386                    << " and max value " << maxValue << " is less than step value " << stepValue;
1387         return false;
1388     }
1389     // Root-power quantities are used in curve:
1390     // 10^((minMb / 100 + (maxMb / 100 - minMb / 100) * gainIndex / totalSteps) / (10 * 2))
1391     // where 100 is the conversion from mB to dB, 10 comes from the log 10 conversion from power
1392     // ratios, and 2 means are the square of amplitude.
1393     float gain =
1394             pow(10, (minValue + (maxValue - minValue) * (gainIndex / (float)totalSteps)) / 2000);
1395     if (gain < 0) {
1396         LOG(ERROR) << __func__ << ": gain " << gain << " is less than 0";
1397         return false;
1398     }
1399     for (const auto& route : getConfig().routes) {
1400         if (route.sinkPortId != port.id) {
1401             continue;
1402         }
1403         for (const auto sourcePortId : route.sourcePortIds) {
1404             mStreams.setGain(sourcePortId, gain);
1405         }
1406     }
1407     return true;
1408 }
1409 
resetAudioPatch(int32_t in_patchId)1410 ndk::ScopedAStatus Module::resetAudioPatch(int32_t in_patchId) {
1411     auto& patches = getConfig().patches;
1412     auto patchIt = findById<AudioPatch>(patches, in_patchId);
1413     if (patchIt != patches.end()) {
1414         auto patchesBackup = mPatches;
1415         cleanUpPatch(patchIt->id);
1416         if (auto status = updateStreamsConnectedState(*patchIt, AudioPatch{}); !status.isOk()) {
1417             mPatches = std::move(patchesBackup);
1418             return status;
1419         }
1420         patches.erase(patchIt);
1421         LOG(DEBUG) << __func__ << ": " << mType << ": erased patch " << in_patchId;
1422         return ndk::ScopedAStatus::ok();
1423     }
1424     LOG(ERROR) << __func__ << ": " << mType << ": patch id " << in_patchId << " not found";
1425     return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1426 }
1427 
resetAudioPortConfig(int32_t in_portConfigId)1428 ndk::ScopedAStatus Module::resetAudioPortConfig(int32_t in_portConfigId) {
1429     auto& configs = getConfig().portConfigs;
1430     auto configIt = findById<AudioPortConfig>(configs, in_portConfigId);
1431     if (configIt != configs.end()) {
1432         if (mStreams.count(in_portConfigId) != 0) {
1433             LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1434                        << " has a stream opened on it";
1435             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1436         }
1437         auto patchIt = mPatches.find(in_portConfigId);
1438         if (patchIt != mPatches.end()) {
1439             LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1440                        << " is used by the patch with id " << patchIt->second;
1441             return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1442         }
1443         auto& initials = getConfig().initialConfigs;
1444         auto initialIt = findById<AudioPortConfig>(initials, in_portConfigId);
1445         if (initialIt == initials.end()) {
1446             configs.erase(configIt);
1447             LOG(DEBUG) << __func__ << ": " << mType << ": erased port config " << in_portConfigId;
1448         } else if (*configIt != *initialIt) {
1449             *configIt = *initialIt;
1450             LOG(DEBUG) << __func__ << ": " << mType << ": reset port config " << in_portConfigId;
1451         }
1452         return ndk::ScopedAStatus::ok();
1453     }
1454     LOG(ERROR) << __func__ << ": " << mType << ": port config id " << in_portConfigId
1455                << " not found";
1456     return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1457 }
1458 
getMasterMute(bool * _aidl_return)1459 ndk::ScopedAStatus Module::getMasterMute(bool* _aidl_return) {
1460     *_aidl_return = mMasterMute;
1461     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1462     return ndk::ScopedAStatus::ok();
1463 }
1464 
setMasterMute(bool in_mute)1465 ndk::ScopedAStatus Module::setMasterMute(bool in_mute) {
1466     LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
1467     auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1468                                                    : onMasterMuteChanged(in_mute);
1469     if (result.isOk()) {
1470         mMasterMute = in_mute;
1471     } else {
1472         LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterMuteChanged("
1473                    << in_mute << "), error=" << result;
1474         // Reset master mute if it failed.
1475         onMasterMuteChanged(mMasterMute);
1476     }
1477     return result;
1478 }
1479 
getMasterVolume(float * _aidl_return)1480 ndk::ScopedAStatus Module::getMasterVolume(float* _aidl_return) {
1481     *_aidl_return = mMasterVolume;
1482     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1483     return ndk::ScopedAStatus::ok();
1484 }
1485 
setMasterVolume(float in_volume)1486 ndk::ScopedAStatus Module::setMasterVolume(float in_volume) {
1487     LOG(DEBUG) << __func__ << ": " << mType << ": " << in_volume;
1488     if (in_volume >= 0.0f && in_volume <= 1.0f) {
1489         auto result = mDebug.simulateDeviceConnections ? ndk::ScopedAStatus::ok()
1490                                                        : onMasterVolumeChanged(in_volume);
1491         if (result.isOk()) {
1492             mMasterVolume = in_volume;
1493         } else {
1494             // Reset master volume if it failed.
1495             LOG(ERROR) << __func__ << ": " << mType << ": failed calling onMasterVolumeChanged("
1496                        << in_volume << "), error=" << result;
1497             onMasterVolumeChanged(mMasterVolume);
1498         }
1499         return result;
1500     }
1501     LOG(ERROR) << __func__ << ": " << mType << ": invalid master volume value: " << in_volume;
1502     return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1503 }
1504 
getMicMute(bool * _aidl_return)1505 ndk::ScopedAStatus Module::getMicMute(bool* _aidl_return) {
1506     *_aidl_return = mMicMute;
1507     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1508     return ndk::ScopedAStatus::ok();
1509 }
1510 
setMicMute(bool in_mute)1511 ndk::ScopedAStatus Module::setMicMute(bool in_mute) {
1512     LOG(DEBUG) << __func__ << ": " << mType << ": " << in_mute;
1513     mMicMute = in_mute;
1514     return ndk::ScopedAStatus::ok();
1515 }
1516 
getMicrophones(std::vector<MicrophoneInfo> * _aidl_return)1517 ndk::ScopedAStatus Module::getMicrophones(std::vector<MicrophoneInfo>* _aidl_return) {
1518     *_aidl_return = getMicrophoneInfos();
1519     LOG(DEBUG) << __func__ << ": " << mType << ": returning "
1520                << ::android::internal::ToString(*_aidl_return);
1521     return ndk::ScopedAStatus::ok();
1522 }
1523 
updateAudioMode(AudioMode in_mode)1524 ndk::ScopedAStatus Module::updateAudioMode(AudioMode in_mode) {
1525     if (!isValidAudioMode(in_mode)) {
1526         LOG(ERROR) << __func__ << ": " << mType << ": invalid mode " << toString(in_mode);
1527         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1528     }
1529     // No checks for supported audio modes here, it's an informative notification.
1530     LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_mode);
1531     return ndk::ScopedAStatus::ok();
1532 }
1533 
updateScreenRotation(ScreenRotation in_rotation)1534 ndk::ScopedAStatus Module::updateScreenRotation(ScreenRotation in_rotation) {
1535     LOG(DEBUG) << __func__ << ": " << mType << ": " << toString(in_rotation);
1536     return ndk::ScopedAStatus::ok();
1537 }
1538 
updateScreenState(bool in_isTurnedOn)1539 ndk::ScopedAStatus Module::updateScreenState(bool in_isTurnedOn) {
1540     LOG(DEBUG) << __func__ << ": " << mType << ": " << in_isTurnedOn;
1541     return ndk::ScopedAStatus::ok();
1542 }
1543 
getSoundDose(std::shared_ptr<ISoundDose> * _aidl_return)1544 ndk::ScopedAStatus Module::getSoundDose(std::shared_ptr<ISoundDose>* _aidl_return) {
1545     if (!mSoundDose) {
1546         mSoundDose = ndk::SharedRefBase::make<sounddose::SoundDose>();
1547     }
1548     *_aidl_return = mSoundDose.getInstance();
1549     LOG(DEBUG) << __func__ << ": " << mType
1550                << ": returning instance of ISoundDose: " << _aidl_return->get();
1551     return ndk::ScopedAStatus::ok();
1552 }
1553 
generateHwAvSyncId(int32_t * _aidl_return)1554 ndk::ScopedAStatus Module::generateHwAvSyncId(int32_t* _aidl_return) {
1555     LOG(DEBUG) << __func__ << ": " << mType;
1556     (void)_aidl_return;
1557     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1558 }
1559 
1560 const std::string Module::VendorDebug::kForceTransientBurstName = "aosp.forceTransientBurst";
1561 const std::string Module::VendorDebug::kForceSynchronousDrainName = "aosp.forceSynchronousDrain";
1562 const std::string Module::kClipTransitionSupportName = "aosp.clipTransitionSupport";
1563 
getVendorParameters(const std::vector<std::string> & in_ids,std::vector<VendorParameter> * _aidl_return)1564 ndk::ScopedAStatus Module::getVendorParameters(const std::vector<std::string>& in_ids,
1565                                                std::vector<VendorParameter>* _aidl_return) {
1566     LOG(VERBOSE) << __func__ << ": " << mType << ": id count: " << in_ids.size();
1567     bool allParametersKnown = true;
1568     for (const auto& id : in_ids) {
1569         if (id == VendorDebug::kForceTransientBurstName) {
1570             VendorParameter forceTransientBurst{.id = id};
1571             forceTransientBurst.ext.setParcelable(Boolean{mVendorDebug.forceTransientBurst});
1572             _aidl_return->push_back(std::move(forceTransientBurst));
1573         } else if (id == VendorDebug::kForceSynchronousDrainName) {
1574             VendorParameter forceSynchronousDrain{.id = id};
1575             forceSynchronousDrain.ext.setParcelable(Boolean{mVendorDebug.forceSynchronousDrain});
1576             _aidl_return->push_back(std::move(forceSynchronousDrain));
1577         } else if (id == kClipTransitionSupportName) {
1578             VendorParameter clipTransitionSupport{.id = id};
1579             clipTransitionSupport.ext.setParcelable(Boolean{true});
1580             _aidl_return->push_back(std::move(clipTransitionSupport));
1581         } else {
1582             allParametersKnown = false;
1583             LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << id << "\"";
1584         }
1585     }
1586     if (allParametersKnown) return ndk::ScopedAStatus::ok();
1587     return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1588 }
1589 
1590 namespace {
1591 
1592 template <typename W>
extractParameter(const VendorParameter & p,decltype(W::value) * v)1593 bool extractParameter(const VendorParameter& p, decltype(W::value)* v) {
1594     std::optional<W> value;
1595     binder_status_t result = p.ext.getParcelable(&value);
1596     if (result == STATUS_OK && value.has_value()) {
1597         *v = value.value().value;
1598         return true;
1599     }
1600     LOG(ERROR) << __func__ << ": failed to read the value of the parameter \"" << p.id
1601                << "\": " << result;
1602     return false;
1603 }
1604 
1605 }  // namespace
1606 
setVendorParameters(const std::vector<VendorParameter> & in_parameters,bool in_async)1607 ndk::ScopedAStatus Module::setVendorParameters(const std::vector<VendorParameter>& in_parameters,
1608                                                bool in_async) {
1609     LOG(VERBOSE) << __func__ << ": " << mType << ": parameter count " << in_parameters.size()
1610                  << ", async: " << in_async;
1611     bool allParametersKnown = true;
1612     for (const auto& p : in_parameters) {
1613         if (p.id == VendorDebug::kForceTransientBurstName) {
1614             if (!extractParameter<Boolean>(p, &mVendorDebug.forceTransientBurst)) {
1615                 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1616             }
1617         } else if (p.id == VendorDebug::kForceSynchronousDrainName) {
1618             if (!extractParameter<Boolean>(p, &mVendorDebug.forceSynchronousDrain)) {
1619                 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1620             }
1621         } else {
1622             allParametersKnown = false;
1623             LOG(VERBOSE) << __func__ << ": " << mType << ": unrecognized parameter \"" << p.id
1624                          << "\"";
1625         }
1626     }
1627     if (allParametersKnown) return ndk::ScopedAStatus::ok();
1628     return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1629 }
1630 
addDeviceEffect(int32_t in_portConfigId,const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> & in_effect)1631 ndk::ScopedAStatus Module::addDeviceEffect(
1632         int32_t in_portConfigId,
1633         const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1634     if (in_effect == nullptr) {
1635         LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1636                    << ", null effect";
1637     } else {
1638         LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1639                    << ", effect Binder " << in_effect->asBinder().get();
1640     }
1641     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1642 }
1643 
removeDeviceEffect(int32_t in_portConfigId,const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> & in_effect)1644 ndk::ScopedAStatus Module::removeDeviceEffect(
1645         int32_t in_portConfigId,
1646         const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
1647     if (in_effect == nullptr) {
1648         LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1649                    << ", null effect";
1650     } else {
1651         LOG(DEBUG) << __func__ << ": " << mType << ": port id " << in_portConfigId
1652                    << ", effect Binder " << in_effect->asBinder().get();
1653     }
1654     return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1655 }
1656 
getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,std::vector<AudioMMapPolicyInfo> * _aidl_return)1657 ndk::ScopedAStatus Module::getMmapPolicyInfos(AudioMMapPolicyType mmapPolicyType,
1658                                               std::vector<AudioMMapPolicyInfo>* _aidl_return) {
1659     LOG(DEBUG) << __func__ << ": " << mType << ": mmap policy type " << toString(mmapPolicyType);
1660     std::set<int32_t> mmapSinks;
1661     std::set<int32_t> mmapSources;
1662     auto& ports = getConfig().ports;
1663     for (const auto& port : ports) {
1664         if (port.flags.getTag() == AudioIoFlags::Tag::input &&
1665             isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::input>(),
1666                                  AudioInputFlags::MMAP_NOIRQ)) {
1667             mmapSinks.insert(port.id);
1668         } else if (port.flags.getTag() == AudioIoFlags::Tag::output &&
1669                    isBitPositionFlagSet(port.flags.get<AudioIoFlags::Tag::output>(),
1670                                         AudioOutputFlags::MMAP_NOIRQ)) {
1671             mmapSources.insert(port.id);
1672         }
1673     }
1674     if (mmapSources.empty() && mmapSinks.empty()) {
1675         AudioMMapPolicyInfo never;
1676         never.mmapPolicy = AudioMMapPolicy::NEVER;
1677         _aidl_return->push_back(never);
1678         return ndk::ScopedAStatus::ok();
1679     }
1680     for (const auto& route : getConfig().routes) {
1681         if (mmapSinks.count(route.sinkPortId) != 0) {
1682             // The sink is a mix port, add the sources if they are device ports.
1683             for (int sourcePortId : route.sourcePortIds) {
1684                 auto sourcePortIt = findById<AudioPort>(ports, sourcePortId);
1685                 if (sourcePortIt == ports.end()) {
1686                     // This must not happen
1687                     LOG(ERROR) << __func__ << ": " << mType << ": port id " << sourcePortId
1688                                << " cannot be found";
1689                     continue;
1690                 }
1691                 if (sourcePortIt->ext.getTag() != AudioPortExt::Tag::device) {
1692                     // The source is not a device port, skip
1693                     continue;
1694                 }
1695                 AudioMMapPolicyInfo policyInfo;
1696                 policyInfo.device = sourcePortIt->ext.get<AudioPortExt::Tag::device>().device;
1697                 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1698                 // default implementation.
1699                 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1700                 _aidl_return->push_back(policyInfo);
1701             }
1702         } else {
1703             auto sinkPortIt = findById<AudioPort>(ports, route.sinkPortId);
1704             if (sinkPortIt == ports.end()) {
1705                 // This must not happen
1706                 LOG(ERROR) << __func__ << ": " << mType << ": port id " << route.sinkPortId
1707                            << " cannot be found";
1708                 continue;
1709             }
1710             if (sinkPortIt->ext.getTag() != AudioPortExt::Tag::device) {
1711                 // The sink is not a device port, skip
1712                 continue;
1713             }
1714             if (count_any(mmapSources, route.sourcePortIds)) {
1715                 AudioMMapPolicyInfo policyInfo;
1716                 policyInfo.device = sinkPortIt->ext.get<AudioPortExt::Tag::device>().device;
1717                 // Always return AudioMMapPolicy.AUTO if the device supports mmap for
1718                 // default implementation.
1719                 policyInfo.mmapPolicy = AudioMMapPolicy::AUTO;
1720                 _aidl_return->push_back(policyInfo);
1721             }
1722         }
1723     }
1724     return ndk::ScopedAStatus::ok();
1725 }
1726 
supportsVariableLatency(bool * _aidl_return)1727 ndk::ScopedAStatus Module::supportsVariableLatency(bool* _aidl_return) {
1728     LOG(DEBUG) << __func__ << ": " << mType;
1729     *_aidl_return = false;
1730     return ndk::ScopedAStatus::ok();
1731 }
1732 
getAAudioMixerBurstCount(int32_t * _aidl_return)1733 ndk::ScopedAStatus Module::getAAudioMixerBurstCount(int32_t* _aidl_return) {
1734     if (!isMmapSupported()) {
1735         LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
1736         return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1737     }
1738     *_aidl_return = DEFAULT_AAUDIO_MIXER_BURST_COUNT;
1739     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1740     return ndk::ScopedAStatus::ok();
1741 }
1742 
getAAudioHardwareBurstMinUsec(int32_t * _aidl_return)1743 ndk::ScopedAStatus Module::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) {
1744     if (!isMmapSupported()) {
1745         LOG(DEBUG) << __func__ << ": " << mType << ": mmap is not supported ";
1746         return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1747     }
1748     *_aidl_return = DEFAULT_AAUDIO_HARDWARE_BURST_MIN_DURATION_US;
1749     LOG(DEBUG) << __func__ << ": " << mType << ": returning " << *_aidl_return;
1750     return ndk::ScopedAStatus::ok();
1751 }
1752 
isMmapSupported()1753 bool Module::isMmapSupported() {
1754     if (mIsMmapSupported.has_value()) {
1755         return mIsMmapSupported.value();
1756     }
1757     std::vector<AudioMMapPolicyInfo> mmapPolicyInfos;
1758     if (!getMmapPolicyInfos(AudioMMapPolicyType::DEFAULT, &mmapPolicyInfos).isOk()) {
1759         mIsMmapSupported = false;
1760     } else {
1761         mIsMmapSupported =
1762                 std::find_if(mmapPolicyInfos.begin(), mmapPolicyInfos.end(), [](const auto& info) {
1763                     return info.mmapPolicy == AudioMMapPolicy::AUTO ||
1764                            info.mmapPolicy == AudioMMapPolicy::ALWAYS;
1765                 }) != mmapPolicyInfos.end();
1766     }
1767     return mIsMmapSupported.value();
1768 }
1769 
populateConnectedDevicePort(AudioPort * audioPort,int32_t)1770 ndk::ScopedAStatus Module::populateConnectedDevicePort(AudioPort* audioPort, int32_t) {
1771     if (audioPort->ext.getTag() != AudioPortExt::device) {
1772         LOG(ERROR) << __func__ << ": " << mType << ": not a device port: " << audioPort->toString();
1773         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1774     }
1775     const auto& devicePort = audioPort->ext.get<AudioPortExt::device>();
1776     if (!devicePort.device.type.connection.empty()) {
1777         LOG(ERROR) << __func__ << ": " << mType << ": module implementation must override "
1778                                                   "'populateConnectedDevicePort' "
1779                    << "to handle connection of external devices.";
1780         return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1781     }
1782     LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1783     return ndk::ScopedAStatus::ok();
1784 }
1785 
checkAudioPatchEndpointsMatch(const std::vector<AudioPortConfig * > & sources __unused,const std::vector<AudioPortConfig * > & sinks __unused)1786 ndk::ScopedAStatus Module::checkAudioPatchEndpointsMatch(
1787         const std::vector<AudioPortConfig*>& sources __unused,
1788         const std::vector<AudioPortConfig*>& sinks __unused) {
1789     LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1790     return ndk::ScopedAStatus::ok();
1791 }
1792 
onExternalDeviceConnectionChanged(const::aidl::android::media::audio::common::AudioPort & audioPort __unused,bool connected __unused)1793 void Module::onExternalDeviceConnectionChanged(
1794         const ::aidl::android::media::audio::common::AudioPort& audioPort __unused,
1795         bool connected __unused) {
1796     LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
1797 }
1798 
onPrepareToDisconnectExternalDevice(const::aidl::android::media::audio::common::AudioPort & audioPort __unused)1799 void Module::onPrepareToDisconnectExternalDevice(
1800         const ::aidl::android::media::audio::common::AudioPort& audioPort __unused) {
1801     LOG(DEBUG) << __func__ << ": " << mType << ": do nothing and return";
1802 }
1803 
onMasterMuteChanged(bool mute __unused)1804 ndk::ScopedAStatus Module::onMasterMuteChanged(bool mute __unused) {
1805     LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1806     return ndk::ScopedAStatus::ok();
1807 }
1808 
onMasterVolumeChanged(float volume __unused)1809 ndk::ScopedAStatus Module::onMasterVolumeChanged(float volume __unused) {
1810     LOG(VERBOSE) << __func__ << ": " << mType << ": do nothing and return ok";
1811     return ndk::ScopedAStatus::ok();
1812 }
1813 
getMicrophoneInfos()1814 std::vector<MicrophoneInfo> Module::getMicrophoneInfos() {
1815     std::vector<MicrophoneInfo> result;
1816     Configuration& config = getConfig();
1817     for (const AudioPort& port : config.ports) {
1818         if (port.ext.getTag() == AudioPortExt::Tag::device) {
1819             const AudioDeviceType deviceType =
1820                     port.ext.get<AudioPortExt::Tag::device>().device.type.type;
1821             if (deviceType == AudioDeviceType::IN_MICROPHONE ||
1822                 deviceType == AudioDeviceType::IN_MICROPHONE_BACK) {
1823                 // Placeholder values. Vendor implementations must populate MicrophoneInfo
1824                 // accordingly based on their physical microphone parameters.
1825                 result.push_back(MicrophoneInfo{
1826                         .id = port.name,
1827                         .device = port.ext.get<AudioPortExt::Tag::device>().device,
1828                         .group = 0,
1829                         .indexInTheGroup = 0,
1830                 });
1831             }
1832         }
1833     }
1834     return result;
1835 }
1836 
bluetoothParametersUpdated()1837 ndk::ScopedAStatus Module::bluetoothParametersUpdated() {
1838     return mStreams.bluetoothParametersUpdated();
1839 }
1840 
1841 }  // namespace aidl::android::hardware::audio::core
1842