1 /*
2 * Copyright (C) 2020 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 #define LOG_TAG "AudioControl"
18 // #define LOG_NDEBUG 0
19
20 #include "AudioControl.h"
21
22 #include <aidl/android/hardware/automotive/audiocontrol/AudioFocusChange.h>
23 #include <aidl/android/hardware/automotive/audiocontrol/DuckingInfo.h>
24 #include <aidl/android/hardware/automotive/audiocontrol/IFocusListener.h>
25
26 #include <android-base/logging.h>
27 #include <android-base/parsebool.h>
28 #include <android-base/parseint.h>
29 #include <android-base/strings.h>
30
31 #include <android_audio_policy_configuration_V7_0-enums.h>
32 #include <private/android_filesystem_config.h>
33
34 #include <numeric>
35
36 #include <stdio.h>
37
38 namespace aidl::android::hardware::automotive::audiocontrol {
39
40 using ::android::base::EqualsIgnoreCase;
41 using ::android::base::ParseBool;
42 using ::android::base::ParseBoolResult;
43 using ::android::base::ParseInt;
44 using ::std::shared_ptr;
45 using ::std::string;
46
47 namespace xsd {
48 using namespace ::android::audio::policy::configuration::V7_0;
49 }
50
51 namespace {
52 const float kLowerBound = -1.0f;
53 const float kUpperBound = 1.0f;
checkCallerHasWritePermissions(int fd)54 bool checkCallerHasWritePermissions(int fd) {
55 // Double check that's only called by root - it should be be blocked at debug() level,
56 // but it doesn't hurt to make sure...
57 if (AIBinder_getCallingUid() != AID_ROOT) {
58 dprintf(fd, "Must be root\n");
59 return false;
60 }
61 return true;
62 }
63
isValidValue(float value)64 bool isValidValue(float value) {
65 return (value >= kLowerBound) && (value <= kUpperBound);
66 }
67
safelyParseInt(string s,int * out)68 bool safelyParseInt(string s, int* out) {
69 if (!ParseInt(s, out)) {
70 return false;
71 }
72 return true;
73 }
74 } // namespace
75
76 namespace {
77 using ::aidl::android::media::audio::common::AudioChannelLayout;
78 using ::aidl::android::media::audio::common::AudioDeviceDescription;
79 using ::aidl::android::media::audio::common::AudioDeviceType;
80 using ::aidl::android::media::audio::common::AudioFormatDescription;
81 using ::aidl::android::media::audio::common::AudioFormatType;
82 using ::aidl::android::media::audio::common::AudioGain;
83 using ::aidl::android::media::audio::common::AudioGainMode;
84 using ::aidl::android::media::audio::common::AudioIoFlags;
85 using ::aidl::android::media::audio::common::AudioOutputFlags;
86 using ::aidl::android::media::audio::common::AudioPort;
87 using ::aidl::android::media::audio::common::AudioPortDeviceExt;
88 using ::aidl::android::media::audio::common::AudioPortExt;
89 using ::aidl::android::media::audio::common::AudioPortMixExt;
90 using ::aidl::android::media::audio::common::AudioProfile;
91 using ::aidl::android::media::audio::common::PcmType;
92
93 // reuse common code artifacts
fillProfile(const std::vector<int32_t> & channelLayouts,const std::vector<int32_t> & sampleRates,AudioProfile * profile)94 void fillProfile(const std::vector<int32_t>& channelLayouts,
95 const std::vector<int32_t>& sampleRates, AudioProfile* profile) {
96 for (auto layout : channelLayouts) {
97 profile->channelMasks.push_back(
98 AudioChannelLayout::make<AudioChannelLayout::layoutMask>(layout));
99 }
100 profile->sampleRates.insert(profile->sampleRates.end(), sampleRates.begin(), sampleRates.end());
101 }
102
createProfile(PcmType pcmType,const std::vector<int32_t> & channelLayouts,const std::vector<int32_t> & sampleRates)103 AudioProfile createProfile(PcmType pcmType, const std::vector<int32_t>& channelLayouts,
104 const std::vector<int32_t>& sampleRates) {
105 AudioProfile profile;
106 profile.format.type = AudioFormatType::PCM;
107 profile.format.pcm = pcmType;
108 fillProfile(channelLayouts, sampleRates, &profile);
109 return profile;
110 }
111
createProfile(const std::string & encodingType,const std::vector<int32_t> & channelLayouts,const std::vector<int32_t> & sampleRates)112 AudioProfile createProfile(const std::string& encodingType,
113 const std::vector<int32_t>& channelLayouts,
114 const std::vector<int32_t>& sampleRates) {
115 AudioProfile profile;
116 profile.format.encoding = encodingType;
117 fillProfile(channelLayouts, sampleRates, &profile);
118 return profile;
119 }
120
createDeviceExt(AudioDeviceType devType,int32_t flags,const std::string & connection="",const std::string & address="")121 AudioPortExt createDeviceExt(AudioDeviceType devType, int32_t flags,
122 const std::string& connection = "", const std::string& address = "") {
123 AudioPortDeviceExt deviceExt;
124 deviceExt.device.type.type = devType;
125 if (devType == AudioDeviceType::IN_MICROPHONE && connection.empty()) {
126 deviceExt.device.address = "bottom";
127 } else if (devType == AudioDeviceType::IN_MICROPHONE_BACK && connection.empty()) {
128 deviceExt.device.address = "back";
129 } else {
130 deviceExt.device.address = std::move(address);
131 }
132 deviceExt.device.type.connection = std::move(connection);
133 deviceExt.flags = flags;
134 return AudioPortExt::make<AudioPortExt::Tag::device>(deviceExt);
135 }
136
createPort(int32_t id,const std::string & name,int32_t flags,bool isInput,const AudioPortExt & ext)137 AudioPort createPort(int32_t id, const std::string& name, int32_t flags, bool isInput,
138 const AudioPortExt& ext) {
139 AudioPort port;
140 port.id = id;
141 port.name = name;
142 port.flags = isInput ? AudioIoFlags::make<AudioIoFlags::Tag::input>(flags)
143 : AudioIoFlags::make<AudioIoFlags::Tag::output>(flags);
144 port.ext = ext;
145 return port;
146 }
147
createGain(int32_t mode,AudioChannelLayout channelMask,int32_t minValue,int32_t maxValue,int32_t defaultValue,int32_t stepValue,int32_t minRampMs=100,int32_t maxRampMs=100,bool useForVolume=true)148 AudioGain createGain(int32_t mode, AudioChannelLayout channelMask, int32_t minValue,
149 int32_t maxValue, int32_t defaultValue, int32_t stepValue,
150 int32_t minRampMs = 100, int32_t maxRampMs = 100, bool useForVolume = true) {
151 AudioGain gain;
152 gain.mode = mode;
153 gain.channelMask = channelMask;
154 gain.minValue = minValue;
155 gain.maxValue = maxValue;
156 gain.defaultValue = defaultValue;
157 gain.stepValue = stepValue;
158 gain.minRampMs = minRampMs;
159 gain.maxRampMs = maxRampMs;
160 gain.useForVolume = useForVolume;
161 return gain;
162 }
163 } // namespace
164
registerFocusListener(const shared_ptr<IFocusListener> & in_listener)165 ndk::ScopedAStatus AudioControl::registerFocusListener(
166 const shared_ptr<IFocusListener>& in_listener) {
167 LOG(DEBUG) << "registering focus listener";
168
169 if (in_listener) {
170 std::atomic_store(&mFocusListener, in_listener);
171 } else {
172 LOG(ERROR) << "Unexpected nullptr for listener resulting in no-op.";
173 }
174 return ndk::ScopedAStatus::ok();
175 }
176
setBalanceTowardRight(float value)177 ndk::ScopedAStatus AudioControl::setBalanceTowardRight(float value) {
178 if (isValidValue(value)) {
179 // Just log in this default mock implementation
180 LOG(INFO) << "Balance set to " << value;
181 return ndk::ScopedAStatus::ok();
182 }
183
184 LOG(ERROR) << "Balance value out of range -1 to 1 at " << value;
185 return ndk::ScopedAStatus::ok();
186 }
187
setFadeTowardFront(float value)188 ndk::ScopedAStatus AudioControl::setFadeTowardFront(float value) {
189 if (isValidValue(value)) {
190 // Just log in this default mock implementation
191 LOG(INFO) << "Fader set to " << value;
192 return ndk::ScopedAStatus::ok();
193 }
194
195 LOG(ERROR) << "Fader value out of range -1 to 1 at " << value;
196 return ndk::ScopedAStatus::ok();
197 }
198
onAudioFocusChange(const string & in_usage,int32_t in_zoneId,AudioFocusChange in_focusChange)199 ndk::ScopedAStatus AudioControl::onAudioFocusChange(const string& in_usage, int32_t in_zoneId,
200 AudioFocusChange in_focusChange) {
201 LOG(INFO) << "Focus changed: " << toString(in_focusChange).c_str() << " for usage "
202 << in_usage.c_str() << " in zone " << in_zoneId;
203 return ndk::ScopedAStatus::ok();
204 }
205
onDevicesToDuckChange(const std::vector<DuckingInfo> & in_duckingInfos)206 ndk::ScopedAStatus AudioControl::onDevicesToDuckChange(
207 const std::vector<DuckingInfo>& in_duckingInfos) {
208 LOG(INFO) << "AudioControl::onDevicesToDuckChange";
209 for (const DuckingInfo& duckingInfo : in_duckingInfos) {
210 LOG(INFO) << "zone: " << duckingInfo.zoneId;
211 LOG(INFO) << "Devices to duck:";
212 for (const auto& addressToDuck : duckingInfo.deviceAddressesToDuck) {
213 LOG(INFO) << addressToDuck;
214 }
215 LOG(INFO) << "Devices to unduck:";
216 for (const auto& addressToUnduck : duckingInfo.deviceAddressesToUnduck) {
217 LOG(INFO) << addressToUnduck;
218 }
219 LOG(INFO) << "Usages holding focus:";
220 for (const auto& usage : duckingInfo.usagesHoldingFocus) {
221 LOG(INFO) << usage;
222 }
223 }
224 return ndk::ScopedAStatus::ok();
225 }
226
onDevicesToMuteChange(const std::vector<MutingInfo> & in_mutingInfos)227 ndk::ScopedAStatus AudioControl::onDevicesToMuteChange(
228 const std::vector<MutingInfo>& in_mutingInfos) {
229 LOG(INFO) << "AudioControl::onDevicesToMuteChange";
230 for (const MutingInfo& mutingInfo : in_mutingInfos) {
231 LOG(INFO) << "zone: " << mutingInfo.zoneId;
232 LOG(INFO) << "Devices to mute:";
233 for (const auto& addressToMute : mutingInfo.deviceAddressesToMute) {
234 LOG(INFO) << addressToMute;
235 }
236 LOG(INFO) << "Devices to unmute:";
237 for (const auto& addressToUnmute : mutingInfo.deviceAddressesToUnmute) {
238 LOG(INFO) << addressToUnmute;
239 }
240 }
241 return ndk::ScopedAStatus::ok();
242 }
243
244 template <typename aidl_type>
toString(const std::vector<aidl_type> & in_values)245 static inline std::string toString(const std::vector<aidl_type>& in_values) {
246 return std::accumulate(std::begin(in_values), std::end(in_values), std::string{},
247 [](const std::string& ls, const aidl_type& rs) {
248 return ls + (ls.empty() ? "" : ",") + rs.toString();
249 });
250 }
251 template <typename aidl_enum_type>
toEnumString(const std::vector<aidl_enum_type> & in_values)252 static inline std::string toEnumString(const std::vector<aidl_enum_type>& in_values) {
253 return std::accumulate(std::begin(in_values), std::end(in_values), std::string{},
254 [](const std::string& ls, const aidl_enum_type& rs) {
255 return ls + (ls.empty() ? "" : ",") + toString(rs);
256 });
257 }
258
onAudioFocusChangeWithMetaData(const audiohalcommon::PlaybackTrackMetadata & in_playbackMetaData,int32_t in_zoneId,AudioFocusChange in_focusChange)259 ndk::ScopedAStatus AudioControl::onAudioFocusChangeWithMetaData(
260 const audiohalcommon::PlaybackTrackMetadata& in_playbackMetaData, int32_t in_zoneId,
261 AudioFocusChange in_focusChange) {
262 LOG(INFO) << "Focus changed: " << toString(in_focusChange).c_str() << " for metadata "
263 << in_playbackMetaData.toString().c_str() << " in zone " << in_zoneId;
264 return ndk::ScopedAStatus::ok();
265 }
266
setAudioDeviceGainsChanged(const std::vector<Reasons> & in_reasons,const std::vector<AudioGainConfigInfo> & in_gains)267 ndk::ScopedAStatus AudioControl::setAudioDeviceGainsChanged(
268 const std::vector<Reasons>& in_reasons, const std::vector<AudioGainConfigInfo>& in_gains) {
269 LOG(INFO) << "Audio Device Gains changed: resons:" << toEnumString(in_reasons).c_str()
270 << " for devices: " << toString(in_gains).c_str();
271 return ndk::ScopedAStatus::ok();
272 }
273
registerGainCallback(const std::shared_ptr<IAudioGainCallback> & in_callback)274 ndk::ScopedAStatus AudioControl::registerGainCallback(
275 const std::shared_ptr<IAudioGainCallback>& in_callback) {
276 LOG(DEBUG) << ": " << __func__;
277 if (in_callback) {
278 std::atomic_store(&mAudioGainCallback, in_callback);
279 } else {
280 LOG(ERROR) << "Unexpected nullptr for audio gain callback resulting in no-op.";
281 }
282 return ndk::ScopedAStatus::ok();
283 }
284
setModuleChangeCallback(const std::shared_ptr<IModuleChangeCallback> & in_callback)285 ndk::ScopedAStatus AudioControl::setModuleChangeCallback(
286 const std::shared_ptr<IModuleChangeCallback>& in_callback) {
287 LOG(DEBUG) << ": " << __func__;
288
289 if (in_callback.get() == nullptr) {
290 LOG(ERROR) << __func__ << ": Callback is nullptr";
291 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
292 }
293 if (mModuleChangeCallback != nullptr) {
294 LOG(ERROR) << __func__ << ": Module change callback was already registered";
295 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
296 }
297 std::atomic_store(&mModuleChangeCallback, in_callback);
298 return ndk::ScopedAStatus::ok();
299 }
300
clearModuleChangeCallback()301 ndk::ScopedAStatus AudioControl::clearModuleChangeCallback() {
302 if (mModuleChangeCallback != nullptr) {
303 shared_ptr<IModuleChangeCallback> nullCallback = nullptr;
304 std::atomic_store(&mModuleChangeCallback, nullCallback);
305 LOG(DEBUG) << ":" << __func__ << ": Unregistered successfully";
306 } else {
307 LOG(DEBUG) << ":" << __func__ << ": No callback registered, no-op";
308 }
309 return ndk::ScopedAStatus::ok();
310 }
311
dump(int fd,const char ** args,uint32_t numArgs)312 binder_status_t AudioControl::dump(int fd, const char** args, uint32_t numArgs) {
313 if (numArgs == 0) {
314 return dumpsys(fd);
315 }
316
317 string option = string(args[0]);
318 if (EqualsIgnoreCase(option, "--help")) {
319 return cmdHelp(fd);
320 } else if (EqualsIgnoreCase(option, "--request")) {
321 return cmdRequestFocus(fd, args, numArgs);
322 } else if (EqualsIgnoreCase(option, "--abandon")) {
323 return cmdAbandonFocus(fd, args, numArgs);
324 } else if (EqualsIgnoreCase(option, "--requestFocusWithMetaData")) {
325 return cmdRequestFocusWithMetaData(fd, args, numArgs);
326 } else if (EqualsIgnoreCase(option, "--abandonFocusWithMetaData")) {
327 return cmdAbandonFocusWithMetaData(fd, args, numArgs);
328 } else if (EqualsIgnoreCase(option, "--audioGainCallback")) {
329 return cmdOnAudioDeviceGainsChanged(fd, args, numArgs);
330 } else if (EqualsIgnoreCase(option, "--audioPortsChangedCallback")) {
331 return cmdOnAudioPortsChanged(fd, args, numArgs);
332 } else {
333 dprintf(fd, "Invalid option: %s\n", option.c_str());
334 return STATUS_BAD_VALUE;
335 }
336 }
337
dumpsys(int fd)338 binder_status_t AudioControl::dumpsys(int fd) {
339 if (mFocusListener == nullptr) {
340 dprintf(fd, "No focus listener registered\n");
341 } else {
342 dprintf(fd, "Focus listener registered\n");
343 }
344 dprintf(fd, "AudioGainCallback %sregistered\n", (mAudioGainCallback == nullptr ? "NOT " : ""));
345 return STATUS_OK;
346 }
347
cmdHelp(int fd) const348 binder_status_t AudioControl::cmdHelp(int fd) const {
349 dprintf(fd, "Usage: \n\n");
350 dprintf(fd, "[no args]: dumps focus listener / gain callback registered status\n");
351 dprintf(fd, "--help: shows this help\n");
352 dprintf(fd,
353 "--request <USAGE> <ZONE_ID> <FOCUS_GAIN>: requests audio focus for specified "
354 "usage (string), audio zone ID (int), and focus gain type (int)\n"
355 "Deprecated, use MetaData instead\n");
356 dprintf(fd,
357 "--abandon <USAGE> <ZONE_ID>: abandons audio focus for specified usage (string) and "
358 "audio zone ID (int)\n"
359 "Deprecated, use MetaData instead\n");
360 dprintf(fd, "See audio_policy_configuration.xsd for valid AudioUsage values.\n");
361
362 dprintf(fd,
363 "--requestFocusWithMetaData <METADATA> <ZONE_ID> <FOCUS_GAIN>: "
364 "requests audio focus for specified metadata, audio zone ID (int), "
365 "and focus gain type (int)\n");
366 dprintf(fd,
367 "--abandonFocusWithMetaData <METADATA> <ZONE_ID>: "
368 "abandons audio focus for specified metadata and audio zone ID (int)\n");
369 dprintf(fd,
370 "--audioGainCallback <ZONE_ID> <REASON_1>[,<REASON_N> ...]"
371 "<DEVICE_ADDRESS_1> <GAIN_INDEX_1> [<DEVICE_ADDRESS_N> <GAIN_INDEX_N> ...]: fire audio "
372 "gain callback for audio zone ID (int), the given reasons (csv int) for given pairs "
373 "of device address (string) and gain index (int) \n");
374
375 dprintf(fd,
376 "Note on <METADATA>: <USAGE,CONTENT_TYPE[,TAGS]> specified as where (int)usage, "
377 "(int)content type and tags (string)string)\n");
378 dprintf(fd,
379 "See android/media/audio/common/AudioUsageType.aidl for valid AudioUsage values.\n");
380 dprintf(fd,
381 "See android/media/audio/common/AudioContentType.aidl for valid AudioContentType "
382 "values.\n");
383 dprintf(fd,
384 "Tags are optional. If provided, it must follow the <key>=<value> pattern, where the "
385 "value is namespaced (for example com.google.strategy=VR).\n");
386 dprintf(fd,
387 "--audioPortsChangedCallback <ID_1> <NAME_1> <BUS_ADDRESS_1> <CONNECTION_TYPE_1> "
388 "<AUDIO_GAINS_1> [<ID_N> <NAME_N> <BUS_ADDRESS_N> <CONNECTION_TYPE_N> "
389 "<AUDIO_GAINS_N>]: fires audio ports changed callback. Carries list of modified "
390 "AudioPorts. "
391 "For simplicity, this command accepts limited information for each AudioPort: "
392 "id(int), name(string), port address(string), connection type (string), "
393 "audio gain (csv int)\n");
394 dprintf(fd, "Notes: \n");
395 dprintf(fd,
396 "1. AudioGain csv should match definition at "
397 "android/media/audio/common/AudioPort.aidl\n");
398 dprintf(fd,
399 "2. See android/media/audio/common/AudioDeviceDescription.aidl for valid "
400 "<CONNECTION_TYPE> values.\n");
401 return STATUS_OK;
402 }
403
cmdRequestFocus(int fd,const char ** args,uint32_t numArgs)404 binder_status_t AudioControl::cmdRequestFocus(int fd, const char** args, uint32_t numArgs) {
405 if (!checkCallerHasWritePermissions(fd)) {
406 return STATUS_PERMISSION_DENIED;
407 }
408 if (numArgs != 4) {
409 dprintf(fd,
410 "Invalid number of arguments: please provide --request <USAGE> <ZONE_ID> "
411 "<FOCUS_GAIN>\n");
412 return STATUS_BAD_VALUE;
413 }
414
415 string usage = string(args[1]);
416 if (xsd::isUnknownAudioUsage(usage)) {
417 dprintf(fd,
418 "Unknown usage provided: %s. Please see audio_policy_configuration.xsd V7_0 "
419 "for supported values\n",
420 usage.c_str());
421 return STATUS_BAD_VALUE;
422 }
423
424 int zoneId;
425 if (!safelyParseInt(string(args[2]), &zoneId)) {
426 dprintf(fd, "Non-integer zoneId provided with request: %s\n", string(args[2]).c_str());
427 return STATUS_BAD_VALUE;
428 }
429
430 int focusGainValue;
431 if (!safelyParseInt(string(args[3]), &focusGainValue)) {
432 dprintf(fd, "Non-integer focusGain provided with request: %s\n", string(args[3]).c_str());
433 return STATUS_BAD_VALUE;
434 }
435 AudioFocusChange focusGain = AudioFocusChange(focusGainValue);
436
437 if (mFocusListener == nullptr) {
438 dprintf(fd, "Unable to request focus - no focus listener registered\n");
439 return STATUS_BAD_VALUE;
440 }
441
442 mFocusListener->requestAudioFocus(usage, zoneId, focusGain);
443 dprintf(fd, "Requested focus for usage %s, zoneId %d, and focusGain %d\n", usage.c_str(),
444 zoneId, focusGain);
445 return STATUS_OK;
446 }
447
cmdAbandonFocus(int fd,const char ** args,uint32_t numArgs)448 binder_status_t AudioControl::cmdAbandonFocus(int fd, const char** args, uint32_t numArgs) {
449 if (!checkCallerHasWritePermissions(fd)) {
450 return STATUS_PERMISSION_DENIED;
451 }
452 if (numArgs != 3) {
453 dprintf(fd, "Invalid number of arguments: please provide --abandon <USAGE> <ZONE_ID>\n");
454 return STATUS_BAD_VALUE;
455 }
456
457 string usage = string(args[1]);
458 if (xsd::isUnknownAudioUsage(usage)) {
459 dprintf(fd,
460 "Unknown usage provided: %s. Please see audio_policy_configuration.xsd V7_0 "
461 "for supported values\n",
462 usage.c_str());
463 return STATUS_BAD_VALUE;
464 }
465
466 int zoneId;
467 if (!safelyParseInt(string(args[2]), &zoneId)) {
468 dprintf(fd, "Non-integer zoneId provided with abandon: %s\n", string(args[2]).c_str());
469 return STATUS_BAD_VALUE;
470 }
471
472 if (mFocusListener == nullptr) {
473 dprintf(fd, "Unable to abandon focus - no focus listener registered\n");
474 return STATUS_BAD_VALUE;
475 }
476
477 mFocusListener->abandonAudioFocus(usage, zoneId);
478 dprintf(fd, "Abandoned focus for usage %s and zoneId %d\n", usage.c_str(), zoneId);
479 return STATUS_OK;
480 }
481
parseMetaData(int fd,const std::string & metadataLiteral,audiohalcommon::PlaybackTrackMetadata & trackMetadata)482 binder_status_t AudioControl::parseMetaData(int fd, const std::string& metadataLiteral,
483 audiohalcommon::PlaybackTrackMetadata& trackMetadata) {
484 std::stringstream csvMetaData(metadataLiteral);
485 std::vector<std::string> splitMetaData;
486 std::string attribute;
487 while (getline(csvMetaData, attribute, ',')) {
488 splitMetaData.push_back(attribute);
489 }
490 if (splitMetaData.size() != 2 && splitMetaData.size() != 3) {
491 dprintf(fd,
492 "Invalid metadata: %s, please provide <METADATA> as <USAGE,CONTENT_TYPE[,TAGS]> "
493 "where (int)usage, (int)content type and tags (string)string)\n",
494 metadataLiteral.c_str());
495 return STATUS_BAD_VALUE;
496 }
497 int usage;
498 if (!safelyParseInt(splitMetaData[0], &usage)) {
499 dprintf(fd, "Non-integer usage provided with request: %s\n", splitMetaData[0].c_str());
500 return STATUS_BAD_VALUE;
501 }
502 int contentType;
503 if (!safelyParseInt(splitMetaData[1], &contentType)) {
504 dprintf(fd, "Non-integer content type provided with request: %s\n",
505 splitMetaData[1].c_str());
506 return STATUS_BAD_VALUE;
507 }
508 const std::string tags = (splitMetaData.size() == 3 ? splitMetaData[2] : "");
509
510 trackMetadata = {.usage = static_cast<audiomediacommon::AudioUsage>(usage),
511 .contentType = static_cast<audiomediacommon::AudioContentType>(contentType),
512 .tags = {tags}};
513 return STATUS_OK;
514 }
515
cmdRequestFocusWithMetaData(int fd,const char ** args,uint32_t numArgs)516 binder_status_t AudioControl::cmdRequestFocusWithMetaData(int fd, const char** args,
517 uint32_t numArgs) {
518 if (!checkCallerHasWritePermissions(fd)) {
519 return STATUS_PERMISSION_DENIED;
520 }
521 if (numArgs != 4) {
522 dprintf(fd,
523 "Invalid number of arguments: please provide:\n"
524 "--requestFocusWithMetaData <METADATA> <ZONE_ID> <FOCUS_GAIN>: "
525 "requests audio focus for specified metadata, audio zone ID (int), "
526 "and focus gain type (int)\n");
527 return STATUS_BAD_VALUE;
528 }
529 std::string metadataLiteral = std::string(args[1]);
530 audiohalcommon::PlaybackTrackMetadata trackMetadata{};
531 auto status = parseMetaData(fd, metadataLiteral, trackMetadata);
532 if (status != STATUS_OK) {
533 return status;
534 }
535
536 int zoneId;
537 if (!safelyParseInt(std::string(args[2]), &zoneId)) {
538 dprintf(fd, "Non-integer zoneId provided with request: %s\n", std::string(args[2]).c_str());
539 return STATUS_BAD_VALUE;
540 }
541
542 int focusGainValue;
543 if (!safelyParseInt(std::string(args[3]), &focusGainValue)) {
544 dprintf(fd, "Non-integer focusGain provided with request: %s\n",
545 std::string(args[3]).c_str());
546 return STATUS_BAD_VALUE;
547 }
548 AudioFocusChange focusGain = AudioFocusChange(focusGainValue);
549
550 if (mFocusListener == nullptr) {
551 dprintf(fd, "Unable to request focus - no focus listener registered\n");
552 return STATUS_BAD_VALUE;
553 }
554 mFocusListener->requestAudioFocusWithMetaData(trackMetadata, zoneId, focusGain);
555 dprintf(fd, "Requested focus for metadata %s, zoneId %d, and focusGain %d\n",
556 trackMetadata.toString().c_str(), zoneId, focusGain);
557 return STATUS_OK;
558 }
559
cmdAbandonFocusWithMetaData(int fd,const char ** args,uint32_t numArgs)560 binder_status_t AudioControl::cmdAbandonFocusWithMetaData(int fd, const char** args,
561 uint32_t numArgs) {
562 if (!checkCallerHasWritePermissions(fd)) {
563 return STATUS_PERMISSION_DENIED;
564 }
565 if (numArgs != 3) {
566 dprintf(fd,
567 "Invalid number of arguments: please provide:\n"
568 "--abandonFocusWithMetaData <METADATA> <ZONE_ID>: "
569 "abandons audio focus for specified metadata and audio zone ID (int)\n");
570 return STATUS_BAD_VALUE;
571 }
572 std::string metadataLiteral = std::string(args[1]);
573 audiohalcommon::PlaybackTrackMetadata trackMetadata{};
574 auto status = parseMetaData(fd, metadataLiteral, trackMetadata);
575 if (status != STATUS_OK) {
576 return status;
577 }
578 int zoneId;
579 if (!safelyParseInt(std::string(args[2]), &zoneId)) {
580 dprintf(fd, "Non-integer zoneId provided with request: %s\n", std::string(args[2]).c_str());
581 return STATUS_BAD_VALUE;
582 }
583 if (mFocusListener == nullptr) {
584 dprintf(fd, "Unable to abandon focus - no focus listener registered\n");
585 return STATUS_BAD_VALUE;
586 }
587
588 mFocusListener->abandonAudioFocusWithMetaData(trackMetadata, zoneId);
589 dprintf(fd, "Abandoned focus for metadata %s and zoneId %d\n", trackMetadata.toString().c_str(),
590 zoneId);
591 return STATUS_OK;
592 }
593
cmdOnAudioDeviceGainsChanged(int fd,const char ** args,uint32_t numArgs)594 binder_status_t AudioControl::cmdOnAudioDeviceGainsChanged(int fd, const char** args,
595 uint32_t numArgs) {
596 if (!checkCallerHasWritePermissions(fd)) {
597 return STATUS_PERMISSION_DENIED;
598 }
599 if ((numArgs + 1) % 2 != 0) {
600 dprintf(fd,
601 "Invalid number of arguments: please provide\n"
602 "--audioGainCallback <ZONE_ID> <REASON_1>[,<REASON_N> ...]"
603 "<DEVICE_ADDRESS_1> <GAIN_INDEX_1> [<DEVICE_ADDRESS_N> <GAIN_INDEX_N> ...]: "
604 "fire audio gain callback for audio zone ID (int), "
605 "with the given reasons (csv int) for given pairs of device address (string) "
606 "and gain index (int) \n");
607 return STATUS_BAD_VALUE;
608 }
609 int zoneId;
610 if (!safelyParseInt(string(args[1]), &zoneId)) {
611 dprintf(fd, "Non-integer zoneId provided with request: %s\n", std::string(args[1]).c_str());
612 return STATUS_BAD_VALUE;
613 }
614 std::string reasonsLiteral = std::string(args[2]);
615 std::stringstream csvReasonsLiteral(reasonsLiteral);
616 std::vector<Reasons> reasons;
617 std::string reasonLiteral;
618 while (getline(csvReasonsLiteral, reasonLiteral, ',')) {
619 int reason;
620 if (!safelyParseInt(reasonLiteral, &reason)) {
621 dprintf(fd, "Invalid Reason(s) provided %s\n", reasonLiteral.c_str());
622 return STATUS_BAD_VALUE;
623 }
624 reasons.push_back(static_cast<Reasons>(reason));
625 }
626
627 std::vector<AudioGainConfigInfo> agcis{};
628 for (uint32_t i = 3; i < numArgs; i += 2) {
629 std::string deviceAddress = std::string(args[i]);
630 int32_t index;
631 if (!safelyParseInt(std::string(args[i + 1]), &index)) {
632 dprintf(fd, "Non-integer index provided with request: %s\n",
633 std::string(args[i + 1]).c_str());
634 return STATUS_BAD_VALUE;
635 }
636 AudioGainConfigInfo agci{zoneId, deviceAddress, index};
637 agcis.push_back(agci);
638 }
639 if (mAudioGainCallback == nullptr) {
640 dprintf(fd,
641 "Unable to trig audio gain callback for reasons=%s and gains=%s\n"
642 " - no audio gain callback registered\n",
643 toEnumString(reasons).c_str(), toString(agcis).c_str());
644 return STATUS_BAD_VALUE;
645 }
646
647 mAudioGainCallback->onAudioDeviceGainsChanged(reasons, agcis);
648 dprintf(fd, "Fired audio gain callback for reasons=%s and gains=%s\n",
649 toEnumString(reasons).c_str(), toString(agcis).c_str());
650 return STATUS_OK;
651 }
652
parseAudioGains(int fd,const std::string & stringGain,std::vector<AudioGain> & gains)653 binder_status_t AudioControl::parseAudioGains(int fd, const std::string& stringGain,
654 std::vector<AudioGain>& gains) {
655 const int kAudioGainSize = 9;
656 std::stringstream csvGain(stringGain);
657 std::vector<std::string> vecGain;
658 std::string value;
659 while (getline(csvGain, value, ',')) {
660 vecGain.push_back(value);
661 }
662
663 if ((vecGain.size() == 0) || ((vecGain.size() % kAudioGainSize) != 0)) {
664 dprintf(fd, "Erroneous input to generate AudioGain: %s\n", stringGain.c_str());
665 return STATUS_BAD_VALUE;
666 }
667
668 // iterate over injected AudioGains
669 for (int index = 0; index < vecGain.size(); index += kAudioGainSize) {
670 int32_t mode;
671 if (!safelyParseInt(vecGain[index], &mode)) {
672 dprintf(fd, "Non-integer index provided with request: %s\n", vecGain[index].c_str());
673 return STATUS_BAD_VALUE;
674 }
675
676 // car audio framework only supports JOINT mode.
677 // skip injected AudioGains that are not compliant with this.
678 if (mode != static_cast<int>(AudioGainMode::JOINT)) {
679 LOG(WARNING) << ":" << __func__ << ": skipping gain since it is not JOINT mode!";
680 continue;
681 }
682
683 int32_t layout;
684 if (!safelyParseInt(vecGain[index + 1], &layout)) {
685 dprintf(fd, "Non-integer index provided with request: %s\n",
686 vecGain[index + 1].c_str());
687 return STATUS_BAD_VALUE;
688 }
689 AudioChannelLayout channelMask =
690 AudioChannelLayout::make<AudioChannelLayout::layoutMask>(layout);
691
692 int32_t minValue;
693 if (!safelyParseInt(vecGain[index + 2], &minValue)) {
694 dprintf(fd, "Non-integer index provided with request: %s\n",
695 vecGain[index + 2].c_str());
696 return STATUS_BAD_VALUE;
697 }
698
699 int32_t maxValue;
700 if (!safelyParseInt(vecGain[index + 3], &maxValue)) {
701 dprintf(fd, "Non-integer index provided with request: %s\n",
702 vecGain[index + 3].c_str());
703 return STATUS_BAD_VALUE;
704 }
705
706 int32_t defaultValue;
707 if (!safelyParseInt(vecGain[index + 4], &defaultValue)) {
708 dprintf(fd, "Non-integer index provided with request: %s\n",
709 vecGain[index + 4].c_str());
710 return STATUS_BAD_VALUE;
711 }
712
713 int32_t stepValue;
714 if (!safelyParseInt(vecGain[index + 5], &stepValue)) {
715 dprintf(fd, "Non-integer index provided with request: %s\n",
716 vecGain[index + 5].c_str());
717 return STATUS_BAD_VALUE;
718 }
719
720 int32_t minRampMs;
721 if (!safelyParseInt(vecGain[index + 6], &minRampMs)) {
722 dprintf(fd, "Non-integer index provided with request: %s\n",
723 vecGain[index + 6].c_str());
724 return STATUS_BAD_VALUE;
725 }
726
727 int32_t maxRampMs;
728 if (!safelyParseInt(vecGain[index + 7], &maxRampMs)) {
729 dprintf(fd, "Non-integer index provided with request: %s\n",
730 vecGain[index + 7].c_str());
731 return STATUS_BAD_VALUE;
732 }
733
734 ParseBoolResult useForVolume = ParseBool(vecGain[index + 8]);
735 if (useForVolume == ParseBoolResult::kError) {
736 dprintf(fd, "Non-boolean index provided with request: %s\n",
737 vecGain[index + 8].c_str());
738 return STATUS_BAD_VALUE;
739 } else if (useForVolume == ParseBoolResult::kFalse) {
740 // at this level we only care about gain stages that are relevant
741 // for volume control. skip the gain stage if its flagged as false.
742 LOG(WARNING) << ":" << __func__
743 << ": skipping gain since it is not for volume control!";
744 continue;
745 }
746
747 AudioGain gain = createGain(mode, channelMask, minValue, maxValue, defaultValue, stepValue,
748 minRampMs, maxRampMs, true /*useForVolume*/);
749 gains.push_back(gain);
750 }
751 return STATUS_OK;
752 }
753
cmdOnAudioPortsChanged(int fd,const char ** args,uint32_t numArgs)754 binder_status_t AudioControl::cmdOnAudioPortsChanged(int fd, const char** args, uint32_t numArgs) {
755 if (!checkCallerHasWritePermissions(fd)) {
756 return STATUS_PERMISSION_DENIED;
757 }
758
759 if ((numArgs < 6) || ((numArgs - 1) % 5 != 0)) {
760 dprintf(fd,
761 "Invalid number of arguments: please provide\n"
762 "--audioPortsChangedCallback <ID_1> <NAME_1> <BUS_ADDRESS_1> <CONNECTION_TYPE_1> "
763 "<AUDIO_GAINS_1> [<ID_N> <NAME_N> <BUS_ADDRESS_N> <CONNECTION_TYPE_N> "
764 "<AUDIO_GAINS_N>]: triggers audio ports changed callback. Carries list of "
765 "modified AudioPorts. "
766 "For simplicity, this command accepts limited information for each AudioPort: "
767 "id(int), name(string), port address(string), connection type (string), "
768 "audio gain (csv int)\n");
769 return STATUS_BAD_VALUE;
770 }
771
772 std::vector<AudioPort> ports;
773 for (uint32_t i = 1; i < numArgs; i += 5) {
774 binder_status_t status;
775 int32_t id;
776 if (!safelyParseInt(std::string(args[i]), &id)) {
777 dprintf(fd, "Non-integer index provided with request: %s\n",
778 std::string(args[i]).c_str());
779 return STATUS_BAD_VALUE;
780 }
781
782 std::string name = std::string(args[i + 1]);
783 std::string address = std::string(args[i + 2]);
784 std::string connection = std::string(args[i + 3]);
785
786 std::string stringGains = std::string(args[i + 4]);
787 std::vector<AudioGain> gains;
788 status = parseAudioGains(fd, stringGains, gains);
789 if (status != STATUS_OK) {
790 return status;
791 }
792
793 AudioPort port = createPort(
794 id, name, 0 /*flags*/, false /*isInput*/,
795 createDeviceExt(AudioDeviceType::OUT_DEVICE, 0 /*flags*/, connection, address));
796 port.gains.insert(port.gains.begin(), gains.begin(), gains.end());
797
798 ports.push_back(port);
799 }
800
801 if (mModuleChangeCallback == nullptr) {
802 dprintf(fd,
803 "Unable to trigger audio port callback for ports: %s \n"
804 " - no module change callback registered\n",
805 toString(ports).c_str());
806 return STATUS_BAD_VALUE;
807 }
808
809 // TODO (b/269139706) fix atomic read issue
810 mModuleChangeCallback->onAudioPortsChanged(ports);
811 dprintf(fd, "SUCCESS audio port callback for ports: %s \n", toString(ports).c_str());
812 return STATUS_OK;
813 }
814 } // namespace aidl::android::hardware::automotive::audiocontrol
815