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