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