• 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 <dirent.h>
23 #include <math.h>
24 #include <signal.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 
28 #include <binder/IPCThreadState.h>
29 #include <binder/IServiceManager.h>
30 #include <utils/Log.h>
31 #include <utils/Trace.h>
32 #include <binder/Parcel.h>
33 #include <utils/String16.h>
34 #include <utils/threads.h>
35 #include <utils/Atomic.h>
36 
37 #include <cutils/bitops.h>
38 #include <cutils/properties.h>
39 #include <cutils/compiler.h>
40 
41 //#include <private/media/AudioTrackShared.h>
42 //#include <private/media/AudioEffectShared.h>
43 
44 #include <system/audio.h>
45 #include <hardware/audio.h>
46 
47 #include "AudioMixer.h"
48 #include "AudioFlinger.h"
49 #include "ServiceUtilities.h"
50 
51 #include <media/EffectsFactoryApi.h>
52 #include <audio_effects/effect_visualizer.h>
53 #include <audio_effects/effect_ns.h>
54 #include <audio_effects/effect_aec.h>
55 
56 #include <audio_utils/primitives.h>
57 
58 #include <powermanager/PowerManager.h>
59 
60 #include <common_time/cc_helper.h>
61 //#include <common_time/local_clock.h>
62 
63 #include <media/IMediaLogService.h>
64 
65 #include <media/nbaio/Pipe.h>
66 #include <media/nbaio/PipeReader.h>
67 
68 // ----------------------------------------------------------------------------
69 
70 // Note: the following macro is used for extremely verbose logging message.  In
71 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
73 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
74 // turned on.  Do not uncomment the #def below unless you really know what you
75 // are doing and want to see all of the extremely verbose messages.
76 //#define VERY_VERY_VERBOSE_LOGGING
77 #ifdef VERY_VERY_VERBOSE_LOGGING
78 #define ALOGVV ALOGV
79 #else
80 #define ALOGVV(a...) do { } while(0)
81 #endif
82 
83 namespace android {
84 
85 static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
86 static const char kHardwareLockedString[] = "Hardware lock is taken\n";
87 
88 
89 nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
90 
91 uint32_t AudioFlinger::mScreenState;
92 
93 #ifdef TEE_SINK
94 bool AudioFlinger::mTeeSinkInputEnabled = false;
95 bool AudioFlinger::mTeeSinkOutputEnabled = false;
96 bool AudioFlinger::mTeeSinkTrackEnabled = false;
97 
98 size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
99 size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
100 size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
101 #endif
102 
103 // ----------------------------------------------------------------------------
104 
load_audio_interface(const char * if_name,audio_hw_device_t ** dev)105 static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
106 {
107     const hw_module_t *mod;
108     int rc;
109 
110     rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
111     ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
112                  AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
113     if (rc) {
114         goto out;
115     }
116     rc = audio_hw_device_open(mod, dev);
117     ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
118                  AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
119     if (rc) {
120         goto out;
121     }
122     if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
123         ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
124         rc = BAD_VALUE;
125         goto out;
126     }
127     return 0;
128 
129 out:
130     *dev = NULL;
131     return rc;
132 }
133 
134 // ----------------------------------------------------------------------------
135 
AudioFlinger()136 AudioFlinger::AudioFlinger()
137     : BnAudioFlinger(),
138       mPrimaryHardwareDev(NULL),
139       mHardwareStatus(AUDIO_HW_IDLE),
140       mMasterVolume(1.0f),
141       mMasterMute(false),
142       mNextUniqueId(1),
143       mMode(AUDIO_MODE_INVALID),
144       mBtNrecIsOff(false)
145 {
146     getpid_cached = getpid();
147     char value[PROPERTY_VALUE_MAX];
148     bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
149     if (doLog) {
150         mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters");
151     }
152 #ifdef TEE_SINK
153     (void) property_get("ro.debuggable", value, "0");
154     int debuggable = atoi(value);
155     int teeEnabled = 0;
156     if (debuggable) {
157         (void) property_get("af.tee", value, "0");
158         teeEnabled = atoi(value);
159     }
160     if (teeEnabled & 1)
161         mTeeSinkInputEnabled = true;
162     if (teeEnabled & 2)
163         mTeeSinkOutputEnabled = true;
164     if (teeEnabled & 4)
165         mTeeSinkTrackEnabled = true;
166 #endif
167 }
168 
onFirstRef()169 void AudioFlinger::onFirstRef()
170 {
171     int rc = 0;
172 
173     Mutex::Autolock _l(mLock);
174 
175     /* TODO: move all this work into an Init() function */
176     char val_str[PROPERTY_VALUE_MAX] = { 0 };
177     if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
178         uint32_t int_val;
179         if (1 == sscanf(val_str, "%u", &int_val)) {
180             mStandbyTimeInNsecs = milliseconds(int_val);
181             ALOGI("Using %u mSec as standby time.", int_val);
182         } else {
183             mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
184             ALOGI("Using default %u mSec as standby time.",
185                     (uint32_t)(mStandbyTimeInNsecs / 1000000));
186         }
187     }
188 
189     mMode = AUDIO_MODE_NORMAL;
190 }
191 
~AudioFlinger()192 AudioFlinger::~AudioFlinger()
193 {
194     while (!mRecordThreads.isEmpty()) {
195         // closeInput_nonvirtual() will remove specified entry from mRecordThreads
196         closeInput_nonvirtual(mRecordThreads.keyAt(0));
197     }
198     while (!mPlaybackThreads.isEmpty()) {
199         // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
200         closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
201     }
202 
203     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204         // no mHardwareLock needed, as there are no other references to this
205         audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
206         delete mAudioHwDevs.valueAt(i);
207     }
208 }
209 
210 static const char * const audio_interfaces[] = {
211     AUDIO_HARDWARE_MODULE_ID_PRIMARY,
212     AUDIO_HARDWARE_MODULE_ID_A2DP,
213     AUDIO_HARDWARE_MODULE_ID_USB,
214 };
215 #define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
216 
findSuitableHwDev_l(audio_module_handle_t module,audio_devices_t devices)217 AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
218         audio_module_handle_t module,
219         audio_devices_t devices)
220 {
221     // if module is 0, the request comes from an old policy manager and we should load
222     // well known modules
223     if (module == 0) {
224         ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
225         for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
226             loadHwModule_l(audio_interfaces[i]);
227         }
228         // then try to find a module supporting the requested device.
229         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
230             AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
231             audio_hw_device_t *dev = audioHwDevice->hwDevice();
232             if ((dev->get_supported_devices != NULL) &&
233                     (dev->get_supported_devices(dev) & devices) == devices)
234                 return audioHwDevice;
235         }
236     } else {
237         // check a match for the requested module handle
238         AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
239         if (audioHwDevice != NULL) {
240             return audioHwDevice;
241         }
242     }
243 
244     return NULL;
245 }
246 
dumpClients(int fd,const Vector<String16> & args)247 void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
248 {
249     const size_t SIZE = 256;
250     char buffer[SIZE];
251     String8 result;
252 
253     result.append("Clients:\n");
254     for (size_t i = 0; i < mClients.size(); ++i) {
255         sp<Client> client = mClients.valueAt(i).promote();
256         if (client != 0) {
257             snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
258             result.append(buffer);
259         }
260     }
261 
262     result.append("Global session refs:\n");
263     result.append(" session pid count\n");
264     for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
265         AudioSessionRef *r = mAudioSessionRefs[i];
266         snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
267         result.append(buffer);
268     }
269     write(fd, result.string(), result.size());
270 }
271 
272 
dumpInternals(int fd,const Vector<String16> & args)273 void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
274 {
275     const size_t SIZE = 256;
276     char buffer[SIZE];
277     String8 result;
278     hardware_call_state hardwareStatus = mHardwareStatus;
279 
280     snprintf(buffer, SIZE, "Hardware status: %d\n"
281                            "Standby Time mSec: %u\n",
282                             hardwareStatus,
283                             (uint32_t)(mStandbyTimeInNsecs / 1000000));
284     result.append(buffer);
285     write(fd, result.string(), result.size());
286 }
287 
dumpPermissionDenial(int fd,const Vector<String16> & args)288 void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
289 {
290     const size_t SIZE = 256;
291     char buffer[SIZE];
292     String8 result;
293     snprintf(buffer, SIZE, "Permission Denial: "
294             "can't dump AudioFlinger from pid=%d, uid=%d\n",
295             IPCThreadState::self()->getCallingPid(),
296             IPCThreadState::self()->getCallingUid());
297     result.append(buffer);
298     write(fd, result.string(), result.size());
299 }
300 
dumpTryLock(Mutex & mutex)301 bool AudioFlinger::dumpTryLock(Mutex& mutex)
302 {
303     bool locked = false;
304     for (int i = 0; i < kDumpLockRetries; ++i) {
305         if (mutex.tryLock() == NO_ERROR) {
306             locked = true;
307             break;
308         }
309         usleep(kDumpLockSleepUs);
310     }
311     return locked;
312 }
313 
dump(int fd,const Vector<String16> & args)314 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
315 {
316     if (!dumpAllowed()) {
317         dumpPermissionDenial(fd, args);
318     } else {
319         // get state of hardware lock
320         bool hardwareLocked = dumpTryLock(mHardwareLock);
321         if (!hardwareLocked) {
322             String8 result(kHardwareLockedString);
323             write(fd, result.string(), result.size());
324         } else {
325             mHardwareLock.unlock();
326         }
327 
328         bool locked = dumpTryLock(mLock);
329 
330         // failed to lock - AudioFlinger is probably deadlocked
331         if (!locked) {
332             String8 result(kDeadlockedString);
333             write(fd, result.string(), result.size());
334         }
335 
336         dumpClients(fd, args);
337         dumpInternals(fd, args);
338 
339         // dump playback threads
340         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
341             mPlaybackThreads.valueAt(i)->dump(fd, args);
342         }
343 
344         // dump record threads
345         for (size_t i = 0; i < mRecordThreads.size(); i++) {
346             mRecordThreads.valueAt(i)->dump(fd, args);
347         }
348 
349         // dump all hardware devs
350         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
351             audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
352             dev->dump(dev, fd);
353         }
354 
355 #ifdef TEE_SINK
356         // dump the serially shared record tee sink
357         if (mRecordTeeSource != 0) {
358             dumpTee(fd, mRecordTeeSource);
359         }
360 #endif
361 
362         if (locked) {
363             mLock.unlock();
364         }
365 
366         // append a copy of media.log here by forwarding fd to it, but don't attempt
367         // to lookup the service if it's not running, as it will block for a second
368         if (mLogMemoryDealer != 0) {
369             sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
370             if (binder != 0) {
371                 fdprintf(fd, "\nmedia.log:\n");
372                 Vector<String16> args;
373                 binder->dump(fd, args);
374             }
375         }
376     }
377     return NO_ERROR;
378 }
379 
registerPid_l(pid_t pid)380 sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
381 {
382     // If pid is already in the mClients wp<> map, then use that entry
383     // (for which promote() is always != 0), otherwise create a new entry and Client.
384     sp<Client> client = mClients.valueFor(pid).promote();
385     if (client == 0) {
386         client = new Client(this, pid);
387         mClients.add(pid, client);
388     }
389 
390     return client;
391 }
392 
newWriter_l(size_t size,const char * name)393 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
394 {
395     if (mLogMemoryDealer == 0) {
396         return new NBLog::Writer();
397     }
398     sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
399     sp<NBLog::Writer> writer = new NBLog::Writer(size, shared);
400     sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
401     if (binder != 0) {
402         interface_cast<IMediaLogService>(binder)->registerWriter(shared, size, name);
403     }
404     return writer;
405 }
406 
unregisterWriter(const sp<NBLog::Writer> & writer)407 void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
408 {
409     if (writer == 0) {
410         return;
411     }
412     sp<IMemory> iMemory(writer->getIMemory());
413     if (iMemory == 0) {
414         return;
415     }
416     sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
417     if (binder != 0) {
418         interface_cast<IMediaLogService>(binder)->unregisterWriter(iMemory);
419         // Now the media.log remote reference to IMemory is gone.
420         // When our last local reference to IMemory also drops to zero,
421         // the IMemory destructor will deallocate the region from mMemoryDealer.
422     }
423 }
424 
425 // IAudioFlinger interface
426 
427 
createTrack(audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,IAudioFlinger::track_flags_t * flags,const sp<IMemory> & sharedBuffer,audio_io_handle_t output,pid_t tid,int * sessionId,status_t * status)428 sp<IAudioTrack> AudioFlinger::createTrack(
429         audio_stream_type_t streamType,
430         uint32_t sampleRate,
431         audio_format_t format,
432         audio_channel_mask_t channelMask,
433         size_t frameCount,
434         IAudioFlinger::track_flags_t *flags,
435         const sp<IMemory>& sharedBuffer,
436         audio_io_handle_t output,
437         pid_t tid,
438         int *sessionId,
439         status_t *status)
440 {
441     sp<PlaybackThread::Track> track;
442     sp<TrackHandle> trackHandle;
443     sp<Client> client;
444     status_t lStatus;
445     int lSessionId;
446 
447     // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
448     // but if someone uses binder directly they could bypass that and cause us to crash
449     if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
450         ALOGE("createTrack() invalid stream type %d", streamType);
451         lStatus = BAD_VALUE;
452         goto Exit;
453     }
454 
455     // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
456     // and we don't yet support 8.24 or 32-bit PCM
457     if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
458         ALOGE("createTrack() invalid format %d", format);
459         lStatus = BAD_VALUE;
460         goto Exit;
461     }
462 
463     {
464         Mutex::Autolock _l(mLock);
465         PlaybackThread *thread = checkPlaybackThread_l(output);
466         PlaybackThread *effectThread = NULL;
467         if (thread == NULL) {
468             ALOGE("no playback thread found for output handle %d", output);
469             lStatus = BAD_VALUE;
470             goto Exit;
471         }
472 
473         pid_t pid = IPCThreadState::self()->getCallingPid();
474         client = registerPid_l(pid);
475 
476         ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
477         if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
478             // check if an effect chain with the same session ID is present on another
479             // output thread and move it here.
480             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
481                 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
482                 if (mPlaybackThreads.keyAt(i) != output) {
483                     uint32_t sessions = t->hasAudioSession(*sessionId);
484                     if (sessions & PlaybackThread::EFFECT_SESSION) {
485                         effectThread = t.get();
486                         break;
487                     }
488                 }
489             }
490             lSessionId = *sessionId;
491         } else {
492             // if no audio session id is provided, create one here
493             lSessionId = nextUniqueId();
494             if (sessionId != NULL) {
495                 *sessionId = lSessionId;
496             }
497         }
498         ALOGV("createTrack() lSessionId: %d", lSessionId);
499 
500         track = thread->createTrack_l(client, streamType, sampleRate, format,
501                 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
502 
503         // move effect chain to this output thread if an effect on same session was waiting
504         // for a track to be created
505         if (lStatus == NO_ERROR && effectThread != NULL) {
506             Mutex::Autolock _dl(thread->mLock);
507             Mutex::Autolock _sl(effectThread->mLock);
508             moveEffectChain_l(lSessionId, effectThread, thread, true);
509         }
510 
511         // Look for sync events awaiting for a session to be used.
512         for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
513             if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
514                 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
515                     if (lStatus == NO_ERROR) {
516                         (void) track->setSyncEvent(mPendingSyncEvents[i]);
517                     } else {
518                         mPendingSyncEvents[i]->cancel();
519                     }
520                     mPendingSyncEvents.removeAt(i);
521                     i--;
522                 }
523             }
524         }
525     }
526     if (lStatus == NO_ERROR) {
527         trackHandle = new TrackHandle(track);
528     } else {
529         // remove local strong reference to Client before deleting the Track so that the Client
530         // destructor is called by the TrackBase destructor with mLock held
531         client.clear();
532         track.clear();
533     }
534 
535 Exit:
536     if (status != NULL) {
537         *status = lStatus;
538     }
539     return trackHandle;
540 }
541 
sampleRate(audio_io_handle_t output) const542 uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
543 {
544     Mutex::Autolock _l(mLock);
545     PlaybackThread *thread = checkPlaybackThread_l(output);
546     if (thread == NULL) {
547         ALOGW("sampleRate() unknown thread %d", output);
548         return 0;
549     }
550     return thread->sampleRate();
551 }
552 
channelCount(audio_io_handle_t output) const553 int AudioFlinger::channelCount(audio_io_handle_t output) const
554 {
555     Mutex::Autolock _l(mLock);
556     PlaybackThread *thread = checkPlaybackThread_l(output);
557     if (thread == NULL) {
558         ALOGW("channelCount() unknown thread %d", output);
559         return 0;
560     }
561     return thread->channelCount();
562 }
563 
format(audio_io_handle_t output) const564 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
565 {
566     Mutex::Autolock _l(mLock);
567     PlaybackThread *thread = checkPlaybackThread_l(output);
568     if (thread == NULL) {
569         ALOGW("format() unknown thread %d", output);
570         return AUDIO_FORMAT_INVALID;
571     }
572     return thread->format();
573 }
574 
frameCount(audio_io_handle_t output) const575 size_t AudioFlinger::frameCount(audio_io_handle_t output) const
576 {
577     Mutex::Autolock _l(mLock);
578     PlaybackThread *thread = checkPlaybackThread_l(output);
579     if (thread == NULL) {
580         ALOGW("frameCount() unknown thread %d", output);
581         return 0;
582     }
583     // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
584     //       should examine all callers and fix them to handle smaller counts
585     return thread->frameCount();
586 }
587 
latency(audio_io_handle_t output) const588 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
589 {
590     Mutex::Autolock _l(mLock);
591     PlaybackThread *thread = checkPlaybackThread_l(output);
592     if (thread == NULL) {
593         ALOGW("latency(): no playback thread found for output handle %d", output);
594         return 0;
595     }
596     return thread->latency();
597 }
598 
setMasterVolume(float value)599 status_t AudioFlinger::setMasterVolume(float value)
600 {
601     status_t ret = initCheck();
602     if (ret != NO_ERROR) {
603         return ret;
604     }
605 
606     // check calling permissions
607     if (!settingsAllowed()) {
608         return PERMISSION_DENIED;
609     }
610 
611     Mutex::Autolock _l(mLock);
612     mMasterVolume = value;
613 
614     // Set master volume in the HALs which support it.
615     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
616         AutoMutex lock(mHardwareLock);
617         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
618 
619         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
620         if (dev->canSetMasterVolume()) {
621             dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
622         }
623         mHardwareStatus = AUDIO_HW_IDLE;
624     }
625 
626     // Now set the master volume in each playback thread.  Playback threads
627     // assigned to HALs which do not have master volume support will apply
628     // master volume during the mix operation.  Threads with HALs which do
629     // support master volume will simply ignore the setting.
630     for (size_t i = 0; i < mPlaybackThreads.size(); i++)
631         mPlaybackThreads.valueAt(i)->setMasterVolume(value);
632 
633     return NO_ERROR;
634 }
635 
setMode(audio_mode_t mode)636 status_t AudioFlinger::setMode(audio_mode_t mode)
637 {
638     status_t ret = initCheck();
639     if (ret != NO_ERROR) {
640         return ret;
641     }
642 
643     // check calling permissions
644     if (!settingsAllowed()) {
645         return PERMISSION_DENIED;
646     }
647     if (uint32_t(mode) >= AUDIO_MODE_CNT) {
648         ALOGW("Illegal value: setMode(%d)", mode);
649         return BAD_VALUE;
650     }
651 
652     { // scope for the lock
653         AutoMutex lock(mHardwareLock);
654         audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
655         mHardwareStatus = AUDIO_HW_SET_MODE;
656         ret = dev->set_mode(dev, mode);
657         mHardwareStatus = AUDIO_HW_IDLE;
658     }
659 
660     if (NO_ERROR == ret) {
661         Mutex::Autolock _l(mLock);
662         mMode = mode;
663         for (size_t i = 0; i < mPlaybackThreads.size(); i++)
664             mPlaybackThreads.valueAt(i)->setMode(mode);
665     }
666 
667     return ret;
668 }
669 
setMicMute(bool state)670 status_t AudioFlinger::setMicMute(bool state)
671 {
672     status_t ret = initCheck();
673     if (ret != NO_ERROR) {
674         return ret;
675     }
676 
677     // check calling permissions
678     if (!settingsAllowed()) {
679         return PERMISSION_DENIED;
680     }
681 
682     AutoMutex lock(mHardwareLock);
683     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
684     mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
685     ret = dev->set_mic_mute(dev, state);
686     mHardwareStatus = AUDIO_HW_IDLE;
687     return ret;
688 }
689 
getMicMute() const690 bool AudioFlinger::getMicMute() const
691 {
692     status_t ret = initCheck();
693     if (ret != NO_ERROR) {
694         return false;
695     }
696 
697     bool state = AUDIO_MODE_INVALID;
698     AutoMutex lock(mHardwareLock);
699     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
700     mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
701     dev->get_mic_mute(dev, &state);
702     mHardwareStatus = AUDIO_HW_IDLE;
703     return state;
704 }
705 
setMasterMute(bool muted)706 status_t AudioFlinger::setMasterMute(bool muted)
707 {
708     status_t ret = initCheck();
709     if (ret != NO_ERROR) {
710         return ret;
711     }
712 
713     // check calling permissions
714     if (!settingsAllowed()) {
715         return PERMISSION_DENIED;
716     }
717 
718     Mutex::Autolock _l(mLock);
719     mMasterMute = muted;
720 
721     // Set master mute in the HALs which support it.
722     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
723         AutoMutex lock(mHardwareLock);
724         AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
725 
726         mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
727         if (dev->canSetMasterMute()) {
728             dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
729         }
730         mHardwareStatus = AUDIO_HW_IDLE;
731     }
732 
733     // Now set the master mute in each playback thread.  Playback threads
734     // assigned to HALs which do not have master mute support will apply master
735     // mute during the mix operation.  Threads with HALs which do support master
736     // mute will simply ignore the setting.
737     for (size_t i = 0; i < mPlaybackThreads.size(); i++)
738         mPlaybackThreads.valueAt(i)->setMasterMute(muted);
739 
740     return NO_ERROR;
741 }
742 
masterVolume() const743 float AudioFlinger::masterVolume() const
744 {
745     Mutex::Autolock _l(mLock);
746     return masterVolume_l();
747 }
748 
masterMute() const749 bool AudioFlinger::masterMute() const
750 {
751     Mutex::Autolock _l(mLock);
752     return masterMute_l();
753 }
754 
masterVolume_l() const755 float AudioFlinger::masterVolume_l() const
756 {
757     return mMasterVolume;
758 }
759 
masterMute_l() const760 bool AudioFlinger::masterMute_l() const
761 {
762     return mMasterMute;
763 }
764 
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)765 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
766         audio_io_handle_t output)
767 {
768     // check calling permissions
769     if (!settingsAllowed()) {
770         return PERMISSION_DENIED;
771     }
772 
773     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
774         ALOGE("setStreamVolume() invalid stream %d", stream);
775         return BAD_VALUE;
776     }
777 
778     AutoMutex lock(mLock);
779     PlaybackThread *thread = NULL;
780     if (output) {
781         thread = checkPlaybackThread_l(output);
782         if (thread == NULL) {
783             return BAD_VALUE;
784         }
785     }
786 
787     mStreamTypes[stream].volume = value;
788 
789     if (thread == NULL) {
790         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
791             mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
792         }
793     } else {
794         thread->setStreamVolume(stream, value);
795     }
796 
797     return NO_ERROR;
798 }
799 
setStreamMute(audio_stream_type_t stream,bool muted)800 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
801 {
802     // check calling permissions
803     if (!settingsAllowed()) {
804         return PERMISSION_DENIED;
805     }
806 
807     if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
808         uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
809         ALOGE("setStreamMute() invalid stream %d", stream);
810         return BAD_VALUE;
811     }
812 
813     AutoMutex lock(mLock);
814     mStreamTypes[stream].mute = muted;
815     for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
816         mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
817 
818     return NO_ERROR;
819 }
820 
streamVolume(audio_stream_type_t stream,audio_io_handle_t output) const821 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
822 {
823     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
824         return 0.0f;
825     }
826 
827     AutoMutex lock(mLock);
828     float volume;
829     if (output) {
830         PlaybackThread *thread = checkPlaybackThread_l(output);
831         if (thread == NULL) {
832             return 0.0f;
833         }
834         volume = thread->streamVolume(stream);
835     } else {
836         volume = streamVolume_l(stream);
837     }
838 
839     return volume;
840 }
841 
streamMute(audio_stream_type_t stream) const842 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
843 {
844     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
845         return true;
846     }
847 
848     AutoMutex lock(mLock);
849     return streamMute_l(stream);
850 }
851 
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)852 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
853 {
854     ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
855             ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
856 
857     // check calling permissions
858     if (!settingsAllowed()) {
859         return PERMISSION_DENIED;
860     }
861 
862     // ioHandle == 0 means the parameters are global to the audio hardware interface
863     if (ioHandle == 0) {
864         Mutex::Autolock _l(mLock);
865         status_t final_result = NO_ERROR;
866         {
867             AutoMutex lock(mHardwareLock);
868             mHardwareStatus = AUDIO_HW_SET_PARAMETER;
869             for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
870                 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
871                 status_t result = dev->set_parameters(dev, keyValuePairs.string());
872                 final_result = result ?: final_result;
873             }
874             mHardwareStatus = AUDIO_HW_IDLE;
875         }
876         // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
877         AudioParameter param = AudioParameter(keyValuePairs);
878         String8 value;
879         if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
880             bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
881             if (mBtNrecIsOff != btNrecIsOff) {
882                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
883                     sp<RecordThread> thread = mRecordThreads.valueAt(i);
884                     audio_devices_t device = thread->inDevice();
885                     bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
886                     // collect all of the thread's session IDs
887                     KeyedVector<int, bool> ids = thread->sessionIds();
888                     // suspend effects associated with those session IDs
889                     for (size_t j = 0; j < ids.size(); ++j) {
890                         int sessionId = ids.keyAt(j);
891                         thread->setEffectSuspended(FX_IID_AEC,
892                                                    suspend,
893                                                    sessionId);
894                         thread->setEffectSuspended(FX_IID_NS,
895                                                    suspend,
896                                                    sessionId);
897                     }
898                 }
899                 mBtNrecIsOff = btNrecIsOff;
900             }
901         }
902         String8 screenState;
903         if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
904             bool isOff = screenState == "off";
905             if (isOff != (AudioFlinger::mScreenState & 1)) {
906                 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
907             }
908         }
909         return final_result;
910     }
911 
912     // hold a strong ref on thread in case closeOutput() or closeInput() is called
913     // and the thread is exited once the lock is released
914     sp<ThreadBase> thread;
915     {
916         Mutex::Autolock _l(mLock);
917         thread = checkPlaybackThread_l(ioHandle);
918         if (thread == 0) {
919             thread = checkRecordThread_l(ioHandle);
920         } else if (thread == primaryPlaybackThread_l()) {
921             // indicate output device change to all input threads for pre processing
922             AudioParameter param = AudioParameter(keyValuePairs);
923             int value;
924             if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
925                     (value != 0)) {
926                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
927                     mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
928                 }
929             }
930         }
931     }
932     if (thread != 0) {
933         return thread->setParameters(keyValuePairs);
934     }
935     return BAD_VALUE;
936 }
937 
getParameters(audio_io_handle_t ioHandle,const String8 & keys) const938 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
939 {
940     ALOGVV("getParameters() io %d, keys %s, calling pid %d",
941             ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
942 
943     Mutex::Autolock _l(mLock);
944 
945     if (ioHandle == 0) {
946         String8 out_s8;
947 
948         for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
949             char *s;
950             {
951             AutoMutex lock(mHardwareLock);
952             mHardwareStatus = AUDIO_HW_GET_PARAMETER;
953             audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
954             s = dev->get_parameters(dev, keys.string());
955             mHardwareStatus = AUDIO_HW_IDLE;
956             }
957             out_s8 += String8(s ? s : "");
958             free(s);
959         }
960         return out_s8;
961     }
962 
963     PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
964     if (playbackThread != NULL) {
965         return playbackThread->getParameters(keys);
966     }
967     RecordThread *recordThread = checkRecordThread_l(ioHandle);
968     if (recordThread != NULL) {
969         return recordThread->getParameters(keys);
970     }
971     return String8("");
972 }
973 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask) const974 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
975         audio_channel_mask_t channelMask) const
976 {
977     status_t ret = initCheck();
978     if (ret != NO_ERROR) {
979         return 0;
980     }
981 
982     AutoMutex lock(mHardwareLock);
983     mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
984     struct audio_config config = {
985         sample_rate: sampleRate,
986         channel_mask: channelMask,
987         format: format,
988     };
989     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
990     size_t size = dev->get_input_buffer_size(dev, &config);
991     mHardwareStatus = AUDIO_HW_IDLE;
992     return size;
993 }
994 
getInputFramesLost(audio_io_handle_t ioHandle) const995 unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
996 {
997     Mutex::Autolock _l(mLock);
998 
999     RecordThread *recordThread = checkRecordThread_l(ioHandle);
1000     if (recordThread != NULL) {
1001         return recordThread->getInputFramesLost();
1002     }
1003     return 0;
1004 }
1005 
setVoiceVolume(float value)1006 status_t AudioFlinger::setVoiceVolume(float value)
1007 {
1008     status_t ret = initCheck();
1009     if (ret != NO_ERROR) {
1010         return ret;
1011     }
1012 
1013     // check calling permissions
1014     if (!settingsAllowed()) {
1015         return PERMISSION_DENIED;
1016     }
1017 
1018     AutoMutex lock(mHardwareLock);
1019     audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1020     mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1021     ret = dev->set_voice_volume(dev, value);
1022     mHardwareStatus = AUDIO_HW_IDLE;
1023 
1024     return ret;
1025 }
1026 
getRenderPosition(size_t * halFrames,size_t * dspFrames,audio_io_handle_t output) const1027 status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames,
1028         audio_io_handle_t output) const
1029 {
1030     status_t status;
1031 
1032     Mutex::Autolock _l(mLock);
1033 
1034     PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1035     if (playbackThread != NULL) {
1036         return playbackThread->getRenderPosition(halFrames, dspFrames);
1037     }
1038 
1039     return BAD_VALUE;
1040 }
1041 
registerClient(const sp<IAudioFlingerClient> & client)1042 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1043 {
1044 
1045     Mutex::Autolock _l(mLock);
1046 
1047     pid_t pid = IPCThreadState::self()->getCallingPid();
1048     if (mNotificationClients.indexOfKey(pid) < 0) {
1049         sp<NotificationClient> notificationClient = new NotificationClient(this,
1050                                                                             client,
1051                                                                             pid);
1052         ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1053 
1054         mNotificationClients.add(pid, notificationClient);
1055 
1056         sp<IBinder> binder = client->asBinder();
1057         binder->linkToDeath(notificationClient);
1058 
1059         // the config change is always sent from playback or record threads to avoid deadlock
1060         // with AudioSystem::gLock
1061         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1062             mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
1063         }
1064 
1065         for (size_t i = 0; i < mRecordThreads.size(); i++) {
1066             mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
1067         }
1068     }
1069 }
1070 
removeNotificationClient(pid_t pid)1071 void AudioFlinger::removeNotificationClient(pid_t pid)
1072 {
1073     Mutex::Autolock _l(mLock);
1074 
1075     mNotificationClients.removeItem(pid);
1076 
1077     ALOGV("%d died, releasing its sessions", pid);
1078     size_t num = mAudioSessionRefs.size();
1079     bool removed = false;
1080     for (size_t i = 0; i< num; ) {
1081         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1082         ALOGV(" pid %d @ %d", ref->mPid, i);
1083         if (ref->mPid == pid) {
1084             ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1085             mAudioSessionRefs.removeAt(i);
1086             delete ref;
1087             removed = true;
1088             num--;
1089         } else {
1090             i++;
1091         }
1092     }
1093     if (removed) {
1094         purgeStaleEffects_l();
1095     }
1096 }
1097 
1098 // audioConfigChanged_l() must be called with AudioFlinger::mLock held
audioConfigChanged_l(int event,audio_io_handle_t ioHandle,const void * param2)1099 void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
1100 {
1101     size_t size = mNotificationClients.size();
1102     for (size_t i = 0; i < size; i++) {
1103         mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1104                                                                                param2);
1105     }
1106 }
1107 
1108 // removeClient_l() must be called with AudioFlinger::mLock held
removeClient_l(pid_t pid)1109 void AudioFlinger::removeClient_l(pid_t pid)
1110 {
1111     ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1112             IPCThreadState::self()->getCallingPid());
1113     mClients.removeItem(pid);
1114 }
1115 
1116 // getEffectThread_l() must be called with AudioFlinger::mLock held
getEffectThread_l(int sessionId,int EffectId)1117 sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1118 {
1119     sp<PlaybackThread> thread;
1120 
1121     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1122         if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1123             ALOG_ASSERT(thread == 0);
1124             thread = mPlaybackThreads.valueAt(i);
1125         }
1126     }
1127 
1128     return thread;
1129 }
1130 
1131 
1132 
1133 // ----------------------------------------------------------------------------
1134 
Client(const sp<AudioFlinger> & audioFlinger,pid_t pid)1135 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1136     :   RefBase(),
1137         mAudioFlinger(audioFlinger),
1138         // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
1139         mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
1140         mPid(pid),
1141         mTimedTrackCount(0)
1142 {
1143     // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
1144 }
1145 
1146 // Client destructor must be called with AudioFlinger::mLock held
~Client()1147 AudioFlinger::Client::~Client()
1148 {
1149     mAudioFlinger->removeClient_l(mPid);
1150 }
1151 
heap() const1152 sp<MemoryDealer> AudioFlinger::Client::heap() const
1153 {
1154     return mMemoryDealer;
1155 }
1156 
1157 // Reserve one of the limited slots for a timed audio track associated
1158 // with this client
reserveTimedTrack()1159 bool AudioFlinger::Client::reserveTimedTrack()
1160 {
1161     const int kMaxTimedTracksPerClient = 4;
1162 
1163     Mutex::Autolock _l(mTimedTrackLock);
1164 
1165     if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1166         ALOGW("can not create timed track - pid %d has exceeded the limit",
1167              mPid);
1168         return false;
1169     }
1170 
1171     mTimedTrackCount++;
1172     return true;
1173 }
1174 
1175 // Release a slot for a timed audio track
releaseTimedTrack()1176 void AudioFlinger::Client::releaseTimedTrack()
1177 {
1178     Mutex::Autolock _l(mTimedTrackLock);
1179     mTimedTrackCount--;
1180 }
1181 
1182 // ----------------------------------------------------------------------------
1183 
NotificationClient(const sp<AudioFlinger> & audioFlinger,const sp<IAudioFlingerClient> & client,pid_t pid)1184 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1185                                                      const sp<IAudioFlingerClient>& client,
1186                                                      pid_t pid)
1187     : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
1188 {
1189 }
1190 
~NotificationClient()1191 AudioFlinger::NotificationClient::~NotificationClient()
1192 {
1193 }
1194 
binderDied(const wp<IBinder> & who)1195 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
1196 {
1197     sp<NotificationClient> keep(this);
1198     mAudioFlinger->removeNotificationClient(mPid);
1199 }
1200 
1201 
1202 // ----------------------------------------------------------------------------
1203 
openRecord(audio_io_handle_t input,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,IAudioFlinger::track_flags_t flags,pid_t tid,int * sessionId,status_t * status)1204 sp<IAudioRecord> AudioFlinger::openRecord(
1205         audio_io_handle_t input,
1206         uint32_t sampleRate,
1207         audio_format_t format,
1208         audio_channel_mask_t channelMask,
1209         size_t frameCount,
1210         IAudioFlinger::track_flags_t flags,
1211         pid_t tid,
1212         int *sessionId,
1213         status_t *status)
1214 {
1215     sp<RecordThread::RecordTrack> recordTrack;
1216     sp<RecordHandle> recordHandle;
1217     sp<Client> client;
1218     status_t lStatus;
1219     RecordThread *thread;
1220     size_t inFrameCount;
1221     int lSessionId;
1222 
1223     // check calling permissions
1224     if (!recordingAllowed()) {
1225         lStatus = PERMISSION_DENIED;
1226         goto Exit;
1227     }
1228 
1229     // add client to list
1230     { // scope for mLock
1231         Mutex::Autolock _l(mLock);
1232         thread = checkRecordThread_l(input);
1233         if (thread == NULL) {
1234             lStatus = BAD_VALUE;
1235             goto Exit;
1236         }
1237 
1238         pid_t pid = IPCThreadState::self()->getCallingPid();
1239         client = registerPid_l(pid);
1240 
1241         // If no audio session id is provided, create one here
1242         if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1243             lSessionId = *sessionId;
1244         } else {
1245             lSessionId = nextUniqueId();
1246             if (sessionId != NULL) {
1247                 *sessionId = lSessionId;
1248             }
1249         }
1250         // create new record track.
1251         // The record track uses one track in mHardwareMixerThread by convention.
1252         recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
1253                                                   frameCount, lSessionId, flags, tid, &lStatus);
1254     }
1255     if (lStatus != NO_ERROR) {
1256         // remove local strong reference to Client before deleting the RecordTrack so that the
1257         // Client destructor is called by the TrackBase destructor with mLock held
1258         client.clear();
1259         recordTrack.clear();
1260         goto Exit;
1261     }
1262 
1263     // return to handle to client
1264     recordHandle = new RecordHandle(recordTrack);
1265     lStatus = NO_ERROR;
1266 
1267 Exit:
1268     if (status) {
1269         *status = lStatus;
1270     }
1271     return recordHandle;
1272 }
1273 
1274 
1275 
1276 // ----------------------------------------------------------------------------
1277 
loadHwModule(const char * name)1278 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1279 {
1280     if (!settingsAllowed()) {
1281         return 0;
1282     }
1283     Mutex::Autolock _l(mLock);
1284     return loadHwModule_l(name);
1285 }
1286 
1287 // loadHwModule_l() must be called with AudioFlinger::mLock held
loadHwModule_l(const char * name)1288 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1289 {
1290     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1291         if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1292             ALOGW("loadHwModule() module %s already loaded", name);
1293             return mAudioHwDevs.keyAt(i);
1294         }
1295     }
1296 
1297     audio_hw_device_t *dev;
1298 
1299     int rc = load_audio_interface(name, &dev);
1300     if (rc) {
1301         ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1302         return 0;
1303     }
1304 
1305     mHardwareStatus = AUDIO_HW_INIT;
1306     rc = dev->init_check(dev);
1307     mHardwareStatus = AUDIO_HW_IDLE;
1308     if (rc) {
1309         ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1310         return 0;
1311     }
1312 
1313     // Check and cache this HAL's level of support for master mute and master
1314     // volume.  If this is the first HAL opened, and it supports the get
1315     // methods, use the initial values provided by the HAL as the current
1316     // master mute and volume settings.
1317 
1318     AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1319     {  // scope for auto-lock pattern
1320         AutoMutex lock(mHardwareLock);
1321 
1322         if (0 == mAudioHwDevs.size()) {
1323             mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1324             if (NULL != dev->get_master_volume) {
1325                 float mv;
1326                 if (OK == dev->get_master_volume(dev, &mv)) {
1327                     mMasterVolume = mv;
1328                 }
1329             }
1330 
1331             mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1332             if (NULL != dev->get_master_mute) {
1333                 bool mm;
1334                 if (OK == dev->get_master_mute(dev, &mm)) {
1335                     mMasterMute = mm;
1336                 }
1337             }
1338         }
1339 
1340         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1341         if ((NULL != dev->set_master_volume) &&
1342             (OK == dev->set_master_volume(dev, mMasterVolume))) {
1343             flags = static_cast<AudioHwDevice::Flags>(flags |
1344                     AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1345         }
1346 
1347         mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1348         if ((NULL != dev->set_master_mute) &&
1349             (OK == dev->set_master_mute(dev, mMasterMute))) {
1350             flags = static_cast<AudioHwDevice::Flags>(flags |
1351                     AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1352         }
1353 
1354         mHardwareStatus = AUDIO_HW_IDLE;
1355     }
1356 
1357     audio_module_handle_t handle = nextUniqueId();
1358     mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
1359 
1360     ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
1361           name, dev->common.module->name, dev->common.module->id, handle);
1362 
1363     return handle;
1364 
1365 }
1366 
1367 // ----------------------------------------------------------------------------
1368 
getPrimaryOutputSamplingRate()1369 uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
1370 {
1371     Mutex::Autolock _l(mLock);
1372     PlaybackThread *thread = primaryPlaybackThread_l();
1373     return thread != NULL ? thread->sampleRate() : 0;
1374 }
1375 
getPrimaryOutputFrameCount()1376 size_t AudioFlinger::getPrimaryOutputFrameCount()
1377 {
1378     Mutex::Autolock _l(mLock);
1379     PlaybackThread *thread = primaryPlaybackThread_l();
1380     return thread != NULL ? thread->frameCountHAL() : 0;
1381 }
1382 
1383 // ----------------------------------------------------------------------------
1384 
openOutput(audio_module_handle_t module,audio_devices_t * pDevices,uint32_t * pSamplingRate,audio_format_t * pFormat,audio_channel_mask_t * pChannelMask,uint32_t * pLatencyMs,audio_output_flags_t flags)1385 audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
1386                                            audio_devices_t *pDevices,
1387                                            uint32_t *pSamplingRate,
1388                                            audio_format_t *pFormat,
1389                                            audio_channel_mask_t *pChannelMask,
1390                                            uint32_t *pLatencyMs,
1391                                            audio_output_flags_t flags)
1392 {
1393     status_t status;
1394     PlaybackThread *thread = NULL;
1395     struct audio_config config = {
1396         sample_rate: pSamplingRate ? *pSamplingRate : 0,
1397         channel_mask: pChannelMask ? *pChannelMask : 0,
1398         format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
1399     };
1400     audio_stream_out_t *outStream = NULL;
1401     AudioHwDevice *outHwDev;
1402 
1403     ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
1404               module,
1405               (pDevices != NULL) ? *pDevices : 0,
1406               config.sample_rate,
1407               config.format,
1408               config.channel_mask,
1409               flags);
1410 
1411     if (pDevices == NULL || *pDevices == 0) {
1412         return 0;
1413     }
1414 
1415     Mutex::Autolock _l(mLock);
1416 
1417     outHwDev = findSuitableHwDev_l(module, *pDevices);
1418     if (outHwDev == NULL)
1419         return 0;
1420 
1421     audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
1422     audio_io_handle_t id = nextUniqueId();
1423 
1424     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1425 
1426     status = hwDevHal->open_output_stream(hwDevHal,
1427                                           id,
1428                                           *pDevices,
1429                                           (audio_output_flags_t)flags,
1430                                           &config,
1431                                           &outStream);
1432 
1433     mHardwareStatus = AUDIO_HW_IDLE;
1434     ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, "
1435             "Channels %x, status %d",
1436             outStream,
1437             config.sample_rate,
1438             config.format,
1439             config.channel_mask,
1440             status);
1441 
1442     if (status == NO_ERROR && outStream != NULL) {
1443         AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
1444 
1445         if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1446             (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
1447             (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
1448             thread = new DirectOutputThread(this, output, id, *pDevices);
1449             ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
1450         } else {
1451             thread = new MixerThread(this, output, id, *pDevices);
1452             ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
1453         }
1454         mPlaybackThreads.add(id, thread);
1455 
1456         if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
1457         if (pFormat != NULL) *pFormat = config.format;
1458         if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
1459         if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
1460 
1461         // notify client processes of the new output creation
1462         thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
1463 
1464         // the first primary output opened designates the primary hw device
1465         if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
1466             ALOGI("Using module %d has the primary audio interface", module);
1467             mPrimaryHardwareDev = outHwDev;
1468 
1469             AutoMutex lock(mHardwareLock);
1470             mHardwareStatus = AUDIO_HW_SET_MODE;
1471             hwDevHal->set_mode(hwDevHal, mMode);
1472             mHardwareStatus = AUDIO_HW_IDLE;
1473         }
1474         return id;
1475     }
1476 
1477     return 0;
1478 }
1479 
openDuplicateOutput(audio_io_handle_t output1,audio_io_handle_t output2)1480 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1481         audio_io_handle_t output2)
1482 {
1483     Mutex::Autolock _l(mLock);
1484     MixerThread *thread1 = checkMixerThread_l(output1);
1485     MixerThread *thread2 = checkMixerThread_l(output2);
1486 
1487     if (thread1 == NULL || thread2 == NULL) {
1488         ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1489                 output2);
1490         return 0;
1491     }
1492 
1493     audio_io_handle_t id = nextUniqueId();
1494     DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
1495     thread->addOutputTrack(thread2);
1496     mPlaybackThreads.add(id, thread);
1497     // notify client processes of the new output creation
1498     thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
1499     return id;
1500 }
1501 
closeOutput(audio_io_handle_t output)1502 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
1503 {
1504     return closeOutput_nonvirtual(output);
1505 }
1506 
closeOutput_nonvirtual(audio_io_handle_t output)1507 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1508 {
1509     // keep strong reference on the playback thread so that
1510     // it is not destroyed while exit() is executed
1511     sp<PlaybackThread> thread;
1512     {
1513         Mutex::Autolock _l(mLock);
1514         thread = checkPlaybackThread_l(output);
1515         if (thread == NULL) {
1516             return BAD_VALUE;
1517         }
1518 
1519         ALOGV("closeOutput() %d", output);
1520 
1521         if (thread->type() == ThreadBase::MIXER) {
1522             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1523                 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
1524                     DuplicatingThread *dupThread =
1525                             (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
1526                     dupThread->removeOutputTrack((MixerThread *)thread.get());
1527                 }
1528             }
1529         }
1530         audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
1531         mPlaybackThreads.removeItem(output);
1532     }
1533     thread->exit();
1534     // The thread entity (active unit of execution) is no longer running here,
1535     // but the ThreadBase container still exists.
1536 
1537     if (thread->type() != ThreadBase::DUPLICATING) {
1538         AudioStreamOut *out = thread->clearOutput();
1539         ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1540         // from now on thread->mOutput is NULL
1541         out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1542         delete out;
1543     }
1544     return NO_ERROR;
1545 }
1546 
suspendOutput(audio_io_handle_t output)1547 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
1548 {
1549     Mutex::Autolock _l(mLock);
1550     PlaybackThread *thread = checkPlaybackThread_l(output);
1551 
1552     if (thread == NULL) {
1553         return BAD_VALUE;
1554     }
1555 
1556     ALOGV("suspendOutput() %d", output);
1557     thread->suspend();
1558 
1559     return NO_ERROR;
1560 }
1561 
restoreOutput(audio_io_handle_t output)1562 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
1563 {
1564     Mutex::Autolock _l(mLock);
1565     PlaybackThread *thread = checkPlaybackThread_l(output);
1566 
1567     if (thread == NULL) {
1568         return BAD_VALUE;
1569     }
1570 
1571     ALOGV("restoreOutput() %d", output);
1572 
1573     thread->restore();
1574 
1575     return NO_ERROR;
1576 }
1577 
openInput(audio_module_handle_t module,audio_devices_t * pDevices,uint32_t * pSamplingRate,audio_format_t * pFormat,audio_channel_mask_t * pChannelMask)1578 audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
1579                                           audio_devices_t *pDevices,
1580                                           uint32_t *pSamplingRate,
1581                                           audio_format_t *pFormat,
1582                                           audio_channel_mask_t *pChannelMask)
1583 {
1584     status_t status;
1585     RecordThread *thread = NULL;
1586     struct audio_config config = {
1587         sample_rate: pSamplingRate ? *pSamplingRate : 0,
1588         channel_mask: pChannelMask ? *pChannelMask : 0,
1589         format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
1590     };
1591     uint32_t reqSamplingRate = config.sample_rate;
1592     audio_format_t reqFormat = config.format;
1593     audio_channel_mask_t reqChannels = config.channel_mask;
1594     audio_stream_in_t *inStream = NULL;
1595     AudioHwDevice *inHwDev;
1596 
1597     if (pDevices == NULL || *pDevices == 0) {
1598         return 0;
1599     }
1600 
1601     Mutex::Autolock _l(mLock);
1602 
1603     inHwDev = findSuitableHwDev_l(module, *pDevices);
1604     if (inHwDev == NULL)
1605         return 0;
1606 
1607     audio_hw_device_t *inHwHal = inHwDev->hwDevice();
1608     audio_io_handle_t id = nextUniqueId();
1609 
1610     status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
1611                                         &inStream);
1612     ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
1613             "status %d",
1614             inStream,
1615             config.sample_rate,
1616             config.format,
1617             config.channel_mask,
1618             status);
1619 
1620     // If the input could not be opened with the requested parameters and we can handle the
1621     // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
1622     // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
1623     if (status == BAD_VALUE &&
1624         reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
1625         (config.sample_rate <= 2 * reqSamplingRate) &&
1626         (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
1627         ALOGV("openInput() reopening with proposed sampling rate and channel mask");
1628         inStream = NULL;
1629         status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
1630     }
1631 
1632     if (status == NO_ERROR && inStream != NULL) {
1633 
1634 #ifdef TEE_SINK
1635         // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
1636         // or (re-)create if current Pipe is idle and does not match the new format
1637         sp<NBAIO_Sink> teeSink;
1638         enum {
1639             TEE_SINK_NO,    // don't copy input
1640             TEE_SINK_NEW,   // copy input using a new pipe
1641             TEE_SINK_OLD,   // copy input using an existing pipe
1642         } kind;
1643         NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
1644                                         popcount(inStream->common.get_channels(&inStream->common)));
1645         if (!mTeeSinkInputEnabled) {
1646             kind = TEE_SINK_NO;
1647         } else if (format == Format_Invalid) {
1648             kind = TEE_SINK_NO;
1649         } else if (mRecordTeeSink == 0) {
1650             kind = TEE_SINK_NEW;
1651         } else if (mRecordTeeSink->getStrongCount() != 1) {
1652             kind = TEE_SINK_NO;
1653         } else if (format == mRecordTeeSink->format()) {
1654             kind = TEE_SINK_OLD;
1655         } else {
1656             kind = TEE_SINK_NEW;
1657         }
1658         switch (kind) {
1659         case TEE_SINK_NEW: {
1660             Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
1661             size_t numCounterOffers = 0;
1662             const NBAIO_Format offers[1] = {format};
1663             ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
1664             ALOG_ASSERT(index == 0);
1665             PipeReader *pipeReader = new PipeReader(*pipe);
1666             numCounterOffers = 0;
1667             index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
1668             ALOG_ASSERT(index == 0);
1669             mRecordTeeSink = pipe;
1670             mRecordTeeSource = pipeReader;
1671             teeSink = pipe;
1672             }
1673             break;
1674         case TEE_SINK_OLD:
1675             teeSink = mRecordTeeSink;
1676             break;
1677         case TEE_SINK_NO:
1678         default:
1679             break;
1680         }
1681 #endif
1682 
1683         AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
1684 
1685         // Start record thread
1686         // RecorThread require both input and output device indication to forward to audio
1687         // pre processing modules
1688         thread = new RecordThread(this,
1689                                   input,
1690                                   reqSamplingRate,
1691                                   reqChannels,
1692                                   id,
1693                                   primaryOutputDevice_l(),
1694                                   *pDevices
1695 #ifdef TEE_SINK
1696                                   , teeSink
1697 #endif
1698                                   );
1699         mRecordThreads.add(id, thread);
1700         ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
1701         if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
1702         if (pFormat != NULL) *pFormat = config.format;
1703         if (pChannelMask != NULL) *pChannelMask = reqChannels;
1704 
1705         // notify client processes of the new input creation
1706         thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
1707         return id;
1708     }
1709 
1710     return 0;
1711 }
1712 
closeInput(audio_io_handle_t input)1713 status_t AudioFlinger::closeInput(audio_io_handle_t input)
1714 {
1715     return closeInput_nonvirtual(input);
1716 }
1717 
closeInput_nonvirtual(audio_io_handle_t input)1718 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
1719 {
1720     // keep strong reference on the record thread so that
1721     // it is not destroyed while exit() is executed
1722     sp<RecordThread> thread;
1723     {
1724         Mutex::Autolock _l(mLock);
1725         thread = checkRecordThread_l(input);
1726         if (thread == 0) {
1727             return BAD_VALUE;
1728         }
1729 
1730         ALOGV("closeInput() %d", input);
1731         audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
1732         mRecordThreads.removeItem(input);
1733     }
1734     thread->exit();
1735     // The thread entity (active unit of execution) is no longer running here,
1736     // but the ThreadBase container still exists.
1737 
1738     AudioStreamIn *in = thread->clearInput();
1739     ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
1740     // from now on thread->mInput is NULL
1741     in->hwDev()->close_input_stream(in->hwDev(), in->stream);
1742     delete in;
1743 
1744     return NO_ERROR;
1745 }
1746 
setStreamOutput(audio_stream_type_t stream,audio_io_handle_t output)1747 status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
1748 {
1749     Mutex::Autolock _l(mLock);
1750     ALOGV("setStreamOutput() stream %d to output %d", stream, output);
1751 
1752     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1753         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
1754         thread->invalidateTracks(stream);
1755     }
1756 
1757     return NO_ERROR;
1758 }
1759 
1760 
newAudioSessionId()1761 int AudioFlinger::newAudioSessionId()
1762 {
1763     return nextUniqueId();
1764 }
1765 
acquireAudioSessionId(int audioSession)1766 void AudioFlinger::acquireAudioSessionId(int audioSession)
1767 {
1768     Mutex::Autolock _l(mLock);
1769     pid_t caller = IPCThreadState::self()->getCallingPid();
1770     ALOGV("acquiring %d from %d", audioSession, caller);
1771     size_t num = mAudioSessionRefs.size();
1772     for (size_t i = 0; i< num; i++) {
1773         AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
1774         if (ref->mSessionid == audioSession && ref->mPid == caller) {
1775             ref->mCnt++;
1776             ALOGV(" incremented refcount to %d", ref->mCnt);
1777             return;
1778         }
1779     }
1780     mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
1781     ALOGV(" added new entry for %d", audioSession);
1782 }
1783 
releaseAudioSessionId(int audioSession)1784 void AudioFlinger::releaseAudioSessionId(int audioSession)
1785 {
1786     Mutex::Autolock _l(mLock);
1787     pid_t caller = IPCThreadState::self()->getCallingPid();
1788     ALOGV("releasing %d from %d", audioSession, caller);
1789     size_t num = mAudioSessionRefs.size();
1790     for (size_t i = 0; i< num; i++) {
1791         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1792         if (ref->mSessionid == audioSession && ref->mPid == caller) {
1793             ref->mCnt--;
1794             ALOGV(" decremented refcount to %d", ref->mCnt);
1795             if (ref->mCnt == 0) {
1796                 mAudioSessionRefs.removeAt(i);
1797                 delete ref;
1798                 purgeStaleEffects_l();
1799             }
1800             return;
1801         }
1802     }
1803     ALOGW("session id %d not found for pid %d", audioSession, caller);
1804 }
1805 
purgeStaleEffects_l()1806 void AudioFlinger::purgeStaleEffects_l() {
1807 
1808     ALOGV("purging stale effects");
1809 
1810     Vector< sp<EffectChain> > chains;
1811 
1812     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1813         sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
1814         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
1815             sp<EffectChain> ec = t->mEffectChains[j];
1816             if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
1817                 chains.push(ec);
1818             }
1819         }
1820     }
1821     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1822         sp<RecordThread> t = mRecordThreads.valueAt(i);
1823         for (size_t j = 0; j < t->mEffectChains.size(); j++) {
1824             sp<EffectChain> ec = t->mEffectChains[j];
1825             chains.push(ec);
1826         }
1827     }
1828 
1829     for (size_t i = 0; i < chains.size(); i++) {
1830         sp<EffectChain> ec = chains[i];
1831         int sessionid = ec->sessionId();
1832         sp<ThreadBase> t = ec->mThread.promote();
1833         if (t == 0) {
1834             continue;
1835         }
1836         size_t numsessionrefs = mAudioSessionRefs.size();
1837         bool found = false;
1838         for (size_t k = 0; k < numsessionrefs; k++) {
1839             AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
1840             if (ref->mSessionid == sessionid) {
1841                 ALOGV(" session %d still exists for %d with %d refs",
1842                     sessionid, ref->mPid, ref->mCnt);
1843                 found = true;
1844                 break;
1845             }
1846         }
1847         if (!found) {
1848             Mutex::Autolock _l (t->mLock);
1849             // remove all effects from the chain
1850             while (ec->mEffects.size()) {
1851                 sp<EffectModule> effect = ec->mEffects[0];
1852                 effect->unPin();
1853                 t->removeEffect_l(effect);
1854                 if (effect->purgeHandles()) {
1855                     t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
1856                 }
1857                 AudioSystem::unregisterEffect(effect->id());
1858             }
1859         }
1860     }
1861     return;
1862 }
1863 
1864 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
checkPlaybackThread_l(audio_io_handle_t output) const1865 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
1866 {
1867     return mPlaybackThreads.valueFor(output).get();
1868 }
1869 
1870 // checkMixerThread_l() must be called with AudioFlinger::mLock held
checkMixerThread_l(audio_io_handle_t output) const1871 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
1872 {
1873     PlaybackThread *thread = checkPlaybackThread_l(output);
1874     return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
1875 }
1876 
1877 // checkRecordThread_l() must be called with AudioFlinger::mLock held
checkRecordThread_l(audio_io_handle_t input) const1878 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
1879 {
1880     return mRecordThreads.valueFor(input).get();
1881 }
1882 
nextUniqueId()1883 uint32_t AudioFlinger::nextUniqueId()
1884 {
1885     return android_atomic_inc(&mNextUniqueId);
1886 }
1887 
primaryPlaybackThread_l() const1888 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
1889 {
1890     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1891         PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
1892         AudioStreamOut *output = thread->getOutput();
1893         if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
1894             return thread;
1895         }
1896     }
1897     return NULL;
1898 }
1899 
primaryOutputDevice_l() const1900 audio_devices_t AudioFlinger::primaryOutputDevice_l() const
1901 {
1902     PlaybackThread *thread = primaryPlaybackThread_l();
1903 
1904     if (thread == NULL) {
1905         return 0;
1906     }
1907 
1908     return thread->outDevice();
1909 }
1910 
createSyncEvent(AudioSystem::sync_event_t type,int triggerSession,int listenerSession,sync_event_callback_t callBack,void * cookie)1911 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
1912                                     int triggerSession,
1913                                     int listenerSession,
1914                                     sync_event_callback_t callBack,
1915                                     void *cookie)
1916 {
1917     Mutex::Autolock _l(mLock);
1918 
1919     sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
1920     status_t playStatus = NAME_NOT_FOUND;
1921     status_t recStatus = NAME_NOT_FOUND;
1922     for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1923         playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
1924         if (playStatus == NO_ERROR) {
1925             return event;
1926         }
1927     }
1928     for (size_t i = 0; i < mRecordThreads.size(); i++) {
1929         recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
1930         if (recStatus == NO_ERROR) {
1931             return event;
1932         }
1933     }
1934     if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
1935         mPendingSyncEvents.add(event);
1936     } else {
1937         ALOGV("createSyncEvent() invalid event %d", event->type());
1938         event.clear();
1939     }
1940     return event;
1941 }
1942 
1943 // ----------------------------------------------------------------------------
1944 //  Effect management
1945 // ----------------------------------------------------------------------------
1946 
1947 
queryNumberEffects(uint32_t * numEffects) const1948 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
1949 {
1950     Mutex::Autolock _l(mLock);
1951     return EffectQueryNumberEffects(numEffects);
1952 }
1953 
queryEffect(uint32_t index,effect_descriptor_t * descriptor) const1954 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
1955 {
1956     Mutex::Autolock _l(mLock);
1957     return EffectQueryEffect(index, descriptor);
1958 }
1959 
getEffectDescriptor(const effect_uuid_t * pUuid,effect_descriptor_t * descriptor) const1960 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
1961         effect_descriptor_t *descriptor) const
1962 {
1963     Mutex::Autolock _l(mLock);
1964     return EffectGetDescriptor(pUuid, descriptor);
1965 }
1966 
1967 
createEffect(effect_descriptor_t * pDesc,const sp<IEffectClient> & effectClient,int32_t priority,audio_io_handle_t io,int sessionId,status_t * status,int * id,int * enabled)1968 sp<IEffect> AudioFlinger::createEffect(
1969         effect_descriptor_t *pDesc,
1970         const sp<IEffectClient>& effectClient,
1971         int32_t priority,
1972         audio_io_handle_t io,
1973         int sessionId,
1974         status_t *status,
1975         int *id,
1976         int *enabled)
1977 {
1978     status_t lStatus = NO_ERROR;
1979     sp<EffectHandle> handle;
1980     effect_descriptor_t desc;
1981 
1982     pid_t pid = IPCThreadState::self()->getCallingPid();
1983     ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
1984             pid, effectClient.get(), priority, sessionId, io);
1985 
1986     if (pDesc == NULL) {
1987         lStatus = BAD_VALUE;
1988         goto Exit;
1989     }
1990 
1991     // check audio settings permission for global effects
1992     if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
1993         lStatus = PERMISSION_DENIED;
1994         goto Exit;
1995     }
1996 
1997     // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
1998     // that can only be created by audio policy manager (running in same process)
1999     if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
2000         lStatus = PERMISSION_DENIED;
2001         goto Exit;
2002     }
2003 
2004     if (io == 0) {
2005         if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2006             // output must be specified by AudioPolicyManager when using session
2007             // AUDIO_SESSION_OUTPUT_STAGE
2008             lStatus = BAD_VALUE;
2009             goto Exit;
2010         } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2011             // if the output returned by getOutputForEffect() is removed before we lock the
2012             // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2013             // and we will exit safely
2014             io = AudioSystem::getOutputForEffect(&desc);
2015         }
2016     }
2017 
2018     {
2019         Mutex::Autolock _l(mLock);
2020 
2021 
2022         if (!EffectIsNullUuid(&pDesc->uuid)) {
2023             // if uuid is specified, request effect descriptor
2024             lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2025             if (lStatus < 0) {
2026                 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
2027                 goto Exit;
2028             }
2029         } else {
2030             // if uuid is not specified, look for an available implementation
2031             // of the required type in effect factory
2032             if (EffectIsNullUuid(&pDesc->type)) {
2033                 ALOGW("createEffect() no effect type");
2034                 lStatus = BAD_VALUE;
2035                 goto Exit;
2036             }
2037             uint32_t numEffects = 0;
2038             effect_descriptor_t d;
2039             d.flags = 0; // prevent compiler warning
2040             bool found = false;
2041 
2042             lStatus = EffectQueryNumberEffects(&numEffects);
2043             if (lStatus < 0) {
2044                 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
2045                 goto Exit;
2046             }
2047             for (uint32_t i = 0; i < numEffects; i++) {
2048                 lStatus = EffectQueryEffect(i, &desc);
2049                 if (lStatus < 0) {
2050                     ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
2051                     continue;
2052                 }
2053                 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2054                     // If matching type found save effect descriptor. If the session is
2055                     // 0 and the effect is not auxiliary, continue enumeration in case
2056                     // an auxiliary version of this effect type is available
2057                     found = true;
2058                     d = desc;
2059                     if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
2060                             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2061                         break;
2062                     }
2063                 }
2064             }
2065             if (!found) {
2066                 lStatus = BAD_VALUE;
2067                 ALOGW("createEffect() effect not found");
2068                 goto Exit;
2069             }
2070             // For same effect type, chose auxiliary version over insert version if
2071             // connect to output mix (Compliance to OpenSL ES)
2072             if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
2073                     (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
2074                 desc = d;
2075             }
2076         }
2077 
2078         // Do not allow auxiliary effects on a session different from 0 (output mix)
2079         if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
2080              (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2081             lStatus = INVALID_OPERATION;
2082             goto Exit;
2083         }
2084 
2085         // check recording permission for visualizer
2086         if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
2087             !recordingAllowed()) {
2088             lStatus = PERMISSION_DENIED;
2089             goto Exit;
2090         }
2091 
2092         // return effect descriptor
2093         *pDesc = desc;
2094 
2095         // If output is not specified try to find a matching audio session ID in one of the
2096         // output threads.
2097         // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2098         // because of code checking output when entering the function.
2099         // Note: io is never 0 when creating an effect on an input
2100         if (io == 0) {
2101             // look for the thread where the specified audio session is present
2102             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2103                 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2104                     io = mPlaybackThreads.keyAt(i);
2105                     break;
2106                 }
2107             }
2108             if (io == 0) {
2109                 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2110                     if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2111                         io = mRecordThreads.keyAt(i);
2112                         break;
2113                     }
2114                 }
2115             }
2116             // If no output thread contains the requested session ID, default to
2117             // first output. The effect chain will be moved to the correct output
2118             // thread when a track with the same session ID is created
2119             if (io == 0 && mPlaybackThreads.size()) {
2120                 io = mPlaybackThreads.keyAt(0);
2121             }
2122             ALOGV("createEffect() got io %d for effect %s", io, desc.name);
2123         }
2124         ThreadBase *thread = checkRecordThread_l(io);
2125         if (thread == NULL) {
2126             thread = checkPlaybackThread_l(io);
2127             if (thread == NULL) {
2128                 ALOGE("createEffect() unknown output thread");
2129                 lStatus = BAD_VALUE;
2130                 goto Exit;
2131             }
2132         }
2133 
2134         sp<Client> client = registerPid_l(pid);
2135 
2136         // create effect on selected output thread
2137         handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2138                 &desc, enabled, &lStatus);
2139         if (handle != 0 && id != NULL) {
2140             *id = handle->id();
2141         }
2142     }
2143 
2144 Exit:
2145     if (status != NULL) {
2146         *status = lStatus;
2147     }
2148     return handle;
2149 }
2150 
moveEffects(int sessionId,audio_io_handle_t srcOutput,audio_io_handle_t dstOutput)2151 status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2152         audio_io_handle_t dstOutput)
2153 {
2154     ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
2155             sessionId, srcOutput, dstOutput);
2156     Mutex::Autolock _l(mLock);
2157     if (srcOutput == dstOutput) {
2158         ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
2159         return NO_ERROR;
2160     }
2161     PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2162     if (srcThread == NULL) {
2163         ALOGW("moveEffects() bad srcOutput %d", srcOutput);
2164         return BAD_VALUE;
2165     }
2166     PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2167     if (dstThread == NULL) {
2168         ALOGW("moveEffects() bad dstOutput %d", dstOutput);
2169         return BAD_VALUE;
2170     }
2171 
2172     Mutex::Autolock _dl(dstThread->mLock);
2173     Mutex::Autolock _sl(srcThread->mLock);
2174     moveEffectChain_l(sessionId, srcThread, dstThread, false);
2175 
2176     return NO_ERROR;
2177 }
2178 
2179 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
moveEffectChain_l(int sessionId,AudioFlinger::PlaybackThread * srcThread,AudioFlinger::PlaybackThread * dstThread,bool reRegister)2180 status_t AudioFlinger::moveEffectChain_l(int sessionId,
2181                                    AudioFlinger::PlaybackThread *srcThread,
2182                                    AudioFlinger::PlaybackThread *dstThread,
2183                                    bool reRegister)
2184 {
2185     ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
2186             sessionId, srcThread, dstThread);
2187 
2188     sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
2189     if (chain == 0) {
2190         ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
2191                 sessionId, srcThread);
2192         return INVALID_OPERATION;
2193     }
2194 
2195     // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
2196     // so that a new chain is created with correct parameters when first effect is added. This is
2197     // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
2198     // removed.
2199     srcThread->removeEffectChain_l(chain);
2200 
2201     // transfer all effects one by one so that new effect chain is created on new thread with
2202     // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
2203     audio_io_handle_t dstOutput = dstThread->id();
2204     sp<EffectChain> dstChain;
2205     uint32_t strategy = 0; // prevent compiler warning
2206     sp<EffectModule> effect = chain->getEffectFromId_l(0);
2207     while (effect != 0) {
2208         srcThread->removeEffect_l(effect);
2209         dstThread->addEffect_l(effect);
2210         // removeEffect_l() has stopped the effect if it was active so it must be restarted
2211         if (effect->state() == EffectModule::ACTIVE ||
2212                 effect->state() == EffectModule::STOPPING) {
2213             effect->start();
2214         }
2215         // if the move request is not received from audio policy manager, the effect must be
2216         // re-registered with the new strategy and output
2217         if (dstChain == 0) {
2218             dstChain = effect->chain().promote();
2219             if (dstChain == 0) {
2220                 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
2221                 srcThread->addEffect_l(effect);
2222                 return NO_INIT;
2223             }
2224             strategy = dstChain->strategy();
2225         }
2226         if (reRegister) {
2227             AudioSystem::unregisterEffect(effect->id());
2228             AudioSystem::registerEffect(&effect->desc(),
2229                                         dstOutput,
2230                                         strategy,
2231                                         sessionId,
2232                                         effect->id());
2233         }
2234         effect = chain->getEffectFromId_l(0);
2235     }
2236 
2237     return NO_ERROR;
2238 }
2239 
2240 struct Entry {
2241 #define MAX_NAME 32     // %Y%m%d%H%M%S_%d.wav
2242     char mName[MAX_NAME];
2243 };
2244 
comparEntry(const void * p1,const void * p2)2245 int comparEntry(const void *p1, const void *p2)
2246 {
2247     return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName);
2248 }
2249 
2250 #ifdef TEE_SINK
dumpTee(int fd,const sp<NBAIO_Source> & source,audio_io_handle_t id)2251 void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
2252 {
2253     NBAIO_Source *teeSource = source.get();
2254     if (teeSource != NULL) {
2255         // .wav rotation
2256         // There is a benign race condition if 2 threads call this simultaneously.
2257         // They would both traverse the directory, but the result would simply be
2258         // failures at unlink() which are ignored.  It's also unlikely since
2259         // normally dumpsys is only done by bugreport or from the command line.
2260         char teePath[32+256];
2261         strcpy(teePath, "/data/misc/media");
2262         size_t teePathLen = strlen(teePath);
2263         DIR *dir = opendir(teePath);
2264         teePath[teePathLen++] = '/';
2265         if (dir != NULL) {
2266 #define MAX_SORT 20 // number of entries to sort
2267 #define MAX_KEEP 10 // number of entries to keep
2268             struct Entry entries[MAX_SORT];
2269             size_t entryCount = 0;
2270             while (entryCount < MAX_SORT) {
2271                 struct dirent de;
2272                 struct dirent *result = NULL;
2273                 int rc = readdir_r(dir, &de, &result);
2274                 if (rc != 0) {
2275                     ALOGW("readdir_r failed %d", rc);
2276                     break;
2277                 }
2278                 if (result == NULL) {
2279                     break;
2280                 }
2281                 if (result != &de) {
2282                     ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2283                     break;
2284                 }
2285                 // ignore non .wav file entries
2286                 size_t nameLen = strlen(de.d_name);
2287                 if (nameLen <= 4 || nameLen >= MAX_NAME ||
2288                         strcmp(&de.d_name[nameLen - 4], ".wav")) {
2289                     continue;
2290                 }
2291                 strcpy(entries[entryCount++].mName, de.d_name);
2292             }
2293             (void) closedir(dir);
2294             if (entryCount > MAX_KEEP) {
2295                 qsort(entries, entryCount, sizeof(Entry), comparEntry);
2296                 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) {
2297                     strcpy(&teePath[teePathLen], entries[i].mName);
2298                     (void) unlink(teePath);
2299                 }
2300             }
2301         } else {
2302             if (fd >= 0) {
2303                 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
2304             }
2305         }
2306         char teeTime[16];
2307         struct timeval tv;
2308         gettimeofday(&tv, NULL);
2309         struct tm tm;
2310         localtime_r(&tv.tv_sec, &tm);
2311         strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2312         snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2313         // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2314         int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
2315         if (teeFd >= 0) {
2316             char wavHeader[44];
2317             memcpy(wavHeader,
2318                 "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",
2319                 sizeof(wavHeader));
2320             NBAIO_Format format = teeSource->format();
2321             unsigned channelCount = Format_channelCount(format);
2322             ALOG_ASSERT(channelCount <= FCC_2);
2323             uint32_t sampleRate = Format_sampleRate(format);
2324             wavHeader[22] = channelCount;       // number of channels
2325             wavHeader[24] = sampleRate;         // sample rate
2326             wavHeader[25] = sampleRate >> 8;
2327             wavHeader[32] = channelCount * 2;   // block alignment
2328             write(teeFd, wavHeader, sizeof(wavHeader));
2329             size_t total = 0;
2330             bool firstRead = true;
2331             for (;;) {
2332 #define TEE_SINK_READ 1024
2333                 short buffer[TEE_SINK_READ * FCC_2];
2334                 size_t count = TEE_SINK_READ;
2335                 ssize_t actual = teeSource->read(buffer, count,
2336                         AudioBufferProvider::kInvalidPTS);
2337                 bool wasFirstRead = firstRead;
2338                 firstRead = false;
2339                 if (actual <= 0) {
2340                     if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2341                         continue;
2342                     }
2343                     break;
2344                 }
2345                 ALOG_ASSERT(actual <= (ssize_t)count);
2346                 write(teeFd, buffer, actual * channelCount * sizeof(short));
2347                 total += actual;
2348             }
2349             lseek(teeFd, (off_t) 4, SEEK_SET);
2350             uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
2351             write(teeFd, &temp, sizeof(temp));
2352             lseek(teeFd, (off_t) 40, SEEK_SET);
2353             temp =  total * channelCount * sizeof(short);
2354             write(teeFd, &temp, sizeof(temp));
2355             close(teeFd);
2356             if (fd >= 0) {
2357                 fdprintf(fd, "tee copied to %s\n", teePath);
2358             }
2359         } else {
2360             if (fd >= 0) {
2361                 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
2362             }
2363         }
2364     }
2365 }
2366 #endif
2367 
2368 // ----------------------------------------------------------------------------
2369 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)2370 status_t AudioFlinger::onTransact(
2371         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2372 {
2373     return BnAudioFlinger::onTransact(code, data, reply, flags);
2374 }
2375 
2376 }; // namespace android
2377