• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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                                       input.opPackageName);
857         LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
858         // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
859 
860         output.afFrameCount = thread->frameCount();
861         output.afSampleRate = thread->sampleRate();
862         output.afLatencyMs = thread->latency();
863         output.portId = portId;
864 
865         if (lStatus == NO_ERROR) {
866             // Connect secondary outputs. Failure on a secondary output must not imped the primary
867             // Any secondary output setup failure will lead to a desync between the AP and AF until
868             // the track is destroyed.
869             TeePatches teePatches;
870             for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
871                 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
872                 if (secondaryThread == NULL) {
873                     ALOGE("no playback thread found for secondary output %d", output.outputId);
874                     continue;
875                 }
876 
877                 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
878                                           / thread->sampleRate();
879                 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
880                                           / secondaryThread->sampleRate();
881                 // If the secondary output has just been opened, the first secondaryThread write
882                 // will not block as it will fill the empty startup buffer of the HAL,
883                 // so a second sink buffer needs to be ready for the immediate next blocking write.
884                 // Additionally, have a margin of one main thread buffer as the scheduling jitter
885                 // can reorder the writes (eg if thread A&B have the same write intervale,
886                 // the scheduler could schedule AB...BA)
887                 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
888                 // Total secondary output buffer must be at least as the read frames plus
889                 // the margin of a few buffers on both sides in case the
890                 // threads scheduling has some jitter.
891                 // That value should not impact latency as the secondary track is started before
892                 // its buffer is full, see frameCountToBeReady.
893                 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
894                 // The frameCount should also not be smaller than the secondary thread min frame
895                 // count
896                 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
897                             [&] { Mutex::Autolock _l(secondaryThread->mLock);
898                                   return secondaryThread->latency_l(); }(),
899                             secondaryThread->mNormalFrameCount,
900                             secondaryThread->mSampleRate,
901                             output.sampleRate,
902                             input.speed);
903                 frameCount = std::max(frameCount, minFrameCount);
904 
905                 using namespace std::chrono_literals;
906                 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
907                 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
908                                                                output.sampleRate,
909                                                                inChannelMask,
910                                                                input.config.format,
911                                                                frameCount,
912                                                                NULL /* buffer */,
913                                                                (size_t)0 /* bufferSize */,
914                                                                AUDIO_INPUT_FLAG_DIRECT,
915                                                                0ns /* timeout */);
916                 status_t status = patchRecord->initCheck();
917                 if (status != NO_ERROR) {
918                     ALOGE("Secondary output patchRecord init failed: %d", status);
919                     continue;
920                 }
921 
922                 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
923                 // for fast usage: thread has fast mixer, sample rate matches, etc.;
924                 // for now, we exclude fast tracks by removing the Fast flag.
925                 const audio_output_flags_t outputFlags =
926                         (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
927                 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
928                                                                streamType,
929                                                                output.sampleRate,
930                                                                input.config.channel_mask,
931                                                                input.config.format,
932                                                                frameCount,
933                                                                patchRecord->buffer(),
934                                                                patchRecord->bufferSize(),
935                                                                outputFlags,
936                                                                0ns /* timeout */,
937                                                                frameCountToBeReady);
938                 status = patchTrack->initCheck();
939                 if (status != NO_ERROR) {
940                     ALOGE("Secondary output patchTrack init failed: %d", status);
941                     continue;
942                 }
943                 teePatches.push_back({patchRecord, patchTrack});
944                 secondaryThread->addPatchTrack(patchTrack);
945                 // In case the downstream patchTrack on the secondaryThread temporarily outlives
946                 // our created track, ensure the corresponding patchRecord is still alive.
947                 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
948                 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
949             }
950             track->setTeePatches(std::move(teePatches));
951         }
952 
953         // move effect chain to this output thread if an effect on same session was waiting
954         // for a track to be created
955         if (lStatus == NO_ERROR && effectThread != NULL) {
956             // no risk of deadlock because AudioFlinger::mLock is held
957             Mutex::Autolock _dl(thread->mLock);
958             Mutex::Autolock _sl(effectThread->mLock);
959             if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
960                 effectThreadId = thread->id();
961                 effectIds = thread->getEffectIds_l(sessionId);
962             }
963         }
964 
965         // Look for sync events awaiting for a session to be used.
966         for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
967             if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
968                 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
969                     if (lStatus == NO_ERROR) {
970                         (void) track->setSyncEvent(mPendingSyncEvents[i]);
971                     } else {
972                         mPendingSyncEvents[i]->cancel();
973                     }
974                     mPendingSyncEvents.removeAt(i);
975                     i--;
976                 }
977             }
978         }
979 
980         setAudioHwSyncForSession_l(thread, sessionId);
981     }
982 
983     if (lStatus != NO_ERROR) {
984         // remove local strong reference to Client before deleting the Track so that the
985         // Client destructor is called by the TrackBase destructor with mClientLock held
986         // Don't hold mClientLock when releasing the reference on the track as the
987         // destructor will acquire it.
988         {
989             Mutex::Autolock _cl(mClientLock);
990             client.clear();
991         }
992         track.clear();
993         goto Exit;
994     }
995 
996     // effectThreadId is not NONE if an effect chain corresponding to the track session
997     // was found on another thread and must be moved on this thread
998     if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
999         AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1000     }
1001 
1002     // return handle to client
1003     trackHandle = new TrackHandle(track);
1004 
1005 Exit:
1006     if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
1007         AudioSystem::releaseOutput(portId);
1008     }
1009     *status = lStatus;
1010     return trackHandle;
1011 }
1012 
sampleRate(audio_io_handle_t ioHandle) const1013 uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
1014 {
1015     Mutex::Autolock _l(mLock);
1016     ThreadBase *thread = checkThread_l(ioHandle);
1017     if (thread == NULL) {
1018         ALOGW("sampleRate() unknown thread %d", ioHandle);
1019         return 0;
1020     }
1021     return thread->sampleRate();
1022 }
1023 
format(audio_io_handle_t output) const1024 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
1025 {
1026     Mutex::Autolock _l(mLock);
1027     PlaybackThread *thread = checkPlaybackThread_l(output);
1028     if (thread == NULL) {
1029         ALOGW("format() unknown thread %d", output);
1030         return AUDIO_FORMAT_INVALID;
1031     }
1032     return thread->format();
1033 }
1034 
frameCount(audio_io_handle_t ioHandle) const1035 size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
1036 {
1037     Mutex::Autolock _l(mLock);
1038     ThreadBase *thread = checkThread_l(ioHandle);
1039     if (thread == NULL) {
1040         ALOGW("frameCount() unknown thread %d", ioHandle);
1041         return 0;
1042     }
1043     // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1044     //       should examine all callers and fix them to handle smaller counts
1045     return thread->frameCount();
1046 }
1047 
frameCountHAL(audio_io_handle_t ioHandle) const1048 size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1049 {
1050     Mutex::Autolock _l(mLock);
1051     ThreadBase *thread = checkThread_l(ioHandle);
1052     if (thread == NULL) {
1053         ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1054         return 0;
1055     }
1056     return thread->frameCountHAL();
1057 }
1058 
latency(audio_io_handle_t output) const1059 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
1060 {
1061     Mutex::Autolock _l(mLock);
1062     PlaybackThread *thread = checkPlaybackThread_l(output);
1063     if (thread == NULL) {
1064         ALOGW("latency(): no playback thread found for output handle %d", output);
1065         return 0;
1066     }
1067     return thread->latency();
1068 }
1069 
setMasterVolume(float value)1070 status_t AudioFlinger::setMasterVolume(float value)
1071 {
1072     status_t ret = initCheck();
1073     if (ret != NO_ERROR) {
1074         return ret;
1075     }
1076 
1077     // check calling permissions
1078     if (!settingsAllowed()) {
1079         return PERMISSION_DENIED;
1080     }
1081 
1082     Mutex::Autolock _l(mLock);
1083     mMasterVolume = value;
1084 
1085     // Set master volume in the HALs which support it.
1086     {
1087         AutoMutex lock(mHardwareLock);
1088         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1089             AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
1090 
1091             mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1092             if (dev->canSetMasterVolume()) {
1093                 dev->hwDevice()->setMasterVolume(value);
1094             }
1095             mHardwareStatus = AUDIO_HW_IDLE;
1096         }
1097     }
1098     // Now set the master volume in each playback thread.  Playback threads
1099     // assigned to HALs which do not have master volume support will apply
1100     // master volume during the mix operation.  Threads with HALs which do
1101     // support master volume will simply ignore the setting.
1102     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1103         if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1104             continue;
1105         }
1106         mPlaybackThreads.valueAt(i)->setMasterVolume(value);
1107     }
1108 
1109     return NO_ERROR;
1110 }
1111 
setMasterBalance(float balance)1112 status_t AudioFlinger::setMasterBalance(float balance)
1113 {
1114     status_t ret = initCheck();
1115     if (ret != NO_ERROR) {
1116         return ret;
1117     }
1118 
1119     // check calling permissions
1120     if (!settingsAllowed()) {
1121         return PERMISSION_DENIED;
1122     }
1123 
1124     // check range
1125     if (isnan(balance) || fabs(balance) > 1.f) {
1126         return BAD_VALUE;
1127     }
1128 
1129     Mutex::Autolock _l(mLock);
1130 
1131     // short cut.
1132     if (mMasterBalance == balance) return NO_ERROR;
1133 
1134     mMasterBalance = balance;
1135 
1136     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1137         if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1138             continue;
1139         }
1140         mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1141     }
1142 
1143     return NO_ERROR;
1144 }
1145 
setMode(audio_mode_t mode)1146 status_t AudioFlinger::setMode(audio_mode_t mode)
1147 {
1148     status_t ret = initCheck();
1149     if (ret != NO_ERROR) {
1150         return ret;
1151     }
1152 
1153     // check calling permissions
1154     if (!settingsAllowed()) {
1155         return PERMISSION_DENIED;
1156     }
1157     if (uint32_t(mode) >= AUDIO_MODE_CNT) {
1158         ALOGW("Illegal value: setMode(%d)", mode);
1159         return BAD_VALUE;
1160     }
1161 
1162     { // scope for the lock
1163         AutoMutex lock(mHardwareLock);
1164         if (mPrimaryHardwareDev == nullptr) {
1165             return INVALID_OPERATION;
1166         }
1167         sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1168         mHardwareStatus = AUDIO_HW_SET_MODE;
1169         ret = dev->setMode(mode);
1170         mHardwareStatus = AUDIO_HW_IDLE;
1171     }
1172 
1173     if (NO_ERROR == ret) {
1174         Mutex::Autolock _l(mLock);
1175         mMode = mode;
1176         for (size_t i = 0; i < mPlaybackThreads.size(); i++)
1177             mPlaybackThreads.valueAt(i)->setMode(mode);
1178     }
1179 
1180     mediametrics::LogItem(mMetricsId)
1181         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1182         .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1183         .record();
1184     return ret;
1185 }
1186 
setMicMute(bool state)1187 status_t AudioFlinger::setMicMute(bool state)
1188 {
1189     status_t ret = initCheck();
1190     if (ret != NO_ERROR) {
1191         return ret;
1192     }
1193 
1194     // check calling permissions
1195     if (!settingsAllowed()) {
1196         return PERMISSION_DENIED;
1197     }
1198 
1199     AutoMutex lock(mHardwareLock);
1200     if (mPrimaryHardwareDev == nullptr) {
1201         return INVALID_OPERATION;
1202     }
1203     sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1204     if (primaryDev == nullptr) {
1205         ALOGW("%s: no primary HAL device", __func__);
1206         return INVALID_OPERATION;
1207     }
1208     mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
1209     ret = primaryDev->setMicMute(state);
1210     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1211         sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1212         if (dev != primaryDev) {
1213             (void)dev->setMicMute(state);
1214         }
1215     }
1216     mHardwareStatus = AUDIO_HW_IDLE;
1217     ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
1218     return ret;
1219 }
1220 
getMicMute() const1221 bool AudioFlinger::getMicMute() const
1222 {
1223     status_t ret = initCheck();
1224     if (ret != NO_ERROR) {
1225         return false;
1226     }
1227     AutoMutex lock(mHardwareLock);
1228     if (mPrimaryHardwareDev == nullptr) {
1229         return false;
1230     }
1231     sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1232     if (primaryDev == nullptr) {
1233         ALOGW("%s: no primary HAL device", __func__);
1234         return false;
1235     }
1236     bool state;
1237     mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1238     ret = primaryDev->getMicMute(&state);
1239     mHardwareStatus = AUDIO_HW_IDLE;
1240     ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1241     return (ret == NO_ERROR) && state;
1242 }
1243 
setRecordSilenced(audio_port_handle_t portId,bool silenced)1244 void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
1245 {
1246     ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
1247 
1248     AutoMutex lock(mLock);
1249     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1250         mRecordThreads[i]->setRecordSilenced(portId, silenced);
1251     }
1252     for (size_t i = 0; i < mMmapThreads.size(); i++) {
1253         mMmapThreads[i]->setRecordSilenced(portId, silenced);
1254     }
1255 }
1256 
setMasterMute(bool muted)1257 status_t AudioFlinger::setMasterMute(bool muted)
1258 {
1259     status_t ret = initCheck();
1260     if (ret != NO_ERROR) {
1261         return ret;
1262     }
1263 
1264     // check calling permissions
1265     if (!settingsAllowed()) {
1266         return PERMISSION_DENIED;
1267     }
1268 
1269     Mutex::Autolock _l(mLock);
1270     mMasterMute = muted;
1271 
1272     // Set master mute in the HALs which support it.
1273     {
1274         AutoMutex lock(mHardwareLock);
1275         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1276             AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
1277 
1278             mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1279             if (dev->canSetMasterMute()) {
1280                 dev->hwDevice()->setMasterMute(muted);
1281             }
1282             mHardwareStatus = AUDIO_HW_IDLE;
1283         }
1284     }
1285 
1286     // Now set the master mute in each playback thread.  Playback threads
1287     // assigned to HALs which do not have master mute support will apply master
1288     // mute during the mix operation.  Threads with HALs which do support master
1289     // mute will simply ignore the setting.
1290     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1291     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1292         volumeInterfaces[i]->setMasterMute(muted);
1293     }
1294 
1295     return NO_ERROR;
1296 }
1297 
masterVolume() const1298 float AudioFlinger::masterVolume() const
1299 {
1300     Mutex::Autolock _l(mLock);
1301     return masterVolume_l();
1302 }
1303 
getMasterBalance(float * balance) const1304 status_t AudioFlinger::getMasterBalance(float *balance) const
1305 {
1306     Mutex::Autolock _l(mLock);
1307     *balance = getMasterBalance_l();
1308     return NO_ERROR; // if called through binder, may return a transactional error
1309 }
1310 
masterMute() const1311 bool AudioFlinger::masterMute() const
1312 {
1313     Mutex::Autolock _l(mLock);
1314     return masterMute_l();
1315 }
1316 
masterVolume_l() const1317 float AudioFlinger::masterVolume_l() const
1318 {
1319     return mMasterVolume;
1320 }
1321 
getMasterBalance_l() const1322 float AudioFlinger::getMasterBalance_l() const
1323 {
1324     return mMasterBalance;
1325 }
1326 
masterMute_l() const1327 bool AudioFlinger::masterMute_l() const
1328 {
1329     return mMasterMute;
1330 }
1331 
checkStreamType(audio_stream_type_t stream) const1332 status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1333 {
1334     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
1335         ALOGW("checkStreamType() invalid stream %d", stream);
1336         return BAD_VALUE;
1337     }
1338     const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1339     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1340         ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
1341         return PERMISSION_DENIED;
1342     }
1343 
1344     return NO_ERROR;
1345 }
1346 
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)1347 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1348         audio_io_handle_t output)
1349 {
1350     // check calling permissions
1351     if (!settingsAllowed()) {
1352         return PERMISSION_DENIED;
1353     }
1354 
1355     status_t status = checkStreamType(stream);
1356     if (status != NO_ERROR) {
1357         return status;
1358     }
1359     if (output == AUDIO_IO_HANDLE_NONE) {
1360         return BAD_VALUE;
1361     }
1362     LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1363                         "AUDIO_STREAM_PATCH must have full scale volume");
1364 
1365     AutoMutex lock(mLock);
1366     VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1367     if (volumeInterface == NULL) {
1368         return BAD_VALUE;
1369     }
1370     volumeInterface->setStreamVolume(stream, value);
1371 
1372     return NO_ERROR;
1373 }
1374 
setStreamMute(audio_stream_type_t stream,bool muted)1375 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
1376 {
1377     // check calling permissions
1378     if (!settingsAllowed()) {
1379         return PERMISSION_DENIED;
1380     }
1381 
1382     status_t status = checkStreamType(stream);
1383     if (status != NO_ERROR) {
1384         return status;
1385     }
1386     ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1387 
1388     if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
1389         ALOGE("setStreamMute() invalid stream %d", stream);
1390         return BAD_VALUE;
1391     }
1392 
1393     AutoMutex lock(mLock);
1394     mStreamTypes[stream].mute = muted;
1395     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1396     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1397         volumeInterfaces[i]->setStreamMute(stream, muted);
1398     }
1399 
1400     return NO_ERROR;
1401 }
1402 
streamVolume(audio_stream_type_t stream,audio_io_handle_t output) const1403 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
1404 {
1405     status_t status = checkStreamType(stream);
1406     if (status != NO_ERROR) {
1407         return 0.0f;
1408     }
1409     if (output == AUDIO_IO_HANDLE_NONE) {
1410         return 0.0f;
1411     }
1412 
1413     AutoMutex lock(mLock);
1414     VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1415     if (volumeInterface == NULL) {
1416         return 0.0f;
1417     }
1418 
1419     return volumeInterface->streamVolume(stream);
1420 }
1421 
streamMute(audio_stream_type_t stream) const1422 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
1423 {
1424     status_t status = checkStreamType(stream);
1425     if (status != NO_ERROR) {
1426         return true;
1427     }
1428 
1429     AutoMutex lock(mLock);
1430     return streamMute_l(stream);
1431 }
1432 
1433 
broacastParametersToRecordThreads_l(const String8 & keyValuePairs)1434 void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1435 {
1436     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1437         mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1438     }
1439 }
1440 
updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector & devices)1441 void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1442 {
1443     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1444         mRecordThreads.valueAt(i)->updateOutDevices(devices);
1445     }
1446 }
1447 
1448 // 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)1449 void AudioFlinger::forwardParametersToDownstreamPatches_l(
1450         audio_io_handle_t upStream, const String8& keyValuePairs,
1451         std::function<bool(const sp<PlaybackThread>&)> useThread)
1452 {
1453     std::vector<PatchPanel::SoftwarePatch> swPatches;
1454     if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1455     ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1456             __func__, swPatches.size(), upStream);
1457     for (const auto& swPatch : swPatches) {
1458         sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1459         if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1460             downStream->setParameters(keyValuePairs);
1461         }
1462     }
1463 }
1464 
1465 // Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1466 // Some keys are used for audio routing and audio path configuration and should be reserved for use
1467 // by audio policy and audio flinger for functional, privacy and security reasons.
filterReservedParameters(String8 & keyValuePairs,uid_t callingUid)1468 void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1469 {
1470     static const String8 kReservedParameters[] = {
1471         String8(AudioParameter::keyRouting),
1472         String8(AudioParameter::keySamplingRate),
1473         String8(AudioParameter::keyFormat),
1474         String8(AudioParameter::keyChannels),
1475         String8(AudioParameter::keyFrameCount),
1476         String8(AudioParameter::keyInputSource),
1477         String8(AudioParameter::keyMonoOutput),
1478         String8(AudioParameter::keyDeviceConnect),
1479         String8(AudioParameter::keyDeviceDisconnect),
1480         String8(AudioParameter::keyStreamSupportedFormats),
1481         String8(AudioParameter::keyStreamSupportedChannels),
1482         String8(AudioParameter::keyStreamSupportedSamplingRates),
1483     };
1484 
1485     if (isAudioServerUid(callingUid)) {
1486         return; // no need to filter if audioserver.
1487     }
1488 
1489     AudioParameter param = AudioParameter(keyValuePairs);
1490     String8 value;
1491     AudioParameter rejectedParam;
1492     for (auto& key : kReservedParameters) {
1493         if (param.get(key, value) == NO_ERROR) {
1494             rejectedParam.add(key, value);
1495             param.remove(key);
1496         }
1497     }
1498     logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1499                           rejectedParam.size(), rejectedParam.toString(), callingUid);
1500     keyValuePairs = param.toString();
1501 }
1502 
logFilteredParameters(size_t originalKVPSize,const String8 & originalKVPs,size_t rejectedKVPSize,const String8 & rejectedKVPs,uid_t callingUid)1503 void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1504                                          size_t rejectedKVPSize, const String8& rejectedKVPs,
1505                                          uid_t callingUid) {
1506     auto prefix = String8::format("UID %5d", callingUid);
1507     auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1508     if (rejectedKVPSize != 0) {
1509         auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1510         ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1511         mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1512     } else {
1513         auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1514         logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1515     }
1516 }
1517 
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)1518 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
1519 {
1520     ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1521             ioHandle, keyValuePairs.string(),
1522             IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1523 
1524     // check calling permissions
1525     if (!settingsAllowed()) {
1526         return PERMISSION_DENIED;
1527     }
1528 
1529     String8 filteredKeyValuePairs = keyValuePairs;
1530     filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1531 
1532     ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1533 
1534     // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1535     if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1536         Mutex::Autolock _l(mLock);
1537         // result will remain NO_INIT if no audio device is present
1538         status_t final_result = NO_INIT;
1539         {
1540             AutoMutex lock(mHardwareLock);
1541             mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1542             for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1543                 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1544                 status_t result = dev->setParameters(filteredKeyValuePairs);
1545                 // return success if at least one audio device accepts the parameters as not all
1546                 // HALs are requested to support all parameters. If no audio device supports the
1547                 // requested parameters, the last error is reported.
1548                 if (final_result != NO_ERROR) {
1549                     final_result = result;
1550                 }
1551             }
1552             mHardwareStatus = AUDIO_HW_IDLE;
1553         }
1554         // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1555         AudioParameter param = AudioParameter(filteredKeyValuePairs);
1556         String8 value;
1557         if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1558             bool btNrecIsOff = (value == AudioParameter::valueOff);
1559             if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
1560                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1561                     mRecordThreads.valueAt(i)->checkBtNrec();
1562                 }
1563             }
1564         }
1565         String8 screenState;
1566         if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1567             bool isOff = (screenState == AudioParameter::valueOff);
1568             if (isOff != (AudioFlinger::mScreenState & 1)) {
1569                 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
1570             }
1571         }
1572         return final_result;
1573     }
1574 
1575     // hold a strong ref on thread in case closeOutput() or closeInput() is called
1576     // and the thread is exited once the lock is released
1577     sp<ThreadBase> thread;
1578     {
1579         Mutex::Autolock _l(mLock);
1580         thread = checkPlaybackThread_l(ioHandle);
1581         if (thread == 0) {
1582             thread = checkRecordThread_l(ioHandle);
1583             if (thread == 0) {
1584                 thread = checkMmapThread_l(ioHandle);
1585             }
1586         } else if (thread == primaryPlaybackThread_l()) {
1587             // indicate output device change to all input threads for pre processing
1588             AudioParameter param = AudioParameter(filteredKeyValuePairs);
1589             int value;
1590             if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1591                     (value != 0)) {
1592                 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
1593             }
1594         }
1595     }
1596     if (thread != 0) {
1597         status_t result = thread->setParameters(filteredKeyValuePairs);
1598         forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1599         return result;
1600     }
1601     return BAD_VALUE;
1602 }
1603 
getParameters(audio_io_handle_t ioHandle,const String8 & keys) const1604 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
1605 {
1606     ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1607             ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
1608 
1609     Mutex::Autolock _l(mLock);
1610 
1611     if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1612         String8 out_s8;
1613 
1614         AutoMutex lock(mHardwareLock);
1615         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1616             String8 s;
1617             mHardwareStatus = AUDIO_HW_GET_PARAMETER;
1618             sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1619             status_t result = dev->getParameters(keys, &s);
1620             mHardwareStatus = AUDIO_HW_IDLE;
1621             if (result == OK) out_s8 += s;
1622         }
1623         return out_s8;
1624     }
1625 
1626     ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1627     if (thread == NULL) {
1628         thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1629         if (thread == NULL) {
1630             thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1631             if (thread == NULL) {
1632                 return String8("");
1633             }
1634         }
1635     }
1636     return thread->getParameters(keys);
1637 }
1638 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask) const1639 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1640         audio_channel_mask_t channelMask) const
1641 {
1642     status_t ret = initCheck();
1643     if (ret != NO_ERROR) {
1644         return 0;
1645     }
1646     if ((sampleRate == 0) ||
1647             !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
1648             !audio_is_input_channel(channelMask)) {
1649         return 0;
1650     }
1651 
1652     AutoMutex lock(mHardwareLock);
1653     if (mPrimaryHardwareDev == nullptr) {
1654         return 0;
1655     }
1656     mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
1657 
1658     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1659     std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1660     if (channelMask != AUDIO_CHANNEL_IN_MONO)
1661         channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1662     if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1663         channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1664 
1665     std::vector<audio_format_t> formats = {format};
1666     if (format != AUDIO_FORMAT_PCM_16_BIT)
1667         formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1668 
1669     std::vector<uint32_t> sampleRates = {sampleRate};
1670     static const uint32_t SR_44100 = 44100;
1671     static const uint32_t SR_48000 = 48000;
1672 
1673     if (sampleRate != SR_48000)
1674         sampleRates.push_back(SR_48000);
1675     if (sampleRate != SR_44100)
1676         sampleRates.push_back(SR_44100);
1677 
1678     mHardwareStatus = AUDIO_HW_IDLE;
1679 
1680     // Change parameters of the configuration each iteration until we find a
1681     // configuration that the device will support.
1682     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1683     for (auto testChannelMask : channelMasks) {
1684         config.channel_mask = testChannelMask;
1685         for (auto testFormat : formats) {
1686             config.format = testFormat;
1687             for (auto testSampleRate : sampleRates) {
1688                 config.sample_rate = testSampleRate;
1689 
1690                 size_t bytes = 0;
1691                 status_t result = dev->getInputBufferSize(&config, &bytes);
1692                 if (result != OK || bytes == 0) {
1693                     continue;
1694                 }
1695 
1696                 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1697                     config.format != format) {
1698                     uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1699                     uint32_t srcChannelCount =
1700                         audio_channel_count_from_in_mask(config.channel_mask);
1701                     size_t srcFrames =
1702                         bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1703                     size_t dstFrames = destinationFramesPossible(
1704                         srcFrames, config.sample_rate, sampleRate);
1705                     bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1706                 }
1707                 return bytes;
1708             }
1709         }
1710     }
1711 
1712     ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1713               "format %#x, channelMask %#x",sampleRate, format, channelMask);
1714     return 0;
1715 }
1716 
getInputFramesLost(audio_io_handle_t ioHandle) const1717 uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
1718 {
1719     Mutex::Autolock _l(mLock);
1720 
1721     RecordThread *recordThread = checkRecordThread_l(ioHandle);
1722     if (recordThread != NULL) {
1723         return recordThread->getInputFramesLost();
1724     }
1725     return 0;
1726 }
1727 
setVoiceVolume(float value)1728 status_t AudioFlinger::setVoiceVolume(float value)
1729 {
1730     status_t ret = initCheck();
1731     if (ret != NO_ERROR) {
1732         return ret;
1733     }
1734 
1735     // check calling permissions
1736     if (!settingsAllowed()) {
1737         return PERMISSION_DENIED;
1738     }
1739 
1740     AutoMutex lock(mHardwareLock);
1741     if (mPrimaryHardwareDev == nullptr) {
1742         return INVALID_OPERATION;
1743     }
1744     sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
1745     mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1746     ret = dev->setVoiceVolume(value);
1747     mHardwareStatus = AUDIO_HW_IDLE;
1748 
1749     mediametrics::LogItem(mMetricsId)
1750         .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1751         .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1752         .record();
1753     return ret;
1754 }
1755 
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames,audio_io_handle_t output) const1756 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1757         audio_io_handle_t output) const
1758 {
1759     Mutex::Autolock _l(mLock);
1760 
1761     PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1762     if (playbackThread != NULL) {
1763         return playbackThread->getRenderPosition(halFrames, dspFrames);
1764     }
1765 
1766     return BAD_VALUE;
1767 }
1768 
registerClient(const sp<IAudioFlingerClient> & client)1769 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1770 {
1771     Mutex::Autolock _l(mLock);
1772     if (client == 0) {
1773         return;
1774     }
1775     pid_t pid = IPCThreadState::self()->getCallingPid();
1776     const uid_t uid = IPCThreadState::self()->getCallingUid();
1777     {
1778         Mutex::Autolock _cl(mClientLock);
1779         if (mNotificationClients.indexOfKey(pid) < 0) {
1780             sp<NotificationClient> notificationClient = new NotificationClient(this,
1781                                                                                 client,
1782                                                                                 pid,
1783                                                                                 uid);
1784             ALOGV("registerClient() client %p, pid %d, uid %u",
1785                     notificationClient.get(), pid, uid);
1786 
1787             mNotificationClients.add(pid, notificationClient);
1788 
1789             sp<IBinder> binder = IInterface::asBinder(client);
1790             binder->linkToDeath(notificationClient);
1791         }
1792     }
1793 
1794     // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
1795     // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
1796     // the config change is always sent from playback or record threads to avoid deadlock
1797     // with AudioSystem::gLock
1798     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1799         mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
1800     }
1801 
1802     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1803         mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
1804     }
1805 }
1806 
removeNotificationClient(pid_t pid)1807 void AudioFlinger::removeNotificationClient(pid_t pid)
1808 {
1809     std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
1810     {
1811         Mutex::Autolock _l(mLock);
1812         {
1813             Mutex::Autolock _cl(mClientLock);
1814             mNotificationClients.removeItem(pid);
1815         }
1816 
1817         ALOGV("%d died, releasing its sessions", pid);
1818         size_t num = mAudioSessionRefs.size();
1819         bool removed = false;
1820         for (size_t i = 0; i < num; ) {
1821             AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1822             ALOGV(" pid %d @ %zu", ref->mPid, i);
1823             if (ref->mPid == pid) {
1824                 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1825                 mAudioSessionRefs.removeAt(i);
1826                 delete ref;
1827                 removed = true;
1828                 num--;
1829             } else {
1830                 i++;
1831             }
1832         }
1833         if (removed) {
1834             removedEffects = purgeStaleEffects_l();
1835         }
1836     }
1837     for (auto& effect : removedEffects) {
1838         effect->updatePolicyState();
1839     }
1840 }
1841 
ioConfigChanged(audio_io_config_event event,const sp<AudioIoDescriptor> & ioDesc,pid_t pid)1842 void AudioFlinger::ioConfigChanged(audio_io_config_event event,
1843                                    const sp<AudioIoDescriptor>& ioDesc,
1844                                    pid_t pid)
1845 {
1846     Mutex::Autolock _l(mClientLock);
1847     size_t size = mNotificationClients.size();
1848     for (size_t i = 0; i < size; i++) {
1849         if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1850             mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1851         }
1852     }
1853 }
1854 
1855 // removeClient_l() must be called with AudioFlinger::mClientLock held
removeClient_l(pid_t pid)1856 void AudioFlinger::removeClient_l(pid_t pid)
1857 {
1858     ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1859             IPCThreadState::self()->getCallingPid());
1860     mClients.removeItem(pid);
1861 }
1862 
1863 // getEffectThread_l() must be called with AudioFlinger::mLock held
getEffectThread_l(audio_session_t sessionId,int effectId)1864 sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1865         int effectId)
1866 {
1867     sp<ThreadBase> thread;
1868 
1869     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1870         if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1871             ALOG_ASSERT(thread == 0);
1872             thread = mPlaybackThreads.valueAt(i);
1873         }
1874     }
1875     if (thread != nullptr) {
1876         return thread;
1877     }
1878     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1879         if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1880             ALOG_ASSERT(thread == 0);
1881             thread = mRecordThreads.valueAt(i);
1882         }
1883     }
1884     if (thread != nullptr) {
1885         return thread;
1886     }
1887     for (size_t i = 0; i < mMmapThreads.size(); i++) {
1888         if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1889             ALOG_ASSERT(thread == 0);
1890             thread = mMmapThreads.valueAt(i);
1891         }
1892     }
1893     return thread;
1894 }
1895 
1896 
1897 
1898 // ----------------------------------------------------------------------------
1899 
Client(const sp<AudioFlinger> & audioFlinger,pid_t pid)1900 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1901     :   RefBase(),
1902         mAudioFlinger(audioFlinger),
1903         mPid(pid)
1904 {
1905     mMemoryDealer = new MemoryDealer(
1906             audioFlinger->getClientSharedHeapSize(),
1907             (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
1908 }
1909 
1910 // Client destructor must be called with AudioFlinger::mClientLock held
~Client()1911 AudioFlinger::Client::~Client()
1912 {
1913     mAudioFlinger->removeClient_l(mPid);
1914 }
1915 
heap() const1916 sp<MemoryDealer> AudioFlinger::Client::heap() const
1917 {
1918     return mMemoryDealer;
1919 }
1920 
1921 // ----------------------------------------------------------------------------
1922 
NotificationClient(const sp<AudioFlinger> & audioFlinger,const sp<IAudioFlingerClient> & client,pid_t pid,uid_t uid)1923 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1924                                                      const sp<IAudioFlingerClient>& client,
1925                                                      pid_t pid,
1926                                                      uid_t uid)
1927     : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
1928 {
1929 }
1930 
~NotificationClient()1931 AudioFlinger::NotificationClient::~NotificationClient()
1932 {
1933 }
1934 
binderDied(const wp<IBinder> & who __unused)1935 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
1936 {
1937     sp<NotificationClient> keep(this);
1938     mAudioFlinger->removeNotificationClient(mPid);
1939 }
1940 
1941 // ----------------------------------------------------------------------------
MediaLogNotifier()1942 AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1943     : mPendingRequests(false) {}
1944 
1945 
requestMerge()1946 void AudioFlinger::MediaLogNotifier::requestMerge() {
1947     AutoMutex _l(mMutex);
1948     mPendingRequests = true;
1949     mCond.signal();
1950 }
1951 
threadLoop()1952 bool AudioFlinger::MediaLogNotifier::threadLoop() {
1953     // Should already have been checked, but just in case
1954     if (sMediaLogService == 0) {
1955         return false;
1956     }
1957     // Wait until there are pending requests
1958     {
1959         AutoMutex _l(mMutex);
1960         mPendingRequests = false; // to ignore past requests
1961         while (!mPendingRequests) {
1962             mCond.wait(mMutex);
1963             // TODO may also need an exitPending check
1964         }
1965         mPendingRequests = false;
1966     }
1967     // Execute the actual MediaLogService binder call and ignore extra requests for a while
1968     sMediaLogService->requestMergeWakeup();
1969     usleep(kPostTriggerSleepPeriod);
1970     return true;
1971 }
1972 
requestLogMerge()1973 void AudioFlinger::requestLogMerge() {
1974     mMediaLogNotifier->requestMerge();
1975 }
1976 
1977 // ----------------------------------------------------------------------------
1978 
createRecord(const CreateRecordInput & input,CreateRecordOutput & output,status_t * status)1979 sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1980                                                    CreateRecordOutput& output,
1981                                                    status_t *status)
1982 {
1983     sp<RecordThread::RecordTrack> recordTrack;
1984     sp<RecordHandle> recordHandle;
1985     sp<Client> client;
1986     status_t lStatus;
1987     audio_session_t sessionId = input.sessionId;
1988     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1989 
1990     output.cblk.clear();
1991     output.buffers.clear();
1992     output.inputId = AUDIO_IO_HANDLE_NONE;
1993 
1994     bool updatePid = (input.clientInfo.clientPid == -1);
1995     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1996     uid_t clientUid = input.clientInfo.clientUid;
1997     if (!isAudioServerOrMediaServerUid(callingUid)) {
1998         ALOGW_IF(clientUid != callingUid,
1999                 "%s uid %d tried to pass itself off as %d",
2000                 __FUNCTION__, callingUid, clientUid);
2001         clientUid = callingUid;
2002         updatePid = true;
2003     }
2004     pid_t clientPid = input.clientInfo.clientPid;
2005     const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2006     if (updatePid) {
2007         ALOGW_IF(clientPid != -1 && clientPid != callingPid,
2008                  "%s uid %d pid %d tried to pass itself off as pid %d",
2009                  __func__, callingUid, callingPid, clientPid);
2010         clientPid = callingPid;
2011     }
2012 
2013     // we don't yet support anything other than linear PCM
2014     if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2015         ALOGE("createRecord() invalid format %#x", input.config.format);
2016         lStatus = BAD_VALUE;
2017         goto Exit;
2018     }
2019 
2020     // further channel mask checks are performed by createRecordTrack_l()
2021     if (!audio_is_input_channel(input.config.channel_mask)) {
2022         ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
2023         lStatus = BAD_VALUE;
2024         goto Exit;
2025     }
2026 
2027     if (sessionId == AUDIO_SESSION_ALLOCATE) {
2028         sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2029     } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2030         lStatus = BAD_VALUE;
2031         goto Exit;
2032     }
2033 
2034     output.sessionId = sessionId;
2035     output.selectedDeviceId = input.selectedDeviceId;
2036     output.flags = input.flags;
2037 
2038     client = registerPid(clientPid);
2039 
2040     // Not a conventional loop, but a retry loop for at most two iterations total.
2041     // Try first maybe with FAST flag then try again without FAST flag if that fails.
2042     // Exits loop via break on no error of got exit on error
2043     // The sp<> references will be dropped when re-entering scope.
2044     // The lack of indentation is deliberate, to reduce code churn and ease merges.
2045     for (;;) {
2046     // release previously opened input if retrying.
2047     if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2048         recordTrack.clear();
2049         AudioSystem::releaseInput(portId);
2050         output.inputId = AUDIO_IO_HANDLE_NONE;
2051         output.selectedDeviceId = input.selectedDeviceId;
2052         portId = AUDIO_PORT_HANDLE_NONE;
2053     }
2054     lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
2055                                       input.riid,
2056                                       sessionId,
2057                                     // FIXME compare to AudioTrack
2058                                       clientPid,
2059                                       clientUid,
2060                                       input.opPackageName,
2061                                       &input.config,
2062                                       output.flags, &output.selectedDeviceId, &portId);
2063     if (lStatus != NO_ERROR) {
2064         ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2065         goto Exit;
2066     }
2067 
2068     {
2069         Mutex::Autolock _l(mLock);
2070         RecordThread *thread = checkRecordThread_l(output.inputId);
2071         if (thread == NULL) {
2072             ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2073             lStatus = FAILED_TRANSACTION;
2074             goto Exit;
2075         }
2076 
2077         ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
2078 
2079         output.sampleRate = input.config.sample_rate;
2080         output.frameCount = input.frameCount;
2081         output.notificationFrameCount = input.notificationFrameCount;
2082 
2083         recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
2084                                                   input.config.format, input.config.channel_mask,
2085                                                   &output.frameCount, sessionId,
2086                                                   &output.notificationFrameCount,
2087                                                   callingPid, clientUid, &output.flags,
2088                                                   input.clientInfo.clientTid,
2089                                                   &lStatus, portId,
2090                                                   input.opPackageName);
2091         LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
2092 
2093         // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2094         // audio policy manager without FAST constraint
2095         if (lStatus == BAD_TYPE) {
2096             continue;
2097         }
2098 
2099         if (lStatus != NO_ERROR) {
2100             goto Exit;
2101         }
2102 
2103         // Check if one effect chain was awaiting for an AudioRecord to be created on this
2104         // session and move it to this thread.
2105         sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2106         if (chain != 0) {
2107             Mutex::Autolock _l(thread->mLock);
2108             thread->addEffectChain_l(chain);
2109         }
2110         break;
2111     }
2112     // End of retry loop.
2113     // The lack of indentation is deliberate, to reduce code churn and ease merges.
2114     }
2115 
2116     output.cblk = recordTrack->getCblk();
2117     output.buffers = recordTrack->getBuffers();
2118     output.portId = portId;
2119 
2120     // return handle to client
2121     recordHandle = new RecordHandle(recordTrack);
2122 
2123 Exit:
2124     if (lStatus != NO_ERROR) {
2125         // remove local strong reference to Client before deleting the RecordTrack so that the
2126         // Client destructor is called by the TrackBase destructor with mClientLock held
2127         // Don't hold mClientLock when releasing the reference on the track as the
2128         // destructor will acquire it.
2129         {
2130             Mutex::Autolock _cl(mClientLock);
2131             client.clear();
2132         }
2133         recordTrack.clear();
2134         if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2135             AudioSystem::releaseInput(portId);
2136         }
2137     }
2138 
2139     *status = lStatus;
2140     return recordHandle;
2141 }
2142 
2143 
2144 
2145 // ----------------------------------------------------------------------------
2146 
loadHwModule(const char * name)2147 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2148 {
2149     if (name == NULL) {
2150         return AUDIO_MODULE_HANDLE_NONE;
2151     }
2152     if (!settingsAllowed()) {
2153         return AUDIO_MODULE_HANDLE_NONE;
2154     }
2155     Mutex::Autolock _l(mLock);
2156     AutoMutex lock(mHardwareLock);
2157     return loadHwModule_l(name);
2158 }
2159 
2160 // loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
loadHwModule_l(const char * name)2161 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2162 {
2163     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2164         if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2165             ALOGW("loadHwModule() module %s already loaded", name);
2166             return mAudioHwDevs.keyAt(i);
2167         }
2168     }
2169 
2170     sp<DeviceHalInterface> dev;
2171 
2172     int rc = mDevicesFactoryHal->openDevice(name, &dev);
2173     if (rc) {
2174         ALOGE("loadHwModule() error %d loading module %s", rc, name);
2175         return AUDIO_MODULE_HANDLE_NONE;
2176     }
2177 
2178     mHardwareStatus = AUDIO_HW_INIT;
2179     rc = dev->initCheck();
2180     mHardwareStatus = AUDIO_HW_IDLE;
2181     if (rc) {
2182         ALOGE("loadHwModule() init check error %d for module %s", rc, name);
2183         return AUDIO_MODULE_HANDLE_NONE;
2184     }
2185 
2186     // Check and cache this HAL's level of support for master mute and master
2187     // volume.  If this is the first HAL opened, and it supports the get
2188     // methods, use the initial values provided by the HAL as the current
2189     // master mute and volume settings.
2190 
2191     AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2192     if (0 == mAudioHwDevs.size()) {
2193         mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2194         float mv;
2195         if (OK == dev->getMasterVolume(&mv)) {
2196             mMasterVolume = mv;
2197         }
2198 
2199         mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2200         bool mm;
2201         if (OK == dev->getMasterMute(&mm)) {
2202             mMasterMute = mm;
2203         }
2204     }
2205 
2206     mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2207     if (OK == dev->setMasterVolume(mMasterVolume)) {
2208         flags = static_cast<AudioHwDevice::Flags>(flags |
2209                 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2210     }
2211 
2212     mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2213     if (OK == dev->setMasterMute(mMasterMute)) {
2214         flags = static_cast<AudioHwDevice::Flags>(flags |
2215                 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2216     }
2217 
2218     mHardwareStatus = AUDIO_HW_IDLE;
2219 
2220     if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
2221         // An MSD module is inserted before hardware modules in order to mix encoded streams.
2222         flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2223     }
2224 
2225     audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
2226     AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2227     if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2228         mPrimaryHardwareDev = audioDevice;
2229         mHardwareStatus = AUDIO_HW_SET_MODE;
2230         mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2231         mHardwareStatus = AUDIO_HW_IDLE;
2232     }
2233 
2234     mAudioHwDevs.add(handle, audioDevice);
2235 
2236     ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
2237 
2238     return handle;
2239 
2240 }
2241 
2242 // ----------------------------------------------------------------------------
2243 
getPrimaryOutputSamplingRate()2244 uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
2245 {
2246     Mutex::Autolock _l(mLock);
2247     PlaybackThread *thread = fastPlaybackThread_l();
2248     return thread != NULL ? thread->sampleRate() : 0;
2249 }
2250 
getPrimaryOutputFrameCount()2251 size_t AudioFlinger::getPrimaryOutputFrameCount()
2252 {
2253     Mutex::Autolock _l(mLock);
2254     PlaybackThread *thread = fastPlaybackThread_l();
2255     return thread != NULL ? thread->frameCountHAL() : 0;
2256 }
2257 
2258 // ----------------------------------------------------------------------------
2259 
setLowRamDevice(bool isLowRamDevice,int64_t totalMemory)2260 status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
2261 {
2262     uid_t uid = IPCThreadState::self()->getCallingUid();
2263     if (!isAudioServerOrSystemServerUid(uid)) {
2264         return PERMISSION_DENIED;
2265     }
2266     Mutex::Autolock _l(mLock);
2267     if (mIsDeviceTypeKnown) {
2268         return INVALID_OPERATION;
2269     }
2270     mIsLowRamDevice = isLowRamDevice;
2271     mTotalMemory = totalMemory;
2272     // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2273     // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2274     // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2275     // though actual setting is determined through device configuration.
2276     constexpr int64_t GB = 1024 * 1024 * 1024;
2277     mClientSharedHeapSize =
2278             isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2279                     : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2280                     : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2281                     : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2282                     : 32 * kMinimumClientSharedHeapSizeBytes;
2283     mIsDeviceTypeKnown = true;
2284 
2285     // TODO: Cache the client shared heap size in a persistent property.
2286     // It's possible that a native process or Java service or app accesses audioserver
2287     // after it is registered by system server, but before AudioService updates
2288     // the memory info.  This would occur immediately after boot or an audioserver
2289     // crash and restore. Before update from AudioService, the client would get the
2290     // minimum heap size.
2291 
2292     ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2293             (isLowRamDevice ? "true" : "false"),
2294             (long long)mTotalMemory,
2295             mClientSharedHeapSize.load());
2296     return NO_ERROR;
2297 }
2298 
getClientSharedHeapSize() const2299 size_t AudioFlinger::getClientSharedHeapSize() const
2300 {
2301     size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2302     if (heapSizeInBytes != 0) { // read-only property overrides all.
2303         return heapSizeInBytes;
2304     }
2305     return mClientSharedHeapSize;
2306 }
2307 
setAudioPortConfig(const struct audio_port_config * config)2308 status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2309 {
2310     ALOGV(__func__);
2311 
2312     audio_module_handle_t module;
2313     if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2314         module = config->ext.device.hw_module;
2315     } else {
2316         module = config->ext.mix.hw_module;
2317     }
2318 
2319     Mutex::Autolock _l(mLock);
2320     AutoMutex lock(mHardwareLock);
2321     ssize_t index = mAudioHwDevs.indexOfKey(module);
2322     if (index < 0) {
2323         ALOGW("%s() bad hw module %d", __func__, module);
2324         return BAD_VALUE;
2325     }
2326 
2327     AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2328     return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2329 }
2330 
getAudioHwSyncForSession(audio_session_t sessionId)2331 audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2332 {
2333     Mutex::Autolock _l(mLock);
2334 
2335     ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2336     if (index >= 0) {
2337         ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2338               mHwAvSyncIds.valueAt(index), sessionId);
2339         return mHwAvSyncIds.valueAt(index);
2340     }
2341 
2342     sp<DeviceHalInterface> dev;
2343     {
2344         AutoMutex lock(mHardwareLock);
2345         if (mPrimaryHardwareDev == nullptr) {
2346             return AUDIO_HW_SYNC_INVALID;
2347         }
2348         dev = mPrimaryHardwareDev->hwDevice();
2349     }
2350     if (dev == nullptr) {
2351         return AUDIO_HW_SYNC_INVALID;
2352     }
2353     String8 reply;
2354     AudioParameter param;
2355     if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
2356         param = AudioParameter(reply);
2357     }
2358 
2359     int value;
2360     if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
2361         ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2362         return AUDIO_HW_SYNC_INVALID;
2363     }
2364 
2365     // allow only one session for a given HW A/V sync ID.
2366     for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2367         if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2368             ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2369                   value, mHwAvSyncIds.keyAt(i));
2370             mHwAvSyncIds.removeItemsAt(i);
2371             break;
2372         }
2373     }
2374 
2375     mHwAvSyncIds.add(sessionId, value);
2376 
2377     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2378         sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2379         uint32_t sessions = thread->hasAudioSession(sessionId);
2380         if (sessions & ThreadBase::TRACK_SESSION) {
2381             AudioParameter param = AudioParameter();
2382             param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
2383             String8 keyValuePairs = param.toString();
2384             thread->setParameters(keyValuePairs);
2385             forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2386                     [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
2387             break;
2388         }
2389     }
2390 
2391     ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2392     return (audio_hw_sync_t)value;
2393 }
2394 
systemReady()2395 status_t AudioFlinger::systemReady()
2396 {
2397     Mutex::Autolock _l(mLock);
2398     ALOGI("%s", __FUNCTION__);
2399     if (mSystemReady) {
2400         ALOGW("%s called twice", __FUNCTION__);
2401         return NO_ERROR;
2402     }
2403     mSystemReady = true;
2404     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2405         ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2406         thread->systemReady();
2407     }
2408     for (size_t i = 0; i < mRecordThreads.size(); i++) {
2409         ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2410         thread->systemReady();
2411     }
2412     return NO_ERROR;
2413 }
2414 
getMicrophones(std::vector<media::MicrophoneInfo> * microphones)2415 status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2416 {
2417     AutoMutex lock(mHardwareLock);
2418     status_t status = INVALID_OPERATION;
2419 
2420     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2421         std::vector<media::MicrophoneInfo> mics;
2422         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2423         mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2424         status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2425         mHardwareStatus = AUDIO_HW_IDLE;
2426         if (devStatus == NO_ERROR) {
2427             microphones->insert(microphones->begin(), mics.begin(), mics.end());
2428             // report success if at least one HW module supports the function.
2429             status = NO_ERROR;
2430         }
2431     }
2432 
2433     return status;
2434 }
2435 
2436 // setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
setAudioHwSyncForSession_l(PlaybackThread * thread,audio_session_t sessionId)2437 void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2438 {
2439     ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2440     if (index >= 0) {
2441         audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2442         ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2443         AudioParameter param = AudioParameter();
2444         param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
2445         String8 keyValuePairs = param.toString();
2446         thread->setParameters(keyValuePairs);
2447         forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2448                 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
2449     }
2450 }
2451 
2452 
2453 // ----------------------------------------------------------------------------
2454 
2455 
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)2456 sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
2457                                                         audio_io_handle_t *output,
2458                                                         audio_config_t *config,
2459                                                         audio_devices_t deviceType,
2460                                                         const String8& address,
2461                                                         audio_output_flags_t flags)
2462 {
2463     AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
2464     if (outHwDev == NULL) {
2465         return 0;
2466     }
2467 
2468     if (*output == AUDIO_IO_HANDLE_NONE) {
2469         *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2470     } else {
2471         // Audio Policy does not currently request a specific output handle.
2472         // If this is ever needed, see openInput_l() for example code.
2473         ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2474         return 0;
2475     }
2476 
2477     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2478 
2479     // FOR TESTING ONLY:
2480     // This if statement allows overriding the audio policy settings
2481     // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2482     if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2483         // Check only for Normal Mixing mode
2484         if (kEnableExtendedPrecision) {
2485             // Specify format (uncomment one below to choose)
2486             //config->format = AUDIO_FORMAT_PCM_FLOAT;
2487             //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2488             //config->format = AUDIO_FORMAT_PCM_32_BIT;
2489             //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
2490             // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
2491         }
2492         if (kEnableExtendedChannels) {
2493             // Specify channel mask (uncomment one below to choose)
2494             //config->channel_mask = audio_channel_out_mask_from_count(4);  // for USB 4ch
2495             //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2496             //        AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1);  // another 4ch example
2497         }
2498     }
2499 
2500     AudioStreamOut *outputStream = NULL;
2501     status_t status = outHwDev->openOutputStream(
2502             &outputStream,
2503             *output,
2504             deviceType,
2505             flags,
2506             config,
2507             address.string());
2508 
2509     mHardwareStatus = AUDIO_HW_IDLE;
2510 
2511     if (status == NO_ERROR) {
2512         if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2513             sp<MmapPlaybackThread> thread =
2514                     new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
2515             mMmapThreads.add(*output, thread);
2516             ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2517                   *output, thread.get());
2518             return thread;
2519         } else {
2520             sp<PlaybackThread> thread;
2521             if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2522                 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
2523                 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2524                       *output, thread.get());
2525             } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2526                     || !isValidPcmSinkFormat(config->format)
2527                     || !isValidPcmSinkChannelMask(config->channel_mask)) {
2528                 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
2529                 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2530                       *output, thread.get());
2531             } else {
2532                 thread = new MixerThread(this, outputStream, *output, mSystemReady);
2533                 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2534                       *output, thread.get());
2535             }
2536             mPlaybackThreads.add(*output, thread);
2537             mPatchPanel.notifyStreamOpened(outHwDev, *output);
2538             return thread;
2539         }
2540     }
2541 
2542     return 0;
2543 }
2544 
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)2545 status_t AudioFlinger::openOutput(audio_module_handle_t module,
2546                                   audio_io_handle_t *output,
2547                                   audio_config_t *config,
2548                                   const sp<DeviceDescriptorBase>& device,
2549                                   uint32_t *latencyMs,
2550                                   audio_output_flags_t flags)
2551 {
2552     ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
2553               "Channels %#x, flags %#x",
2554               this, module,
2555               device->toString().c_str(),
2556               config->sample_rate,
2557               config->format,
2558               config->channel_mask,
2559               flags);
2560 
2561     audio_devices_t deviceType = device->type();
2562     const String8 address = String8(device->address().c_str());
2563 
2564     if (deviceType == AUDIO_DEVICE_NONE) {
2565         return BAD_VALUE;
2566     }
2567 
2568     Mutex::Autolock _l(mLock);
2569 
2570     sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
2571     if (thread != 0) {
2572         if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2573             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2574             *latencyMs = playbackThread->latency();
2575 
2576             // notify client processes of the new output creation
2577             playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
2578 
2579             // the first primary output opened designates the primary hw device if no HW module
2580             // named "primary" was already loaded.
2581             AutoMutex lock(mHardwareLock);
2582             if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
2583                 ALOGI("Using module %d as the primary audio interface", module);
2584                 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
2585 
2586                 mHardwareStatus = AUDIO_HW_SET_MODE;
2587                 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2588                 mHardwareStatus = AUDIO_HW_IDLE;
2589             }
2590         } else {
2591             MmapThread *mmapThread = (MmapThread *)thread.get();
2592             mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
2593         }
2594         return NO_ERROR;
2595     }
2596 
2597     return NO_INIT;
2598 }
2599 
openDuplicateOutput(audio_io_handle_t output1,audio_io_handle_t output2)2600 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2601         audio_io_handle_t output2)
2602 {
2603     Mutex::Autolock _l(mLock);
2604     MixerThread *thread1 = checkMixerThread_l(output1);
2605     MixerThread *thread2 = checkMixerThread_l(output2);
2606 
2607     if (thread1 == NULL || thread2 == NULL) {
2608         ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2609                 output2);
2610         return AUDIO_IO_HANDLE_NONE;
2611     }
2612 
2613     audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2614     DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
2615     thread->addOutputTrack(thread2);
2616     mPlaybackThreads.add(id, thread);
2617     // notify client processes of the new output creation
2618     thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
2619     return id;
2620 }
2621 
closeOutput(audio_io_handle_t output)2622 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
2623 {
2624     return closeOutput_nonvirtual(output);
2625 }
2626 
closeOutput_nonvirtual(audio_io_handle_t output)2627 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2628 {
2629     // keep strong reference on the playback thread so that
2630     // it is not destroyed while exit() is executed
2631     sp<PlaybackThread> playbackThread;
2632     sp<MmapPlaybackThread> mmapThread;
2633     {
2634         Mutex::Autolock _l(mLock);
2635         playbackThread = checkPlaybackThread_l(output);
2636         if (playbackThread != NULL) {
2637             ALOGV("closeOutput() %d", output);
2638 
2639             dumpToThreadLog_l(playbackThread);
2640 
2641             if (playbackThread->type() == ThreadBase::MIXER) {
2642                 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2643                     if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2644                         DuplicatingThread *dupThread =
2645                                 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2646                         dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2647                     }
2648                 }
2649             }
2650 
2651 
2652             mPlaybackThreads.removeItem(output);
2653             // save all effects to the default thread
2654             if (mPlaybackThreads.size()) {
2655                 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2656                 if (dstThread != NULL) {
2657                     // audioflinger lock is held so order of thread lock acquisition doesn't matter
2658                     Mutex::Autolock _dl(dstThread->mLock);
2659                     Mutex::Autolock _sl(playbackThread->mLock);
2660                     Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2661                     for (size_t i = 0; i < effectChains.size(); i ++) {
2662                         moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2663                                 dstThread);
2664                     }
2665                 }
2666             }
2667         } else {
2668             mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2669             if (mmapThread == 0) {
2670                 return BAD_VALUE;
2671             }
2672             dumpToThreadLog_l(mmapThread);
2673             mMmapThreads.removeItem(output);
2674             ALOGD("closing mmapThread %p", mmapThread.get());
2675         }
2676         const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2677         ioDesc->mIoHandle = output;
2678         ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
2679         mPatchPanel.notifyStreamClosed(output);
2680     }
2681     // The thread entity (active unit of execution) is no longer running here,
2682     // but the ThreadBase container still exists.
2683 
2684     if (playbackThread != 0) {
2685         playbackThread->exit();
2686         if (!playbackThread->isDuplicating()) {
2687             closeOutputFinish(playbackThread);
2688         }
2689     } else if (mmapThread != 0) {
2690         ALOGD("mmapThread exit()");
2691         mmapThread->exit();
2692         AudioStreamOut *out = mmapThread->clearOutput();
2693         ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2694         // from now on thread->mOutput is NULL
2695         delete out;
2696     }
2697     return NO_ERROR;
2698 }
2699 
closeOutputFinish(const sp<PlaybackThread> & thread)2700 void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
2701 {
2702     AudioStreamOut *out = thread->clearOutput();
2703     ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2704     // from now on thread->mOutput is NULL
2705     delete out;
2706 }
2707 
closeThreadInternal_l(const sp<PlaybackThread> & thread)2708 void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
2709 {
2710     mPlaybackThreads.removeItem(thread->mId);
2711     thread->exit();
2712     closeOutputFinish(thread);
2713 }
2714 
suspendOutput(audio_io_handle_t output)2715 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
2716 {
2717     Mutex::Autolock _l(mLock);
2718     PlaybackThread *thread = checkPlaybackThread_l(output);
2719 
2720     if (thread == NULL) {
2721         return BAD_VALUE;
2722     }
2723 
2724     ALOGV("suspendOutput() %d", output);
2725     thread->suspend();
2726 
2727     return NO_ERROR;
2728 }
2729 
restoreOutput(audio_io_handle_t output)2730 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
2731 {
2732     Mutex::Autolock _l(mLock);
2733     PlaybackThread *thread = checkPlaybackThread_l(output);
2734 
2735     if (thread == NULL) {
2736         return BAD_VALUE;
2737     }
2738 
2739     ALOGV("restoreOutput() %d", output);
2740 
2741     thread->restore();
2742 
2743     return NO_ERROR;
2744 }
2745 
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)2746 status_t AudioFlinger::openInput(audio_module_handle_t module,
2747                                           audio_io_handle_t *input,
2748                                           audio_config_t *config,
2749                                           audio_devices_t *devices,
2750                                           const String8& address,
2751                                           audio_source_t source,
2752                                           audio_input_flags_t flags)
2753 {
2754     Mutex::Autolock _l(mLock);
2755 
2756     if (*devices == AUDIO_DEVICE_NONE) {
2757         return BAD_VALUE;
2758     }
2759 
2760     sp<ThreadBase> thread = openInput_l(
2761             module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
2762 
2763     if (thread != 0) {
2764         // notify client processes of the new input creation
2765         thread->ioConfigChanged(AUDIO_INPUT_OPENED);
2766         return NO_ERROR;
2767     }
2768     return NO_INIT;
2769 }
2770 
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)2771 sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
2772                                                          audio_io_handle_t *input,
2773                                                          audio_config_t *config,
2774                                                          audio_devices_t devices,
2775                                                          const String8& address,
2776                                                          audio_source_t source,
2777                                                          audio_input_flags_t flags,
2778                                                          audio_devices_t outputDevice,
2779                                                          const String8& outputDeviceAddress)
2780 {
2781     AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
2782     if (inHwDev == NULL) {
2783         *input = AUDIO_IO_HANDLE_NONE;
2784         return 0;
2785     }
2786 
2787     // Audio Policy can request a specific handle for hardware hotword.
2788     // The goal here is not to re-open an already opened input.
2789     // It is to use a pre-assigned I/O handle.
2790     if (*input == AUDIO_IO_HANDLE_NONE) {
2791         *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2792     } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2793         ALOGE("openInput_l() requested input handle %d is invalid", *input);
2794         return 0;
2795     } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2796         // This should not happen in a transient state with current design.
2797         ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2798         return 0;
2799     }
2800 
2801     audio_config_t halconfig = *config;
2802     sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
2803     sp<StreamInHalInterface> inStream;
2804     status_t status = inHwHal->openInputStream(
2805             *input, devices, &halconfig, flags, address.string(), source,
2806             outputDevice, outputDeviceAddress, &inStream);
2807     ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2808            ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
2809             inStream.get(),
2810             devices,
2811             halconfig.sample_rate,
2812             halconfig.format,
2813             halconfig.channel_mask,
2814             flags,
2815             status, address.string());
2816 
2817     // If the input could not be opened with the requested parameters and we can handle the
2818     // conversion internally, try to open again with the proposed parameters.
2819     if (status == BAD_VALUE &&
2820         audio_is_linear_pcm(config->format) &&
2821         audio_is_linear_pcm(halconfig.format) &&
2822         (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
2823         (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2824         (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
2825         // FIXME describe the change proposed by HAL (save old values so we can log them here)
2826         ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
2827         inStream.clear();
2828         status = inHwHal->openInputStream(
2829                 *input, devices, &halconfig, flags, address.string(), source,
2830                 outputDevice, outputDeviceAddress, &inStream);
2831         // FIXME log this new status; HAL should not propose any further changes
2832     }
2833 
2834     if (status == NO_ERROR && inStream != 0) {
2835         AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
2836         if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2837             sp<MmapCaptureThread> thread =
2838                     new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
2839             mMmapThreads.add(*input, thread);
2840             ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2841                     thread.get());
2842             return thread;
2843         } else {
2844             // Start record thread
2845             // RecordThread requires both input and output device indication to forward to audio
2846             // pre processing modules
2847             sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
2848             mRecordThreads.add(*input, thread);
2849             ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2850             return thread;
2851         }
2852     }
2853 
2854     *input = AUDIO_IO_HANDLE_NONE;
2855     return 0;
2856 }
2857 
closeInput(audio_io_handle_t input)2858 status_t AudioFlinger::closeInput(audio_io_handle_t input)
2859 {
2860     return closeInput_nonvirtual(input);
2861 }
2862 
closeInput_nonvirtual(audio_io_handle_t input)2863 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2864 {
2865     // keep strong reference on the record thread so that
2866     // it is not destroyed while exit() is executed
2867     sp<RecordThread> recordThread;
2868     sp<MmapCaptureThread> mmapThread;
2869     {
2870         Mutex::Autolock _l(mLock);
2871         recordThread = checkRecordThread_l(input);
2872         if (recordThread != 0) {
2873             ALOGV("closeInput() %d", input);
2874 
2875             dumpToThreadLog_l(recordThread);
2876 
2877             // If we still have effect chains, it means that a client still holds a handle
2878             // on at least one effect. We must either move the chain to an existing thread with the
2879             // same session ID or put it aside in case a new record thread is opened for a
2880             // new capture on the same session
2881             sp<EffectChain> chain;
2882             {
2883                 Mutex::Autolock _sl(recordThread->mLock);
2884                 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2885                 // Note: maximum one chain per record thread
2886                 if (effectChains.size() != 0) {
2887                     chain = effectChains[0];
2888                 }
2889             }
2890             if (chain != 0) {
2891                 // first check if a record thread is already opened with a client on same session.
2892                 // This should only happen in case of overlap between one thread tear down and the
2893                 // creation of its replacement
2894                 size_t i;
2895                 for (i = 0; i < mRecordThreads.size(); i++) {
2896                     sp<RecordThread> t = mRecordThreads.valueAt(i);
2897                     if (t == recordThread) {
2898                         continue;
2899                     }
2900                     if (t->hasAudioSession(chain->sessionId()) != 0) {
2901                         Mutex::Autolock _l(t->mLock);
2902                         ALOGV("closeInput() found thread %d for effect session %d",
2903                               t->id(), chain->sessionId());
2904                         t->addEffectChain_l(chain);
2905                         break;
2906                     }
2907                 }
2908                 // put the chain aside if we could not find a record thread with the same session id
2909                 if (i == mRecordThreads.size()) {
2910                     putOrphanEffectChain_l(chain);
2911                 }
2912             }
2913             mRecordThreads.removeItem(input);
2914         } else {
2915             mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2916             if (mmapThread == 0) {
2917                 return BAD_VALUE;
2918             }
2919             dumpToThreadLog_l(mmapThread);
2920             mMmapThreads.removeItem(input);
2921         }
2922         const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2923         ioDesc->mIoHandle = input;
2924         ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
2925     }
2926     // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2927     // we have a different lock for notification client
2928     if (recordThread != 0) {
2929         closeInputFinish(recordThread);
2930     } else if (mmapThread != 0) {
2931         mmapThread->exit();
2932         AudioStreamIn *in = mmapThread->clearInput();
2933         ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2934         // from now on thread->mInput is NULL
2935         delete in;
2936     }
2937     return NO_ERROR;
2938 }
2939 
closeInputFinish(const sp<RecordThread> & thread)2940 void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
2941 {
2942     thread->exit();
2943     AudioStreamIn *in = thread->clearInput();
2944     ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2945     // from now on thread->mInput is NULL
2946     delete in;
2947 }
2948 
closeThreadInternal_l(const sp<RecordThread> & thread)2949 void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
2950 {
2951     mRecordThreads.removeItem(thread->mId);
2952     closeInputFinish(thread);
2953 }
2954 
invalidateStream(audio_stream_type_t stream)2955 status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
2956 {
2957     Mutex::Autolock _l(mLock);
2958     ALOGV("invalidateStream() stream %d", stream);
2959 
2960     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2961         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2962         thread->invalidateTracks(stream);
2963     }
2964     for (size_t i = 0; i < mMmapThreads.size(); i++) {
2965         mMmapThreads[i]->invalidateTracks(stream);
2966     }
2967     return NO_ERROR;
2968 }
2969 
2970 
newAudioUniqueId(audio_unique_id_use_t use)2971 audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
2972 {
2973     // This is a binder API, so a malicious client could pass in a bad parameter.
2974     // Check for that before calling the internal API nextUniqueId().
2975     if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2976         ALOGE("newAudioUniqueId invalid use %d", use);
2977         return AUDIO_UNIQUE_ID_ALLOCATE;
2978     }
2979     return nextUniqueId(use);
2980 }
2981 
acquireAudioSessionId(audio_session_t audioSession,pid_t pid,uid_t uid)2982 void AudioFlinger::acquireAudioSessionId(
2983         audio_session_t audioSession, pid_t pid, uid_t uid)
2984 {
2985     Mutex::Autolock _l(mLock);
2986     pid_t caller = IPCThreadState::self()->getCallingPid();
2987     ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2988     const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2989     if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
2990         caller = pid;  // check must match releaseAudioSessionId()
2991     }
2992     if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
2993         uid = callerUid;
2994     }
2995 
2996     {
2997         Mutex::Autolock _cl(mClientLock);
2998         // Ignore requests received from processes not known as notification client. The request
2999         // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3000         // called from a different pid leaving a stale session reference.  Also we don't know how
3001         // to clear this reference if the client process dies.
3002         if (mNotificationClients.indexOfKey(caller) < 0) {
3003             ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3004             return;
3005         }
3006     }
3007 
3008     size_t num = mAudioSessionRefs.size();
3009     for (size_t i = 0; i < num; i++) {
3010         AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
3011         if (ref->mSessionid == audioSession && ref->mPid == caller) {
3012             ref->mCnt++;
3013             ALOGV(" incremented refcount to %d", ref->mCnt);
3014             return;
3015         }
3016     }
3017     mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
3018     ALOGV(" added new entry for %d", audioSession);
3019 }
3020 
releaseAudioSessionId(audio_session_t audioSession,pid_t pid)3021 void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
3022 {
3023     std::vector< sp<EffectModule> > removedEffects;
3024     {
3025         Mutex::Autolock _l(mLock);
3026         pid_t caller = IPCThreadState::self()->getCallingPid();
3027         ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3028         const uid_t callerUid = IPCThreadState::self()->getCallingUid();
3029         if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3030             caller = pid;  // check must match acquireAudioSessionId()
3031         }
3032         size_t num = mAudioSessionRefs.size();
3033         for (size_t i = 0; i < num; i++) {
3034             AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3035             if (ref->mSessionid == audioSession && ref->mPid == caller) {
3036                 ref->mCnt--;
3037                 ALOGV(" decremented refcount to %d", ref->mCnt);
3038                 if (ref->mCnt == 0) {
3039                     mAudioSessionRefs.removeAt(i);
3040                     delete ref;
3041                     std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3042                     removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3043                 }
3044                 goto Exit;
3045             }
3046         }
3047         // If the caller is audioserver it is likely that the session being released was acquired
3048         // on behalf of a process not in notification clients and we ignore the warning.
3049         ALOGW_IF(!isAudioServerUid(callerUid),
3050                  "session id %d not found for pid %d", audioSession, caller);
3051     }
3052 
3053 Exit:
3054     for (auto& effect : removedEffects) {
3055         effect->updatePolicyState();
3056     }
3057 }
3058 
isSessionAcquired_l(audio_session_t audioSession)3059 bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3060 {
3061     size_t num = mAudioSessionRefs.size();
3062     for (size_t i = 0; i < num; i++) {
3063         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3064         if (ref->mSessionid == audioSession) {
3065             return true;
3066         }
3067     }
3068     return false;
3069 }
3070 
purgeStaleEffects_l()3071 std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
3072 
3073     ALOGV("purging stale effects");
3074 
3075     Vector< sp<EffectChain> > chains;
3076     std::vector< sp<EffectModule> > removedEffects;
3077 
3078     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3079         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3080         Mutex::Autolock _l(t->mLock);
3081         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3082             sp<EffectChain> ec = t->mEffectChains[j];
3083             if (!audio_is_global_session(ec->sessionId())) {
3084                 chains.push(ec);
3085             }
3086         }
3087     }
3088 
3089     for (size_t i = 0; i < mRecordThreads.size(); i++) {
3090         sp<RecordThread> t = mRecordThreads.valueAt(i);
3091         Mutex::Autolock _l(t->mLock);
3092         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3093             sp<EffectChain> ec = t->mEffectChains[j];
3094             chains.push(ec);
3095         }
3096     }
3097 
3098     for (size_t i = 0; i < mMmapThreads.size(); i++) {
3099         sp<MmapThread> t = mMmapThreads.valueAt(i);
3100         Mutex::Autolock _l(t->mLock);
3101         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3102             sp<EffectChain> ec = t->mEffectChains[j];
3103             chains.push(ec);
3104         }
3105     }
3106 
3107     for (size_t i = 0; i < chains.size(); i++) {
3108         sp<EffectChain> ec = chains[i];
3109         int sessionid = ec->sessionId();
3110         sp<ThreadBase> t = ec->thread().promote();
3111         if (t == 0) {
3112             continue;
3113         }
3114         size_t numsessionrefs = mAudioSessionRefs.size();
3115         bool found = false;
3116         for (size_t k = 0; k < numsessionrefs; k++) {
3117             AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
3118             if (ref->mSessionid == sessionid) {
3119                 ALOGV(" session %d still exists for %d with %d refs",
3120                     sessionid, ref->mPid, ref->mCnt);
3121                 found = true;
3122                 break;
3123             }
3124         }
3125         if (!found) {
3126             Mutex::Autolock _l(t->mLock);
3127             // remove all effects from the chain
3128             while (ec->mEffects.size()) {
3129                 sp<EffectModule> effect = ec->mEffects[0];
3130                 effect->unPin();
3131                 t->removeEffect_l(effect, /*release*/ true);
3132                 if (effect->purgeHandles()) {
3133                     effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
3134                 }
3135                 removedEffects.push_back(effect);
3136             }
3137         }
3138     }
3139     return removedEffects;
3140 }
3141 
3142 // dumpToThreadLog_l() must be called with AudioFlinger::mLock held
dumpToThreadLog_l(const sp<ThreadBase> & thread)3143 void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3144 {
3145     audio_utils::FdToString fdToString;
3146     const int fd = fdToString.fd();
3147     if (fd >= 0) {
3148         thread->dump(fd, {} /* args */);
3149         mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3150     }
3151 }
3152 
3153 // checkThread_l() must be called with AudioFlinger::mLock held
checkThread_l(audio_io_handle_t ioHandle) const3154 AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3155 {
3156     ThreadBase *thread = checkMmapThread_l(ioHandle);
3157     if (thread == 0) {
3158         switch (audio_unique_id_get_use(ioHandle)) {
3159         case AUDIO_UNIQUE_ID_USE_OUTPUT:
3160             thread = checkPlaybackThread_l(ioHandle);
3161             break;
3162         case AUDIO_UNIQUE_ID_USE_INPUT:
3163             thread = checkRecordThread_l(ioHandle);
3164             break;
3165         default:
3166             break;
3167         }
3168     }
3169     return thread;
3170 }
3171 
3172 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
checkPlaybackThread_l(audio_io_handle_t output) const3173 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
3174 {
3175     return mPlaybackThreads.valueFor(output).get();
3176 }
3177 
3178 // checkMixerThread_l() must be called with AudioFlinger::mLock held
checkMixerThread_l(audio_io_handle_t output) const3179 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
3180 {
3181     PlaybackThread *thread = checkPlaybackThread_l(output);
3182     return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
3183 }
3184 
3185 // checkRecordThread_l() must be called with AudioFlinger::mLock held
checkRecordThread_l(audio_io_handle_t input) const3186 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
3187 {
3188     return mRecordThreads.valueFor(input).get();
3189 }
3190 
3191 // checkMmapThread_l() must be called with AudioFlinger::mLock held
checkMmapThread_l(audio_io_handle_t io) const3192 AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3193 {
3194     return mMmapThreads.valueFor(io).get();
3195 }
3196 
3197 
3198 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
getVolumeInterface_l(audio_io_handle_t output) const3199 AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3200 {
3201     VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
3202     if (volumeInterface == nullptr) {
3203         MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3204         if (mmapThread != nullptr) {
3205             if (mmapThread->isOutput()) {
3206                 MmapPlaybackThread *mmapPlaybackThread =
3207                         static_cast<MmapPlaybackThread *>(mmapThread);
3208                 volumeInterface = mmapPlaybackThread;
3209             }
3210         }
3211     }
3212     return volumeInterface;
3213 }
3214 
getAllVolumeInterfaces_l() const3215 Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3216 {
3217     Vector <VolumeInterface *> volumeInterfaces;
3218     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3219         volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
3220     }
3221     for (size_t i = 0; i < mMmapThreads.size(); i++) {
3222         if (mMmapThreads.valueAt(i)->isOutput()) {
3223             MmapPlaybackThread *mmapPlaybackThread =
3224                     static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3225             volumeInterfaces.add(mmapPlaybackThread);
3226         }
3227     }
3228     return volumeInterfaces;
3229 }
3230 
nextUniqueId(audio_unique_id_use_t use)3231 audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
3232 {
3233     // This is the internal API, so it is OK to assert on bad parameter.
3234     LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
3235     const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3236     for (int retry = 0; retry < maxRetries; retry++) {
3237         // The cast allows wraparound from max positive to min negative instead of abort
3238         uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3239                 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3240         ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3241         // allow wrap by skipping 0 and -1 for session ids
3242         if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3243             ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3244             return (audio_unique_id_t) (base | use);
3245         }
3246     }
3247     // We have no way of recovering from wraparound
3248     LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3249     // TODO Use a floor after wraparound.  This may need a mutex.
3250 }
3251 
primaryPlaybackThread_l() const3252 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
3253 {
3254     AutoMutex lock(mHardwareLock);
3255     if (mPrimaryHardwareDev == nullptr) {
3256         return nullptr;
3257     }
3258     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3259         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3260         if(thread->isDuplicating()) {
3261             continue;
3262         }
3263         AudioStreamOut *output = thread->getOutput();
3264         if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
3265             return thread;
3266         }
3267     }
3268     return nullptr;
3269 }
3270 
primaryOutputDevice_l() const3271 DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
3272 {
3273     PlaybackThread *thread = primaryPlaybackThread_l();
3274 
3275     if (thread == NULL) {
3276         return DeviceTypeSet();
3277     }
3278 
3279     return thread->outDeviceTypes();
3280 }
3281 
fastPlaybackThread_l() const3282 AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3283 {
3284     size_t minFrameCount = 0;
3285     PlaybackThread *minThread = NULL;
3286     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3287         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3288         if (!thread->isDuplicating()) {
3289             size_t frameCount = thread->frameCountHAL();
3290             if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3291                     (frameCount == minFrameCount && thread->hasFastMixer() &&
3292                     /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3293                 minFrameCount = frameCount;
3294                 minThread = thread;
3295             }
3296         }
3297     }
3298     return minThread;
3299 }
3300 
createSyncEvent(AudioSystem::sync_event_t type,audio_session_t triggerSession,audio_session_t listenerSession,sync_event_callback_t callBack,const wp<RefBase> & cookie)3301 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
3302                                     audio_session_t triggerSession,
3303                                     audio_session_t listenerSession,
3304                                     sync_event_callback_t callBack,
3305                                     const wp<RefBase>& cookie)
3306 {
3307     Mutex::Autolock _l(mLock);
3308 
3309     sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3310     status_t playStatus = NAME_NOT_FOUND;
3311     status_t recStatus = NAME_NOT_FOUND;
3312     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3313         playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3314         if (playStatus == NO_ERROR) {
3315             return event;
3316         }
3317     }
3318     for (size_t i = 0; i < mRecordThreads.size(); i++) {
3319         recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3320         if (recStatus == NO_ERROR) {
3321             return event;
3322         }
3323     }
3324     if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3325         mPendingSyncEvents.add(event);
3326     } else {
3327         ALOGV("createSyncEvent() invalid event %d", event->type());
3328         event.clear();
3329     }
3330     return event;
3331 }
3332 
3333 // ----------------------------------------------------------------------------
3334 //  Effect management
3335 // ----------------------------------------------------------------------------
3336 
getEffectsFactory()3337 sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3338     return mEffectsFactoryHal;
3339 }
3340 
queryNumberEffects(uint32_t * numEffects) const3341 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
3342 {
3343     Mutex::Autolock _l(mLock);
3344     if (mEffectsFactoryHal.get()) {
3345         return mEffectsFactoryHal->queryNumberEffects(numEffects);
3346     } else {
3347         return -ENODEV;
3348     }
3349 }
3350 
queryEffect(uint32_t index,effect_descriptor_t * descriptor) const3351 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
3352 {
3353     Mutex::Autolock _l(mLock);
3354     if (mEffectsFactoryHal.get()) {
3355         return mEffectsFactoryHal->getDescriptor(index, descriptor);
3356     } else {
3357         return -ENODEV;
3358     }
3359 }
3360 
getEffectDescriptor(const effect_uuid_t * pUuid,const effect_uuid_t * pTypeUuid,uint32_t preferredTypeFlag,effect_descriptor_t * descriptor) const3361 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
3362                                            const effect_uuid_t *pTypeUuid,
3363                                            uint32_t preferredTypeFlag,
3364                                            effect_descriptor_t *descriptor) const
3365 {
3366     if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3367         return BAD_VALUE;
3368     }
3369 
3370     Mutex::Autolock _l(mLock);
3371 
3372     if (!mEffectsFactoryHal.get()) {
3373         return -ENODEV;
3374     }
3375 
3376     status_t status = NO_ERROR;
3377     if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3378         // If uuid is specified, request effect descriptor from that.
3379         status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3380     } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3381         // If uuid is not specified, look for an available implementation
3382         // of the required type instead.
3383 
3384         // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3385         effect_descriptor_t desc;
3386         desc.flags = 0; // prevent compiler warning
3387 
3388         uint32_t numEffects = 0;
3389         status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3390         if (status < 0) {
3391             ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3392             return status;
3393         }
3394 
3395         bool found = false;
3396         for (uint32_t i = 0; i < numEffects; i++) {
3397             status = mEffectsFactoryHal->getDescriptor(i, &desc);
3398             if (status < 0) {
3399                 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3400                 continue;
3401             }
3402             if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3403                 // If matching type found save effect descriptor.
3404                 found = true;
3405                 *descriptor = desc;
3406 
3407                 // If there's no preferred flag or this descriptor matches the preferred
3408                 // flag, success! If this descriptor doesn't match the preferred
3409                 // flag, continue enumeration in case a better matching version of this
3410                 // effect type is available. Note that this means if no effect with a
3411                 // correct flag is found, the descriptor returned will correspond to the
3412                 // last effect that at least had a matching type uuid (if any).
3413                 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3414                     (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3415                     break;
3416                 }
3417             }
3418         }
3419 
3420         if (!found) {
3421             status = NAME_NOT_FOUND;
3422             ALOGW("getEffectDescriptor(): Effect not found by type.");
3423         }
3424     } else {
3425         status = BAD_VALUE;
3426         ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3427     }
3428     return status;
3429 }
3430 
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)3431 sp<IEffect> AudioFlinger::createEffect(
3432         effect_descriptor_t *pDesc,
3433         const sp<IEffectClient>& effectClient,
3434         int32_t priority,
3435         audio_io_handle_t io,
3436         audio_session_t sessionId,
3437         const AudioDeviceTypeAddr& device,
3438         const String16& opPackageName,
3439         pid_t pid,
3440         bool probe,
3441         status_t *status,
3442         int *id,
3443         int *enabled)
3444 {
3445     status_t lStatus = NO_ERROR;
3446     sp<EffectHandle> handle;
3447     effect_descriptor_t desc;
3448 
3449     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
3450     if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
3451         const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3452         ALOGW_IF(pid != -1 && pid != callingPid,
3453                  "%s uid %d pid %d tried to pass itself off as pid %d",
3454                  __func__, callingUid, callingPid, pid);
3455         pid = callingPid;
3456     }
3457 
3458     ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3459             pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
3460 
3461     if (pDesc == NULL) {
3462         lStatus = BAD_VALUE;
3463         goto Exit;
3464     }
3465 
3466     if (mEffectsFactoryHal == 0) {
3467         ALOGE("%s: no effects factory hal", __func__);
3468         lStatus = NO_INIT;
3469         goto Exit;
3470     }
3471 
3472     // check audio settings permission for global effects
3473     if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3474         if (!settingsAllowed()) {
3475             ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3476             lStatus = PERMISSION_DENIED;
3477             goto Exit;
3478         }
3479     } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3480         if (!isAudioServerUid(callingUid)) {
3481             ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3482             lStatus = PERMISSION_DENIED;
3483             goto Exit;
3484         }
3485 
3486         if (io == AUDIO_IO_HANDLE_NONE) {
3487             ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3488             lStatus = BAD_VALUE;
3489             goto Exit;
3490         }
3491     } else if (sessionId == AUDIO_SESSION_DEVICE) {
3492         if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3493             ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3494             lStatus = PERMISSION_DENIED;
3495             goto Exit;
3496         }
3497         if (io != AUDIO_IO_HANDLE_NONE) {
3498             ALOGE("%s: io handle should not be specified for device effect", __func__);
3499             lStatus = BAD_VALUE;
3500             goto Exit;
3501         }
3502     } else {
3503         // general sessionId.
3504 
3505         if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3506             ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3507             lStatus = BAD_VALUE;
3508             goto Exit;
3509         }
3510 
3511         // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3512         // to prevent creating an effect when one doesn't actually have track with that session?
3513     }
3514 
3515     {
3516         // Get the full effect descriptor from the uuid/type.
3517         // If the session is the output mix, prefer an auxiliary effect,
3518         // otherwise no preference.
3519         uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3520                                   EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3521         lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3522         if (lStatus < 0) {
3523             ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3524             goto Exit;
3525         }
3526 
3527         // Do not allow auxiliary effects on a session different from 0 (output mix)
3528         if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
3529              (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3530             lStatus = INVALID_OPERATION;
3531             goto Exit;
3532         }
3533 
3534         // check recording permission for visualizer
3535         if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
3536             // TODO: Do we need to start/stop op - i.e. is there recording being performed?
3537             !recordingAllowed(opPackageName, pid, callingUid)) {
3538             lStatus = PERMISSION_DENIED;
3539             goto Exit;
3540         }
3541 
3542         // return effect descriptor
3543         *pDesc = desc;
3544         if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3545             // if the output returned by getOutputForEffect() is removed before we lock the
3546             // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3547             // and we will exit safely
3548             io = AudioSystem::getOutputForEffect(&desc);
3549             ALOGV("createEffect got output %d", io);
3550         }
3551 
3552         Mutex::Autolock _l(mLock);
3553 
3554         if (sessionId == AUDIO_SESSION_DEVICE) {
3555             sp<Client> client = registerPid(pid);
3556             ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
3557             handle = mDeviceEffectManager.createEffect_l(
3558                     &desc, device, client, effectClient, mPatchPanel.patches_l(),
3559                     enabled, &lStatus, probe);
3560             if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3561                 // remove local strong reference to Client with mClientLock held
3562                 Mutex::Autolock _cl(mClientLock);
3563                 client.clear();
3564             } else {
3565                 // handle must be valid here, but check again to be safe.
3566                 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3567             }
3568             goto Register;
3569         }
3570 
3571         // If output is not specified try to find a matching audio session ID in one of the
3572         // output threads.
3573         // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3574         // because of code checking output when entering the function.
3575         // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3576         // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
3577         if (io == AUDIO_IO_HANDLE_NONE) {
3578             // look for the thread where the specified audio session is present
3579             io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3580             if (io == AUDIO_IO_HANDLE_NONE) {
3581                 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
3582             }
3583             if (io == AUDIO_IO_HANDLE_NONE) {
3584                 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
3585             }
3586 
3587             // If you wish to create a Record preprocessing AudioEffect in Java,
3588             // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3589             // Otherwise it will fail when created on a Playback thread by legacy
3590             // handling below.  Ditto with Mmap, the associated Mmap track must be created
3591             // before creating the AudioEffect or the io handle must be specified.
3592             //
3593             // Detect if the effect is created after an AudioRecord is destroyed.
3594             if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3595                 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3596                         " for session %d no longer exists",
3597                          __func__, desc.name, sessionId);
3598                 lStatus = PERMISSION_DENIED;
3599                 goto Exit;
3600             }
3601 
3602             // Legacy handling of creating an effect on an expired or made-up
3603             // session id.  We think that it is a Playback effect.
3604             //
3605             // If no output thread contains the requested session ID, default to
3606             // first output. The effect chain will be moved to the correct output
3607             // thread when a track with the same session ID is created
3608             if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
3609                 io = mPlaybackThreads.keyAt(0);
3610             }
3611             ALOGV("createEffect() got io %d for effect %s", io, desc.name);
3612         } else if (checkPlaybackThread_l(io) != nullptr) {
3613             // allow only one effect chain per sessionId on mPlaybackThreads.
3614             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3615                 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3616                 if (io == checkIo) continue;
3617                 const uint32_t sessionType =
3618                         mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3619                 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3620                     ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3621                             __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3622                     android_errorWriteLog(0x534e4554, "123237974");
3623                     lStatus = BAD_VALUE;
3624                     goto Exit;
3625                 }
3626             }
3627         }
3628         ThreadBase *thread = checkRecordThread_l(io);
3629         if (thread == NULL) {
3630             thread = checkPlaybackThread_l(io);
3631             if (thread == NULL) {
3632                 thread = checkMmapThread_l(io);
3633                 if (thread == NULL) {
3634                     ALOGE("createEffect() unknown output thread");
3635                     lStatus = BAD_VALUE;
3636                     goto Exit;
3637                 }
3638             }
3639         } else {
3640             // Check if one effect chain was awaiting for an effect to be created on this
3641             // session and used it instead of creating a new one.
3642             sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
3643             if (chain != 0) {
3644                 Mutex::Autolock _l(thread->mLock);
3645                 thread->addEffectChain_l(chain);
3646             }
3647         }
3648 
3649         sp<Client> client = registerPid(pid);
3650 
3651         // create effect on selected output thread
3652         bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
3653         handle = thread->createEffect_l(client, effectClient, priority, sessionId,
3654                 &desc, enabled, &lStatus, pinned, probe);
3655         if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3656             // remove local strong reference to Client with mClientLock held
3657             Mutex::Autolock _cl(mClientLock);
3658             client.clear();
3659         } else {
3660             // handle must be valid here, but check again to be safe.
3661             if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3662         }
3663     }
3664 
3665 Register:
3666     if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
3667         // Check CPU and memory usage
3668         sp<EffectBase> effect = handle->effect().promote();
3669         if (effect != nullptr) {
3670             status_t rStatus = effect->updatePolicyState();
3671             if (rStatus != NO_ERROR) {
3672                 lStatus = rStatus;
3673             }
3674         }
3675     } else {
3676         handle.clear();
3677     }
3678 
3679 Exit:
3680     *status = lStatus;
3681     return handle;
3682 }
3683 
moveEffects(audio_session_t sessionId,audio_io_handle_t srcOutput,audio_io_handle_t dstOutput)3684 status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
3685         audio_io_handle_t dstOutput)
3686 {
3687     ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
3688             sessionId, srcOutput, dstOutput);
3689     Mutex::Autolock _l(mLock);
3690     if (srcOutput == dstOutput) {
3691         ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
3692         return NO_ERROR;
3693     }
3694     PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3695     if (srcThread == NULL) {
3696         ALOGW("moveEffects() bad srcOutput %d", srcOutput);
3697         return BAD_VALUE;
3698     }
3699     PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3700     if (dstThread == NULL) {
3701         ALOGW("moveEffects() bad dstOutput %d", dstOutput);
3702         return BAD_VALUE;
3703     }
3704 
3705     Mutex::Autolock _dl(dstThread->mLock);
3706     Mutex::Autolock _sl(srcThread->mLock);
3707     return moveEffectChain_l(sessionId, srcThread, dstThread);
3708 }
3709 
3710 
setEffectSuspended(int effectId,audio_session_t sessionId,bool suspended)3711 void AudioFlinger::setEffectSuspended(int effectId,
3712                                 audio_session_t sessionId,
3713                                 bool suspended)
3714 {
3715     Mutex::Autolock _l(mLock);
3716 
3717     sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3718     if (thread == nullptr) {
3719       return;
3720     }
3721     Mutex::Autolock _sl(thread->mLock);
3722     sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3723     thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3724 }
3725 
3726 
3727 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
moveEffectChain_l(audio_session_t sessionId,AudioFlinger::PlaybackThread * srcThread,AudioFlinger::PlaybackThread * dstThread)3728 status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
3729                                    AudioFlinger::PlaybackThread *srcThread,
3730                                    AudioFlinger::PlaybackThread *dstThread)
3731 {
3732     ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
3733             sessionId, srcThread, dstThread);
3734 
3735     sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
3736     if (chain == 0) {
3737         ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
3738                 sessionId, srcThread);
3739         return INVALID_OPERATION;
3740     }
3741 
3742     // Check whether the destination thread and all effects in the chain are compatible
3743     if (!chain->isCompatibleWithThread_l(dstThread)) {
3744         ALOGW("moveEffectChain_l() effect chain failed because"
3745                 " destination thread %p is not compatible with effects in the chain",
3746                 dstThread);
3747         return INVALID_OPERATION;
3748     }
3749 
3750     // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
3751     // so that a new chain is created with correct parameters when first effect is added. This is
3752     // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
3753     // removed.
3754     srcThread->removeEffectChain_l(chain);
3755 
3756     // transfer all effects one by one so that new effect chain is created on new thread with
3757     // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
3758     sp<EffectChain> dstChain;
3759     uint32_t strategy = 0; // prevent compiler warning
3760     sp<EffectModule> effect = chain->getEffectFromId_l(0);
3761     Vector< sp<EffectModule> > removed;
3762     status_t status = NO_ERROR;
3763     while (effect != 0) {
3764         srcThread->removeEffect_l(effect);
3765         removed.add(effect);
3766         status = dstThread->addEffect_l(effect);
3767         if (status != NO_ERROR) {
3768             break;
3769         }
3770         // removeEffect_l() has stopped the effect if it was active so it must be restarted
3771         if (effect->state() == EffectModule::ACTIVE ||
3772                 effect->state() == EffectModule::STOPPING) {
3773             effect->start();
3774         }
3775         // if the move request is not received from audio policy manager, the effect must be
3776         // re-registered with the new strategy and output
3777         if (dstChain == 0) {
3778             dstChain = effect->callback()->chain().promote();
3779             if (dstChain == 0) {
3780                 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
3781                 status = NO_INIT;
3782                 break;
3783             }
3784             strategy = dstChain->strategy();
3785         }
3786         effect = chain->getEffectFromId_l(0);
3787     }
3788 
3789     if (status != NO_ERROR) {
3790         for (size_t i = 0; i < removed.size(); i++) {
3791             srcThread->addEffect_l(removed[i]);
3792         }
3793     }
3794 
3795     return status;
3796 }
3797 
moveAuxEffectToIo(int EffectId,const sp<PlaybackThread> & dstThread,sp<PlaybackThread> * srcThread)3798 status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3799                                          const sp<PlaybackThread>& dstThread,
3800                                          sp<PlaybackThread> *srcThread)
3801 {
3802     status_t status = NO_ERROR;
3803     Mutex::Autolock _l(mLock);
3804     sp<PlaybackThread> thread =
3805         static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
3806 
3807     if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3808         Mutex::Autolock _dl(dstThread->mLock);
3809         Mutex::Autolock _sl(thread->mLock);
3810         sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3811         sp<EffectChain> dstChain;
3812         if (srcChain == 0) {
3813             return INVALID_OPERATION;
3814         }
3815 
3816         sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3817         if (effect == 0) {
3818             return INVALID_OPERATION;
3819         }
3820         thread->removeEffect_l(effect);
3821         status = dstThread->addEffect_l(effect);
3822         if (status != NO_ERROR) {
3823             thread->addEffect_l(effect);
3824             status = INVALID_OPERATION;
3825             goto Exit;
3826         }
3827 
3828         dstChain = effect->callback()->chain().promote();
3829         if (dstChain == 0) {
3830             thread->addEffect_l(effect);
3831             status = INVALID_OPERATION;
3832         }
3833 
3834 Exit:
3835         // removeEffect_l() has stopped the effect if it was active so it must be restarted
3836         if (effect->state() == EffectModule::ACTIVE ||
3837             effect->state() == EffectModule::STOPPING) {
3838             effect->start();
3839         }
3840     }
3841 
3842     if (status == NO_ERROR && srcThread != nullptr) {
3843         *srcThread = thread;
3844     }
3845     return status;
3846 }
3847 
isNonOffloadableGlobalEffectEnabled_l()3848 bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
3849 {
3850     if (mGlobalEffectEnableTime != 0 &&
3851             ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3852         return true;
3853     }
3854 
3855     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3856         sp<EffectChain> ec =
3857                 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3858         if (ec != 0 && ec->isNonOffloadableEnabled()) {
3859             return true;
3860         }
3861     }
3862     return false;
3863 }
3864 
onNonOffloadableGlobalEffectEnable()3865 void AudioFlinger::onNonOffloadableGlobalEffectEnable()
3866 {
3867     Mutex::Autolock _l(mLock);
3868 
3869     mGlobalEffectEnableTime = systemTime();
3870 
3871     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3872         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3873         if (t->mType == ThreadBase::OFFLOAD) {
3874             t->invalidateTracks(AUDIO_STREAM_MUSIC);
3875         }
3876     }
3877 
3878 }
3879 
putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain> & chain)3880 status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3881 {
3882     // clear possible suspended state before parking the chain so that it starts in default state
3883     // when attached to a new record thread
3884     chain->setEffectSuspended_l(FX_IID_AEC, false);
3885     chain->setEffectSuspended_l(FX_IID_NS, false);
3886 
3887     audio_session_t session = chain->sessionId();
3888     ssize_t index = mOrphanEffectChains.indexOfKey(session);
3889     ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
3890     if (index >= 0) {
3891         ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3892         return ALREADY_EXISTS;
3893     }
3894     mOrphanEffectChains.add(session, chain);
3895     return NO_ERROR;
3896 }
3897 
getOrphanEffectChain_l(audio_session_t session)3898 sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3899 {
3900     sp<EffectChain> chain;
3901     ssize_t index = mOrphanEffectChains.indexOfKey(session);
3902     ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
3903     if (index >= 0) {
3904         chain = mOrphanEffectChains.valueAt(index);
3905         mOrphanEffectChains.removeItemsAt(index);
3906     }
3907     return chain;
3908 }
3909 
updateOrphanEffectChains(const sp<AudioFlinger::EffectModule> & effect)3910 bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3911 {
3912     Mutex::Autolock _l(mLock);
3913     audio_session_t session = effect->sessionId();
3914     ssize_t index = mOrphanEffectChains.indexOfKey(session);
3915     ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
3916     if (index >= 0) {
3917         sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
3918         if (chain->removeEffect_l(effect, true) == 0) {
3919             ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
3920             mOrphanEffectChains.removeItemsAt(index);
3921         }
3922         return true;
3923     }
3924     return false;
3925 }
3926 
3927 
3928 // ----------------------------------------------------------------------------
3929 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)3930 status_t AudioFlinger::onTransact(
3931         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3932 {
3933     return BnAudioFlinger::onTransact(code, data, reply, flags);
3934 }
3935 
3936 } // namespace android
3937