1 /*
2 **
3 ** Copyright 2007, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 
19 #define LOG_TAG "AudioFlinger"
20 //#define LOG_NDEBUG 0
21 
22 // Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23 #define AUDIO_ARRAYS_STATIC_CHECK 1
24 
25 #include "Configuration.h"
26 #include <dirent.h>
27 #include <math.h>
28 #include <signal.h>
29 #include <string>
30 #include <sys/time.h>
31 #include <sys/resource.h>
32 #include <thread>
33 
34 #include <android/os/IExternalVibratorService.h>
35 #include <binder/IPCThreadState.h>
36 #include <binder/IServiceManager.h>
37 #include <utils/Log.h>
38 #include <utils/Trace.h>
39 #include <binder/Parcel.h>
40 #include <media/audiohal/DeviceHalInterface.h>
41 #include <media/audiohal/DevicesFactoryHalInterface.h>
42 #include <media/audiohal/EffectsFactoryHalInterface.h>
43 #include <media/AudioParameter.h>
44 #include <media/TypeConverter.h>
45 #include <memunreachable/memunreachable.h>
46 #include <utils/String16.h>
47 #include <utils/threads.h>
48 
49 #include <cutils/atomic.h>
50 #include <cutils/properties.h>
51 
52 #include <system/audio.h>
53 #include <audiomanager/AudioManager.h>
54 
55 #include "AudioFlinger.h"
56 #include "NBAIO_Tee.h"
57 
58 #include <media/AudioResamplerPublic.h>
59 
60 #include <system/audio_effects/effect_visualizer.h>
61 #include <system/audio_effects/effect_ns.h>
62 #include <system/audio_effects/effect_aec.h>
63 
64 #include <audio_utils/primitives.h>
65 
66 #include <powermanager/PowerManager.h>
67 
68 #include <media/IMediaLogService.h>
69 #include <media/MemoryLeakTrackUtil.h>
70 #include <media/nbaio/Pipe.h>
71 #include <media/nbaio/PipeReader.h>
72 #include <mediautils/BatteryNotifier.h>
73 #include <mediautils/ServiceUtilities.h>
74 #include <mediautils/TimeCheck.h>
75 #include <private/android_filesystem_config.h>
76 
77 //#define BUFLOG_NDEBUG 0
78 #include <BufLog.h>
79 
80 #include "TypedLogger.h"
81 
82 // ----------------------------------------------------------------------------
83 
84 // Note: the following macro is used for extremely verbose logging message.  In
85 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
86 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
87 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
88 // turned on.  Do not uncomment the #def below unless you really know what you
89 // are doing and want to see all of the extremely verbose messages.
90 //#define VERY_VERY_VERBOSE_LOGGING
91 #ifdef VERY_VERY_VERBOSE_LOGGING
92 #define ALOGVV ALOGV
93 #else
94 #define ALOGVV(a...) do { } while(0)
95 #endif
96 
97 namespace android {
98 
99 static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
100 static const char kHardwareLockedString[] = "Hardware lock is taken\n";
101 static const char kClientLockedString[] = "Client lock is taken\n";
102 static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
103 
104 
105 nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
106 
107 uint32_t AudioFlinger::mScreenState;
108 
109 // In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
110 // we define a minimum time during which a global effect is considered enabled.
111 static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
112 
113 Mutex gLock;
114 wp<AudioFlinger> gAudioFlinger;
115 
116 // Keep a strong reference to media.log service around forever.
117 // The service is within our parent process so it can never die in a way that we could observe.
118 // These two variables are const after initialization.
119 static sp<IBinder> sMediaLogServiceAsBinder;
120 static sp<IMediaLogService> sMediaLogService;
121 
122 static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
123 
sMediaLogInit()124 static void sMediaLogInit()
125 {
126     sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
127     if (sMediaLogServiceAsBinder != 0) {
128         sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
129     }
130 }
131 
132 // Keep a strong reference to external vibrator service
133 static sp<os::IExternalVibratorService> sExternalVibratorService;
134 
getExternalVibratorService()135 static sp<os::IExternalVibratorService> getExternalVibratorService() {
136     if (sExternalVibratorService == 0) {
137         sp<IBinder> binder = defaultServiceManager()->getService(
138             String16("external_vibrator_service"));
139         if (binder != 0) {
140             sExternalVibratorService =
141                 interface_cast<os::IExternalVibratorService>(binder);
142         }
143     }
144     return sExternalVibratorService;
145 }
146 
147 class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
148   public:
onNewDevicesAvailable()149     void onNewDevicesAvailable() override {
150         // Start a detached thread to execute notification in parallel.
151         // This is done to prevent mutual blocking of audio_flinger and
152         // audio_policy services during system initialization.
153         std::thread notifier([]() {
154             AudioSystem::onNewAudioModulesAvailable();
155         });
156         notifier.detach();
157     }
158 };
159 
160 // ----------------------------------------------------------------------------
161 
formatToString(audio_format_t format)162 std::string formatToString(audio_format_t format) {
163     std::string result;
164     FormatConverter::toString(format, result);
165     return result;
166 }
167 
168 // ----------------------------------------------------------------------------
169 
AudioFlinger()170 AudioFlinger::AudioFlinger()
171     : BnAudioFlinger(),
172       mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
173       mPrimaryHardwareDev(NULL),
174       mAudioHwDevs(NULL),
175       mHardwareStatus(AUDIO_HW_IDLE),
176       mMasterVolume(1.0f),
177       mMasterMute(false),
178       // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
179       mMode(AUDIO_MODE_INVALID),
180       mBtNrecIsOff(false),
181       mIsLowRamDevice(true),
182       mIsDeviceTypeKnown(false),
183       mTotalMemory(0),
184       mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
185       mGlobalEffectEnableTime(0),
186       mPatchPanel(this),
187       mDeviceEffectManager(this),
188       mSystemReady(false)
189 {
190     // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
191     for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
192         // zero ID has a special meaning, so unavailable
193         mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
194     }
195 
196     const bool doLog = property_get_bool("ro.test_harness", false);
197     if (doLog) {
198         mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
199                 MemoryHeapBase::READ_ONLY);
200         (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
201     }
202 
203     // reset battery stats.
204     // if the audio service has crashed, battery stats could be left
205     // in bad state, reset the state upon service start.
206     BatteryNotifier::getInstance().noteResetAudio();
207 
208     mDevicesFactoryHal = DevicesFactoryHalInterface::create();
209     mEffectsFactoryHal = EffectsFactoryHalInterface::create();
210 
211     mMediaLogNotifier->run("MediaLogNotifier");
212     std::vector<pid_t> halPids;
213     mDevicesFactoryHal->getHalPids(&halPids);
214     TimeCheck::setAudioHalPids(halPids);
215 }
216 
onFirstRef()217 void AudioFlinger::onFirstRef()
218 {
219     Mutex::Autolock _l(mLock);
220 
221     /* TODO: move all this work into an Init() function */
222     char val_str[PROPERTY_VALUE_MAX] = { 0 };
223     if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
224         uint32_t int_val;
225         if (1 == sscanf(val_str, "%u", &int_val)) {
226             mStandbyTimeInNsecs = milliseconds(int_val);
227             ALOGI("Using %u mSec as standby time.", int_val);
228         } else {
229             mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
230             ALOGI("Using default %u mSec as standby time.",
231                     (uint32_t)(mStandbyTimeInNsecs / 1000000));
232         }
233     }
234 
235     mMode = AUDIO_MODE_NORMAL;
236 
237     gAudioFlinger = this;
238 
239     mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
240     mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
241 }
242 
setAudioHalPids(const std::vector<pid_t> & pids)243 status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
244   TimeCheck::setAudioHalPids(pids);
245   return NO_ERROR;
246 }
247 
~AudioFlinger()248 AudioFlinger::~AudioFlinger()
249 {
250     while (!mRecordThreads.isEmpty()) {
251         // closeInput_nonvirtual() will remove specified entry from mRecordThreads
252         closeInput_nonvirtual(mRecordThreads.keyAt(0));
253     }
254     while (!mPlaybackThreads.isEmpty()) {
255         // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
256         closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
257     }
258     while (!mMmapThreads.isEmpty()) {
259         const audio_io_handle_t io = mMmapThreads.keyAt(0);
260         if (mMmapThreads.valueAt(0)->isOutput()) {
261             closeOutput_nonvirtual(io); // removes entry from mMmapThreads
262         } else {
263             closeInput_nonvirtual(io);  // removes entry from mMmapThreads
264         }
265     }
266 
267     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
268         // no mHardwareLock needed, as there are no other references to this
269         delete mAudioHwDevs.valueAt(i);
270     }
271 
272     // Tell media.log service about any old writers that still need to be unregistered
273     if (sMediaLogService != 0) {
274         for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
275             sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
276             mUnregisteredWriters.pop();
277             sMediaLogService->unregisterWriter(iMemory);
278         }
279     }
280 }
281 
282 //static
283 __attribute__ ((visibility ("default")))
openMmapStream(MmapStreamInterface::stream_direction_t direction,const audio_attributes_t * attr,audio_config_base_t * config,const AudioClient & client,audio_port_handle_t * deviceId,audio_session_t * sessionId,const sp<MmapStreamCallback> & callback,sp<MmapStreamInterface> & interface,audio_port_handle_t * handle)284 status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
285                                              const audio_attributes_t *attr,
286                                              audio_config_base_t *config,
287                                              const AudioClient& client,
288                                              audio_port_handle_t *deviceId,
289                                              audio_session_t *sessionId,
290                                              const sp<MmapStreamCallback>& callback,
291                                              sp<MmapStreamInterface>& interface,
292                                              audio_port_handle_t *handle)
293 {
294     sp<AudioFlinger> af;
295     {
296         Mutex::Autolock _l(gLock);
297         af = gAudioFlinger.promote();
298     }
299     status_t ret = NO_INIT;
300     if (af != 0) {
301         ret = af->openMmapStream(
302                 direction, attr, config, client, deviceId,
303                 sessionId, callback, interface, handle);
304     }
305     return ret;
306 }
307 
openMmapStream(MmapStreamInterface::stream_direction_t direction,const audio_attributes_t * attr,audio_config_base_t * config,const AudioClient & client,audio_port_handle_t * deviceId,audio_session_t * sessionId,const sp<MmapStreamCallback> & callback,sp<MmapStreamInterface> & interface,audio_port_handle_t * handle)308 status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
309                                       const audio_attributes_t *attr,
310                                       audio_config_base_t *config,
311                                       const AudioClient& client,
312                                       audio_port_handle_t *deviceId,
313                                       audio_session_t *sessionId,
314                                       const sp<MmapStreamCallback>& callback,
315                                       sp<MmapStreamInterface>& interface,
316                                       audio_port_handle_t *handle)
317 {
318     status_t ret = initCheck();
319     if (ret != NO_ERROR) {
320         return ret;
321     }
322     audio_session_t actualSessionId = *sessionId;
323     if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
324         actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
325     }
326     audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
327     audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
328     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
329     audio_attributes_t localAttr = *attr;
330     if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
331         audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
332         fullConfig.sample_rate = config->sample_rate;
333         fullConfig.channel_mask = config->channel_mask;
334         fullConfig.format = config->format;
335         std::vector<audio_io_handle_t> secondaryOutputs;
336 
337         ret = AudioSystem::getOutputForAttr(&localAttr, &io,
338                                             actualSessionId,
339                                             &streamType, client.clientPid, client.clientUid,
340                                             &fullConfig,
341                                             (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
342                                                     AUDIO_OUTPUT_FLAG_DIRECT),
343                                             deviceId, &portId, &secondaryOutputs);
344         ALOGW_IF(!secondaryOutputs.empty(),
345                  "%s does not support secondary outputs, ignoring them", __func__);
346     } else {
347         ret = AudioSystem::getInputForAttr(&localAttr, &io,
348                                               RECORD_RIID_INVALID,
349                                               actualSessionId,
350                                               client.clientPid,
351                                               client.clientUid,
352                                               client.packageName,
353                                               config,
354                                               AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
355     }
356     if (ret != NO_ERROR) {
357         return ret;
358     }
359 
360     // at this stage, a MmapThread was created when openOutput() or openInput() was called by
361     // audio policy manager and we can retrieve it
362     sp<MmapThread> thread = mMmapThreads.valueFor(io);
363     if (thread != 0) {
364         interface = new MmapThreadHandle(thread);
365         thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
366         *handle = portId;
367         *sessionId = actualSessionId;
368     } else {
369         if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
370             AudioSystem::releaseOutput(portId);
371         } else {
372             AudioSystem::releaseInput(portId);
373         }
374         ret = NO_INIT;
375     }
376 
377     ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
378 
379     return ret;
380 }
381 
382 /* static */
onExternalVibrationStart(const sp<os::ExternalVibration> & externalVibration)383 int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
384     sp<os::IExternalVibratorService> evs = getExternalVibratorService();
385     if (evs != 0) {
386         int32_t ret;
387         binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
388         if (status.isOk()) {
389             return ret;
390         }
391     }
392     return AudioMixer::HAPTIC_SCALE_MUTE;
393 }
394 
395 /* static */
onExternalVibrationStop(const sp<os::ExternalVibration> & externalVibration)396 void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
397     sp<os::IExternalVibratorService> evs = getExternalVibratorService();
398     if (evs != 0) {
399         evs->onExternalVibrationStop(*externalVibration);
400     }
401 }
402 
addEffectToHal(audio_port_handle_t deviceId,audio_module_handle_t hwModuleId,sp<EffectHalInterface> effect)403 status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
404         audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
405     AutoMutex lock(mHardwareLock);
406     AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
407     if (audioHwDevice == nullptr) {
408         return NO_INIT;
409     }
410     return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
411 }
412 
removeEffectFromHal(audio_port_handle_t deviceId,audio_module_handle_t hwModuleId,sp<EffectHalInterface> effect)413 status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
414         audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
415     AutoMutex lock(mHardwareLock);
416     AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
417     if (audioHwDevice == nullptr) {
418         return NO_INIT;
419     }
420     return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
421 }
422 
423 static const char * const audio_interfaces[] = {
424     AUDIO_HARDWARE_MODULE_ID_PRIMARY,
425     AUDIO_HARDWARE_MODULE_ID_A2DP,
426     AUDIO_HARDWARE_MODULE_ID_USB,
427 };
428 
findSuitableHwDev_l(audio_module_handle_t module,audio_devices_t deviceType)429 AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
430         audio_module_handle_t module,
431         audio_devices_t deviceType)
432 {
433     // if module is 0, the request comes from an old policy manager and we should load
434     // well known modules
435     AutoMutex lock(mHardwareLock);
436     if (module == 0) {
437         ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
438         for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
439             loadHwModule_l(audio_interfaces[i]);
440         }
441         // then try to find a module supporting the requested device.
442         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
443             AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
444             sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
445             uint32_t supportedDevices;
446             if (dev->getSupportedDevices(&supportedDevices) == OK &&
447                     (supportedDevices & deviceType) == deviceType) {
448                 return audioHwDevice;
449             }
450         }
451     } else {
452         // check a match for the requested module handle
453         AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
454         if (audioHwDevice != NULL) {
455             return audioHwDevice;
456         }
457     }
458 
459     return NULL;
460 }
461 
dumpClients(int fd,const Vector<String16> & args __unused)462 void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
463 {
464     const size_t SIZE = 256;
465     char buffer[SIZE];
466     String8 result;
467 
468     result.append("Clients:\n");
469     for (size_t i = 0; i < mClients.size(); ++i) {
470         sp<Client> client = mClients.valueAt(i).promote();
471         if (client != 0) {
472             snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
473             result.append(buffer);
474         }
475     }
476 
477     result.append("Notification Clients:\n");
478     for (size_t i = 0; i < mNotificationClients.size(); ++i) {
479         snprintf(buffer, SIZE, "  pid: %d\n", mNotificationClients.keyAt(i));
480         result.append(buffer);
481     }
482 
483     result.append("Global session refs:\n");
484     result.append("  session   pid count\n");
485     for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
486         AudioSessionRef *r = mAudioSessionRefs[i];
487         snprintf(buffer, SIZE, "  %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
488         result.append(buffer);
489     }
490     write(fd, result.string(), result.size());
491 }
492 
493 
dumpInternals(int fd,const Vector<String16> & args __unused)494 void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
495 {
496     const size_t SIZE = 256;
497     char buffer[SIZE];
498     String8 result;
499     hardware_call_state hardwareStatus = mHardwareStatus;
500 
501     snprintf(buffer, SIZE, "Hardware status: %d\n"
502                            "Standby Time mSec: %u\n",
503                             hardwareStatus,
504                             (uint32_t)(mStandbyTimeInNsecs / 1000000));
505     result.append(buffer);
506     write(fd, result.string(), result.size());
507 }
508 
dumpPermissionDenial(int fd,const Vector<String16> & args __unused)509 void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
510 {
511     const size_t SIZE = 256;
512     char buffer[SIZE];
513     String8 result;
514     snprintf(buffer, SIZE, "Permission Denial: "
515             "can't dump AudioFlinger from pid=%d, uid=%d\n",
516             IPCThreadState::self()->getCallingPid(),
517             IPCThreadState::self()->getCallingUid());
518     result.append(buffer);
519     write(fd, result.string(), result.size());
520 }
521 
dumpTryLock(Mutex & mutex)522 bool AudioFlinger::dumpTryLock(Mutex& mutex)
523 {
524     status_t err = mutex.timedLock(kDumpLockTimeoutNs);
525     return err == NO_ERROR;
526 }
527 
dump(int fd,const Vector<String16> & args)528 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
529 {
530     if (!dumpAllowed()) {
531         dumpPermissionDenial(fd, args);
532     } else {
533         // get state of hardware lock
534         bool hardwareLocked = dumpTryLock(mHardwareLock);
535         if (!hardwareLocked) {
536             String8 result(kHardwareLockedString);
537             write(fd, result.string(), result.size());
538         } else {
539             mHardwareLock.unlock();
540         }
541 
542         const bool locked = dumpTryLock(mLock);
543 
544         // failed to lock - AudioFlinger is probably deadlocked
545         if (!locked) {
546             String8 result(kDeadlockedString);
547             write(fd, result.string(), result.size());
548         }
549 
550         bool clientLocked = dumpTryLock(mClientLock);
551         if (!clientLocked) {
552             String8 result(kClientLockedString);
553             write(fd, result.string(), result.size());
554         }
555 
556         if (mEffectsFactoryHal != 0) {
557             mEffectsFactoryHal->dumpEffects(fd);
558         } else {
559             String8 result(kNoEffectsFactory);
560             write(fd, result.string(), result.size());
561         }
562 
563         dumpClients(fd, args);
564         if (clientLocked) {
565             mClientLock.unlock();
566         }
567 
568         dumpInternals(fd, args);
569 
570         // dump playback threads
571         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
572             mPlaybackThreads.valueAt(i)->dump(fd, args);
573         }
574 
575         // dump record threads
576         for (size_t i = 0; i < mRecordThreads.size(); i++) {
577             mRecordThreads.valueAt(i)->dump(fd, args);
578         }
579 
580         // dump mmap threads
581         for (size_t i = 0; i < mMmapThreads.size(); i++) {
582             mMmapThreads.valueAt(i)->dump(fd, args);
583         }
584 
585         // dump orphan effect chains
586         if (mOrphanEffectChains.size() != 0) {
587             write(fd, "  Orphan Effect Chains\n", strlen("  Orphan Effect Chains\n"));
588             for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
589                 mOrphanEffectChains.valueAt(i)->dump(fd, args);
590             }
591         }
592         // dump all hardware devs
593         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
594             sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
595             dev->dump(fd);
596         }
597 
598         mPatchPanel.dump(fd);
599 
600         mDeviceEffectManager.dump(fd);
601 
602         // dump external setParameters
603         auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
604             dprintf(fd, "\n%s setParameters:\n", name);
605             logger.dump(fd, "    " /* prefix */);
606         };
607         dumpLogger(mRejectedSetParameterLog, "Rejected");
608         dumpLogger(mAppSetParameterLog, "App");
609         dumpLogger(mSystemSetParameterLog, "System");
610 
611         // dump historical threads in the last 10 seconds
612         const std::string threadLog = mThreadLog.dumpToString(
613                 "Historical Thread Log ", 0 /* lines */,
614                 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
615         write(fd, threadLog.c_str(), threadLog.size());
616 
617         BUFLOG_RESET;
618 
619         if (locked) {
620             mLock.unlock();
621         }
622 
623 #ifdef TEE_SINK
624         // NBAIO_Tee dump is safe to call outside of AF lock.
625         NBAIO_Tee::dumpAll(fd, "_DUMP");
626 #endif
627         // append a copy of media.log here by forwarding fd to it, but don't attempt
628         // to lookup the service if it's not running, as it will block for a second
629         if (sMediaLogServiceAsBinder != 0) {
630             dprintf(fd, "\nmedia.log:\n");
631             Vector<String16> args;
632             sMediaLogServiceAsBinder->dump(fd, args);
633         }
634 
635         // check for optional arguments
636         bool dumpMem = false;
637         bool unreachableMemory = false;
638         for (const auto &arg : args) {
639             if (arg == String16("-m")) {
640                 dumpMem = true;
641             } else if (arg == String16("--unreachable")) {
642                 unreachableMemory = true;
643             }
644         }
645 
646         if (dumpMem) {
647             dprintf(fd, "\nDumping memory:\n");
648             std::string s = dumpMemoryAddresses(100 /* limit */);
649             write(fd, s.c_str(), s.size());
650         }
651         if (unreachableMemory) {
652             dprintf(fd, "\nDumping unreachable memory:\n");
653             // TODO - should limit be an argument parameter?
654             std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
655             write(fd, s.c_str(), s.size());
656         }
657     }
658     return NO_ERROR;
659 }
660 
registerPid(pid_t pid)661 sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
662 {
663     Mutex::Autolock _cl(mClientLock);
664     // If pid is already in the mClients wp<> map, then use that entry
665     // (for which promote() is always != 0), otherwise create a new entry and Client.
666     sp<Client> client = mClients.valueFor(pid).promote();
667     if (client == 0) {
668         client = new Client(this, pid);
669         mClients.add(pid, client);
670     }
671 
672     return client;
673 }
674 
newWriter_l(size_t size,const char * name)675 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
676 {
677     // If there is no memory allocated for logs, return a no-op writer that does nothing.
678     // Similarly if we can't contact the media.log service, also return a no-op writer.
679     if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
680         return new NBLog::Writer();
681     }
682     sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
683     // If allocation fails, consult the vector of previously unregistered writers
684     // and garbage-collect one or more them until an allocation succeeds
685     if (shared == 0) {
686         Mutex::Autolock _l(mUnregisteredWritersLock);
687         for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
688             {
689                 // Pick the oldest stale writer to garbage-collect
690                 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
691                 mUnregisteredWriters.removeAt(0);
692                 sMediaLogService->unregisterWriter(iMemory);
693                 // Now the media.log remote reference to IMemory is gone.  When our last local
694                 // reference to IMemory also drops to zero at end of this block,
695                 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
696             }
697             // Re-attempt the allocation
698             shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
699             if (shared != 0) {
700                 goto success;
701             }
702         }
703         // Even after garbage-collecting all old writers, there is still not enough memory,
704         // so return a no-op writer
705         return new NBLog::Writer();
706     }
707 success:
708     NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
709     new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
710                                                 // explicit destructor not needed since it is POD
711     sMediaLogService->registerWriter(shared, size, name);
712     return new NBLog::Writer(shared, size);
713 }
714 
unregisterWriter(const sp<NBLog::Writer> & writer)715 void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
716 {
717     if (writer == 0) {
718         return;
719     }
720     sp<IMemory> iMemory(writer->getIMemory());
721     if (iMemory == 0) {
722         return;
723     }
724     // Rather than removing the writer immediately, append it to a queue of old writers to
725     // be garbage-collected later.  This allows us to continue to view old logs for a while.
726     Mutex::Autolock _l(mUnregisteredWritersLock);
727     mUnregisteredWriters.push(writer);
728 }
729 
730 // IAudioFlinger interface
731 
createTrack(const CreateTrackInput & input,CreateTrackOutput & output,status_t * status)732 sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
733                                           CreateTrackOutput& output,
734                                           status_t *status)
735 {
736     sp<PlaybackThread::Track> track;
737     sp<TrackHandle> trackHandle;
738     sp<Client> client;
739     status_t lStatus;
740     audio_stream_type_t streamType;
741     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
742     std::vector<audio_io_handle_t> secondaryOutputs;
743 
744     bool updatePid = (input.clientInfo.clientPid == -1);
745     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
746     uid_t clientUid = input.clientInfo.clientUid;
747     audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
748     std::vector<int> effectIds;
749     audio_attributes_t localAttr = input.attr;
750 
751     if (!isAudioServerOrMediaServerUid(callingUid)) {
752         ALOGW_IF(clientUid != callingUid,
753                 "%s uid %d tried to pass itself off as %d",
754                 __FUNCTION__, callingUid, clientUid);
755         clientUid = callingUid;
756         updatePid = true;
757     }
758     pid_t clientPid = input.clientInfo.clientPid;
759     const pid_t callingPid = IPCThreadState::self()->getCallingPid();
760     if (updatePid) {
761         ALOGW_IF(clientPid != -1 && clientPid != callingPid,
762                  "%s uid %d pid %d tried to pass itself off as pid %d",
763                  __func__, callingUid, callingPid, clientPid);
764         clientPid = callingPid;
765     }
766 
767     audio_session_t sessionId = input.sessionId;
768     if (sessionId == AUDIO_SESSION_ALLOCATE) {
769         sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
770     } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
771         lStatus = BAD_VALUE;
772         goto Exit;
773     }
774 
775     output.sessionId = sessionId;
776     output.outputId = AUDIO_IO_HANDLE_NONE;
777     output.selectedDeviceId = input.selectedDeviceId;
778     lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
779                                             clientPid, clientUid, &input.config, input.flags,
780                                             &output.selectedDeviceId, &portId, &secondaryOutputs);
781 
782     if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
783         ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
784         goto Exit;
785     }
786     // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
787     // but if someone uses binder directly they could bypass that and cause us to crash
788     if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
789         ALOGE("createTrack() invalid stream type %d", streamType);
790         lStatus = BAD_VALUE;
791         goto Exit;
792     }
793 
794     // further channel mask checks are performed by createTrack_l() depending on the thread type
795     if (!audio_is_output_channel(input.config.channel_mask)) {
796         ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
797         lStatus = BAD_VALUE;
798         goto Exit;
799     }
800 
801     // further format checks are performed by createTrack_l() depending on the thread type
802     if (!audio_is_valid_format(input.config.format)) {
803         ALOGE("createTrack() invalid format %#x", input.config.format);
804         lStatus = BAD_VALUE;
805         goto Exit;
806     }
807 
808     {
809         Mutex::Autolock _l(mLock);
810         PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
811         if (thread == NULL) {
812             ALOGE("no playback thread found for output handle %d", output.outputId);
813             lStatus = BAD_VALUE;
814             goto Exit;
815         }
816 
817         client = registerPid(clientPid);
818 
819         PlaybackThread *effectThread = NULL;
820         // check if an effect chain with the same session ID is present on another
821         // output thread and move it here.
822         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
823             sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
824             if (mPlaybackThreads.keyAt(i) != output.outputId) {
825                 uint32_t sessions = t->hasAudioSession(sessionId);
826                 if (sessions & ThreadBase::EFFECT_SESSION) {
827                     effectThread = t.get();
828                     break;
829                 }
830             }
831         }
832         ALOGV("createTrack() sessionId: %d", sessionId);
833 
834         output.sampleRate = input.config.sample_rate;
835         output.frameCount = input.frameCount;
836         output.notificationFrameCount = input.notificationFrameCount;
837         output.flags = input.flags;
838 
839         track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
840                                       input.config.format, input.config.channel_mask,
841                                       &output.frameCount, &output.notificationFrameCount,
842                                       input.notificationsPerBuffer, input.speed,
843                                       input.sharedBuffer, sessionId, &output.flags,
844                                       callingPid, input.clientInfo.clientTid, clientUid,
845                                       &lStatus, portId);
846         LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
847         // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
848 
849         output.afFrameCount = thread->frameCount();
850         output.afSampleRate = thread->sampleRate();
851         output.afLatencyMs = thread->latency();
852         output.portId = portId;
853 
854         if (lStatus == NO_ERROR) {
855             // Connect secondary outputs. Failure on a secondary output must not imped the primary
856             // Any secondary output setup failure will lead to a desync between the AP and AF until
857             // the track is destroyed.
858             TeePatches teePatches;
859             for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
860                 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
861                 if (secondaryThread == NULL) {
862                     ALOGE("no playback thread found for secondary output %d", output.outputId);
863                     continue;
864                 }
865 
866                 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
867                                           / thread->sampleRate();
868                 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
869                                           / secondaryThread->sampleRate();
870                 // If the secondary output has just been opened, the first secondaryThread write
871                 // will not block as it will fill the empty startup buffer of the HAL,
872                 // so a second sink buffer needs to be ready for the immediate next blocking write.
873                 // Additionally, have a margin of one main thread buffer as the scheduling jitter
874                 // can reorder the writes (eg if thread A&B have the same write intervale,
875                 // the scheduler could schedule AB...BA)
876                 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
877                 // Total secondary output buffer must be at least as the read frames plus
878                 // the margin of a few buffers on both sides in case the
879                 // threads scheduling has some jitter.
880                 // That value should not impact latency as the secondary track is started before
881                 // its buffer is full, see frameCountToBeReady.
882                 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
883                 // The frameCount should also not be smaller than the secondary thread min frame
884                 // count
885                 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
886                             [&] { Mutex::Autolock _l(secondaryThread->mLock);
887                                   return secondaryThread->latency_l(); }(),
888                             secondaryThread->mNormalFrameCount,
889                             secondaryThread->mSampleRate,
890                             output.sampleRate,
891                             input.speed);
892                 frameCount = std::max(frameCount, minFrameCount);
893 
894                 using namespace std::chrono_literals;
895                 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
896                 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
897                                                                output.sampleRate,
898                                                                inChannelMask,
899                                                                input.config.format,
900                                                                frameCount,
901                                                                NULL /* buffer */,
902                                                                (size_t)0 /* bufferSize */,
903                                                                AUDIO_INPUT_FLAG_DIRECT,
904                                                                0ns /* timeout */);
905                 status_t status = patchRecord->initCheck();
906                 if (status != NO_ERROR) {
907                     ALOGE("Secondary output patchRecord init failed: %d", status);
908                     continue;
909                 }
910 
911                 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
912                 // for fast usage: thread has fast mixer, sample rate matches, etc.;
913                 // for now, we exclude fast tracks by removing the Fast flag.
914                 const audio_output_flags_t outputFlags =
915                         (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
916                 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
917                                                                streamType,
918                                                                output.sampleRate,
919                                                                input.config.channel_mask,
920                                                                input.config.format,
921                                                                frameCount,
922                                                                patchRecord->buffer(),
923                                                                patchRecord->bufferSize(),
924                                                                outputFlags,
925                                                                0ns /* timeout */,
926                                                                frameCountToBeReady);
927                 status = patchTrack->initCheck();
928                 if (status != NO_ERROR) {
929                     ALOGE("Secondary output patchTrack init failed: %d", status);
930                     continue;
931                 }
932                 teePatches.push_back({patchRecord, patchTrack});
933                 secondaryThread->addPatchTrack(patchTrack);
934                 // In case the downstream patchTrack on the secondaryThread temporarily outlives
935                 // our created track, ensure the corresponding patchRecord is still alive.
936                 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
937                 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
938             }
939             track->setTeePatches(std::move(teePatches));
940         }
941 
942         // move effect chain to this output thread if an effect on same session was waiting
943         // for a track to be created
944         if (lStatus == NO_ERROR && effectThread != NULL) {
945             // no risk of deadlock because AudioFlinger::mLock is held
946             Mutex::Autolock _dl(thread->mLock);
947             Mutex::Autolock _sl(effectThread->mLock);
948             if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
949                 effectThreadId = thread->id();
950                 effectIds = thread->getEffectIds_l(sessionId);
951             }
952         }
953 
954         // Look for sync events awaiting for a session to be used.
955         for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
956             if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
957                 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
958                     if (lStatus == NO_ERROR) {
959                         (void) track->setSyncEvent(mPendingSyncEvents[i]);
960                     } else {
961                         mPendingSyncEvents[i]->cancel();
962                     }
963                     mPendingSyncEvents.removeAt(i);
964                     i--;
965                 }
966             }
967         }
968 
969         setAudioHwSyncForSession_l(thread, sessionId);
970     }
971 
972     if (lStatus != NO_ERROR) {
973         // remove local strong reference to Client before deleting the Track so that the
974         // Client destructor is called by the TrackBase destructor with mClientLock held
975         // Don't hold mClientLock when releasing the reference on the track as the
976         // destructor will acquire it.
977         {
978             Mutex::Autolock _cl(mClientLock);
979             client.clear();
980         }
981         track.clear();
982         goto Exit;
983     }
984 
985     // effectThreadId is not NONE if an effect chain corresponding to the track session
986     // was found on another thread and must be moved on this thread
987     if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
988         AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
989     }
990 
991     // return handle to client
992     trackHandle = new TrackHandle(track);
993 
994 Exit:
995     if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
996         AudioSystem::releaseOutput(portId);
997     }
998     *status = lStatus;
999     return trackHandle;
1000 }
1001 
sampleRate(audio_io_handle_t ioHandle) const1002 uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
1003 {
1004     Mutex::Autolock _l(mLock);
1005     ThreadBase *thread = checkThread_l(ioHandle);
1006     if (thread == NULL) {
1007         ALOGW("sampleRate() unknown thread %d", ioHandle);
1008         return 0;
1009     }
1010     return thread->sampleRate();
1011 }
1012 
format(audio_io_handle_t output) const1013 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
1014 {
1015     Mutex::Autolock _l(mLock);
1016     PlaybackThread *thread = checkPlaybackThread_l(output);
1017     if (thread == NULL) {
1018         ALOGW("format() unknown thread %d", output);
1019         return AUDIO_FORMAT_INVALID;
1020     }
1021     return thread->format();
1022 }
1023 
frameCount(audio_io_handle_t ioHandle) const1024 size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
1025 {
1026     Mutex::Autolock _l(mLock);
1027     ThreadBase *thread = checkThread_l(ioHandle);
1028     if (thread == NULL) {
1029         ALOGW("frameCount() unknown thread %d", ioHandle);
1030         return 0;
1031     }
1032     // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1033     //       should examine all callers and fix them to handle smaller counts
1034     return thread->frameCount();
1035 }
1036 
frameCountHAL(audio_io_handle_t ioHandle) const1037 size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1038 {
1039     Mutex::Autolock _l(mLock);
1040     ThreadBase *thread = checkThread_l(ioHandle);
1041     if (thread == NULL) {
1042         ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1043         return 0;
1044     }
1045     return thread->frameCountHAL();
1046 }
1047 
latency(audio_io_handle_t output) const1048 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
1049 {
1050     Mutex::Autolock _l(mLock);
1051     PlaybackThread *thread = checkPlaybackThread_l(output);
1052     if (thread == NULL) {
1053         ALOGW("latency(): no playback thread found for output handle %d", output);
1054         return 0;
1055     }
1056     return thread->latency();
1057 }
1058 
setMasterVolume(float value)1059 status_t AudioFlinger::setMasterVolume(float value)
1060 {
1061     status_t ret = initCheck();
1062     if (ret != NO_ERROR) {
1063         return ret;
1064     }
1065 
1066     // check calling permissions
1067     if (!settingsAllowed()) {
1068         return PERMISSION_DENIED;
1069     }
1070 
1071     Mutex::Autolock _l(mLock);
1072     mMasterVolume = value;
1073 
1074     // Set master volume in the HALs which support it.
1075     {
1076         AutoMutex lock(mHardwareLock);
1077         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1078             AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
1079 
1080             mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1081             if (dev->canSetMasterVolume()) {
1082                 dev->hwDevice()->setMasterVolume(value);
1083             }
1084             mHardwareStatus = AUDIO_HW_IDLE;
1085         }
1086     }
1087     // Now set the master volume in each playback thread.  Playback threads
1088     // assigned to HALs which do not have master volume support will apply
1089     // master volume during the mix operation.  Threads with HALs which do
1090     // support master volume will simply ignore the setting.
1091     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1092         if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1093             continue;
1094         }
1095         mPlaybackThreads.valueAt(i)->setMasterVolume(value);
1096     }
1097 
1098     return NO_ERROR;
1099 }
1100 
setMasterBalance(float balance)1101 status_t AudioFlinger::setMasterBalance(float balance)
1102 {
1103     status_t ret = initCheck();
1104     if (ret != NO_ERROR) {
1105         return ret;
1106     }
1107 
1108     // check calling permissions
1109     if (!settingsAllowed()) {
1110         return PERMISSION_DENIED;
1111     }
1112 
1113     // check range
1114     if (isnan(balance) || fabs(balance) > 1.f) {
1115         return BAD_VALUE;
1116     }
1117 
1118     Mutex::Autolock _l(mLock);
1119 
1120     // short cut.
1121     if (mMasterBalance == balance) return NO_ERROR;
1122 
1123     mMasterBalance = balance;
1124 
1125     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1126         if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1127             continue;
1128         }
1129         mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1130     }
1131 
1132     return NO_ERROR;
1133 }
1134 
setMode(audio_mode_t mode)1135 status_t AudioFlinger::setMode(audio_mode_t mode)
1136 {
1137     status_t ret = initCheck();
1138     if (ret != NO_ERROR) {
1139         return ret;
1140     }
1141 
1142     // check calling permissions
1143     if (!settingsAllowed()) {
1144         return PERMISSION_DENIED;
1145     }
1146     if (uint32_t(mode) >= AUDIO_MODE_CNT) {
1147         ALOGW("Illegal value: setMode(%d)", mode);
1148         return BAD_VALUE;
1149     }
1150 
1151     { // scope for the lock
1152         AutoMutex lock(mHardwareLock);
1153         if (mPrimaryHardwareDev == nullptr) {
1154             return INVALID_OPERATION;
1155         }
1156         sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1157         mHardwareStatus = AUDIO_HW_SET_MODE;
1158         ret = dev->setMode(mode);
1159         mHardwareStatus = AUDIO_HW_IDLE;
1160     }
1161 
1162     if (NO_ERROR == ret) {
1163         Mutex::Autolock _l(mLock);
1164         mMode = mode;
1165         for (size_t i = 0; i < mPlaybackThreads.size(); i++)
1166             mPlaybackThreads.valueAt(i)->setMode(mode);
1167     }
1168 
1169     return ret;
1170 }
1171 
setMicMute(bool state)1172 status_t AudioFlinger::setMicMute(bool state)
1173 {
1174     status_t ret = initCheck();
1175     if (ret != NO_ERROR) {
1176         return ret;
1177     }
1178 
1179     // check calling permissions
1180     if (!settingsAllowed()) {
1181         return PERMISSION_DENIED;
1182     }
1183 
1184     AutoMutex lock(mHardwareLock);
1185     if (mPrimaryHardwareDev == nullptr) {
1186         return INVALID_OPERATION;
1187     }
1188     sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1189     if (primaryDev == nullptr) {
1190         ALOGW("%s: no primary HAL device", __func__);
1191         return INVALID_OPERATION;
1192     }
1193     mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
1194     ret = primaryDev->setMicMute(state);
1195     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1196         sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1197         if (dev != primaryDev) {
1198             (void)dev->setMicMute(state);
1199         }
1200     }
1201     mHardwareStatus = AUDIO_HW_IDLE;
1202     ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
1203     return ret;
1204 }
1205 
getMicMute() const1206 bool AudioFlinger::getMicMute() const
1207 {
1208     status_t ret = initCheck();
1209     if (ret != NO_ERROR) {
1210         return false;
1211     }
1212     AutoMutex lock(mHardwareLock);
1213     if (mPrimaryHardwareDev == nullptr) {
1214         return false;
1215     }
1216     sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1217     if (primaryDev == nullptr) {
1218         ALOGW("%s: no primary HAL device", __func__);
1219         return false;
1220     }
1221     bool state;
1222     mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1223     ret = primaryDev->getMicMute(&state);
1224     mHardwareStatus = AUDIO_HW_IDLE;
1225     ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1226     return (ret == NO_ERROR) && state;
1227 }
1228 
setRecordSilenced(uid_t uid,bool silenced)1229 void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1230 {
1231     ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1232 
1233     AutoMutex lock(mLock);
1234     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1235         mRecordThreads[i]->setRecordSilenced(uid, silenced);
1236     }
1237     for (size_t i = 0; i < mMmapThreads.size(); i++) {
1238         mMmapThreads[i]->setRecordSilenced(uid, silenced);
1239     }
1240 }
1241 
setMasterMute(bool muted)1242 status_t AudioFlinger::setMasterMute(bool muted)
1243 {
1244     status_t ret = initCheck();
1245     if (ret != NO_ERROR) {
1246         return ret;
1247     }
1248 
1249     // check calling permissions
1250     if (!settingsAllowed()) {
1251         return PERMISSION_DENIED;
1252     }
1253 
1254     Mutex::Autolock _l(mLock);
1255     mMasterMute = muted;
1256 
1257     // Set master mute in the HALs which support it.
1258     {
1259         AutoMutex lock(mHardwareLock);
1260         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1261             AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
1262 
1263             mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1264             if (dev->canSetMasterMute()) {
1265                 dev->hwDevice()->setMasterMute(muted);
1266             }
1267             mHardwareStatus = AUDIO_HW_IDLE;
1268         }
1269     }
1270 
1271     // Now set the master mute in each playback thread.  Playback threads
1272     // assigned to HALs which do not have master mute support will apply master
1273     // mute during the mix operation.  Threads with HALs which do support master
1274     // mute will simply ignore the setting.
1275     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1276     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1277         volumeInterfaces[i]->setMasterMute(muted);
1278     }
1279 
1280     return NO_ERROR;
1281 }
1282 
masterVolume() const1283 float AudioFlinger::masterVolume() const
1284 {
1285     Mutex::Autolock _l(mLock);
1286     return masterVolume_l();
1287 }
1288 
getMasterBalance(float * balance) const1289 status_t AudioFlinger::getMasterBalance(float *balance) const
1290 {
1291     Mutex::Autolock _l(mLock);
1292     *balance = getMasterBalance_l();
1293     return NO_ERROR; // if called through binder, may return a transactional error
1294 }
1295 
masterMute() const1296 bool AudioFlinger::masterMute() const
1297 {
1298     Mutex::Autolock _l(mLock);
1299     return masterMute_l();
1300 }
1301 
masterVolume_l() const1302 float AudioFlinger::masterVolume_l() const
1303 {
1304     return mMasterVolume;
1305 }
1306 
getMasterBalance_l() const1307 float AudioFlinger::getMasterBalance_l() const
1308 {
1309     return mMasterBalance;
1310 }
1311 
masterMute_l() const1312 bool AudioFlinger::masterMute_l() const
1313 {
1314     return mMasterMute;
1315 }
1316 
checkStreamType(audio_stream_type_t stream) const1317 status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1318 {
1319     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
1320         ALOGW("checkStreamType() invalid stream %d", stream);
1321         return BAD_VALUE;
1322     }
1323     const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1324     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1325         ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
1326         return PERMISSION_DENIED;
1327     }
1328 
1329     return NO_ERROR;
1330 }
1331 
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)1332 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1333         audio_io_handle_t output)
1334 {
1335     // check calling permissions
1336     if (!settingsAllowed()) {
1337         return PERMISSION_DENIED;
1338     }
1339 
1340     status_t status = checkStreamType(stream);
1341     if (status != NO_ERROR) {
1342         return status;
1343     }
1344     if (output == AUDIO_IO_HANDLE_NONE) {
1345         return BAD_VALUE;
1346     }
1347     LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1348                         "AUDIO_STREAM_PATCH must have full scale volume");
1349 
1350     AutoMutex lock(mLock);
1351     VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1352     if (volumeInterface == NULL) {
1353         return BAD_VALUE;
1354     }
1355     volumeInterface->setStreamVolume(stream, value);
1356 
1357     return NO_ERROR;
1358 }
1359 
setStreamMute(audio_stream_type_t stream,bool muted)1360 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
1361 {
1362     // check calling permissions
1363     if (!settingsAllowed()) {
1364         return PERMISSION_DENIED;
1365     }
1366 
1367     status_t status = checkStreamType(stream);
1368     if (status != NO_ERROR) {
1369         return status;
1370     }
1371     ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1372 
1373     if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
1374         ALOGE("setStreamMute() invalid stream %d", stream);
1375         return BAD_VALUE;
1376     }
1377 
1378     AutoMutex lock(mLock);
1379     mStreamTypes[stream].mute = muted;
1380     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1381     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1382         volumeInterfaces[i]->setStreamMute(stream, muted);
1383     }
1384 
1385     return NO_ERROR;
1386 }
1387 
streamVolume(audio_stream_type_t stream,audio_io_handle_t output) const1388 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
1389 {
1390     status_t status = checkStreamType(stream);
1391     if (status != NO_ERROR) {
1392         return 0.0f;
1393     }
1394     if (output == AUDIO_IO_HANDLE_NONE) {
1395         return 0.0f;
1396     }
1397 
1398     AutoMutex lock(mLock);
1399     VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1400     if (volumeInterface == NULL) {
1401         return 0.0f;
1402     }
1403 
1404     return volumeInterface->streamVolume(stream);
1405 }
1406 
streamMute(audio_stream_type_t stream) const1407 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
1408 {
1409     status_t status = checkStreamType(stream);
1410     if (status != NO_ERROR) {
1411         return true;
1412     }
1413 
1414     AutoMutex lock(mLock);
1415     return streamMute_l(stream);
1416 }
1417 
1418 
broacastParametersToRecordThreads_l(const String8 & keyValuePairs)1419 void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1420 {
1421     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1422         mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1423     }
1424 }
1425 
updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector & devices)1426 void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1427 {
1428     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1429         mRecordThreads.valueAt(i)->updateOutDevices(devices);
1430     }
1431 }
1432 
1433 // forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
forwardParametersToDownstreamPatches_l(audio_io_handle_t upStream,const String8 & keyValuePairs,std::function<bool (const sp<PlaybackThread> &)> useThread)1434 void AudioFlinger::forwardParametersToDownstreamPatches_l(
1435         audio_io_handle_t upStream, const String8& keyValuePairs,
1436         std::function<bool(const sp<PlaybackThread>&)> useThread)
1437 {
1438     std::vector<PatchPanel::SoftwarePatch> swPatches;
1439     if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1440     ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1441             __func__, swPatches.size(), upStream);
1442     for (const auto& swPatch : swPatches) {
1443         sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1444         if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1445             downStream->setParameters(keyValuePairs);
1446         }
1447     }
1448 }
1449 
1450 // Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1451 // Some keys are used for audio routing and audio path configuration and should be reserved for use
1452 // by audio policy and audio flinger for functional, privacy and security reasons.
filterReservedParameters(String8 & keyValuePairs,uid_t callingUid)1453 void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1454 {
1455     static const String8 kReservedParameters[] = {
1456         String8(AudioParameter::keyRouting),
1457         String8(AudioParameter::keySamplingRate),
1458         String8(AudioParameter::keyFormat),
1459         String8(AudioParameter::keyChannels),
1460         String8(AudioParameter::keyFrameCount),
1461         String8(AudioParameter::keyInputSource),
1462         String8(AudioParameter::keyMonoOutput),
1463         String8(AudioParameter::keyDeviceConnect),
1464         String8(AudioParameter::keyDeviceDisconnect),
1465         String8(AudioParameter::keyStreamSupportedFormats),
1466         String8(AudioParameter::keyStreamSupportedChannels),
1467         String8(AudioParameter::keyStreamSupportedSamplingRates),
1468     };
1469 
1470     if (isAudioServerUid(callingUid)) {
1471         return; // no need to filter if audioserver.
1472     }
1473 
1474     AudioParameter param = AudioParameter(keyValuePairs);
1475     String8 value;
1476     AudioParameter rejectedParam;
1477     for (auto& key : kReservedParameters) {
1478         if (param.get(key, value) == NO_ERROR) {
1479             rejectedParam.add(key, value);
1480             param.remove(key);
1481         }
1482     }
1483     logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1484                           rejectedParam.size(), rejectedParam.toString(), callingUid);
1485     keyValuePairs = param.toString();
1486 }
1487 
logFilteredParameters(size_t originalKVPSize,const String8 & originalKVPs,size_t rejectedKVPSize,const String8 & rejectedKVPs,uid_t callingUid)1488 void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1489                                          size_t rejectedKVPSize, const String8& rejectedKVPs,
1490                                          uid_t callingUid) {
1491     auto prefix = String8::format("UID %5d", callingUid);
1492     auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1493     if (rejectedKVPSize != 0) {
1494         auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1495         ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1496         mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1497     } else {
1498         auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1499         logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1500     }
1501 }
1502 
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)1503 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
1504 {
1505     ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1506             ioHandle, keyValuePairs.string(),
1507             IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1508 
1509     // check calling permissions
1510     if (!settingsAllowed()) {
1511         return PERMISSION_DENIED;
1512     }
1513 
1514     String8 filteredKeyValuePairs = keyValuePairs;
1515     filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1516 
1517     ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1518 
1519     // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1520     if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1521         Mutex::Autolock _l(mLock);
1522         // result will remain NO_INIT if no audio device is present
1523         status_t final_result = NO_INIT;
1524         {
1525             AutoMutex lock(mHardwareLock);
1526             mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1527             for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1528                 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1529                 status_t result = dev->setParameters(filteredKeyValuePairs);
1530                 // return success if at least one audio device accepts the parameters as not all
1531                 // HALs are requested to support all parameters. If no audio device supports the
1532                 // requested parameters, the last error is reported.
1533                 if (final_result != NO_ERROR) {
1534                     final_result = result;
1535                 }
1536             }
1537             mHardwareStatus = AUDIO_HW_IDLE;
1538         }
1539         // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1540         AudioParameter param = AudioParameter(filteredKeyValuePairs);
1541         String8 value;
1542         if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1543             bool btNrecIsOff = (value == AudioParameter::valueOff);
1544             if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
1545                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1546                     mRecordThreads.valueAt(i)->checkBtNrec();
1547                 }
1548             }
1549         }
1550         String8 screenState;
1551         if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1552             bool isOff = (screenState == AudioParameter::valueOff);
1553             if (isOff != (AudioFlinger::mScreenState & 1)) {
1554                 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
1555             }
1556         }
1557         return final_result;
1558     }
1559 
1560     // hold a strong ref on thread in case closeOutput() or closeInput() is called
1561     // and the thread is exited once the lock is released
1562     sp<ThreadBase> thread;
1563     {
1564         Mutex::Autolock _l(mLock);
1565         thread = checkPlaybackThread_l(ioHandle);
1566         if (thread == 0) {
1567             thread = checkRecordThread_l(ioHandle);
1568             if (thread == 0) {
1569                 thread = checkMmapThread_l(ioHandle);
1570             }
1571         } else if (thread == primaryPlaybackThread_l()) {
1572             // indicate output device change to all input threads for pre processing
1573             AudioParameter param = AudioParameter(filteredKeyValuePairs);
1574             int value;
1575             if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1576                     (value != 0)) {
1577                 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
1578             }
1579         }
1580     }
1581     if (thread != 0) {
1582         status_t result = thread->setParameters(filteredKeyValuePairs);
1583         forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1584         return result;
1585     }
1586     return BAD_VALUE;
1587 }
1588 
getParameters(audio_io_handle_t ioHandle,const String8 & keys) const1589 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
1590 {
1591     ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1592             ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
1593 
1594     Mutex::Autolock _l(mLock);
1595 
1596     if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1597         String8 out_s8;
1598 
1599         AutoMutex lock(mHardwareLock);
1600         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1601             String8 s;
1602             mHardwareStatus = AUDIO_HW_GET_PARAMETER;
1603             sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1604             status_t result = dev->getParameters(keys, &s);
1605             mHardwareStatus = AUDIO_HW_IDLE;
1606             if (result == OK) out_s8 += s;
1607         }
1608         return out_s8;
1609     }
1610 
1611     ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1612     if (thread == NULL) {
1613         thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1614         if (thread == NULL) {
1615             thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1616             if (thread == NULL) {
1617                 return String8("");
1618             }
1619         }
1620     }
1621     return thread->getParameters(keys);
1622 }
1623 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask) const1624 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1625         audio_channel_mask_t channelMask) const
1626 {
1627     status_t ret = initCheck();
1628     if (ret != NO_ERROR) {
1629         return 0;
1630     }
1631     if ((sampleRate == 0) ||
1632             !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
1633             !audio_is_input_channel(channelMask)) {
1634         return 0;
1635     }
1636 
1637     AutoMutex lock(mHardwareLock);
1638     if (mPrimaryHardwareDev == nullptr) {
1639         return 0;
1640     }
1641     mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
1642     audio_config_t config, proposed;
1643     memset(&proposed, 0, sizeof(proposed));
1644     proposed.sample_rate = sampleRate;
1645     proposed.channel_mask = channelMask;
1646     proposed.format = format;
1647 
1648     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1649     size_t frames = 0;
1650     for (;;) {
1651         // Note: config is currently a const parameter for get_input_buffer_size()
1652         // but we use a copy from proposed in case config changes from the call.
1653         config = proposed;
1654         status_t result = dev->getInputBufferSize(&config, &frames);
1655         if (result == OK && frames != 0) {
1656             break; // hal success, config is the result
1657         }
1658         // change one parameter of the configuration each iteration to a more "common" value
1659         // to see if the device will support it.
1660         if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1661             proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1662         } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1663             proposed.sample_rate = 44100;           // legacy AudioRecord.java. TODO: Query hw?
1664         } else {
1665             ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1666                     "format %#x, channelMask 0x%X",
1667                     sampleRate, format, channelMask);
1668             break; // retries failed, break out of loop with frames == 0.
1669         }
1670     }
1671     mHardwareStatus = AUDIO_HW_IDLE;
1672     if (frames > 0 && config.sample_rate != sampleRate) {
1673         frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1674     }
1675     return frames; // may be converted to bytes at the Java level.
1676 }
1677 
getInputFramesLost(audio_io_handle_t ioHandle) const1678 uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
1679 {
1680     Mutex::Autolock _l(mLock);
1681 
1682     RecordThread *recordThread = checkRecordThread_l(ioHandle);
1683     if (recordThread != NULL) {
1684         return recordThread->getInputFramesLost();
1685     }
1686     return 0;
1687 }
1688 
setVoiceVolume(float value)1689 status_t AudioFlinger::setVoiceVolume(float value)
1690 {
1691     status_t ret = initCheck();
1692     if (ret != NO_ERROR) {
1693         return ret;
1694     }
1695 
1696     // check calling permissions
1697     if (!settingsAllowed()) {
1698         return PERMISSION_DENIED;
1699     }
1700 
1701     AutoMutex lock(mHardwareLock);
1702     if (mPrimaryHardwareDev == nullptr) {
1703         return INVALID_OPERATION;
1704     }
1705     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1706     mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1707     ret = dev->setVoiceVolume(value);
1708     mHardwareStatus = AUDIO_HW_IDLE;
1709 
1710     return ret;
1711 }
1712 
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames,audio_io_handle_t output) const1713 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1714         audio_io_handle_t output) const
1715 {
1716     Mutex::Autolock _l(mLock);
1717 
1718     PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1719     if (playbackThread != NULL) {
1720         return playbackThread->getRenderPosition(halFrames, dspFrames);
1721     }
1722 
1723     return BAD_VALUE;
1724 }
1725 
registerClient(const sp<IAudioFlingerClient> & client)1726 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1727 {
1728     Mutex::Autolock _l(mLock);
1729     if (client == 0) {
1730         return;
1731     }
1732     pid_t pid = IPCThreadState::self()->getCallingPid();
1733     {
1734         Mutex::Autolock _cl(mClientLock);
1735         if (mNotificationClients.indexOfKey(pid) < 0) {
1736             sp<NotificationClient> notificationClient = new NotificationClient(this,
1737                                                                                 client,
1738                                                                                 pid);
1739             ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1740 
1741             mNotificationClients.add(pid, notificationClient);
1742 
1743             sp<IBinder> binder = IInterface::asBinder(client);
1744             binder->linkToDeath(notificationClient);
1745         }
1746     }
1747 
1748     // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
1749     // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
1750     // the config change is always sent from playback or record threads to avoid deadlock
1751     // with AudioSystem::gLock
1752     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1753         mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
1754     }
1755 
1756     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1757         mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
1758     }
1759 }
1760 
removeNotificationClient(pid_t pid)1761 void AudioFlinger::removeNotificationClient(pid_t pid)
1762 {
1763     std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
1764     {
1765         Mutex::Autolock _l(mLock);
1766         {
1767             Mutex::Autolock _cl(mClientLock);
1768             mNotificationClients.removeItem(pid);
1769         }
1770 
1771         ALOGV("%d died, releasing its sessions", pid);
1772         size_t num = mAudioSessionRefs.size();
1773         bool removed = false;
1774         for (size_t i = 0; i < num; ) {
1775             AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1776             ALOGV(" pid %d @ %zu", ref->mPid, i);
1777             if (ref->mPid == pid) {
1778                 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1779                 mAudioSessionRefs.removeAt(i);
1780                 delete ref;
1781                 removed = true;
1782                 num--;
1783             } else {
1784                 i++;
1785             }
1786         }
1787         if (removed) {
1788             removedEffects = purgeStaleEffects_l();
1789         }
1790     }
1791     for (auto& effect : removedEffects) {
1792         effect->updatePolicyState();
1793     }
1794 }
1795 
ioConfigChanged(audio_io_config_event event,const sp<AudioIoDescriptor> & ioDesc,pid_t pid)1796 void AudioFlinger::ioConfigChanged(audio_io_config_event event,
1797                                    const sp<AudioIoDescriptor>& ioDesc,
1798                                    pid_t pid)
1799 {
1800     Mutex::Autolock _l(mClientLock);
1801     size_t size = mNotificationClients.size();
1802     for (size_t i = 0; i < size; i++) {
1803         if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1804             mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1805         }
1806     }
1807 }
1808 
1809 // removeClient_l() must be called with AudioFlinger::mClientLock held
removeClient_l(pid_t pid)1810 void AudioFlinger::removeClient_l(pid_t pid)
1811 {
1812     ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1813             IPCThreadState::self()->getCallingPid());
1814     mClients.removeItem(pid);
1815 }
1816 
1817 // getEffectThread_l() must be called with AudioFlinger::mLock held
getEffectThread_l(audio_session_t sessionId,int effectId)1818 sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1819         int effectId)
1820 {
1821     sp<ThreadBase> thread;
1822 
1823     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1824         if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1825             ALOG_ASSERT(thread == 0);
1826             thread = mPlaybackThreads.valueAt(i);
1827         }
1828     }
1829     if (thread != nullptr) {
1830         return thread;
1831     }
1832     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1833         if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1834             ALOG_ASSERT(thread == 0);
1835             thread = mRecordThreads.valueAt(i);
1836         }
1837     }
1838     if (thread != nullptr) {
1839         return thread;
1840     }
1841     for (size_t i = 0; i < mMmapThreads.size(); i++) {
1842         if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1843             ALOG_ASSERT(thread == 0);
1844             thread = mMmapThreads.valueAt(i);
1845         }
1846     }
1847     return thread;
1848 }
1849 
1850 
1851 
1852 // ----------------------------------------------------------------------------
1853 
Client(const sp<AudioFlinger> & audioFlinger,pid_t pid)1854 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1855     :   RefBase(),
1856         mAudioFlinger(audioFlinger),
1857         mPid(pid)
1858 {
1859     mMemoryDealer = new MemoryDealer(
1860             audioFlinger->getClientSharedHeapSize(),
1861             (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
1862 }
1863 
1864 // Client destructor must be called with AudioFlinger::mClientLock held
~Client()1865 AudioFlinger::Client::~Client()
1866 {
1867     mAudioFlinger->removeClient_l(mPid);
1868 }
1869 
heap() const1870 sp<MemoryDealer> AudioFlinger::Client::heap() const
1871 {
1872     return mMemoryDealer;
1873 }
1874 
1875 // ----------------------------------------------------------------------------
1876 
NotificationClient(const sp<AudioFlinger> & audioFlinger,const sp<IAudioFlingerClient> & client,pid_t pid)1877 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1878                                                      const sp<IAudioFlingerClient>& client,
1879                                                      pid_t pid)
1880     : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
1881 {
1882 }
1883 
~NotificationClient()1884 AudioFlinger::NotificationClient::~NotificationClient()
1885 {
1886 }
1887 
binderDied(const wp<IBinder> & who __unused)1888 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
1889 {
1890     sp<NotificationClient> keep(this);
1891     mAudioFlinger->removeNotificationClient(mPid);
1892 }
1893 
1894 // ----------------------------------------------------------------------------
MediaLogNotifier()1895 AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1896     : mPendingRequests(false) {}
1897 
1898 
requestMerge()1899 void AudioFlinger::MediaLogNotifier::requestMerge() {
1900     AutoMutex _l(mMutex);
1901     mPendingRequests = true;
1902     mCond.signal();
1903 }
1904 
threadLoop()1905 bool AudioFlinger::MediaLogNotifier::threadLoop() {
1906     // Should already have been checked, but just in case
1907     if (sMediaLogService == 0) {
1908         return false;
1909     }
1910     // Wait until there are pending requests
1911     {
1912         AutoMutex _l(mMutex);
1913         mPendingRequests = false; // to ignore past requests
1914         while (!mPendingRequests) {
1915             mCond.wait(mMutex);
1916             // TODO may also need an exitPending check
1917         }
1918         mPendingRequests = false;
1919     }
1920     // Execute the actual MediaLogService binder call and ignore extra requests for a while
1921     sMediaLogService->requestMergeWakeup();
1922     usleep(kPostTriggerSleepPeriod);
1923     return true;
1924 }
1925 
requestLogMerge()1926 void AudioFlinger::requestLogMerge() {
1927     mMediaLogNotifier->requestMerge();
1928 }
1929 
1930 // ----------------------------------------------------------------------------
1931 
createRecord(const CreateRecordInput & input,CreateRecordOutput & output,status_t * status)1932 sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1933                                                    CreateRecordOutput& output,
1934                                                    status_t *status)
1935 {
1936     sp<RecordThread::RecordTrack> recordTrack;
1937     sp<RecordHandle> recordHandle;
1938     sp<Client> client;
1939     status_t lStatus;
1940     audio_session_t sessionId = input.sessionId;
1941     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1942 
1943     output.cblk.clear();
1944     output.buffers.clear();
1945     output.inputId = AUDIO_IO_HANDLE_NONE;
1946 
1947     bool updatePid = (input.clientInfo.clientPid == -1);
1948     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1949     uid_t clientUid = input.clientInfo.clientUid;
1950     if (!isAudioServerOrMediaServerUid(callingUid)) {
1951         ALOGW_IF(clientUid != callingUid,
1952                 "%s uid %d tried to pass itself off as %d",
1953                 __FUNCTION__, callingUid, clientUid);
1954         clientUid = callingUid;
1955         updatePid = true;
1956     }
1957     pid_t clientPid = input.clientInfo.clientPid;
1958     const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1959     if (updatePid) {
1960         ALOGW_IF(clientPid != -1 && clientPid != callingPid,
1961                  "%s uid %d pid %d tried to pass itself off as pid %d",
1962                  __func__, callingUid, callingPid, clientPid);
1963         clientPid = callingPid;
1964     }
1965 
1966     // we don't yet support anything other than linear PCM
1967     if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1968         ALOGE("createRecord() invalid format %#x", input.config.format);
1969         lStatus = BAD_VALUE;
1970         goto Exit;
1971     }
1972 
1973     // further channel mask checks are performed by createRecordTrack_l()
1974     if (!audio_is_input_channel(input.config.channel_mask)) {
1975         ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
1976         lStatus = BAD_VALUE;
1977         goto Exit;
1978     }
1979 
1980     if (sessionId == AUDIO_SESSION_ALLOCATE) {
1981         sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1982     } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1983         lStatus = BAD_VALUE;
1984         goto Exit;
1985     }
1986 
1987     output.sessionId = sessionId;
1988     output.selectedDeviceId = input.selectedDeviceId;
1989     output.flags = input.flags;
1990 
1991     client = registerPid(clientPid);
1992 
1993     // Not a conventional loop, but a retry loop for at most two iterations total.
1994     // Try first maybe with FAST flag then try again without FAST flag if that fails.
1995     // Exits loop via break on no error of got exit on error
1996     // The sp<> references will be dropped when re-entering scope.
1997     // The lack of indentation is deliberate, to reduce code churn and ease merges.
1998     for (;;) {
1999     // release previously opened input if retrying.
2000     if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2001         recordTrack.clear();
2002         AudioSystem::releaseInput(portId);
2003         output.inputId = AUDIO_IO_HANDLE_NONE;
2004         output.selectedDeviceId = input.selectedDeviceId;
2005         portId = AUDIO_PORT_HANDLE_NONE;
2006     }
2007     lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
2008                                       input.riid,
2009                                       sessionId,
2010                                     // FIXME compare to AudioTrack
2011                                       clientPid,
2012                                       clientUid,
2013                                       input.opPackageName,
2014                                       &input.config,
2015                                       output.flags, &output.selectedDeviceId, &portId);
2016     if (lStatus != NO_ERROR) {
2017         ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2018         goto Exit;
2019     }
2020 
2021     {
2022         Mutex::Autolock _l(mLock);
2023         RecordThread *thread = checkRecordThread_l(output.inputId);
2024         if (thread == NULL) {
2025             ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2026             lStatus = BAD_VALUE;
2027             goto Exit;
2028         }
2029 
2030         ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
2031 
2032         output.sampleRate = input.config.sample_rate;
2033         output.frameCount = input.frameCount;
2034         output.notificationFrameCount = input.notificationFrameCount;
2035 
2036         recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
2037                                                   input.config.format, input.config.channel_mask,
2038                                                   &output.frameCount, sessionId,
2039                                                   &output.notificationFrameCount,
2040                                                   callingPid, clientUid, &output.flags,
2041                                                   input.clientInfo.clientTid,
2042                                                   &lStatus, portId,
2043                                                   input.opPackageName);
2044         LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
2045 
2046         // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2047         // audio policy manager without FAST constraint
2048         if (lStatus == BAD_TYPE) {
2049             continue;
2050         }
2051 
2052         if (lStatus != NO_ERROR) {
2053             goto Exit;
2054         }
2055 
2056         // Check if one effect chain was awaiting for an AudioRecord to be created on this
2057         // session and move it to this thread.
2058         sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2059         if (chain != 0) {
2060             Mutex::Autolock _l(thread->mLock);
2061             thread->addEffectChain_l(chain);
2062         }
2063         break;
2064     }
2065     // End of retry loop.
2066     // The lack of indentation is deliberate, to reduce code churn and ease merges.
2067     }
2068 
2069     output.cblk = recordTrack->getCblk();
2070     output.buffers = recordTrack->getBuffers();
2071     output.portId = portId;
2072 
2073     // return handle to client
2074     recordHandle = new RecordHandle(recordTrack);
2075 
2076 Exit:
2077     if (lStatus != NO_ERROR) {
2078         // remove local strong reference to Client before deleting the RecordTrack so that the
2079         // Client destructor is called by the TrackBase destructor with mClientLock held
2080         // Don't hold mClientLock when releasing the reference on the track as the
2081         // destructor will acquire it.
2082         {
2083             Mutex::Autolock _cl(mClientLock);
2084             client.clear();
2085         }
2086         recordTrack.clear();
2087         if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2088             AudioSystem::releaseInput(portId);
2089         }
2090     }
2091 
2092     *status = lStatus;
2093     return recordHandle;
2094 }
2095 
2096 
2097 
2098 // ----------------------------------------------------------------------------
2099 
loadHwModule(const char * name)2100 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2101 {
2102     if (name == NULL) {
2103         return AUDIO_MODULE_HANDLE_NONE;
2104     }
2105     if (!settingsAllowed()) {
2106         return AUDIO_MODULE_HANDLE_NONE;
2107     }
2108     Mutex::Autolock _l(mLock);
2109     AutoMutex lock(mHardwareLock);
2110     return loadHwModule_l(name);
2111 }
2112 
2113 // loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
loadHwModule_l(const char * name)2114 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2115 {
2116     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2117         if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2118             ALOGW("loadHwModule() module %s already loaded", name);
2119             return mAudioHwDevs.keyAt(i);
2120         }
2121     }
2122 
2123     sp<DeviceHalInterface> dev;
2124 
2125     int rc = mDevicesFactoryHal->openDevice(name, &dev);
2126     if (rc) {
2127         ALOGE("loadHwModule() error %d loading module %s", rc, name);
2128         return AUDIO_MODULE_HANDLE_NONE;
2129     }
2130 
2131     mHardwareStatus = AUDIO_HW_INIT;
2132     rc = dev->initCheck();
2133     mHardwareStatus = AUDIO_HW_IDLE;
2134     if (rc) {
2135         ALOGE("loadHwModule() init check error %d for module %s", rc, name);
2136         return AUDIO_MODULE_HANDLE_NONE;
2137     }
2138 
2139     // Check and cache this HAL's level of support for master mute and master
2140     // volume.  If this is the first HAL opened, and it supports the get
2141     // methods, use the initial values provided by the HAL as the current
2142     // master mute and volume settings.
2143 
2144     AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2145     if (0 == mAudioHwDevs.size()) {
2146         mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2147         float mv;
2148         if (OK == dev->getMasterVolume(&mv)) {
2149             mMasterVolume = mv;
2150         }
2151 
2152         mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2153         bool mm;
2154         if (OK == dev->getMasterMute(&mm)) {
2155             mMasterMute = mm;
2156         }
2157     }
2158 
2159     mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2160     if (OK == dev->setMasterVolume(mMasterVolume)) {
2161         flags = static_cast<AudioHwDevice::Flags>(flags |
2162                 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2163     }
2164 
2165     mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2166     if (OK == dev->setMasterMute(mMasterMute)) {
2167         flags = static_cast<AudioHwDevice::Flags>(flags |
2168                 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2169     }
2170 
2171     mHardwareStatus = AUDIO_HW_IDLE;
2172 
2173     if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
2174         // An MSD module is inserted before hardware modules in order to mix encoded streams.
2175         flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2176     }
2177 
2178     audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
2179     AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2180     if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2181         mPrimaryHardwareDev = audioDevice;
2182         mHardwareStatus = AUDIO_HW_SET_MODE;
2183         mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2184         mHardwareStatus = AUDIO_HW_IDLE;
2185     }
2186 
2187     mAudioHwDevs.add(handle, audioDevice);
2188 
2189     ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
2190 
2191     return handle;
2192 
2193 }
2194 
2195 // ----------------------------------------------------------------------------
2196 
getPrimaryOutputSamplingRate()2197 uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
2198 {
2199     Mutex::Autolock _l(mLock);
2200     PlaybackThread *thread = fastPlaybackThread_l();
2201     return thread != NULL ? thread->sampleRate() : 0;
2202 }
2203 
getPrimaryOutputFrameCount()2204 size_t AudioFlinger::getPrimaryOutputFrameCount()
2205 {
2206     Mutex::Autolock _l(mLock);
2207     PlaybackThread *thread = fastPlaybackThread_l();
2208     return thread != NULL ? thread->frameCountHAL() : 0;
2209 }
2210 
2211 // ----------------------------------------------------------------------------
2212 
setLowRamDevice(bool isLowRamDevice,int64_t totalMemory)2213 status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
2214 {
2215     uid_t uid = IPCThreadState::self()->getCallingUid();
2216     if (!isAudioServerOrSystemServerUid(uid)) {
2217         return PERMISSION_DENIED;
2218     }
2219     Mutex::Autolock _l(mLock);
2220     if (mIsDeviceTypeKnown) {
2221         return INVALID_OPERATION;
2222     }
2223     mIsLowRamDevice = isLowRamDevice;
2224     mTotalMemory = totalMemory;
2225     // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2226     // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2227     // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2228     // though actual setting is determined through device configuration.
2229     constexpr int64_t GB = 1024 * 1024 * 1024;
2230     mClientSharedHeapSize =
2231             isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2232                     : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2233                     : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2234                     : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2235                     : 32 * kMinimumClientSharedHeapSizeBytes;
2236     mIsDeviceTypeKnown = true;
2237 
2238     // TODO: Cache the client shared heap size in a persistent property.
2239     // It's possible that a native process or Java service or app accesses audioserver
2240     // after it is registered by system server, but before AudioService updates
2241     // the memory info.  This would occur immediately after boot or an audioserver
2242     // crash and restore. Before update from AudioService, the client would get the
2243     // minimum heap size.
2244 
2245     ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2246             (isLowRamDevice ? "true" : "false"),
2247             (long long)mTotalMemory,
2248             mClientSharedHeapSize.load());
2249     return NO_ERROR;
2250 }
2251 
getClientSharedHeapSize() const2252 size_t AudioFlinger::getClientSharedHeapSize() const
2253 {
2254     size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2255     if (heapSizeInBytes != 0) { // read-only property overrides all.
2256         return heapSizeInBytes;
2257     }
2258     return mClientSharedHeapSize;
2259 }
2260 
setAudioPortConfig(const struct audio_port_config * config)2261 status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2262 {
2263     ALOGV(__func__);
2264 
2265     audio_module_handle_t module;
2266     if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2267         module = config->ext.device.hw_module;
2268     } else {
2269         module = config->ext.mix.hw_module;
2270     }
2271 
2272     Mutex::Autolock _l(mLock);
2273     AutoMutex lock(mHardwareLock);
2274     ssize_t index = mAudioHwDevs.indexOfKey(module);
2275     if (index < 0) {
2276         ALOGW("%s() bad hw module %d", __func__, module);
2277         return BAD_VALUE;
2278     }
2279 
2280     AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2281     return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2282 }
2283 
getAudioHwSyncForSession(audio_session_t sessionId)2284 audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2285 {
2286     Mutex::Autolock _l(mLock);
2287 
2288     ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2289     if (index >= 0) {
2290         ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2291               mHwAvSyncIds.valueAt(index), sessionId);
2292         return mHwAvSyncIds.valueAt(index);
2293     }
2294 
2295     sp<DeviceHalInterface> dev;
2296     {
2297         AutoMutex lock(mHardwareLock);
2298         if (mPrimaryHardwareDev == nullptr) {
2299             return AUDIO_HW_SYNC_INVALID;
2300         }
2301         dev = mPrimaryHardwareDev->hwDevice();
2302     }
2303     if (dev == nullptr) {
2304         return AUDIO_HW_SYNC_INVALID;
2305     }
2306     String8 reply;
2307     AudioParameter param;
2308     if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
2309         param = AudioParameter(reply);
2310     }
2311 
2312     int value;
2313     if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
2314         ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2315         return AUDIO_HW_SYNC_INVALID;
2316     }
2317 
2318     // allow only one session for a given HW A/V sync ID.
2319     for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2320         if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2321             ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2322                   value, mHwAvSyncIds.keyAt(i));
2323             mHwAvSyncIds.removeItemsAt(i);
2324             break;
2325         }
2326     }
2327 
2328     mHwAvSyncIds.add(sessionId, value);
2329 
2330     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2331         sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2332         uint32_t sessions = thread->hasAudioSession(sessionId);
2333         if (sessions & ThreadBase::TRACK_SESSION) {
2334             AudioParameter param = AudioParameter();
2335             param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
2336             String8 keyValuePairs = param.toString();
2337             thread->setParameters(keyValuePairs);
2338             forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2339                     [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
2340             break;
2341         }
2342     }
2343 
2344     ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2345     return (audio_hw_sync_t)value;
2346 }
2347 
systemReady()2348 status_t AudioFlinger::systemReady()
2349 {
2350     Mutex::Autolock _l(mLock);
2351     ALOGI("%s", __FUNCTION__);
2352     if (mSystemReady) {
2353         ALOGW("%s called twice", __FUNCTION__);
2354         return NO_ERROR;
2355     }
2356     mSystemReady = true;
2357     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2358         ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2359         thread->systemReady();
2360     }
2361     for (size_t i = 0; i < mRecordThreads.size(); i++) {
2362         ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2363         thread->systemReady();
2364     }
2365     return NO_ERROR;
2366 }
2367 
getMicrophones(std::vector<media::MicrophoneInfo> * microphones)2368 status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2369 {
2370     AutoMutex lock(mHardwareLock);
2371     status_t status = INVALID_OPERATION;
2372 
2373     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2374         std::vector<media::MicrophoneInfo> mics;
2375         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2376         mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2377         status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2378         mHardwareStatus = AUDIO_HW_IDLE;
2379         if (devStatus == NO_ERROR) {
2380             microphones->insert(microphones->begin(), mics.begin(), mics.end());
2381             // report success if at least one HW module supports the function.
2382             status = NO_ERROR;
2383         }
2384     }
2385 
2386     return status;
2387 }
2388 
2389 // setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
setAudioHwSyncForSession_l(PlaybackThread * thread,audio_session_t sessionId)2390 void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2391 {
2392     ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2393     if (index >= 0) {
2394         audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2395         ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2396         AudioParameter param = AudioParameter();
2397         param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
2398         String8 keyValuePairs = param.toString();
2399         thread->setParameters(keyValuePairs);
2400         forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2401                 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
2402     }
2403 }
2404 
2405 
2406 // ----------------------------------------------------------------------------
2407 
2408 
openOutput_l(audio_module_handle_t module,audio_io_handle_t * output,audio_config_t * config,audio_devices_t deviceType,const String8 & address,audio_output_flags_t flags)2409 sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
2410                                                         audio_io_handle_t *output,
2411                                                         audio_config_t *config,
2412                                                         audio_devices_t deviceType,
2413                                                         const String8& address,
2414                                                         audio_output_flags_t flags)
2415 {
2416     AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
2417     if (outHwDev == NULL) {
2418         return 0;
2419     }
2420 
2421     if (*output == AUDIO_IO_HANDLE_NONE) {
2422         *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2423     } else {
2424         // Audio Policy does not currently request a specific output handle.
2425         // If this is ever needed, see openInput_l() for example code.
2426         ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2427         return 0;
2428     }
2429 
2430     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2431 
2432     // FOR TESTING ONLY:
2433     // This if statement allows overriding the audio policy settings
2434     // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2435     if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2436         // Check only for Normal Mixing mode
2437         if (kEnableExtendedPrecision) {
2438             // Specify format (uncomment one below to choose)
2439             //config->format = AUDIO_FORMAT_PCM_FLOAT;
2440             //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2441             //config->format = AUDIO_FORMAT_PCM_32_BIT;
2442             //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
2443             // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
2444         }
2445         if (kEnableExtendedChannels) {
2446             // Specify channel mask (uncomment one below to choose)
2447             //config->channel_mask = audio_channel_out_mask_from_count(4);  // for USB 4ch
2448             //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2449             //        AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1);  // another 4ch example
2450         }
2451     }
2452 
2453     AudioStreamOut *outputStream = NULL;
2454     status_t status = outHwDev->openOutputStream(
2455             &outputStream,
2456             *output,
2457             deviceType,
2458             flags,
2459             config,
2460             address.string());
2461 
2462     mHardwareStatus = AUDIO_HW_IDLE;
2463 
2464     if (status == NO_ERROR) {
2465         if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2466             sp<MmapPlaybackThread> thread =
2467                     new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
2468             mMmapThreads.add(*output, thread);
2469             ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2470                   *output, thread.get());
2471             return thread;
2472         } else {
2473             sp<PlaybackThread> thread;
2474             if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2475                 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
2476                 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2477                       *output, thread.get());
2478             } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2479                     || !isValidPcmSinkFormat(config->format)
2480                     || !isValidPcmSinkChannelMask(config->channel_mask)) {
2481                 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
2482                 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2483                       *output, thread.get());
2484             } else {
2485                 thread = new MixerThread(this, outputStream, *output, mSystemReady);
2486                 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2487                       *output, thread.get());
2488             }
2489             mPlaybackThreads.add(*output, thread);
2490             mPatchPanel.notifyStreamOpened(outHwDev, *output);
2491             return thread;
2492         }
2493     }
2494 
2495     return 0;
2496 }
2497 
openOutput(audio_module_handle_t module,audio_io_handle_t * output,audio_config_t * config,const sp<DeviceDescriptorBase> & device,uint32_t * latencyMs,audio_output_flags_t flags)2498 status_t AudioFlinger::openOutput(audio_module_handle_t module,
2499                                   audio_io_handle_t *output,
2500                                   audio_config_t *config,
2501                                   const sp<DeviceDescriptorBase>& device,
2502                                   uint32_t *latencyMs,
2503                                   audio_output_flags_t flags)
2504 {
2505     ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
2506               "Channels %#x, flags %#x",
2507               this, module,
2508               device->toString().c_str(),
2509               config->sample_rate,
2510               config->format,
2511               config->channel_mask,
2512               flags);
2513 
2514     audio_devices_t deviceType = device->type();
2515     const String8 address = String8(device->address().c_str());
2516 
2517     if (deviceType == AUDIO_DEVICE_NONE) {
2518         return BAD_VALUE;
2519     }
2520 
2521     Mutex::Autolock _l(mLock);
2522 
2523     sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
2524     if (thread != 0) {
2525         if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2526             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2527             *latencyMs = playbackThread->latency();
2528 
2529             // notify client processes of the new output creation
2530             playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
2531 
2532             // the first primary output opened designates the primary hw device if no HW module
2533             // named "primary" was already loaded.
2534             AutoMutex lock(mHardwareLock);
2535             if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
2536                 ALOGI("Using module %d as the primary audio interface", module);
2537                 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
2538 
2539                 mHardwareStatus = AUDIO_HW_SET_MODE;
2540                 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2541                 mHardwareStatus = AUDIO_HW_IDLE;
2542             }
2543         } else {
2544             MmapThread *mmapThread = (MmapThread *)thread.get();
2545             mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
2546         }
2547         return NO_ERROR;
2548     }
2549 
2550     return NO_INIT;
2551 }
2552 
openDuplicateOutput(audio_io_handle_t output1,audio_io_handle_t output2)2553 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2554         audio_io_handle_t output2)
2555 {
2556     Mutex::Autolock _l(mLock);
2557     MixerThread *thread1 = checkMixerThread_l(output1);
2558     MixerThread *thread2 = checkMixerThread_l(output2);
2559 
2560     if (thread1 == NULL || thread2 == NULL) {
2561         ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2562                 output2);
2563         return AUDIO_IO_HANDLE_NONE;
2564     }
2565 
2566     audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2567     DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
2568     thread->addOutputTrack(thread2);
2569     mPlaybackThreads.add(id, thread);
2570     // notify client processes of the new output creation
2571     thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
2572     return id;
2573 }
2574 
closeOutput(audio_io_handle_t output)2575 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
2576 {
2577     return closeOutput_nonvirtual(output);
2578 }
2579 
closeOutput_nonvirtual(audio_io_handle_t output)2580 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2581 {
2582     // keep strong reference on the playback thread so that
2583     // it is not destroyed while exit() is executed
2584     sp<PlaybackThread> playbackThread;
2585     sp<MmapPlaybackThread> mmapThread;
2586     {
2587         Mutex::Autolock _l(mLock);
2588         playbackThread = checkPlaybackThread_l(output);
2589         if (playbackThread != NULL) {
2590             ALOGV("closeOutput() %d", output);
2591 
2592             dumpToThreadLog_l(playbackThread);
2593 
2594             if (playbackThread->type() == ThreadBase::MIXER) {
2595                 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2596                     if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2597                         DuplicatingThread *dupThread =
2598                                 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2599                         dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2600                     }
2601                 }
2602             }
2603 
2604 
2605             mPlaybackThreads.removeItem(output);
2606             // save all effects to the default thread
2607             if (mPlaybackThreads.size()) {
2608                 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2609                 if (dstThread != NULL) {
2610                     // audioflinger lock is held so order of thread lock acquisition doesn't matter
2611                     Mutex::Autolock _dl(dstThread->mLock);
2612                     Mutex::Autolock _sl(playbackThread->mLock);
2613                     Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2614                     for (size_t i = 0; i < effectChains.size(); i ++) {
2615                         moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2616                                 dstThread);
2617                     }
2618                 }
2619             }
2620         } else {
2621             mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2622             if (mmapThread == 0) {
2623                 return BAD_VALUE;
2624             }
2625             dumpToThreadLog_l(mmapThread);
2626             mMmapThreads.removeItem(output);
2627             ALOGD("closing mmapThread %p", mmapThread.get());
2628         }
2629         const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2630         ioDesc->mIoHandle = output;
2631         ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
2632         mPatchPanel.notifyStreamClosed(output);
2633     }
2634     // The thread entity (active unit of execution) is no longer running here,
2635     // but the ThreadBase container still exists.
2636 
2637     if (playbackThread != 0) {
2638         playbackThread->exit();
2639         if (!playbackThread->isDuplicating()) {
2640             closeOutputFinish(playbackThread);
2641         }
2642     } else if (mmapThread != 0) {
2643         ALOGD("mmapThread exit()");
2644         mmapThread->exit();
2645         AudioStreamOut *out = mmapThread->clearOutput();
2646         ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2647         // from now on thread->mOutput is NULL
2648         delete out;
2649     }
2650     return NO_ERROR;
2651 }
2652 
closeOutputFinish(const sp<PlaybackThread> & thread)2653 void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
2654 {
2655     AudioStreamOut *out = thread->clearOutput();
2656     ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2657     // from now on thread->mOutput is NULL
2658     delete out;
2659 }
2660 
closeThreadInternal_l(const sp<PlaybackThread> & thread)2661 void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
2662 {
2663     mPlaybackThreads.removeItem(thread->mId);
2664     thread->exit();
2665     closeOutputFinish(thread);
2666 }
2667 
suspendOutput(audio_io_handle_t output)2668 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
2669 {
2670     Mutex::Autolock _l(mLock);
2671     PlaybackThread *thread = checkPlaybackThread_l(output);
2672 
2673     if (thread == NULL) {
2674         return BAD_VALUE;
2675     }
2676 
2677     ALOGV("suspendOutput() %d", output);
2678     thread->suspend();
2679 
2680     return NO_ERROR;
2681 }
2682 
restoreOutput(audio_io_handle_t output)2683 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
2684 {
2685     Mutex::Autolock _l(mLock);
2686     PlaybackThread *thread = checkPlaybackThread_l(output);
2687 
2688     if (thread == NULL) {
2689         return BAD_VALUE;
2690     }
2691 
2692     ALOGV("restoreOutput() %d", output);
2693 
2694     thread->restore();
2695 
2696     return NO_ERROR;
2697 }
2698 
openInput(audio_module_handle_t module,audio_io_handle_t * input,audio_config_t * config,audio_devices_t * devices,const String8 & address,audio_source_t source,audio_input_flags_t flags)2699 status_t AudioFlinger::openInput(audio_module_handle_t module,
2700                                           audio_io_handle_t *input,
2701                                           audio_config_t *config,
2702                                           audio_devices_t *devices,
2703                                           const String8& address,
2704                                           audio_source_t source,
2705                                           audio_input_flags_t flags)
2706 {
2707     Mutex::Autolock _l(mLock);
2708 
2709     if (*devices == AUDIO_DEVICE_NONE) {
2710         return BAD_VALUE;
2711     }
2712 
2713     sp<ThreadBase> thread = openInput_l(
2714             module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
2715 
2716     if (thread != 0) {
2717         // notify client processes of the new input creation
2718         thread->ioConfigChanged(AUDIO_INPUT_OPENED);
2719         return NO_ERROR;
2720     }
2721     return NO_INIT;
2722 }
2723 
openInput_l(audio_module_handle_t module,audio_io_handle_t * input,audio_config_t * config,audio_devices_t devices,const String8 & address,audio_source_t source,audio_input_flags_t flags,audio_devices_t outputDevice,const String8 & outputDeviceAddress)2724 sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
2725                                                          audio_io_handle_t *input,
2726                                                          audio_config_t *config,
2727                                                          audio_devices_t devices,
2728                                                          const String8& address,
2729                                                          audio_source_t source,
2730                                                          audio_input_flags_t flags,
2731                                                          audio_devices_t outputDevice,
2732                                                          const String8& outputDeviceAddress)
2733 {
2734     AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
2735     if (inHwDev == NULL) {
2736         *input = AUDIO_IO_HANDLE_NONE;
2737         return 0;
2738     }
2739 
2740     // Some flags are specific to framework and must not leak to the HAL.
2741     flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2742 
2743     // Audio Policy can request a specific handle for hardware hotword.
2744     // The goal here is not to re-open an already opened input.
2745     // It is to use a pre-assigned I/O handle.
2746     if (*input == AUDIO_IO_HANDLE_NONE) {
2747         *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2748     } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2749         ALOGE("openInput_l() requested input handle %d is invalid", *input);
2750         return 0;
2751     } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2752         // This should not happen in a transient state with current design.
2753         ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2754         return 0;
2755     }
2756 
2757     audio_config_t halconfig = *config;
2758     sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
2759     sp<StreamInHalInterface> inStream;
2760     status_t status = inHwHal->openInputStream(
2761             *input, devices, &halconfig, flags, address.string(), source,
2762             outputDevice, outputDeviceAddress, &inStream);
2763     ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2764            ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
2765             inStream.get(),
2766             devices,
2767             halconfig.sample_rate,
2768             halconfig.format,
2769             halconfig.channel_mask,
2770             flags,
2771             status, address.string());
2772 
2773     // If the input could not be opened with the requested parameters and we can handle the
2774     // conversion internally, try to open again with the proposed parameters.
2775     if (status == BAD_VALUE &&
2776         audio_is_linear_pcm(config->format) &&
2777         audio_is_linear_pcm(halconfig.format) &&
2778         (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
2779         (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2780         (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
2781         // FIXME describe the change proposed by HAL (save old values so we can log them here)
2782         ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
2783         inStream.clear();
2784         status = inHwHal->openInputStream(
2785                 *input, devices, &halconfig, flags, address.string(), source,
2786                 outputDevice, outputDeviceAddress, &inStream);
2787         // FIXME log this new status; HAL should not propose any further changes
2788     }
2789 
2790     if (status == NO_ERROR && inStream != 0) {
2791         AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
2792         if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2793             sp<MmapCaptureThread> thread =
2794                     new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
2795             mMmapThreads.add(*input, thread);
2796             ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2797                     thread.get());
2798             return thread;
2799         } else {
2800             // Start record thread
2801             // RecordThread requires both input and output device indication to forward to audio
2802             // pre processing modules
2803             sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
2804             mRecordThreads.add(*input, thread);
2805             ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2806             return thread;
2807         }
2808     }
2809 
2810     *input = AUDIO_IO_HANDLE_NONE;
2811     return 0;
2812 }
2813 
closeInput(audio_io_handle_t input)2814 status_t AudioFlinger::closeInput(audio_io_handle_t input)
2815 {
2816     return closeInput_nonvirtual(input);
2817 }
2818 
closeInput_nonvirtual(audio_io_handle_t input)2819 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2820 {
2821     // keep strong reference on the record thread so that
2822     // it is not destroyed while exit() is executed
2823     sp<RecordThread> recordThread;
2824     sp<MmapCaptureThread> mmapThread;
2825     {
2826         Mutex::Autolock _l(mLock);
2827         recordThread = checkRecordThread_l(input);
2828         if (recordThread != 0) {
2829             ALOGV("closeInput() %d", input);
2830 
2831             dumpToThreadLog_l(recordThread);
2832 
2833             // If we still have effect chains, it means that a client still holds a handle
2834             // on at least one effect. We must either move the chain to an existing thread with the
2835             // same session ID or put it aside in case a new record thread is opened for a
2836             // new capture on the same session
2837             sp<EffectChain> chain;
2838             {
2839                 Mutex::Autolock _sl(recordThread->mLock);
2840                 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2841                 // Note: maximum one chain per record thread
2842                 if (effectChains.size() != 0) {
2843                     chain = effectChains[0];
2844                 }
2845             }
2846             if (chain != 0) {
2847                 // first check if a record thread is already opened with a client on same session.
2848                 // This should only happen in case of overlap between one thread tear down and the
2849                 // creation of its replacement
2850                 size_t i;
2851                 for (i = 0; i < mRecordThreads.size(); i++) {
2852                     sp<RecordThread> t = mRecordThreads.valueAt(i);
2853                     if (t == recordThread) {
2854                         continue;
2855                     }
2856                     if (t->hasAudioSession(chain->sessionId()) != 0) {
2857                         Mutex::Autolock _l(t->mLock);
2858                         ALOGV("closeInput() found thread %d for effect session %d",
2859                               t->id(), chain->sessionId());
2860                         t->addEffectChain_l(chain);
2861                         break;
2862                     }
2863                 }
2864                 // put the chain aside if we could not find a record thread with the same session id
2865                 if (i == mRecordThreads.size()) {
2866                     putOrphanEffectChain_l(chain);
2867                 }
2868             }
2869             mRecordThreads.removeItem(input);
2870         } else {
2871             mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2872             if (mmapThread == 0) {
2873                 return BAD_VALUE;
2874             }
2875             dumpToThreadLog_l(mmapThread);
2876             mMmapThreads.removeItem(input);
2877         }
2878         const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2879         ioDesc->mIoHandle = input;
2880         ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
2881     }
2882     // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2883     // we have a different lock for notification client
2884     if (recordThread != 0) {
2885         closeInputFinish(recordThread);
2886     } else if (mmapThread != 0) {
2887         mmapThread->exit();
2888         AudioStreamIn *in = mmapThread->clearInput();
2889         ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2890         // from now on thread->mInput is NULL
2891         delete in;
2892     }
2893     return NO_ERROR;
2894 }
2895 
closeInputFinish(const sp<RecordThread> & thread)2896 void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
2897 {
2898     thread->exit();
2899     AudioStreamIn *in = thread->clearInput();
2900     ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2901     // from now on thread->mInput is NULL
2902     delete in;
2903 }
2904 
closeThreadInternal_l(const sp<RecordThread> & thread)2905 void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
2906 {
2907     mRecordThreads.removeItem(thread->mId);
2908     closeInputFinish(thread);
2909 }
2910 
invalidateStream(audio_stream_type_t stream)2911 status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
2912 {
2913     Mutex::Autolock _l(mLock);
2914     ALOGV("invalidateStream() stream %d", stream);
2915 
2916     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2917         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2918         thread->invalidateTracks(stream);
2919     }
2920     for (size_t i = 0; i < mMmapThreads.size(); i++) {
2921         mMmapThreads[i]->invalidateTracks(stream);
2922     }
2923     return NO_ERROR;
2924 }
2925 
2926 
newAudioUniqueId(audio_unique_id_use_t use)2927 audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
2928 {
2929     // This is a binder API, so a malicious client could pass in a bad parameter.
2930     // Check for that before calling the internal API nextUniqueId().
2931     if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2932         ALOGE("newAudioUniqueId invalid use %d", use);
2933         return AUDIO_UNIQUE_ID_ALLOCATE;
2934     }
2935     return nextUniqueId(use);
2936 }
2937 
acquireAudioSessionId(audio_session_t audioSession,pid_t pid)2938 void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
2939 {
2940     Mutex::Autolock _l(mLock);
2941     pid_t caller = IPCThreadState::self()->getCallingPid();
2942     ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2943     const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2944     if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
2945         caller = pid;
2946     }
2947 
2948     {
2949         Mutex::Autolock _cl(mClientLock);
2950         // Ignore requests received from processes not known as notification client. The request
2951         // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2952         // called from a different pid leaving a stale session reference.  Also we don't know how
2953         // to clear this reference if the client process dies.
2954         if (mNotificationClients.indexOfKey(caller) < 0) {
2955             ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2956             return;
2957         }
2958     }
2959 
2960     size_t num = mAudioSessionRefs.size();
2961     for (size_t i = 0; i < num; i++) {
2962         AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
2963         if (ref->mSessionid == audioSession && ref->mPid == caller) {
2964             ref->mCnt++;
2965             ALOGV(" incremented refcount to %d", ref->mCnt);
2966             return;
2967         }
2968     }
2969     mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2970     ALOGV(" added new entry for %d", audioSession);
2971 }
2972 
releaseAudioSessionId(audio_session_t audioSession,pid_t pid)2973 void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
2974 {
2975     std::vector< sp<EffectModule> > removedEffects;
2976     {
2977         Mutex::Autolock _l(mLock);
2978         pid_t caller = IPCThreadState::self()->getCallingPid();
2979         ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2980         const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2981         if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2982             caller = pid;
2983         }
2984         size_t num = mAudioSessionRefs.size();
2985         for (size_t i = 0; i < num; i++) {
2986             AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2987             if (ref->mSessionid == audioSession && ref->mPid == caller) {
2988                 ref->mCnt--;
2989                 ALOGV(" decremented refcount to %d", ref->mCnt);
2990                 if (ref->mCnt == 0) {
2991                     mAudioSessionRefs.removeAt(i);
2992                     delete ref;
2993                     std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2994                     removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2995                 }
2996                 goto Exit;
2997             }
2998         }
2999         // If the caller is audioserver it is likely that the session being released was acquired
3000         // on behalf of a process not in notification clients and we ignore the warning.
3001         ALOGW_IF(!isAudioServerUid(callerUid),
3002                  "session id %d not found for pid %d", audioSession, caller);
3003     }
3004 
3005 Exit:
3006     for (auto& effect : removedEffects) {
3007         effect->updatePolicyState();
3008     }
3009 }
3010 
isSessionAcquired_l(audio_session_t audioSession)3011 bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3012 {
3013     size_t num = mAudioSessionRefs.size();
3014     for (size_t i = 0; i < num; i++) {
3015         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3016         if (ref->mSessionid == audioSession) {
3017             return true;
3018         }
3019     }
3020     return false;
3021 }
3022 
purgeStaleEffects_l()3023 std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
3024 
3025     ALOGV("purging stale effects");
3026 
3027     Vector< sp<EffectChain> > chains;
3028     std::vector< sp<EffectModule> > removedEffects;
3029 
3030     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3031         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3032         Mutex::Autolock _l(t->mLock);
3033         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3034             sp<EffectChain> ec = t->mEffectChains[j];
3035             if (!audio_is_global_session(ec->sessionId())) {
3036                 chains.push(ec);
3037             }
3038         }
3039     }
3040 
3041     for (size_t i = 0; i < mRecordThreads.size(); i++) {
3042         sp<RecordThread> t = mRecordThreads.valueAt(i);
3043         Mutex::Autolock _l(t->mLock);
3044         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3045             sp<EffectChain> ec = t->mEffectChains[j];
3046             chains.push(ec);
3047         }
3048     }
3049 
3050     for (size_t i = 0; i < mMmapThreads.size(); i++) {
3051         sp<MmapThread> t = mMmapThreads.valueAt(i);
3052         Mutex::Autolock _l(t->mLock);
3053         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3054             sp<EffectChain> ec = t->mEffectChains[j];
3055             chains.push(ec);
3056         }
3057     }
3058 
3059     for (size_t i = 0; i < chains.size(); i++) {
3060         sp<EffectChain> ec = chains[i];
3061         int sessionid = ec->sessionId();
3062         sp<ThreadBase> t = ec->thread().promote();
3063         if (t == 0) {
3064             continue;
3065         }
3066         size_t numsessionrefs = mAudioSessionRefs.size();
3067         bool found = false;
3068         for (size_t k = 0; k < numsessionrefs; k++) {
3069             AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
3070             if (ref->mSessionid == sessionid) {
3071                 ALOGV(" session %d still exists for %d with %d refs",
3072                     sessionid, ref->mPid, ref->mCnt);
3073                 found = true;
3074                 break;
3075             }
3076         }
3077         if (!found) {
3078             Mutex::Autolock _l(t->mLock);
3079             // remove all effects from the chain
3080             while (ec->mEffects.size()) {
3081                 sp<EffectModule> effect = ec->mEffects[0];
3082                 effect->unPin();
3083                 t->removeEffect_l(effect, /*release*/ true);
3084                 if (effect->purgeHandles()) {
3085                     effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
3086                 }
3087                 removedEffects.push_back(effect);
3088             }
3089         }
3090     }
3091     return removedEffects;
3092 }
3093 
3094 // dumpToThreadLog_l() must be called with AudioFlinger::mLock held
dumpToThreadLog_l(const sp<ThreadBase> & thread)3095 void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3096 {
3097     audio_utils::FdToString fdToString;
3098     const int fd = fdToString.fd();
3099     if (fd >= 0) {
3100         thread->dump(fd, {} /* args */);
3101         mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3102     }
3103 }
3104 
3105 // checkThread_l() must be called with AudioFlinger::mLock held
checkThread_l(audio_io_handle_t ioHandle) const3106 AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3107 {
3108     ThreadBase *thread = checkMmapThread_l(ioHandle);
3109     if (thread == 0) {
3110         switch (audio_unique_id_get_use(ioHandle)) {
3111         case AUDIO_UNIQUE_ID_USE_OUTPUT:
3112             thread = checkPlaybackThread_l(ioHandle);
3113             break;
3114         case AUDIO_UNIQUE_ID_USE_INPUT:
3115             thread = checkRecordThread_l(ioHandle);
3116             break;
3117         default:
3118             break;
3119         }
3120     }
3121     return thread;
3122 }
3123 
3124 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
checkPlaybackThread_l(audio_io_handle_t output) const3125 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
3126 {
3127     return mPlaybackThreads.valueFor(output).get();
3128 }
3129 
3130 // checkMixerThread_l() must be called with AudioFlinger::mLock held
checkMixerThread_l(audio_io_handle_t output) const3131 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
3132 {
3133     PlaybackThread *thread = checkPlaybackThread_l(output);
3134     return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
3135 }
3136 
3137 // checkRecordThread_l() must be called with AudioFlinger::mLock held
checkRecordThread_l(audio_io_handle_t input) const3138 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
3139 {
3140     return mRecordThreads.valueFor(input).get();
3141 }
3142 
3143 // checkMmapThread_l() must be called with AudioFlinger::mLock held
checkMmapThread_l(audio_io_handle_t io) const3144 AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3145 {
3146     return mMmapThreads.valueFor(io).get();
3147 }
3148 
3149 
3150 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
getVolumeInterface_l(audio_io_handle_t output) const3151 AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3152 {
3153     VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
3154     if (volumeInterface == nullptr) {
3155         MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3156         if (mmapThread != nullptr) {
3157             if (mmapThread->isOutput()) {
3158                 MmapPlaybackThread *mmapPlaybackThread =
3159                         static_cast<MmapPlaybackThread *>(mmapThread);
3160                 volumeInterface = mmapPlaybackThread;
3161             }
3162         }
3163     }
3164     return volumeInterface;
3165 }
3166 
getAllVolumeInterfaces_l() const3167 Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3168 {
3169     Vector <VolumeInterface *> volumeInterfaces;
3170     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3171         volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
3172     }
3173     for (size_t i = 0; i < mMmapThreads.size(); i++) {
3174         if (mMmapThreads.valueAt(i)->isOutput()) {
3175             MmapPlaybackThread *mmapPlaybackThread =
3176                     static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3177             volumeInterfaces.add(mmapPlaybackThread);
3178         }
3179     }
3180     return volumeInterfaces;
3181 }
3182 
nextUniqueId(audio_unique_id_use_t use)3183 audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
3184 {
3185     // This is the internal API, so it is OK to assert on bad parameter.
3186     LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
3187     const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3188     for (int retry = 0; retry < maxRetries; retry++) {
3189         // The cast allows wraparound from max positive to min negative instead of abort
3190         uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3191                 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3192         ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3193         // allow wrap by skipping 0 and -1 for session ids
3194         if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3195             ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3196             return (audio_unique_id_t) (base | use);
3197         }
3198     }
3199     // We have no way of recovering from wraparound
3200     LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3201     // TODO Use a floor after wraparound.  This may need a mutex.
3202 }
3203 
primaryPlaybackThread_l() const3204 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
3205 {
3206     AutoMutex lock(mHardwareLock);
3207     if (mPrimaryHardwareDev == nullptr) {
3208         return nullptr;
3209     }
3210     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3211         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3212         if(thread->isDuplicating()) {
3213             continue;
3214         }
3215         AudioStreamOut *output = thread->getOutput();
3216         if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
3217             return thread;
3218         }
3219     }
3220     return nullptr;
3221 }
3222 
primaryOutputDevice_l() const3223 DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
3224 {
3225     PlaybackThread *thread = primaryPlaybackThread_l();
3226 
3227     if (thread == NULL) {
3228         return DeviceTypeSet();
3229     }
3230 
3231     return thread->outDeviceTypes();
3232 }
3233 
fastPlaybackThread_l() const3234 AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3235 {
3236     size_t minFrameCount = 0;
3237     PlaybackThread *minThread = NULL;
3238     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3239         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3240         if (!thread->isDuplicating()) {
3241             size_t frameCount = thread->frameCountHAL();
3242             if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3243                     (frameCount == minFrameCount && thread->hasFastMixer() &&
3244                     /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3245                 minFrameCount = frameCount;
3246                 minThread = thread;
3247             }
3248         }
3249     }
3250     return minThread;
3251 }
3252 
createSyncEvent(AudioSystem::sync_event_t type,audio_session_t triggerSession,audio_session_t listenerSession,sync_event_callback_t callBack,const wp<RefBase> & cookie)3253 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
3254                                     audio_session_t triggerSession,
3255                                     audio_session_t listenerSession,
3256                                     sync_event_callback_t callBack,
3257                                     const wp<RefBase>& cookie)
3258 {
3259     Mutex::Autolock _l(mLock);
3260 
3261     sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3262     status_t playStatus = NAME_NOT_FOUND;
3263     status_t recStatus = NAME_NOT_FOUND;
3264     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3265         playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3266         if (playStatus == NO_ERROR) {
3267             return event;
3268         }
3269     }
3270     for (size_t i = 0; i < mRecordThreads.size(); i++) {
3271         recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3272         if (recStatus == NO_ERROR) {
3273             return event;
3274         }
3275     }
3276     if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3277         mPendingSyncEvents.add(event);
3278     } else {
3279         ALOGV("createSyncEvent() invalid event %d", event->type());
3280         event.clear();
3281     }
3282     return event;
3283 }
3284 
3285 // ----------------------------------------------------------------------------
3286 //  Effect management
3287 // ----------------------------------------------------------------------------
3288 
getEffectsFactory()3289 sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3290     return mEffectsFactoryHal;
3291 }
3292 
queryNumberEffects(uint32_t * numEffects) const3293 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
3294 {
3295     Mutex::Autolock _l(mLock);
3296     if (mEffectsFactoryHal.get()) {
3297         return mEffectsFactoryHal->queryNumberEffects(numEffects);
3298     } else {
3299         return -ENODEV;
3300     }
3301 }
3302 
queryEffect(uint32_t index,effect_descriptor_t * descriptor) const3303 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
3304 {
3305     Mutex::Autolock _l(mLock);
3306     if (mEffectsFactoryHal.get()) {
3307         return mEffectsFactoryHal->getDescriptor(index, descriptor);
3308     } else {
3309         return -ENODEV;
3310     }
3311 }
3312 
getEffectDescriptor(const effect_uuid_t * pUuid,const effect_uuid_t * pTypeUuid,uint32_t preferredTypeFlag,effect_descriptor_t * descriptor) const3313 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
3314                                            const effect_uuid_t *pTypeUuid,
3315                                            uint32_t preferredTypeFlag,
3316                                            effect_descriptor_t *descriptor) const
3317 {
3318     if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3319         return BAD_VALUE;
3320     }
3321 
3322     Mutex::Autolock _l(mLock);
3323 
3324     if (!mEffectsFactoryHal.get()) {
3325         return -ENODEV;
3326     }
3327 
3328     status_t status = NO_ERROR;
3329     if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3330         // If uuid is specified, request effect descriptor from that.
3331         status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3332     } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3333         // If uuid is not specified, look for an available implementation
3334         // of the required type instead.
3335 
3336         // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3337         effect_descriptor_t desc;
3338         desc.flags = 0; // prevent compiler warning
3339 
3340         uint32_t numEffects = 0;
3341         status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3342         if (status < 0) {
3343             ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3344             return status;
3345         }
3346 
3347         bool found = false;
3348         for (uint32_t i = 0; i < numEffects; i++) {
3349             status = mEffectsFactoryHal->getDescriptor(i, &desc);
3350             if (status < 0) {
3351                 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3352                 continue;
3353             }
3354             if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3355                 // If matching type found save effect descriptor.
3356                 found = true;
3357                 *descriptor = desc;
3358 
3359                 // If there's no preferred flag or this descriptor matches the preferred
3360                 // flag, success! If this descriptor doesn't match the preferred
3361                 // flag, continue enumeration in case a better matching version of this
3362                 // effect type is available. Note that this means if no effect with a
3363                 // correct flag is found, the descriptor returned will correspond to the
3364                 // last effect that at least had a matching type uuid (if any).
3365                 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3366                     (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3367                     break;
3368                 }
3369             }
3370         }
3371 
3372         if (!found) {
3373             status = NAME_NOT_FOUND;
3374             ALOGW("getEffectDescriptor(): Effect not found by type.");
3375         }
3376     } else {
3377         status = BAD_VALUE;
3378         ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3379     }
3380     return status;
3381 }
3382 
createEffect(effect_descriptor_t * pDesc,const sp<IEffectClient> & effectClient,int32_t priority,audio_io_handle_t io,audio_session_t sessionId,const AudioDeviceTypeAddr & device,const String16 & opPackageName,pid_t pid,status_t * status,int * id,int * enabled)3383 sp<IEffect> AudioFlinger::createEffect(
3384         effect_descriptor_t *pDesc,
3385         const sp<IEffectClient>& effectClient,
3386         int32_t priority,
3387         audio_io_handle_t io,
3388         audio_session_t sessionId,
3389         const AudioDeviceTypeAddr& device,
3390         const String16& opPackageName,
3391         pid_t pid,
3392         status_t *status,
3393         int *id,
3394         int *enabled)
3395 {
3396     status_t lStatus = NO_ERROR;
3397     sp<EffectHandle> handle;
3398     effect_descriptor_t desc;
3399 
3400     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
3401     if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
3402         const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3403         ALOGW_IF(pid != -1 && pid != callingPid,
3404                  "%s uid %d pid %d tried to pass itself off as pid %d",
3405                  __func__, callingUid, callingPid, pid);
3406         pid = callingPid;
3407     }
3408 
3409     ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3410             pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
3411 
3412     if (pDesc == NULL) {
3413         lStatus = BAD_VALUE;
3414         goto Exit;
3415     }
3416 
3417     if (mEffectsFactoryHal == 0) {
3418         ALOGE("%s: no effects factory hal", __func__);
3419         lStatus = NO_INIT;
3420         goto Exit;
3421     }
3422 
3423     // check audio settings permission for global effects
3424     if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3425         if (!settingsAllowed()) {
3426             ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3427             lStatus = PERMISSION_DENIED;
3428             goto Exit;
3429         }
3430     } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3431         if (!isAudioServerUid(callingUid)) {
3432             ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3433             lStatus = PERMISSION_DENIED;
3434             goto Exit;
3435         }
3436 
3437         if (io == AUDIO_IO_HANDLE_NONE) {
3438             ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3439             lStatus = BAD_VALUE;
3440             goto Exit;
3441         }
3442     } else if (sessionId == AUDIO_SESSION_DEVICE) {
3443         if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3444             ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3445             lStatus = PERMISSION_DENIED;
3446             goto Exit;
3447         }
3448         if (io != AUDIO_IO_HANDLE_NONE) {
3449             ALOGE("%s: io handle should not be specified for device effect", __func__);
3450             lStatus = BAD_VALUE;
3451             goto Exit;
3452         }
3453     } else {
3454         // general sessionId.
3455 
3456         if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3457             ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3458             lStatus = BAD_VALUE;
3459             goto Exit;
3460         }
3461 
3462         // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3463         // to prevent creating an effect when one doesn't actually have track with that session?
3464     }
3465 
3466     {
3467         // Get the full effect descriptor from the uuid/type.
3468         // If the session is the output mix, prefer an auxiliary effect,
3469         // otherwise no preference.
3470         uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3471                                   EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3472         lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3473         if (lStatus < 0) {
3474             ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3475             goto Exit;
3476         }
3477 
3478         // Do not allow auxiliary effects on a session different from 0 (output mix)
3479         if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
3480              (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3481             lStatus = INVALID_OPERATION;
3482             goto Exit;
3483         }
3484 
3485         // check recording permission for visualizer
3486         if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
3487             // TODO: Do we need to start/stop op - i.e. is there recording being performed?
3488             !recordingAllowed(opPackageName, pid, callingUid)) {
3489             lStatus = PERMISSION_DENIED;
3490             goto Exit;
3491         }
3492 
3493         // return effect descriptor
3494         *pDesc = desc;
3495         if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3496             // if the output returned by getOutputForEffect() is removed before we lock the
3497             // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3498             // and we will exit safely
3499             io = AudioSystem::getOutputForEffect(&desc);
3500             ALOGV("createEffect got output %d", io);
3501         }
3502 
3503         Mutex::Autolock _l(mLock);
3504 
3505         if (sessionId == AUDIO_SESSION_DEVICE) {
3506             sp<Client> client = registerPid(pid);
3507             ALOGV("%s device type %d address %s", __func__, device.mType, device.getAddress());
3508             handle = mDeviceEffectManager.createEffect_l(
3509                     &desc, device, client, effectClient, mPatchPanel.patches_l(),
3510                     enabled, &lStatus);
3511             if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3512                 // remove local strong reference to Client with mClientLock held
3513                 Mutex::Autolock _cl(mClientLock);
3514                 client.clear();
3515             } else {
3516                 // handle must be valid here, but check again to be safe.
3517                 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3518             }
3519             goto Register;
3520         }
3521 
3522         // If output is not specified try to find a matching audio session ID in one of the
3523         // output threads.
3524         // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3525         // because of code checking output when entering the function.
3526         // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3527         // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
3528         if (io == AUDIO_IO_HANDLE_NONE) {
3529             // look for the thread where the specified audio session is present
3530             io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3531             if (io == AUDIO_IO_HANDLE_NONE) {
3532                 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
3533             }
3534             if (io == AUDIO_IO_HANDLE_NONE) {
3535                 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
3536             }
3537 
3538             // If you wish to create a Record preprocessing AudioEffect in Java,
3539             // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3540             // Otherwise it will fail when created on a Playback thread by legacy
3541             // handling below.  Ditto with Mmap, the associated Mmap track must be created
3542             // before creating the AudioEffect or the io handle must be specified.
3543             //
3544             // Detect if the effect is created after an AudioRecord is destroyed.
3545             if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3546                 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3547                         " for session %d no longer exists",
3548                          __func__, desc.name, sessionId);
3549                 lStatus = PERMISSION_DENIED;
3550                 goto Exit;
3551             }
3552 
3553             // Legacy handling of creating an effect on an expired or made-up
3554             // session id.  We think that it is a Playback effect.
3555             //
3556             // If no output thread contains the requested session ID, default to
3557             // first output. The effect chain will be moved to the correct output
3558             // thread when a track with the same session ID is created
3559             if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
3560                 io = mPlaybackThreads.keyAt(0);
3561             }
3562             ALOGV("createEffect() got io %d for effect %s", io, desc.name);
3563         } else if (checkPlaybackThread_l(io) != nullptr) {
3564             // allow only one effect chain per sessionId on mPlaybackThreads.
3565             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3566                 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3567                 if (io == checkIo) continue;
3568                 const uint32_t sessionType =
3569                         mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3570                 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3571                     ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3572                             __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3573                     android_errorWriteLog(0x534e4554, "123237974");
3574                     lStatus = BAD_VALUE;
3575                     goto Exit;
3576                 }
3577             }
3578         }
3579         ThreadBase *thread = checkRecordThread_l(io);
3580         if (thread == NULL) {
3581             thread = checkPlaybackThread_l(io);
3582             if (thread == NULL) {
3583                 thread = checkMmapThread_l(io);
3584                 if (thread == NULL) {
3585                     ALOGE("createEffect() unknown output thread");
3586                     lStatus = BAD_VALUE;
3587                     goto Exit;
3588                 }
3589             }
3590         } else {
3591             // Check if one effect chain was awaiting for an effect to be created on this
3592             // session and used it instead of creating a new one.
3593             sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
3594             if (chain != 0) {
3595                 Mutex::Autolock _l(thread->mLock);
3596                 thread->addEffectChain_l(chain);
3597             }
3598         }
3599 
3600         sp<Client> client = registerPid(pid);
3601 
3602         // create effect on selected output thread
3603         bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
3604         handle = thread->createEffect_l(client, effectClient, priority, sessionId,
3605                 &desc, enabled, &lStatus, pinned);
3606         if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3607             // remove local strong reference to Client with mClientLock held
3608             Mutex::Autolock _cl(mClientLock);
3609             client.clear();
3610         } else {
3611             // handle must be valid here, but check again to be safe.
3612             if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3613         }
3614     }
3615 
3616 Register:
3617     if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3618         // Check CPU and memory usage
3619         sp<EffectBase> effect = handle->effect().promote();
3620         if (effect != nullptr) {
3621             status_t rStatus = effect->updatePolicyState();
3622             if (rStatus != NO_ERROR) {
3623                 lStatus = rStatus;
3624             }
3625         }
3626     } else {
3627         handle.clear();
3628     }
3629 
3630 Exit:
3631     *status = lStatus;
3632     return handle;
3633 }
3634 
moveEffects(audio_session_t sessionId,audio_io_handle_t srcOutput,audio_io_handle_t dstOutput)3635 status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
3636         audio_io_handle_t dstOutput)
3637 {
3638     ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
3639             sessionId, srcOutput, dstOutput);
3640     Mutex::Autolock _l(mLock);
3641     if (srcOutput == dstOutput) {
3642         ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
3643         return NO_ERROR;
3644     }
3645     PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3646     if (srcThread == NULL) {
3647         ALOGW("moveEffects() bad srcOutput %d", srcOutput);
3648         return BAD_VALUE;
3649     }
3650     PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3651     if (dstThread == NULL) {
3652         ALOGW("moveEffects() bad dstOutput %d", dstOutput);
3653         return BAD_VALUE;
3654     }
3655 
3656     Mutex::Autolock _dl(dstThread->mLock);
3657     Mutex::Autolock _sl(srcThread->mLock);
3658     return moveEffectChain_l(sessionId, srcThread, dstThread);
3659 }
3660 
3661 
setEffectSuspended(int effectId,audio_session_t sessionId,bool suspended)3662 void AudioFlinger::setEffectSuspended(int effectId,
3663                                 audio_session_t sessionId,
3664                                 bool suspended)
3665 {
3666     Mutex::Autolock _l(mLock);
3667 
3668     sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3669     if (thread == nullptr) {
3670       return;
3671     }
3672     Mutex::Autolock _sl(thread->mLock);
3673     sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3674     thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3675 }
3676 
3677 
3678 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
moveEffectChain_l(audio_session_t sessionId,AudioFlinger::PlaybackThread * srcThread,AudioFlinger::PlaybackThread * dstThread)3679 status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
3680                                    AudioFlinger::PlaybackThread *srcThread,
3681                                    AudioFlinger::PlaybackThread *dstThread)
3682 {
3683     ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
3684             sessionId, srcThread, dstThread);
3685 
3686     sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
3687     if (chain == 0) {
3688         ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
3689                 sessionId, srcThread);
3690         return INVALID_OPERATION;
3691     }
3692 
3693     // Check whether the destination thread and all effects in the chain are compatible
3694     if (!chain->isCompatibleWithThread_l(dstThread)) {
3695         ALOGW("moveEffectChain_l() effect chain failed because"
3696                 " destination thread %p is not compatible with effects in the chain",
3697                 dstThread);
3698         return INVALID_OPERATION;
3699     }
3700 
3701     // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
3702     // so that a new chain is created with correct parameters when first effect is added. This is
3703     // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
3704     // removed.
3705     srcThread->removeEffectChain_l(chain);
3706 
3707     // transfer all effects one by one so that new effect chain is created on new thread with
3708     // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
3709     sp<EffectChain> dstChain;
3710     uint32_t strategy = 0; // prevent compiler warning
3711     sp<EffectModule> effect = chain->getEffectFromId_l(0);
3712     Vector< sp<EffectModule> > removed;
3713     status_t status = NO_ERROR;
3714     while (effect != 0) {
3715         srcThread->removeEffect_l(effect);
3716         removed.add(effect);
3717         status = dstThread->addEffect_l(effect);
3718         if (status != NO_ERROR) {
3719             break;
3720         }
3721         // removeEffect_l() has stopped the effect if it was active so it must be restarted
3722         if (effect->state() == EffectModule::ACTIVE ||
3723                 effect->state() == EffectModule::STOPPING) {
3724             effect->start();
3725         }
3726         // if the move request is not received from audio policy manager, the effect must be
3727         // re-registered with the new strategy and output
3728         if (dstChain == 0) {
3729             dstChain = effect->callback()->chain().promote();
3730             if (dstChain == 0) {
3731                 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
3732                 status = NO_INIT;
3733                 break;
3734             }
3735             strategy = dstChain->strategy();
3736         }
3737         effect = chain->getEffectFromId_l(0);
3738     }
3739 
3740     if (status != NO_ERROR) {
3741         for (size_t i = 0; i < removed.size(); i++) {
3742             srcThread->addEffect_l(removed[i]);
3743         }
3744     }
3745 
3746     return status;
3747 }
3748 
moveAuxEffectToIo(int EffectId,const sp<PlaybackThread> & dstThread,sp<PlaybackThread> * srcThread)3749 status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3750                                          const sp<PlaybackThread>& dstThread,
3751                                          sp<PlaybackThread> *srcThread)
3752 {
3753     status_t status = NO_ERROR;
3754     Mutex::Autolock _l(mLock);
3755     sp<PlaybackThread> thread =
3756         static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
3757 
3758     if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3759         Mutex::Autolock _dl(dstThread->mLock);
3760         Mutex::Autolock _sl(thread->mLock);
3761         sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3762         sp<EffectChain> dstChain;
3763         if (srcChain == 0) {
3764             return INVALID_OPERATION;
3765         }
3766 
3767         sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3768         if (effect == 0) {
3769             return INVALID_OPERATION;
3770         }
3771         thread->removeEffect_l(effect);
3772         status = dstThread->addEffect_l(effect);
3773         if (status != NO_ERROR) {
3774             thread->addEffect_l(effect);
3775             status = INVALID_OPERATION;
3776             goto Exit;
3777         }
3778 
3779         dstChain = effect->callback()->chain().promote();
3780         if (dstChain == 0) {
3781             thread->addEffect_l(effect);
3782             status = INVALID_OPERATION;
3783         }
3784 
3785 Exit:
3786         // removeEffect_l() has stopped the effect if it was active so it must be restarted
3787         if (effect->state() == EffectModule::ACTIVE ||
3788             effect->state() == EffectModule::STOPPING) {
3789             effect->start();
3790         }
3791     }
3792 
3793     if (status == NO_ERROR && srcThread != nullptr) {
3794         *srcThread = thread;
3795     }
3796     return status;
3797 }
3798 
isNonOffloadableGlobalEffectEnabled_l()3799 bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
3800 {
3801     if (mGlobalEffectEnableTime != 0 &&
3802             ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3803         return true;
3804     }
3805 
3806     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3807         sp<EffectChain> ec =
3808                 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3809         if (ec != 0 && ec->isNonOffloadableEnabled()) {
3810             return true;
3811         }
3812     }
3813     return false;
3814 }
3815 
onNonOffloadableGlobalEffectEnable()3816 void AudioFlinger::onNonOffloadableGlobalEffectEnable()
3817 {
3818     Mutex::Autolock _l(mLock);
3819 
3820     mGlobalEffectEnableTime = systemTime();
3821 
3822     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3823         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3824         if (t->mType == ThreadBase::OFFLOAD) {
3825             t->invalidateTracks(AUDIO_STREAM_MUSIC);
3826         }
3827     }
3828 
3829 }
3830 
putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain> & chain)3831 status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3832 {
3833     // clear possible suspended state before parking the chain so that it starts in default state
3834     // when attached to a new record thread
3835     chain->setEffectSuspended_l(FX_IID_AEC, false);
3836     chain->setEffectSuspended_l(FX_IID_NS, false);
3837 
3838     audio_session_t session = chain->sessionId();
3839     ssize_t index = mOrphanEffectChains.indexOfKey(session);
3840     ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
3841     if (index >= 0) {
3842         ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3843         return ALREADY_EXISTS;
3844     }
3845     mOrphanEffectChains.add(session, chain);
3846     return NO_ERROR;
3847 }
3848 
getOrphanEffectChain_l(audio_session_t session)3849 sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3850 {
3851     sp<EffectChain> chain;
3852     ssize_t index = mOrphanEffectChains.indexOfKey(session);
3853     ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
3854     if (index >= 0) {
3855         chain = mOrphanEffectChains.valueAt(index);
3856         mOrphanEffectChains.removeItemsAt(index);
3857     }
3858     return chain;
3859 }
3860 
updateOrphanEffectChains(const sp<AudioFlinger::EffectModule> & effect)3861 bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3862 {
3863     Mutex::Autolock _l(mLock);
3864     audio_session_t session = effect->sessionId();
3865     ssize_t index = mOrphanEffectChains.indexOfKey(session);
3866     ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
3867     if (index >= 0) {
3868         sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
3869         if (chain->removeEffect_l(effect, true) == 0) {
3870             ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
3871             mOrphanEffectChains.removeItemsAt(index);
3872         }
3873         return true;
3874     }
3875     return false;
3876 }
3877 
3878 
3879 // ----------------------------------------------------------------------------
3880 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)3881 status_t AudioFlinger::onTransact(
3882         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3883 {
3884     return BnAudioFlinger::onTransact(code, data, reply, flags);
3885 }
3886 
3887 } // namespace android
3888