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