1 /*
2 * Copyright (C) 2014 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 "AudioPolicyEffects"
18 //#define LOG_NDEBUG 0
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <memory>
24 #include <cutils/misc.h>
25 #include <media/AudioEffect.h>
26 #include <media/EffectsConfig.h>
27 #include <mediautils/ServiceUtilities.h>
28 #include <system/audio.h>
29 #include <system/audio_effects/audio_effects_conf.h>
30 #include <utils/Vector.h>
31 #include <utils/SortedVector.h>
32 #include <cutils/config_utils.h>
33 #include <binder/IPCThreadState.h>
34 #include "AudioPolicyEffects.h"
35
36 namespace android {
37
38 using content::AttributionSourceState;
39
40 // ----------------------------------------------------------------------------
41 // AudioPolicyEffects Implementation
42 // ----------------------------------------------------------------------------
43
AudioPolicyEffects(const sp<EffectsFactoryHalInterface> & effectsFactoryHal)44 AudioPolicyEffects::AudioPolicyEffects(const sp<EffectsFactoryHalInterface>& effectsFactoryHal) {
45 // Note: clang thread-safety permits the ctor to call guarded _l methods without
46 // acquiring the associated mutex capability as standard practice is to assume
47 // single threaded construction and destruction.
48
49 // load xml config with effectsFactoryHal
50 status_t loadResult = loadAudioEffectConfig_ll(effectsFactoryHal);
51 if (loadResult < 0) {
52 ALOGW("Failed to query effect configuration, fallback to load .conf");
53 // load automatic audio effect modules
54 if (access(AUDIO_EFFECT_VENDOR_CONFIG_FILE, R_OK) == 0) {
55 loadAudioEffectConfigLegacy_l(AUDIO_EFFECT_VENDOR_CONFIG_FILE);
56 } else if (access(AUDIO_EFFECT_DEFAULT_CONFIG_FILE, R_OK) == 0) {
57 loadAudioEffectConfigLegacy_l(AUDIO_EFFECT_DEFAULT_CONFIG_FILE);
58 }
59 } else if (loadResult > 0) {
60 ALOGE("Effect config is partially invalid, skipped %d elements", loadResult);
61 }
62 }
63
addInputEffects(audio_io_handle_t input,audio_source_t inputSource,audio_session_t audioSession)64 status_t AudioPolicyEffects::addInputEffects(audio_io_handle_t input,
65 audio_source_t inputSource,
66 audio_session_t audioSession)
67 {
68 status_t status = NO_ERROR;
69
70 // create audio pre processors according to input source
71 audio_source_t aliasSource = (inputSource == AUDIO_SOURCE_HOTWORD) ?
72 AUDIO_SOURCE_VOICE_RECOGNITION : inputSource;
73
74 audio_utils::lock_guard _l(mMutex);
75 auto sourceIt = mInputSources.find(aliasSource);
76 if (sourceIt == mInputSources.end()) {
77 ALOGV("addInputEffects(): no processing needs to be attached to this source");
78 return status;
79 }
80 std::shared_ptr<EffectVector>& sessionDesc = mInputSessions[audioSession];
81 if (sessionDesc == nullptr) {
82 sessionDesc = std::make_shared<EffectVector>(audioSession);
83 }
84 sessionDesc->mRefCount++;
85
86 ALOGV("addInputEffects(): input: %d, refCount: %d", input, sessionDesc->mRefCount);
87 if (sessionDesc->mRefCount == 1) {
88 int64_t token = IPCThreadState::self()->clearCallingIdentity();
89 const std::shared_ptr<EffectDescVector>& effects = sourceIt->second;
90 for (const std::shared_ptr<EffectDesc>& effect : *effects) {
91 AttributionSourceState attributionSource;
92 attributionSource.packageName = "android";
93 attributionSource.token = sp<BBinder>::make();
94 auto fx = sp<AudioEffect>::make(attributionSource);
95 fx->set(nullptr /*type */, &effect->mUuid, -1 /* priority */, nullptr /* callback */,
96 audioSession, input);
97 status_t status = fx->initCheck();
98 if (status != NO_ERROR && status != ALREADY_EXISTS) {
99 ALOGW("addInputEffects(): failed to create Fx %s on source %d",
100 effect->mName.c_str(), (int32_t)aliasSource);
101 // fx goes out of scope and strong ref on AudioEffect is released
102 continue;
103 }
104 for (size_t j = 0; j < effect->mParams.size(); j++) {
105 // const_cast here due to API.
106 fx->setParameter(const_cast<effect_param_t*>(effect->mParams[j].get()));
107 }
108 ALOGV("addInputEffects(): added Fx %s on source: %d",
109 effect->mName.c_str(), (int32_t)aliasSource);
110 sessionDesc->mEffects.push_back(std::move(fx));
111 }
112 sessionDesc->setProcessorEnabled(true);
113 IPCThreadState::self()->restoreCallingIdentity(token);
114 }
115 return status;
116 }
117
118
releaseInputEffects(audio_io_handle_t input,audio_session_t audioSession)119 status_t AudioPolicyEffects::releaseInputEffects(audio_io_handle_t input,
120 audio_session_t audioSession)
121 {
122 status_t status = NO_ERROR;
123
124 audio_utils::lock_guard _l(mMutex);
125 auto it = mInputSessions.find(audioSession);
126 if (it == mInputSessions.end()) {
127 return status;
128 }
129 std::shared_ptr<EffectVector> sessionDesc = it->second;
130 sessionDesc->mRefCount--;
131 ALOGV("releaseInputEffects(): input: %d, refCount: %d", input, sessionDesc->mRefCount);
132 if (sessionDesc->mRefCount == 0) {
133 sessionDesc->setProcessorEnabled(false);
134 mInputSessions.erase(it);
135 ALOGV("releaseInputEffects(): all effects released");
136 }
137 return status;
138 }
139
queryDefaultInputEffects(audio_session_t audioSession,effect_descriptor_t * descriptors,uint32_t * count)140 status_t AudioPolicyEffects::queryDefaultInputEffects(audio_session_t audioSession,
141 effect_descriptor_t *descriptors,
142 uint32_t *count)
143 {
144 status_t status = NO_ERROR;
145
146 audio_utils::lock_guard _l(mMutex);
147 auto it = mInputSessions.find(audioSession);
148 if (it == mInputSessions.end()) {
149 *count = 0;
150 return BAD_VALUE;
151 }
152 const std::vector<sp<AudioEffect>>& effects = it->second->mEffects;
153 const size_t copysize = std::min(effects.size(), (size_t)*count);
154 for (size_t i = 0; i < copysize; i++) {
155 descriptors[i] = effects[i]->descriptor();
156 }
157 if (effects.size() > *count) {
158 status = NO_MEMORY;
159 }
160 *count = effects.size();
161 return status;
162 }
163
164
queryDefaultOutputSessionEffects(audio_session_t audioSession,effect_descriptor_t * descriptors,uint32_t * count)165 status_t AudioPolicyEffects::queryDefaultOutputSessionEffects(audio_session_t audioSession,
166 effect_descriptor_t *descriptors,
167 uint32_t *count)
168 {
169 status_t status = NO_ERROR;
170
171 audio_utils::lock_guard _l(mMutex);
172 auto it = mOutputSessions.find(audioSession);
173 if (it == mOutputSessions.end()) {
174 *count = 0;
175 return BAD_VALUE;
176 }
177 const std::vector<sp<AudioEffect>>& effects = it->second->mEffects;
178 const size_t copysize = std::min(effects.size(), (size_t)*count);
179 for (size_t i = 0; i < copysize; i++) {
180 descriptors[i] = effects[i]->descriptor();
181 }
182 if (effects.size() > *count) {
183 status = NO_MEMORY;
184 }
185 *count = effects.size();
186 return status;
187 }
188
189
addOutputSessionEffects(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t audioSession)190 status_t AudioPolicyEffects::addOutputSessionEffects(audio_io_handle_t output,
191 audio_stream_type_t stream,
192 audio_session_t audioSession)
193 {
194 status_t status = NO_ERROR;
195
196 audio_utils::lock_guard _l(mMutex);
197 // create audio processors according to stream
198 // FIXME: should we have specific post processing settings for internal streams?
199 // default to media for now.
200 if (stream >= AUDIO_STREAM_PUBLIC_CNT) {
201 stream = AUDIO_STREAM_MUSIC;
202 }
203 auto it = mOutputStreams.find(stream);
204 if (it == mOutputStreams.end()) {
205 ALOGV("addOutputSessionEffects(): no output processing needed for this stream");
206 return NO_ERROR;
207 }
208
209 std::shared_ptr<EffectVector>& procDesc = mOutputSessions[audioSession];
210 if (procDesc == nullptr) {
211 procDesc = std::make_shared<EffectVector>(audioSession);
212 }
213 procDesc->mRefCount++;
214
215 ALOGV("addOutputSessionEffects(): session: %d, refCount: %d",
216 audioSession, procDesc->mRefCount);
217 if (procDesc->mRefCount == 1) {
218 // make sure effects are associated to audio server even if we are executing a binder call
219 int64_t token = IPCThreadState::self()->clearCallingIdentity();
220 const std::shared_ptr<EffectDescVector>& effects = it->second;
221 for (const std::shared_ptr<EffectDesc>& effect : *effects) {
222 AttributionSourceState attributionSource;
223 attributionSource.packageName = "android";
224 attributionSource.token = sp<BBinder>::make();
225 auto fx = sp<AudioEffect>::make(attributionSource);
226 fx->set(nullptr /* type */, &effect->mUuid, 0 /* priority */, nullptr /* callback */,
227 audioSession, output);
228 status_t status = fx->initCheck();
229 if (status != NO_ERROR && status != ALREADY_EXISTS) {
230 ALOGE("addOutputSessionEffects(): failed to create Fx %s on session %d",
231 effect->mName.c_str(), audioSession);
232 // fx goes out of scope and strong ref on AudioEffect is released
233 continue;
234 }
235 ALOGV("addOutputSessionEffects(): added Fx %s on session: %d for stream: %d",
236 effect->mName.c_str(), audioSession, (int32_t)stream);
237 procDesc->mEffects.push_back(std::move(fx));
238 }
239
240 procDesc->setProcessorEnabled(true);
241 IPCThreadState::self()->restoreCallingIdentity(token);
242 }
243 return status;
244 }
245
releaseOutputSessionEffects(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t audioSession)246 status_t AudioPolicyEffects::releaseOutputSessionEffects(audio_io_handle_t output,
247 audio_stream_type_t stream,
248 audio_session_t audioSession)
249 {
250 (void) output; // argument not used for now
251 (void) stream; // argument not used for now
252
253 audio_utils::lock_guard _l(mMutex);
254 auto it = mOutputSessions.find(audioSession);
255 if (it == mOutputSessions.end()) {
256 ALOGV("releaseOutputSessionEffects: no output processing was attached to this stream");
257 return NO_ERROR;
258 }
259
260 std::shared_ptr<EffectVector> procDesc = it->second;
261 procDesc->mRefCount--;
262 ALOGV("releaseOutputSessionEffects(): session: %d, refCount: %d",
263 audioSession, procDesc->mRefCount);
264 if (procDesc->mRefCount == 0) {
265 procDesc->setProcessorEnabled(false);
266 procDesc->mEffects.clear();
267 mOutputSessions.erase(it);
268 ALOGV("releaseOutputSessionEffects(): output processing released from session: %d",
269 audioSession);
270 }
271 return NO_ERROR;
272 }
273
addSourceDefaultEffect(const effect_uuid_t * type,const String16 & opPackageName,const effect_uuid_t * uuid,int32_t priority,audio_source_t source,audio_unique_id_t * id)274 status_t AudioPolicyEffects::addSourceDefaultEffect(const effect_uuid_t *type,
275 const String16& opPackageName,
276 const effect_uuid_t *uuid,
277 int32_t priority,
278 audio_source_t source,
279 audio_unique_id_t* id)
280 {
281 if (uuid == NULL || type == NULL) {
282 ALOGE("addSourceDefaultEffect(): Null uuid or type uuid pointer");
283 return BAD_VALUE;
284 }
285
286 // HOTWORD, FM_TUNER and ECHO_REFERENCE are special case sources > MAX.
287 if (source < AUDIO_SOURCE_DEFAULT ||
288 (source > AUDIO_SOURCE_MAX &&
289 source != AUDIO_SOURCE_HOTWORD &&
290 source != AUDIO_SOURCE_FM_TUNER &&
291 source != AUDIO_SOURCE_ECHO_REFERENCE &&
292 source != AUDIO_SOURCE_ULTRASOUND)) {
293 ALOGE("addSourceDefaultEffect(): Unsupported source type %d", source);
294 return BAD_VALUE;
295 }
296
297 // Check that |uuid| or |type| corresponds to an effect on the system.
298 effect_descriptor_t descriptor = {};
299 status_t res = AudioEffect::getEffectDescriptor(
300 uuid, type, EFFECT_FLAG_TYPE_PRE_PROC, &descriptor);
301 if (res != OK) {
302 ALOGE("addSourceDefaultEffect(): Failed to find effect descriptor matching uuid/type.");
303 return res;
304 }
305
306 // Only pre-processing effects can be added dynamically as source defaults.
307 if ((descriptor.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
308 ALOGE("addSourceDefaultEffect(): Desired effect cannot be attached "
309 "as a source default effect.");
310 return BAD_VALUE;
311 }
312
313 audio_utils::lock_guard _l(mMutex);
314
315 // Find the EffectDescVector for the given source type, or create a new one if necessary.
316 std::shared_ptr<EffectDescVector>& desc = mInputSources[source];
317 if (desc == nullptr) {
318 desc = std::make_shared<EffectDescVector>();
319 }
320
321 // Create a new effect and add it to the vector.
322 res = AudioEffect::newEffectUniqueId(id);
323 if (res != OK) {
324 ALOGE("addSourceDefaultEffect(): failed to get new unique id.");
325 return res;
326 }
327 std::shared_ptr<EffectDesc> effect = std::make_shared<EffectDesc>(
328 descriptor.name, descriptor.type, opPackageName, descriptor.uuid, priority, *id);
329 desc->push_back(std::move(effect));
330 // TODO(b/71813697): Support setting params as well.
331
332 // TODO(b/71814300): Retroactively attach to any existing sources of the given type.
333 // This requires tracking the source type of each session id in addition to what is
334 // already being tracked.
335
336 return NO_ERROR;
337 }
338
addStreamDefaultEffect(const effect_uuid_t * type,const String16 & opPackageName,const effect_uuid_t * uuid,int32_t priority,audio_usage_t usage,audio_unique_id_t * id)339 status_t AudioPolicyEffects::addStreamDefaultEffect(const effect_uuid_t *type,
340 const String16& opPackageName,
341 const effect_uuid_t *uuid,
342 int32_t priority,
343 audio_usage_t usage,
344 audio_unique_id_t* id)
345 {
346 if (uuid == NULL || type == NULL) {
347 ALOGE("addStreamDefaultEffect(): Null uuid or type uuid pointer");
348 return BAD_VALUE;
349 }
350 audio_stream_type_t stream = AudioSystem::attributesToStreamType(attributes_initializer(usage));
351
352 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
353 ALOGE("addStreamDefaultEffect(): Unsupported stream type %d", stream);
354 return BAD_VALUE;
355 }
356
357 // Check that |uuid| or |type| corresponds to an effect on the system.
358 effect_descriptor_t descriptor = {};
359 status_t res = AudioEffect::getEffectDescriptor(
360 uuid, type, EFFECT_FLAG_TYPE_INSERT, &descriptor);
361 if (res != OK) {
362 ALOGE("addStreamDefaultEffect(): Failed to find effect descriptor matching uuid/type.");
363 return res;
364 }
365
366 // Only insert effects can be added dynamically as stream defaults.
367 if ((descriptor.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_INSERT) {
368 ALOGE("addStreamDefaultEffect(): Desired effect cannot be attached "
369 "as a stream default effect.");
370 return BAD_VALUE;
371 }
372
373 audio_utils::lock_guard _l(mMutex);
374
375 // Find the EffectDescVector for the given stream type, or create a new one if necessary.
376 std::shared_ptr<EffectDescVector>& desc = mOutputStreams[stream];
377 if (desc == nullptr) {
378 // No effects for this stream type yet.
379 desc = std::make_shared<EffectDescVector>();
380 }
381
382 // Create a new effect and add it to the vector.
383 res = AudioEffect::newEffectUniqueId(id);
384 if (res != OK) {
385 ALOGE("addStreamDefaultEffect(): failed to get new unique id.");
386 return res;
387 }
388 std::shared_ptr<EffectDesc> effect = std::make_shared<EffectDesc>(
389 descriptor.name, descriptor.type, opPackageName, descriptor.uuid, priority, *id);
390 desc->push_back(std::move(effect));
391 // TODO(b/71813697): Support setting params as well.
392
393 // TODO(b/71814300): Retroactively attach to any existing streams of the given type.
394 // This requires tracking the stream type of each session id in addition to what is
395 // already being tracked.
396
397 return NO_ERROR;
398 }
399
removeSourceDefaultEffect(audio_unique_id_t id)400 status_t AudioPolicyEffects::removeSourceDefaultEffect(audio_unique_id_t id)
401 {
402 if (id == AUDIO_UNIQUE_ID_ALLOCATE) {
403 // ALLOCATE is not a unique identifier, but rather a reserved value indicating
404 // a real id has not been assigned. For default effects, this value is only used
405 // by system-owned defaults from the loaded config, which cannot be removed.
406 return BAD_VALUE;
407 }
408
409 audio_utils::lock_guard _l(mMutex);
410
411 // Check each source type.
412 for (auto& [source, descVector] : mInputSources) {
413 // Check each effect for each source.
414 for (auto desc = descVector->begin(); desc != descVector->end(); ++desc) {
415 if ((*desc)->mId == id) {
416 // Found it!
417 // TODO(b/71814300): Remove from any sources the effect was attached to.
418 descVector->erase(desc);
419 // Handles are unique; there can only be one match, so return early.
420 return NO_ERROR;
421 }
422 }
423 }
424
425 // Effect wasn't found, so it's been trivially removed successfully.
426 return NO_ERROR;
427 }
428
removeStreamDefaultEffect(audio_unique_id_t id)429 status_t AudioPolicyEffects::removeStreamDefaultEffect(audio_unique_id_t id)
430 {
431 if (id == AUDIO_UNIQUE_ID_ALLOCATE) {
432 // ALLOCATE is not a unique identifier, but rather a reserved value indicating
433 // a real id has not been assigned. For default effects, this value is only used
434 // by system-owned defaults from the loaded config, which cannot be removed.
435 return BAD_VALUE;
436 }
437
438 audio_utils::lock_guard _l(mMutex);
439
440 // Check each stream type.
441 for (auto& [stream, descVector] : mOutputStreams) {
442 // Check each effect for each stream.
443 for (auto desc = descVector->begin(); desc != descVector->end(); ++desc) {
444 if ((*desc)->mId == id) {
445 // Found it!
446 // TODO(b/71814300): Remove from any streams the effect was attached to.
447 descVector->erase(desc);
448 // Handles are unique; there can only be one match, so return early.
449 return NO_ERROR;
450 }
451 }
452 }
453
454 // Effect wasn't found, so it's been trivially removed successfully.
455 return NO_ERROR;
456 }
457
setProcessorEnabled(bool enabled)458 void AudioPolicyEffects::EffectVector::setProcessorEnabled(bool enabled)
459 {
460 for (const auto& effect : mEffects) {
461 effect->setEnabled(enabled);
462 }
463 }
464
465
466 // ----------------------------------------------------------------------------
467 // Audio processing configuration
468 // ----------------------------------------------------------------------------
469
470 // we keep to const char* instead of std::string_view as comparison is believed faster.
471 constexpr const char* kInputSourceNames[AUDIO_SOURCE_CNT - 1] = {
472 MIC_SRC_TAG,
473 VOICE_UL_SRC_TAG,
474 VOICE_DL_SRC_TAG,
475 VOICE_CALL_SRC_TAG,
476 CAMCORDER_SRC_TAG,
477 VOICE_REC_SRC_TAG,
478 VOICE_COMM_SRC_TAG,
479 REMOTE_SUBMIX_SRC_TAG,
480 UNPROCESSED_SRC_TAG,
481 VOICE_PERFORMANCE_SRC_TAG
482 };
483
484 // returns the audio_source_t enum corresponding to the input source name or
485 // AUDIO_SOURCE_CNT is no match found
inputSourceNameToEnum(const char * name)486 /*static*/ audio_source_t AudioPolicyEffects::inputSourceNameToEnum(const char *name)
487 {
488 int i;
489 for (i = AUDIO_SOURCE_MIC; i < AUDIO_SOURCE_CNT; i++) {
490 if (strcmp(name, kInputSourceNames[i - AUDIO_SOURCE_MIC]) == 0) {
491 ALOGV("inputSourceNameToEnum found source %s %d", name, i);
492 break;
493 }
494 }
495 return (audio_source_t)i;
496 }
497
498 // +1 as enum starts from -1
499 constexpr const char* kStreamNames[AUDIO_STREAM_PUBLIC_CNT + 1] = {
500 AUDIO_STREAM_DEFAULT_TAG,
501 AUDIO_STREAM_VOICE_CALL_TAG,
502 AUDIO_STREAM_SYSTEM_TAG,
503 AUDIO_STREAM_RING_TAG,
504 AUDIO_STREAM_MUSIC_TAG,
505 AUDIO_STREAM_ALARM_TAG,
506 AUDIO_STREAM_NOTIFICATION_TAG,
507 AUDIO_STREAM_BLUETOOTH_SCO_TAG,
508 AUDIO_STREAM_ENFORCED_AUDIBLE_TAG,
509 AUDIO_STREAM_DTMF_TAG,
510 AUDIO_STREAM_TTS_TAG,
511 AUDIO_STREAM_ASSISTANT_TAG
512 };
513
514 // returns the audio_stream_t enum corresponding to the output stream name or
515 // AUDIO_STREAM_PUBLIC_CNT is no match found
516 /* static */
streamNameToEnum(const char * name)517 audio_stream_type_t AudioPolicyEffects::streamNameToEnum(const char *name)
518 {
519 int i;
520 for (i = AUDIO_STREAM_DEFAULT; i < AUDIO_STREAM_PUBLIC_CNT; i++) {
521 if (strcmp(name, kStreamNames[i - AUDIO_STREAM_DEFAULT]) == 0) {
522 ALOGV("streamNameToEnum found stream %s %d", name, i);
523 break;
524 }
525 }
526 return (audio_stream_type_t)i;
527 }
528
529 // ----------------------------------------------------------------------------
530 // Audio Effect Config parser
531 // ----------------------------------------------------------------------------
532
533 /* static */
growParamSize(char ** param,size_t size,size_t * curSize,size_t * totSize)534 size_t AudioPolicyEffects::growParamSize(char **param,
535 size_t size,
536 size_t *curSize,
537 size_t *totSize)
538 {
539 // *curSize is at least sizeof(effect_param_t) + 2 * sizeof(int)
540 size_t pos = ((*curSize - 1 ) / size + 1) * size;
541
542 if (pos + size > *totSize) {
543 while (pos + size > *totSize) {
544 *totSize += ((*totSize + 7) / 8) * 4;
545 }
546 char *newParam = (char *)realloc(*param, *totSize);
547 if (newParam == NULL) {
548 ALOGE("%s realloc error for size %zu", __func__, *totSize);
549 return 0;
550 }
551 *param = newParam;
552 }
553 *curSize = pos + size;
554 return pos;
555 }
556
557 /* static */
readParamValue(cnode * node,char ** param,size_t * curSize,size_t * totSize)558 size_t AudioPolicyEffects::readParamValue(cnode *node,
559 char **param,
560 size_t *curSize,
561 size_t *totSize)
562 {
563 size_t len = 0;
564 size_t pos;
565
566 if (strncmp(node->name, SHORT_TAG, sizeof(SHORT_TAG) + 1) == 0) {
567 pos = growParamSize(param, sizeof(short), curSize, totSize);
568 if (pos == 0) {
569 goto exit;
570 }
571 *(short *)(*param + pos) = (short)atoi(node->value);
572 ALOGV("readParamValue() reading short %d", *(short *)(*param + pos));
573 len = sizeof(short);
574 } else if (strncmp(node->name, INT_TAG, sizeof(INT_TAG) + 1) == 0) {
575 pos = growParamSize(param, sizeof(int), curSize, totSize);
576 if (pos == 0) {
577 goto exit;
578 }
579 *(int *)(*param + pos) = atoi(node->value);
580 ALOGV("readParamValue() reading int %d", *(int *)(*param + pos));
581 len = sizeof(int);
582 } else if (strncmp(node->name, FLOAT_TAG, sizeof(FLOAT_TAG) + 1) == 0) {
583 pos = growParamSize(param, sizeof(float), curSize, totSize);
584 if (pos == 0) {
585 goto exit;
586 }
587 *(float *)(*param + pos) = (float)atof(node->value);
588 ALOGV("readParamValue() reading float %f",*(float *)(*param + pos));
589 len = sizeof(float);
590 } else if (strncmp(node->name, BOOL_TAG, sizeof(BOOL_TAG) + 1) == 0) {
591 pos = growParamSize(param, sizeof(bool), curSize, totSize);
592 if (pos == 0) {
593 goto exit;
594 }
595 if (strncmp(node->value, "true", strlen("true") + 1) == 0) {
596 *(bool *)(*param + pos) = true;
597 } else {
598 *(bool *)(*param + pos) = false;
599 }
600 ALOGV("readParamValue() reading bool %s",
601 *(bool *)(*param + pos) ? "true" : "false");
602 len = sizeof(bool);
603 } else if (strncmp(node->name, STRING_TAG, sizeof(STRING_TAG) + 1) == 0) {
604 len = strnlen(node->value, EFFECT_STRING_LEN_MAX);
605 if (*curSize + len + 1 > *totSize) {
606 *totSize = *curSize + len + 1;
607 char *newParam = (char *)realloc(*param, *totSize);
608 if (newParam == NULL) {
609 len = 0;
610 ALOGE("%s realloc error for string len %zu", __func__, *totSize);
611 goto exit;
612 }
613 *param = newParam;
614 }
615 strncpy(*param + *curSize, node->value, len);
616 *curSize += len;
617 (*param)[*curSize] = '\0';
618 ALOGV("readParamValue() reading string %s", *param + *curSize - len);
619 } else {
620 ALOGW("readParamValue() unknown param type %s", node->name);
621 }
622 exit:
623 return len;
624 }
625
626 /* static */
loadEffectParameter(cnode * root)627 std::shared_ptr<const effect_param_t> AudioPolicyEffects::loadEffectParameter(cnode* root)
628 {
629 cnode *param;
630 cnode *value;
631 size_t curSize = sizeof(effect_param_t);
632 size_t totSize = sizeof(effect_param_t) + 2 * sizeof(int);
633 effect_param_t *fx_param = (effect_param_t *)malloc(totSize);
634
635 if (fx_param == NULL) {
636 ALOGE("%s malloc error for effect structure of size %zu",
637 __func__, totSize);
638 return NULL;
639 }
640
641 param = config_find(root, PARAM_TAG);
642 value = config_find(root, VALUE_TAG);
643 if (param == NULL && value == NULL) {
644 // try to parse simple parameter form {int int}
645 param = root->first_child;
646 if (param != NULL) {
647 // Note: that a pair of random strings is read as 0 0
648 int *ptr = (int *)fx_param->data;
649 #if LOG_NDEBUG == 0
650 int *ptr2 = (int *)((char *)param + sizeof(effect_param_t));
651 ALOGV("loadEffectParameter() ptr %p ptr2 %p", ptr, ptr2);
652 #endif
653 *ptr++ = atoi(param->name);
654 *ptr = atoi(param->value);
655 fx_param->psize = sizeof(int);
656 fx_param->vsize = sizeof(int);
657 return {fx_param, free};
658 }
659 }
660 if (param == NULL || value == NULL) {
661 ALOGW("loadEffectParameter() invalid parameter description %s",
662 root->name);
663 goto error;
664 }
665
666 fx_param->psize = 0;
667 param = param->first_child;
668 while (param) {
669 ALOGV("loadEffectParameter() reading param of type %s", param->name);
670 size_t size =
671 readParamValue(param, (char **)&fx_param, &curSize, &totSize);
672 if (size == 0) {
673 goto error;
674 }
675 fx_param->psize += size;
676 param = param->next;
677 }
678
679 // align start of value field on 32 bit boundary
680 curSize = ((curSize - 1 ) / sizeof(int) + 1) * sizeof(int);
681
682 fx_param->vsize = 0;
683 value = value->first_child;
684 while (value) {
685 ALOGV("loadEffectParameter() reading value of type %s", value->name);
686 size_t size =
687 readParamValue(value, (char **)&fx_param, &curSize, &totSize);
688 if (size == 0) {
689 goto error;
690 }
691 fx_param->vsize += size;
692 value = value->next;
693 }
694
695 return {fx_param, free};
696
697 error:
698 free(fx_param);
699 return NULL;
700 }
701
702 /* static */
loadEffectParameters(cnode * root,std::vector<std::shared_ptr<const effect_param_t>> & params)703 void AudioPolicyEffects::loadEffectParameters(
704 cnode* root, std::vector<std::shared_ptr<const effect_param_t>>& params)
705 {
706 cnode *node = root->first_child;
707 while (node) {
708 ALOGV("loadEffectParameters() loading param %s", node->name);
709 const auto param = loadEffectParameter(node);
710 if (param != nullptr) {
711 params.push_back(param);
712 }
713 node = node->next;
714 }
715 }
716
717 /* static */
loadEffectConfig(cnode * root,const EffectDescVector & effects)718 std::shared_ptr<AudioPolicyEffects::EffectDescVector> AudioPolicyEffects::loadEffectConfig(
719 cnode* root, const EffectDescVector& effects)
720 {
721 cnode *node = root->first_child;
722 if (node == NULL) {
723 ALOGW("loadInputSource() empty element %s", root->name);
724 return NULL;
725 }
726 auto desc = std::make_shared<EffectDescVector>();
727 while (node) {
728 size_t i;
729
730 for (i = 0; i < effects.size(); i++) {
731 if (effects[i]->mName == node->name) {
732 ALOGV("loadEffectConfig() found effect %s in list", node->name);
733 break;
734 }
735 }
736 if (i == effects.size()) {
737 ALOGV("loadEffectConfig() effect %s not in list", node->name);
738 node = node->next;
739 continue;
740 }
741 auto effect = std::make_shared<EffectDesc>(*effects[i]); // deep copy
742 loadEffectParameters(node, effect->mParams);
743 ALOGV("loadEffectConfig() adding effect %s uuid %08x",
744 effect->mName.c_str(), effect->mUuid.timeLow);
745 desc->push_back(std::move(effect));
746 node = node->next;
747 }
748 if (desc->empty()) {
749 ALOGW("loadEffectConfig() no valid effects found in config %s", root->name);
750 return nullptr;
751 }
752 return desc;
753 }
754
loadInputEffectConfigurations_l(cnode * root,const EffectDescVector & effects)755 status_t AudioPolicyEffects::loadInputEffectConfigurations_l(cnode* root,
756 const EffectDescVector& effects)
757 {
758 cnode *node = config_find(root, PREPROCESSING_TAG);
759 if (node == NULL) {
760 return -ENOENT;
761 }
762 node = node->first_child;
763 while (node) {
764 audio_source_t source = inputSourceNameToEnum(node->name);
765 if (source == AUDIO_SOURCE_CNT) {
766 ALOGW("%s() invalid input source %s", __func__, node->name);
767 node = node->next;
768 continue;
769 }
770 ALOGV("%s() loading input source %s", __func__, node->name);
771 auto desc = loadEffectConfig(node, effects);
772 if (desc == NULL) {
773 node = node->next;
774 continue;
775 }
776 mInputSources[source] = std::move(desc);
777 node = node->next;
778 }
779 return NO_ERROR;
780 }
781
loadStreamEffectConfigurations_l(cnode * root,const EffectDescVector & effects)782 status_t AudioPolicyEffects::loadStreamEffectConfigurations_l(cnode* root,
783 const EffectDescVector& effects)
784 {
785 cnode *node = config_find(root, OUTPUT_SESSION_PROCESSING_TAG);
786 if (node == NULL) {
787 return -ENOENT;
788 }
789 node = node->first_child;
790 while (node) {
791 audio_stream_type_t stream = streamNameToEnum(node->name);
792 if (stream == AUDIO_STREAM_PUBLIC_CNT) {
793 ALOGW("%s() invalid output stream %s", __func__, node->name);
794 node = node->next;
795 continue;
796 }
797 ALOGV("%s() loading output stream %s", __func__, node->name);
798 std::shared_ptr<EffectDescVector> desc = loadEffectConfig(node, effects);
799 if (desc == NULL) {
800 node = node->next;
801 continue;
802 }
803 mOutputStreams[stream] = std::move(desc);
804 node = node->next;
805 }
806 return NO_ERROR;
807 }
808
809 /* static */
loadEffect(cnode * root)810 std::shared_ptr<AudioPolicyEffects::EffectDesc> AudioPolicyEffects::loadEffect(cnode* root)
811 {
812 cnode *node = config_find(root, UUID_TAG);
813 if (node == NULL) {
814 return NULL;
815 }
816 effect_uuid_t uuid;
817 if (AudioEffect::stringToGuid(node->value, &uuid) != NO_ERROR) {
818 ALOGW("loadEffect() invalid uuid %s", node->value);
819 return NULL;
820 }
821 return std::make_shared<EffectDesc>(root->name, uuid);
822 }
823
824 /* static */
loadEffects(cnode * root)825 android::AudioPolicyEffects::EffectDescVector AudioPolicyEffects::loadEffects(cnode *root)
826 {
827 EffectDescVector effects;
828 cnode *node = config_find(root, EFFECTS_TAG);
829 if (node == NULL) {
830 ALOGW("%s() Cannot find %s configuration", __func__, EFFECTS_TAG);
831 return effects;
832 }
833 node = node->first_child;
834 while (node) {
835 ALOGV("loadEffects() loading effect %s", node->name);
836 auto effect = loadEffect(node);
837 if (effect == NULL) {
838 node = node->next;
839 continue;
840 }
841 effects.push_back(std::move(effect));
842 node = node->next;
843 }
844 return effects;
845 }
846
loadAudioEffectConfig_ll(const sp<EffectsFactoryHalInterface> & effectsFactoryHal)847 status_t AudioPolicyEffects::loadAudioEffectConfig_ll(
848 const sp<EffectsFactoryHalInterface>& effectsFactoryHal) {
849 if (!effectsFactoryHal) {
850 ALOGE("%s Null EffectsFactoryHalInterface", __func__);
851 return UNEXPECTED_NULL;
852 }
853
854 const auto skippedElements = VALUE_OR_RETURN_STATUS(effectsFactoryHal->getSkippedElements());
855 const auto processings = effectsFactoryHal->getProcessings();
856 if (!processings) {
857 ALOGE("%s Null processings with %zu skipped elements", __func__, skippedElements);
858 return UNEXPECTED_NULL;
859 }
860
861 auto loadProcessingChain = [](auto& processingChain, auto& streams) {
862 for (auto& stream : processingChain) {
863 auto effectDescs = std::make_shared<EffectDescVector>();
864 for (auto& effect : stream.effects) {
865 effectDescs->push_back(
866 std::make_shared<EffectDesc>(effect->name, effect->uuid));
867 }
868 streams[stream.type] = std::move(effectDescs);
869 }
870 };
871
872 auto loadDeviceProcessingChain = [](auto& processingChain, auto& devicesEffects) {
873 for (auto& deviceProcess : processingChain) {
874 auto effectDescs = std::make_unique<EffectDescVector>();
875 for (auto& effect : deviceProcess.effects) {
876 effectDescs->push_back(
877 std::make_shared<EffectDesc>(effect->name, effect->uuid));
878 }
879 auto devEffects = std::make_unique<DeviceEffects>(
880 std::move(effectDescs), deviceProcess.type, deviceProcess.address);
881 devicesEffects.emplace(deviceProcess.address, std::move(devEffects));
882 }
883 };
884
885 // access to mInputSources and mOutputStreams requires mMutex;
886 loadProcessingChain(processings->preprocess, mInputSources);
887 loadProcessingChain(processings->postprocess, mOutputStreams);
888
889 // access to mDeviceEffects requires mDeviceEffectsMutex
890 loadDeviceProcessingChain(processings->deviceprocess, mDeviceEffects);
891
892 return skippedElements;
893 }
894
loadAudioEffectConfigLegacy_l(const char * path)895 status_t AudioPolicyEffects::loadAudioEffectConfigLegacy_l(const char *path)
896 {
897 cnode *root;
898 char *data;
899
900 data = (char *)load_file(path, NULL);
901 if (data == NULL) {
902 return -ENODEV;
903 }
904 root = config_node("", "");
905 config_load(root, data);
906
907 const EffectDescVector effects = loadEffects(root);
908
909 // requires mMutex
910 loadInputEffectConfigurations_l(root, effects);
911 loadStreamEffectConfigurations_l(root, effects);
912 config_free(root);
913 free(root);
914 free(data);
915
916 return NO_ERROR;
917 }
918
initDefaultDeviceEffects()919 void AudioPolicyEffects::initDefaultDeviceEffects()
920 {
921 std::lock_guard _l(mDeviceEffectsMutex);
922 for (const auto& deviceEffectsIter : mDeviceEffects) {
923 const auto& deviceEffects = deviceEffectsIter.second;
924 for (const auto& effectDesc : *deviceEffects->mEffectDescriptors) {
925 AttributionSourceState attributionSource;
926 attributionSource.packageName = "android";
927 attributionSource.token = sp<BBinder>::make();
928 sp<AudioEffect> fx = sp<AudioEffect>::make(attributionSource);
929 fx->set(EFFECT_UUID_NULL, &effectDesc->mUuid, 0 /* priority */, nullptr /* callback */,
930 AUDIO_SESSION_DEVICE, AUDIO_IO_HANDLE_NONE,
931 AudioDeviceTypeAddr{deviceEffects->getDeviceType(),
932 deviceEffects->getDeviceAddress()});
933 status_t status = fx->initCheck();
934 if (status != NO_ERROR && status != ALREADY_EXISTS) {
935 ALOGE("%s(): failed to create Fx %s on port type=%d address=%s", __func__,
936 effectDesc->mName.c_str(), deviceEffects->getDeviceType(),
937 deviceEffects->getDeviceAddress().c_str());
938 // fx goes out of scope and strong ref on AudioEffect is released
939 continue;
940 }
941 fx->setEnabled(true);
942 ALOGV("%s(): create Fx %s added on port type=%d address=%s", __func__,
943 effectDesc->mName.c_str(), deviceEffects->getDeviceType(),
944 deviceEffects->getDeviceAddress().c_str());
945 deviceEffects->mEffects.push_back(std::move(fx));
946 }
947 }
948 }
949
950 } // namespace android
951