1 /*
2 **
3 ** Copyright 2007, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 ** http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18
19 #define LOG_TAG "AudioFlinger"
20 //#define LOG_NDEBUG 0
21
22 #include "Configuration.h"
23 #include <dirent.h>
24 #include <math.h>
25 #include <signal.h>
26 #include <sys/time.h>
27 #include <sys/resource.h>
28
29 #include <binder/IPCThreadState.h>
30 #include <binder/IServiceManager.h>
31 #include <utils/Log.h>
32 #include <utils/Trace.h>
33 #include <binder/Parcel.h>
34 #include <utils/String16.h>
35 #include <utils/threads.h>
36 #include <utils/Atomic.h>
37
38 #include <cutils/bitops.h>
39 #include <cutils/properties.h>
40
41 #include <system/audio.h>
42 #include <hardware/audio.h>
43
44 #include "AudioMixer.h"
45 #include "AudioFlinger.h"
46 #include "ServiceUtilities.h"
47
48 #include <media/EffectsFactoryApi.h>
49 #include <audio_effects/effect_visualizer.h>
50 #include <audio_effects/effect_ns.h>
51 #include <audio_effects/effect_aec.h>
52
53 #include <audio_utils/primitives.h>
54
55 #include <powermanager/PowerManager.h>
56
57 #include <common_time/cc_helper.h>
58
59 #include <media/IMediaLogService.h>
60
61 #include <media/nbaio/Pipe.h>
62 #include <media/nbaio/PipeReader.h>
63 #include <media/AudioParameter.h>
64 #include <private/android_filesystem_config.h>
65
66 // ----------------------------------------------------------------------------
67
68 // Note: the following macro is used for extremely verbose logging message. In
69 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
70 // 0; but one side effect of this is to turn all LOGV's as well. Some messages
71 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
72 // turned on. Do not uncomment the #def below unless you really know what you
73 // are doing and want to see all of the extremely verbose messages.
74 //#define VERY_VERY_VERBOSE_LOGGING
75 #ifdef VERY_VERY_VERBOSE_LOGGING
76 #define ALOGVV ALOGV
77 #else
78 #define ALOGVV(a...) do { } while(0)
79 #endif
80
81 namespace android {
82
83 static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
84 static const char kHardwareLockedString[] = "Hardware lock is taken\n";
85 static const char kClientLockedString[] = "Client lock is taken\n";
86
87
88 nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
89
90 uint32_t AudioFlinger::mScreenState;
91
92 #ifdef TEE_SINK
93 bool AudioFlinger::mTeeSinkInputEnabled = false;
94 bool AudioFlinger::mTeeSinkOutputEnabled = false;
95 bool AudioFlinger::mTeeSinkTrackEnabled = false;
96
97 size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
98 size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
99 size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
100 #endif
101
102 // In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
103 // we define a minimum time during which a global effect is considered enabled.
104 static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
105
106 // ----------------------------------------------------------------------------
107
formatToString(audio_format_t format)108 const char *formatToString(audio_format_t format) {
109 switch (format & AUDIO_FORMAT_MAIN_MASK) {
110 case AUDIO_FORMAT_PCM:
111 switch (format) {
112 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
113 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
114 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
115 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
116 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
117 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
118 default:
119 break;
120 }
121 break;
122 case AUDIO_FORMAT_MP3: return "mp3";
123 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
124 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
125 case AUDIO_FORMAT_AAC: return "aac";
126 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
127 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
128 case AUDIO_FORMAT_VORBIS: return "vorbis";
129 case AUDIO_FORMAT_OPUS: return "opus";
130 case AUDIO_FORMAT_AC3: return "ac-3";
131 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
132 default:
133 break;
134 }
135 return "unknown";
136 }
137
load_audio_interface(const char * if_name,audio_hw_device_t ** dev)138 static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
139 {
140 const hw_module_t *mod;
141 int rc;
142
143 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
144 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
145 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
146 if (rc) {
147 goto out;
148 }
149 rc = audio_hw_device_open(mod, dev);
150 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
151 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
152 if (rc) {
153 goto out;
154 }
155 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
156 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
157 rc = BAD_VALUE;
158 goto out;
159 }
160 return 0;
161
162 out:
163 *dev = NULL;
164 return rc;
165 }
166
167 // ----------------------------------------------------------------------------
168
AudioFlinger()169 AudioFlinger::AudioFlinger()
170 : BnAudioFlinger(),
171 mPrimaryHardwareDev(NULL),
172 mAudioHwDevs(NULL),
173 mHardwareStatus(AUDIO_HW_IDLE),
174 mMasterVolume(1.0f),
175 mMasterMute(false),
176 mNextUniqueId(1),
177 mMode(AUDIO_MODE_INVALID),
178 mBtNrecIsOff(false),
179 mIsLowRamDevice(true),
180 mIsDeviceTypeKnown(false),
181 mGlobalEffectEnableTime(0),
182 mPrimaryOutputSampleRate(0)
183 {
184 getpid_cached = getpid();
185 char value[PROPERTY_VALUE_MAX];
186 bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
187 if (doLog) {
188 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters", MemoryHeapBase::READ_ONLY);
189 }
190
191 #ifdef TEE_SINK
192 (void) property_get("ro.debuggable", value, "0");
193 int debuggable = atoi(value);
194 int teeEnabled = 0;
195 if (debuggable) {
196 (void) property_get("af.tee", value, "0");
197 teeEnabled = atoi(value);
198 }
199 // FIXME symbolic constants here
200 if (teeEnabled & 1) {
201 mTeeSinkInputEnabled = true;
202 }
203 if (teeEnabled & 2) {
204 mTeeSinkOutputEnabled = true;
205 }
206 if (teeEnabled & 4) {
207 mTeeSinkTrackEnabled = true;
208 }
209 #endif
210 }
211
onFirstRef()212 void AudioFlinger::onFirstRef()
213 {
214 int rc = 0;
215
216 Mutex::Autolock _l(mLock);
217
218 /* TODO: move all this work into an Init() function */
219 char val_str[PROPERTY_VALUE_MAX] = { 0 };
220 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
221 uint32_t int_val;
222 if (1 == sscanf(val_str, "%u", &int_val)) {
223 mStandbyTimeInNsecs = milliseconds(int_val);
224 ALOGI("Using %u mSec as standby time.", int_val);
225 } else {
226 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
227 ALOGI("Using default %u mSec as standby time.",
228 (uint32_t)(mStandbyTimeInNsecs / 1000000));
229 }
230 }
231
232 mPatchPanel = new PatchPanel(this);
233
234 mMode = AUDIO_MODE_NORMAL;
235 }
236
~AudioFlinger()237 AudioFlinger::~AudioFlinger()
238 {
239 while (!mRecordThreads.isEmpty()) {
240 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
241 closeInput_nonvirtual(mRecordThreads.keyAt(0));
242 }
243 while (!mPlaybackThreads.isEmpty()) {
244 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
245 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
246 }
247
248 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
249 // no mHardwareLock needed, as there are no other references to this
250 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
251 delete mAudioHwDevs.valueAt(i);
252 }
253
254 // Tell media.log service about any old writers that still need to be unregistered
255 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
256 if (binder != 0) {
257 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
258 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
259 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
260 mUnregisteredWriters.pop();
261 mediaLogService->unregisterWriter(iMemory);
262 }
263 }
264
265 }
266
267 static const char * const audio_interfaces[] = {
268 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
269 AUDIO_HARDWARE_MODULE_ID_A2DP,
270 AUDIO_HARDWARE_MODULE_ID_USB,
271 };
272 #define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
273
findSuitableHwDev_l(audio_module_handle_t module,audio_devices_t devices)274 AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
275 audio_module_handle_t module,
276 audio_devices_t devices)
277 {
278 // if module is 0, the request comes from an old policy manager and we should load
279 // well known modules
280 if (module == 0) {
281 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283 loadHwModule_l(audio_interfaces[i]);
284 }
285 // then try to find a module supporting the requested device.
286 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
287 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
288 audio_hw_device_t *dev = audioHwDevice->hwDevice();
289 if ((dev->get_supported_devices != NULL) &&
290 (dev->get_supported_devices(dev) & devices) == devices)
291 return audioHwDevice;
292 }
293 } else {
294 // check a match for the requested module handle
295 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
296 if (audioHwDevice != NULL) {
297 return audioHwDevice;
298 }
299 }
300
301 return NULL;
302 }
303
dumpClients(int fd,const Vector<String16> & args __unused)304 void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
305 {
306 const size_t SIZE = 256;
307 char buffer[SIZE];
308 String8 result;
309
310 result.append("Clients:\n");
311 for (size_t i = 0; i < mClients.size(); ++i) {
312 sp<Client> client = mClients.valueAt(i).promote();
313 if (client != 0) {
314 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
315 result.append(buffer);
316 }
317 }
318
319 result.append("Notification Clients:\n");
320 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
321 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
322 result.append(buffer);
323 }
324
325 result.append("Global session refs:\n");
326 result.append(" session pid count\n");
327 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
328 AudioSessionRef *r = mAudioSessionRefs[i];
329 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
330 result.append(buffer);
331 }
332 write(fd, result.string(), result.size());
333 }
334
335
dumpInternals(int fd,const Vector<String16> & args __unused)336 void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
337 {
338 const size_t SIZE = 256;
339 char buffer[SIZE];
340 String8 result;
341 hardware_call_state hardwareStatus = mHardwareStatus;
342
343 snprintf(buffer, SIZE, "Hardware status: %d\n"
344 "Standby Time mSec: %u\n",
345 hardwareStatus,
346 (uint32_t)(mStandbyTimeInNsecs / 1000000));
347 result.append(buffer);
348 write(fd, result.string(), result.size());
349 }
350
dumpPermissionDenial(int fd,const Vector<String16> & args __unused)351 void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
352 {
353 const size_t SIZE = 256;
354 char buffer[SIZE];
355 String8 result;
356 snprintf(buffer, SIZE, "Permission Denial: "
357 "can't dump AudioFlinger from pid=%d, uid=%d\n",
358 IPCThreadState::self()->getCallingPid(),
359 IPCThreadState::self()->getCallingUid());
360 result.append(buffer);
361 write(fd, result.string(), result.size());
362 }
363
dumpTryLock(Mutex & mutex)364 bool AudioFlinger::dumpTryLock(Mutex& mutex)
365 {
366 bool locked = false;
367 for (int i = 0; i < kDumpLockRetries; ++i) {
368 if (mutex.tryLock() == NO_ERROR) {
369 locked = true;
370 break;
371 }
372 usleep(kDumpLockSleepUs);
373 }
374 return locked;
375 }
376
dump(int fd,const Vector<String16> & args)377 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
378 {
379 if (!dumpAllowed()) {
380 dumpPermissionDenial(fd, args);
381 } else {
382 // get state of hardware lock
383 bool hardwareLocked = dumpTryLock(mHardwareLock);
384 if (!hardwareLocked) {
385 String8 result(kHardwareLockedString);
386 write(fd, result.string(), result.size());
387 } else {
388 mHardwareLock.unlock();
389 }
390
391 bool locked = dumpTryLock(mLock);
392
393 // failed to lock - AudioFlinger is probably deadlocked
394 if (!locked) {
395 String8 result(kDeadlockedString);
396 write(fd, result.string(), result.size());
397 }
398
399 bool clientLocked = dumpTryLock(mClientLock);
400 if (!clientLocked) {
401 String8 result(kClientLockedString);
402 write(fd, result.string(), result.size());
403 }
404 dumpClients(fd, args);
405 if (clientLocked) {
406 mClientLock.unlock();
407 }
408
409 dumpInternals(fd, args);
410
411 // dump playback threads
412 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
413 mPlaybackThreads.valueAt(i)->dump(fd, args);
414 }
415
416 // dump record threads
417 for (size_t i = 0; i < mRecordThreads.size(); i++) {
418 mRecordThreads.valueAt(i)->dump(fd, args);
419 }
420
421 // dump orphan effect chains
422 if (mOrphanEffectChains.size() != 0) {
423 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
424 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
425 mOrphanEffectChains.valueAt(i)->dump(fd, args);
426 }
427 }
428 // dump all hardware devs
429 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
430 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
431 dev->dump(dev, fd);
432 }
433
434 #ifdef TEE_SINK
435 // dump the serially shared record tee sink
436 if (mRecordTeeSource != 0) {
437 dumpTee(fd, mRecordTeeSource);
438 }
439 #endif
440
441 if (locked) {
442 mLock.unlock();
443 }
444
445 // append a copy of media.log here by forwarding fd to it, but don't attempt
446 // to lookup the service if it's not running, as it will block for a second
447 if (mLogMemoryDealer != 0) {
448 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
449 if (binder != 0) {
450 dprintf(fd, "\nmedia.log:\n");
451 Vector<String16> args;
452 binder->dump(fd, args);
453 }
454 }
455 }
456 return NO_ERROR;
457 }
458
registerPid(pid_t pid)459 sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
460 {
461 Mutex::Autolock _cl(mClientLock);
462 // If pid is already in the mClients wp<> map, then use that entry
463 // (for which promote() is always != 0), otherwise create a new entry and Client.
464 sp<Client> client = mClients.valueFor(pid).promote();
465 if (client == 0) {
466 client = new Client(this, pid);
467 mClients.add(pid, client);
468 }
469
470 return client;
471 }
472
newWriter_l(size_t size,const char * name)473 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
474 {
475 // If there is no memory allocated for logs, return a dummy writer that does nothing
476 if (mLogMemoryDealer == 0) {
477 return new NBLog::Writer();
478 }
479 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
480 // Similarly if we can't contact the media.log service, also return a dummy writer
481 if (binder == 0) {
482 return new NBLog::Writer();
483 }
484 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
485 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
486 // If allocation fails, consult the vector of previously unregistered writers
487 // and garbage-collect one or more them until an allocation succeeds
488 if (shared == 0) {
489 Mutex::Autolock _l(mUnregisteredWritersLock);
490 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
491 {
492 // Pick the oldest stale writer to garbage-collect
493 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
494 mUnregisteredWriters.removeAt(0);
495 mediaLogService->unregisterWriter(iMemory);
496 // Now the media.log remote reference to IMemory is gone. When our last local
497 // reference to IMemory also drops to zero at end of this block,
498 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
499 }
500 // Re-attempt the allocation
501 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
502 if (shared != 0) {
503 goto success;
504 }
505 }
506 // Even after garbage-collecting all old writers, there is still not enough memory,
507 // so return a dummy writer
508 return new NBLog::Writer();
509 }
510 success:
511 mediaLogService->registerWriter(shared, size, name);
512 return new NBLog::Writer(size, shared);
513 }
514
unregisterWriter(const sp<NBLog::Writer> & writer)515 void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
516 {
517 if (writer == 0) {
518 return;
519 }
520 sp<IMemory> iMemory(writer->getIMemory());
521 if (iMemory == 0) {
522 return;
523 }
524 // Rather than removing the writer immediately, append it to a queue of old writers to
525 // be garbage-collected later. This allows us to continue to view old logs for a while.
526 Mutex::Autolock _l(mUnregisteredWritersLock);
527 mUnregisteredWriters.push(writer);
528 }
529
530 // IAudioFlinger interface
531
532
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,int clientUid,status_t * status)533 sp<IAudioTrack> AudioFlinger::createTrack(
534 audio_stream_type_t streamType,
535 uint32_t sampleRate,
536 audio_format_t format,
537 audio_channel_mask_t channelMask,
538 size_t *frameCount,
539 IAudioFlinger::track_flags_t *flags,
540 const sp<IMemory>& sharedBuffer,
541 audio_io_handle_t output,
542 pid_t tid,
543 int *sessionId,
544 int clientUid,
545 status_t *status)
546 {
547 sp<PlaybackThread::Track> track;
548 sp<TrackHandle> trackHandle;
549 sp<Client> client;
550 status_t lStatus;
551 int lSessionId;
552
553 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
554 // but if someone uses binder directly they could bypass that and cause us to crash
555 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
556 ALOGE("createTrack() invalid stream type %d", streamType);
557 lStatus = BAD_VALUE;
558 goto Exit;
559 }
560
561 // further sample rate checks are performed by createTrack_l() depending on the thread type
562 if (sampleRate == 0) {
563 ALOGE("createTrack() invalid sample rate %u", sampleRate);
564 lStatus = BAD_VALUE;
565 goto Exit;
566 }
567
568 // further channel mask checks are performed by createTrack_l() depending on the thread type
569 if (!audio_is_output_channel(channelMask)) {
570 ALOGE("createTrack() invalid channel mask %#x", channelMask);
571 lStatus = BAD_VALUE;
572 goto Exit;
573 }
574
575 // further format checks are performed by createTrack_l() depending on the thread type
576 if (!audio_is_valid_format(format)) {
577 ALOGE("createTrack() invalid format %#x", format);
578 lStatus = BAD_VALUE;
579 goto Exit;
580 }
581
582 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
583 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
584 lStatus = BAD_VALUE;
585 goto Exit;
586 }
587
588 {
589 Mutex::Autolock _l(mLock);
590 PlaybackThread *thread = checkPlaybackThread_l(output);
591 if (thread == NULL) {
592 ALOGE("no playback thread found for output handle %d", output);
593 lStatus = BAD_VALUE;
594 goto Exit;
595 }
596
597 pid_t pid = IPCThreadState::self()->getCallingPid();
598 client = registerPid(pid);
599
600 PlaybackThread *effectThread = NULL;
601 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
602 lSessionId = *sessionId;
603 // check if an effect chain with the same session ID is present on another
604 // output thread and move it here.
605 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
606 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
607 if (mPlaybackThreads.keyAt(i) != output) {
608 uint32_t sessions = t->hasAudioSession(lSessionId);
609 if (sessions & PlaybackThread::EFFECT_SESSION) {
610 effectThread = t.get();
611 break;
612 }
613 }
614 }
615 } else {
616 // if no audio session id is provided, create one here
617 lSessionId = nextUniqueId();
618 if (sessionId != NULL) {
619 *sessionId = lSessionId;
620 }
621 }
622 ALOGV("createTrack() lSessionId: %d", lSessionId);
623
624 track = thread->createTrack_l(client, streamType, sampleRate, format,
625 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
626 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
627 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
628
629 // move effect chain to this output thread if an effect on same session was waiting
630 // for a track to be created
631 if (lStatus == NO_ERROR && effectThread != NULL) {
632 // no risk of deadlock because AudioFlinger::mLock is held
633 Mutex::Autolock _dl(thread->mLock);
634 Mutex::Autolock _sl(effectThread->mLock);
635 moveEffectChain_l(lSessionId, effectThread, thread, true);
636 }
637
638 // Look for sync events awaiting for a session to be used.
639 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
640 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
641 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
642 if (lStatus == NO_ERROR) {
643 (void) track->setSyncEvent(mPendingSyncEvents[i]);
644 } else {
645 mPendingSyncEvents[i]->cancel();
646 }
647 mPendingSyncEvents.removeAt(i);
648 i--;
649 }
650 }
651 }
652
653 }
654
655 if (lStatus != NO_ERROR) {
656 // remove local strong reference to Client before deleting the Track so that the
657 // Client destructor is called by the TrackBase destructor with mClientLock held
658 // Don't hold mClientLock when releasing the reference on the track as the
659 // destructor will acquire it.
660 {
661 Mutex::Autolock _cl(mClientLock);
662 client.clear();
663 }
664 track.clear();
665 goto Exit;
666 }
667
668 // return handle to client
669 trackHandle = new TrackHandle(track);
670
671 Exit:
672 *status = lStatus;
673 return trackHandle;
674 }
675
sampleRate(audio_io_handle_t output) const676 uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
677 {
678 Mutex::Autolock _l(mLock);
679 PlaybackThread *thread = checkPlaybackThread_l(output);
680 if (thread == NULL) {
681 ALOGW("sampleRate() unknown thread %d", output);
682 return 0;
683 }
684 return thread->sampleRate();
685 }
686
format(audio_io_handle_t output) const687 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
688 {
689 Mutex::Autolock _l(mLock);
690 PlaybackThread *thread = checkPlaybackThread_l(output);
691 if (thread == NULL) {
692 ALOGW("format() unknown thread %d", output);
693 return AUDIO_FORMAT_INVALID;
694 }
695 return thread->format();
696 }
697
frameCount(audio_io_handle_t output) const698 size_t AudioFlinger::frameCount(audio_io_handle_t output) const
699 {
700 Mutex::Autolock _l(mLock);
701 PlaybackThread *thread = checkPlaybackThread_l(output);
702 if (thread == NULL) {
703 ALOGW("frameCount() unknown thread %d", output);
704 return 0;
705 }
706 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
707 // should examine all callers and fix them to handle smaller counts
708 return thread->frameCount();
709 }
710
latency(audio_io_handle_t output) const711 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
712 {
713 Mutex::Autolock _l(mLock);
714 PlaybackThread *thread = checkPlaybackThread_l(output);
715 if (thread == NULL) {
716 ALOGW("latency(): no playback thread found for output handle %d", output);
717 return 0;
718 }
719 return thread->latency();
720 }
721
setMasterVolume(float value)722 status_t AudioFlinger::setMasterVolume(float value)
723 {
724 status_t ret = initCheck();
725 if (ret != NO_ERROR) {
726 return ret;
727 }
728
729 // check calling permissions
730 if (!settingsAllowed()) {
731 return PERMISSION_DENIED;
732 }
733
734 Mutex::Autolock _l(mLock);
735 mMasterVolume = value;
736
737 // Set master volume in the HALs which support it.
738 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
739 AutoMutex lock(mHardwareLock);
740 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
741
742 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
743 if (dev->canSetMasterVolume()) {
744 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
745 }
746 mHardwareStatus = AUDIO_HW_IDLE;
747 }
748
749 // Now set the master volume in each playback thread. Playback threads
750 // assigned to HALs which do not have master volume support will apply
751 // master volume during the mix operation. Threads with HALs which do
752 // support master volume will simply ignore the setting.
753 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
754 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
755
756 return NO_ERROR;
757 }
758
setMode(audio_mode_t mode)759 status_t AudioFlinger::setMode(audio_mode_t mode)
760 {
761 status_t ret = initCheck();
762 if (ret != NO_ERROR) {
763 return ret;
764 }
765
766 // check calling permissions
767 if (!settingsAllowed()) {
768 return PERMISSION_DENIED;
769 }
770 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
771 ALOGW("Illegal value: setMode(%d)", mode);
772 return BAD_VALUE;
773 }
774
775 { // scope for the lock
776 AutoMutex lock(mHardwareLock);
777 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
778 mHardwareStatus = AUDIO_HW_SET_MODE;
779 ret = dev->set_mode(dev, mode);
780 mHardwareStatus = AUDIO_HW_IDLE;
781 }
782
783 if (NO_ERROR == ret) {
784 Mutex::Autolock _l(mLock);
785 mMode = mode;
786 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
787 mPlaybackThreads.valueAt(i)->setMode(mode);
788 }
789
790 return ret;
791 }
792
setMicMute(bool state)793 status_t AudioFlinger::setMicMute(bool state)
794 {
795 status_t ret = initCheck();
796 if (ret != NO_ERROR) {
797 return ret;
798 }
799
800 // check calling permissions
801 if (!settingsAllowed()) {
802 return PERMISSION_DENIED;
803 }
804
805 AutoMutex lock(mHardwareLock);
806 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
807 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
808 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
809 status_t result = dev->set_mic_mute(dev, state);
810 if (result != NO_ERROR) {
811 ret = result;
812 }
813 }
814 mHardwareStatus = AUDIO_HW_IDLE;
815 return ret;
816 }
817
getMicMute() const818 bool AudioFlinger::getMicMute() const
819 {
820 status_t ret = initCheck();
821 if (ret != NO_ERROR) {
822 return false;
823 }
824
825 bool state = AUDIO_MODE_INVALID;
826 AutoMutex lock(mHardwareLock);
827 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
828 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
829 dev->get_mic_mute(dev, &state);
830 mHardwareStatus = AUDIO_HW_IDLE;
831 return state;
832 }
833
setMasterMute(bool muted)834 status_t AudioFlinger::setMasterMute(bool muted)
835 {
836 status_t ret = initCheck();
837 if (ret != NO_ERROR) {
838 return ret;
839 }
840
841 // check calling permissions
842 if (!settingsAllowed()) {
843 return PERMISSION_DENIED;
844 }
845
846 Mutex::Autolock _l(mLock);
847 mMasterMute = muted;
848
849 // Set master mute in the HALs which support it.
850 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
851 AutoMutex lock(mHardwareLock);
852 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
853
854 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
855 if (dev->canSetMasterMute()) {
856 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
857 }
858 mHardwareStatus = AUDIO_HW_IDLE;
859 }
860
861 // Now set the master mute in each playback thread. Playback threads
862 // assigned to HALs which do not have master mute support will apply master
863 // mute during the mix operation. Threads with HALs which do support master
864 // mute will simply ignore the setting.
865 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
866 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
867
868 return NO_ERROR;
869 }
870
masterVolume() const871 float AudioFlinger::masterVolume() const
872 {
873 Mutex::Autolock _l(mLock);
874 return masterVolume_l();
875 }
876
masterMute() const877 bool AudioFlinger::masterMute() const
878 {
879 Mutex::Autolock _l(mLock);
880 return masterMute_l();
881 }
882
masterVolume_l() const883 float AudioFlinger::masterVolume_l() const
884 {
885 return mMasterVolume;
886 }
887
masterMute_l() const888 bool AudioFlinger::masterMute_l() const
889 {
890 return mMasterMute;
891 }
892
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)893 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
894 audio_io_handle_t output)
895 {
896 // check calling permissions
897 if (!settingsAllowed()) {
898 return PERMISSION_DENIED;
899 }
900
901 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
902 ALOGE("setStreamVolume() invalid stream %d", stream);
903 return BAD_VALUE;
904 }
905
906 AutoMutex lock(mLock);
907 PlaybackThread *thread = NULL;
908 if (output != AUDIO_IO_HANDLE_NONE) {
909 thread = checkPlaybackThread_l(output);
910 if (thread == NULL) {
911 return BAD_VALUE;
912 }
913 }
914
915 mStreamTypes[stream].volume = value;
916
917 if (thread == NULL) {
918 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
919 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
920 }
921 } else {
922 thread->setStreamVolume(stream, value);
923 }
924
925 return NO_ERROR;
926 }
927
setStreamMute(audio_stream_type_t stream,bool muted)928 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
929 {
930 // check calling permissions
931 if (!settingsAllowed()) {
932 return PERMISSION_DENIED;
933 }
934
935 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
936 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
937 ALOGE("setStreamMute() invalid stream %d", stream);
938 return BAD_VALUE;
939 }
940
941 AutoMutex lock(mLock);
942 mStreamTypes[stream].mute = muted;
943 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
944 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
945
946 return NO_ERROR;
947 }
948
streamVolume(audio_stream_type_t stream,audio_io_handle_t output) const949 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
950 {
951 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
952 return 0.0f;
953 }
954
955 AutoMutex lock(mLock);
956 float volume;
957 if (output != AUDIO_IO_HANDLE_NONE) {
958 PlaybackThread *thread = checkPlaybackThread_l(output);
959 if (thread == NULL) {
960 return 0.0f;
961 }
962 volume = thread->streamVolume(stream);
963 } else {
964 volume = streamVolume_l(stream);
965 }
966
967 return volume;
968 }
969
streamMute(audio_stream_type_t stream) const970 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
971 {
972 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
973 return true;
974 }
975
976 AutoMutex lock(mLock);
977 return streamMute_l(stream);
978 }
979
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)980 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
981 {
982 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
983 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
984
985 // check calling permissions
986 if (!settingsAllowed()) {
987 return PERMISSION_DENIED;
988 }
989
990 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
991 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
992 Mutex::Autolock _l(mLock);
993 status_t final_result = NO_ERROR;
994 {
995 AutoMutex lock(mHardwareLock);
996 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
997 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
998 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
999 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1000 final_result = result ?: final_result;
1001 }
1002 mHardwareStatus = AUDIO_HW_IDLE;
1003 }
1004 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1005 AudioParameter param = AudioParameter(keyValuePairs);
1006 String8 value;
1007 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
1008 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1009 if (mBtNrecIsOff != btNrecIsOff) {
1010 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1011 sp<RecordThread> thread = mRecordThreads.valueAt(i);
1012 audio_devices_t device = thread->inDevice();
1013 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1014 // collect all of the thread's session IDs
1015 KeyedVector<int, bool> ids = thread->sessionIds();
1016 // suspend effects associated with those session IDs
1017 for (size_t j = 0; j < ids.size(); ++j) {
1018 int sessionId = ids.keyAt(j);
1019 thread->setEffectSuspended(FX_IID_AEC,
1020 suspend,
1021 sessionId);
1022 thread->setEffectSuspended(FX_IID_NS,
1023 suspend,
1024 sessionId);
1025 }
1026 }
1027 mBtNrecIsOff = btNrecIsOff;
1028 }
1029 }
1030 String8 screenState;
1031 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1032 bool isOff = screenState == "off";
1033 if (isOff != (AudioFlinger::mScreenState & 1)) {
1034 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
1035 }
1036 }
1037 return final_result;
1038 }
1039
1040 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1041 // and the thread is exited once the lock is released
1042 sp<ThreadBase> thread;
1043 {
1044 Mutex::Autolock _l(mLock);
1045 thread = checkPlaybackThread_l(ioHandle);
1046 if (thread == 0) {
1047 thread = checkRecordThread_l(ioHandle);
1048 } else if (thread == primaryPlaybackThread_l()) {
1049 // indicate output device change to all input threads for pre processing
1050 AudioParameter param = AudioParameter(keyValuePairs);
1051 int value;
1052 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1053 (value != 0)) {
1054 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1055 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1056 }
1057 }
1058 }
1059 }
1060 if (thread != 0) {
1061 return thread->setParameters(keyValuePairs);
1062 }
1063 return BAD_VALUE;
1064 }
1065
getParameters(audio_io_handle_t ioHandle,const String8 & keys) const1066 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
1067 {
1068 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1069 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
1070
1071 Mutex::Autolock _l(mLock);
1072
1073 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1074 String8 out_s8;
1075
1076 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1077 char *s;
1078 {
1079 AutoMutex lock(mHardwareLock);
1080 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
1081 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1082 s = dev->get_parameters(dev, keys.string());
1083 mHardwareStatus = AUDIO_HW_IDLE;
1084 }
1085 out_s8 += String8(s ? s : "");
1086 free(s);
1087 }
1088 return out_s8;
1089 }
1090
1091 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1092 if (playbackThread != NULL) {
1093 return playbackThread->getParameters(keys);
1094 }
1095 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1096 if (recordThread != NULL) {
1097 return recordThread->getParameters(keys);
1098 }
1099 return String8("");
1100 }
1101
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask) const1102 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1103 audio_channel_mask_t channelMask) const
1104 {
1105 status_t ret = initCheck();
1106 if (ret != NO_ERROR) {
1107 return 0;
1108 }
1109
1110 AutoMutex lock(mHardwareLock);
1111 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
1112 audio_config_t config;
1113 memset(&config, 0, sizeof(config));
1114 config.sample_rate = sampleRate;
1115 config.channel_mask = channelMask;
1116 config.format = format;
1117
1118 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1119 size_t size = dev->get_input_buffer_size(dev, &config);
1120 mHardwareStatus = AUDIO_HW_IDLE;
1121 return size;
1122 }
1123
getInputFramesLost(audio_io_handle_t ioHandle) const1124 uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
1125 {
1126 Mutex::Autolock _l(mLock);
1127
1128 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1129 if (recordThread != NULL) {
1130 return recordThread->getInputFramesLost();
1131 }
1132 return 0;
1133 }
1134
setVoiceVolume(float value)1135 status_t AudioFlinger::setVoiceVolume(float value)
1136 {
1137 status_t ret = initCheck();
1138 if (ret != NO_ERROR) {
1139 return ret;
1140 }
1141
1142 // check calling permissions
1143 if (!settingsAllowed()) {
1144 return PERMISSION_DENIED;
1145 }
1146
1147 AutoMutex lock(mHardwareLock);
1148 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1149 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1150 ret = dev->set_voice_volume(dev, value);
1151 mHardwareStatus = AUDIO_HW_IDLE;
1152
1153 return ret;
1154 }
1155
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames,audio_io_handle_t output) const1156 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1157 audio_io_handle_t output) const
1158 {
1159 status_t status;
1160
1161 Mutex::Autolock _l(mLock);
1162
1163 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1164 if (playbackThread != NULL) {
1165 return playbackThread->getRenderPosition(halFrames, dspFrames);
1166 }
1167
1168 return BAD_VALUE;
1169 }
1170
registerClient(const sp<IAudioFlingerClient> & client)1171 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1172 {
1173 Mutex::Autolock _l(mLock);
1174 if (client == 0) {
1175 return;
1176 }
1177 bool clientAdded = false;
1178 {
1179 Mutex::Autolock _cl(mClientLock);
1180
1181 pid_t pid = IPCThreadState::self()->getCallingPid();
1182 if (mNotificationClients.indexOfKey(pid) < 0) {
1183 sp<NotificationClient> notificationClient = new NotificationClient(this,
1184 client,
1185 pid);
1186 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1187
1188 mNotificationClients.add(pid, notificationClient);
1189
1190 sp<IBinder> binder = client->asBinder();
1191 binder->linkToDeath(notificationClient);
1192 clientAdded = true;
1193 }
1194 }
1195
1196 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
1197 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
1198 if (clientAdded) {
1199 // the config change is always sent from playback or record threads to avoid deadlock
1200 // with AudioSystem::gLock
1201 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1202 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
1203 }
1204
1205 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1206 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
1207 }
1208 }
1209 }
1210
removeNotificationClient(pid_t pid)1211 void AudioFlinger::removeNotificationClient(pid_t pid)
1212 {
1213 Mutex::Autolock _l(mLock);
1214 {
1215 Mutex::Autolock _cl(mClientLock);
1216 mNotificationClients.removeItem(pid);
1217 }
1218
1219 ALOGV("%d died, releasing its sessions", pid);
1220 size_t num = mAudioSessionRefs.size();
1221 bool removed = false;
1222 for (size_t i = 0; i< num; ) {
1223 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1224 ALOGV(" pid %d @ %d", ref->mPid, i);
1225 if (ref->mPid == pid) {
1226 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1227 mAudioSessionRefs.removeAt(i);
1228 delete ref;
1229 removed = true;
1230 num--;
1231 } else {
1232 i++;
1233 }
1234 }
1235 if (removed) {
1236 purgeStaleEffects_l();
1237 }
1238 }
1239
audioConfigChanged(int event,audio_io_handle_t ioHandle,const void * param2)1240 void AudioFlinger::audioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2)
1241 {
1242 Mutex::Autolock _l(mClientLock);
1243 size_t size = mNotificationClients.size();
1244 for (size_t i = 0; i < size; i++) {
1245 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event,
1246 ioHandle,
1247 param2);
1248 }
1249 }
1250
1251 // removeClient_l() must be called with AudioFlinger::mClientLock held
removeClient_l(pid_t pid)1252 void AudioFlinger::removeClient_l(pid_t pid)
1253 {
1254 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1255 IPCThreadState::self()->getCallingPid());
1256 mClients.removeItem(pid);
1257 }
1258
1259 // getEffectThread_l() must be called with AudioFlinger::mLock held
getEffectThread_l(int sessionId,int EffectId)1260 sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1261 {
1262 sp<PlaybackThread> thread;
1263
1264 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1265 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1266 ALOG_ASSERT(thread == 0);
1267 thread = mPlaybackThreads.valueAt(i);
1268 }
1269 }
1270
1271 return thread;
1272 }
1273
1274
1275
1276 // ----------------------------------------------------------------------------
1277
Client(const sp<AudioFlinger> & audioFlinger,pid_t pid)1278 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1279 : RefBase(),
1280 mAudioFlinger(audioFlinger),
1281 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
1282 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
1283 mPid(pid),
1284 mTimedTrackCount(0)
1285 {
1286 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
1287 }
1288
1289 // Client destructor must be called with AudioFlinger::mClientLock held
~Client()1290 AudioFlinger::Client::~Client()
1291 {
1292 mAudioFlinger->removeClient_l(mPid);
1293 }
1294
heap() const1295 sp<MemoryDealer> AudioFlinger::Client::heap() const
1296 {
1297 return mMemoryDealer;
1298 }
1299
1300 // Reserve one of the limited slots for a timed audio track associated
1301 // with this client
reserveTimedTrack()1302 bool AudioFlinger::Client::reserveTimedTrack()
1303 {
1304 const int kMaxTimedTracksPerClient = 4;
1305
1306 Mutex::Autolock _l(mTimedTrackLock);
1307
1308 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1309 ALOGW("can not create timed track - pid %d has exceeded the limit",
1310 mPid);
1311 return false;
1312 }
1313
1314 mTimedTrackCount++;
1315 return true;
1316 }
1317
1318 // Release a slot for a timed audio track
releaseTimedTrack()1319 void AudioFlinger::Client::releaseTimedTrack()
1320 {
1321 Mutex::Autolock _l(mTimedTrackLock);
1322 mTimedTrackCount--;
1323 }
1324
1325 // ----------------------------------------------------------------------------
1326
NotificationClient(const sp<AudioFlinger> & audioFlinger,const sp<IAudioFlingerClient> & client,pid_t pid)1327 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1328 const sp<IAudioFlingerClient>& client,
1329 pid_t pid)
1330 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
1331 {
1332 }
1333
~NotificationClient()1334 AudioFlinger::NotificationClient::~NotificationClient()
1335 {
1336 }
1337
binderDied(const wp<IBinder> & who __unused)1338 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
1339 {
1340 sp<NotificationClient> keep(this);
1341 mAudioFlinger->removeNotificationClient(mPid);
1342 }
1343
1344
1345 // ----------------------------------------------------------------------------
1346
deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice)1347 static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
1348 return audio_is_remote_submix_device(inDevice);
1349 }
1350
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,size_t * notificationFrames,sp<IMemory> & cblk,sp<IMemory> & buffers,status_t * status)1351 sp<IAudioRecord> AudioFlinger::openRecord(
1352 audio_io_handle_t input,
1353 uint32_t sampleRate,
1354 audio_format_t format,
1355 audio_channel_mask_t channelMask,
1356 size_t *frameCount,
1357 IAudioFlinger::track_flags_t *flags,
1358 pid_t tid,
1359 int *sessionId,
1360 size_t *notificationFrames,
1361 sp<IMemory>& cblk,
1362 sp<IMemory>& buffers,
1363 status_t *status)
1364 {
1365 sp<RecordThread::RecordTrack> recordTrack;
1366 sp<RecordHandle> recordHandle;
1367 sp<Client> client;
1368 status_t lStatus;
1369 int lSessionId;
1370
1371 cblk.clear();
1372 buffers.clear();
1373
1374 // check calling permissions
1375 if (!recordingAllowed()) {
1376 ALOGE("openRecord() permission denied: recording not allowed");
1377 lStatus = PERMISSION_DENIED;
1378 goto Exit;
1379 }
1380
1381 // further sample rate checks are performed by createRecordTrack_l()
1382 if (sampleRate == 0) {
1383 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1384 lStatus = BAD_VALUE;
1385 goto Exit;
1386 }
1387
1388 // we don't yet support anything other than 16-bit PCM
1389 if (!(audio_is_valid_format(format) &&
1390 audio_is_linear_pcm(format) && format == AUDIO_FORMAT_PCM_16_BIT)) {
1391 ALOGE("openRecord() invalid format %#x", format);
1392 lStatus = BAD_VALUE;
1393 goto Exit;
1394 }
1395
1396 // further channel mask checks are performed by createRecordTrack_l()
1397 if (!audio_is_input_channel(channelMask)) {
1398 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1399 lStatus = BAD_VALUE;
1400 goto Exit;
1401 }
1402
1403 {
1404 Mutex::Autolock _l(mLock);
1405 RecordThread *thread = checkRecordThread_l(input);
1406 if (thread == NULL) {
1407 ALOGE("openRecord() checkRecordThread_l failed");
1408 lStatus = BAD_VALUE;
1409 goto Exit;
1410 }
1411
1412 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice())
1413 && !captureAudioOutputAllowed()) {
1414 ALOGE("openRecord() permission denied: capture not allowed");
1415 lStatus = PERMISSION_DENIED;
1416 goto Exit;
1417 }
1418
1419 pid_t pid = IPCThreadState::self()->getCallingPid();
1420 client = registerPid(pid);
1421
1422 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
1423 lSessionId = *sessionId;
1424 } else {
1425 // if no audio session id is provided, create one here
1426 lSessionId = nextUniqueId();
1427 if (sessionId != NULL) {
1428 *sessionId = lSessionId;
1429 }
1430 }
1431 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
1432
1433 // TODO: the uid should be passed in as a parameter to openRecord
1434 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
1435 frameCount, lSessionId, notificationFrames,
1436 IPCThreadState::self()->getCallingUid(),
1437 flags, tid, &lStatus);
1438 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
1439
1440 if (lStatus == NO_ERROR) {
1441 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1442 // session and move it to this thread.
1443 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)lSessionId);
1444 if (chain != 0) {
1445 Mutex::Autolock _l(thread->mLock);
1446 thread->addEffectChain_l(chain);
1447 }
1448 }
1449 }
1450
1451 if (lStatus != NO_ERROR) {
1452 // remove local strong reference to Client before deleting the RecordTrack so that the
1453 // Client destructor is called by the TrackBase destructor with mClientLock held
1454 // Don't hold mClientLock when releasing the reference on the track as the
1455 // destructor will acquire it.
1456 {
1457 Mutex::Autolock _cl(mClientLock);
1458 client.clear();
1459 }
1460 recordTrack.clear();
1461 goto Exit;
1462 }
1463
1464 cblk = recordTrack->getCblk();
1465 buffers = recordTrack->getBuffers();
1466
1467 // return handle to client
1468 recordHandle = new RecordHandle(recordTrack);
1469
1470 Exit:
1471 *status = lStatus;
1472 return recordHandle;
1473 }
1474
1475
1476
1477 // ----------------------------------------------------------------------------
1478
loadHwModule(const char * name)1479 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1480 {
1481 if (name == NULL) {
1482 return 0;
1483 }
1484 if (!settingsAllowed()) {
1485 return 0;
1486 }
1487 Mutex::Autolock _l(mLock);
1488 return loadHwModule_l(name);
1489 }
1490
1491 // loadHwModule_l() must be called with AudioFlinger::mLock held
loadHwModule_l(const char * name)1492 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1493 {
1494 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1495 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1496 ALOGW("loadHwModule() module %s already loaded", name);
1497 return mAudioHwDevs.keyAt(i);
1498 }
1499 }
1500
1501 audio_hw_device_t *dev;
1502
1503 int rc = load_audio_interface(name, &dev);
1504 if (rc) {
1505 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1506 return 0;
1507 }
1508
1509 mHardwareStatus = AUDIO_HW_INIT;
1510 rc = dev->init_check(dev);
1511 mHardwareStatus = AUDIO_HW_IDLE;
1512 if (rc) {
1513 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1514 return 0;
1515 }
1516
1517 // Check and cache this HAL's level of support for master mute and master
1518 // volume. If this is the first HAL opened, and it supports the get
1519 // methods, use the initial values provided by the HAL as the current
1520 // master mute and volume settings.
1521
1522 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1523 { // scope for auto-lock pattern
1524 AutoMutex lock(mHardwareLock);
1525
1526 if (0 == mAudioHwDevs.size()) {
1527 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1528 if (NULL != dev->get_master_volume) {
1529 float mv;
1530 if (OK == dev->get_master_volume(dev, &mv)) {
1531 mMasterVolume = mv;
1532 }
1533 }
1534
1535 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1536 if (NULL != dev->get_master_mute) {
1537 bool mm;
1538 if (OK == dev->get_master_mute(dev, &mm)) {
1539 mMasterMute = mm;
1540 }
1541 }
1542 }
1543
1544 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1545 if ((NULL != dev->set_master_volume) &&
1546 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1547 flags = static_cast<AudioHwDevice::Flags>(flags |
1548 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1549 }
1550
1551 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1552 if ((NULL != dev->set_master_mute) &&
1553 (OK == dev->set_master_mute(dev, mMasterMute))) {
1554 flags = static_cast<AudioHwDevice::Flags>(flags |
1555 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1556 }
1557
1558 mHardwareStatus = AUDIO_HW_IDLE;
1559 }
1560
1561 audio_module_handle_t handle = nextUniqueId();
1562 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
1563
1564 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
1565 name, dev->common.module->name, dev->common.module->id, handle);
1566
1567 return handle;
1568
1569 }
1570
1571 // ----------------------------------------------------------------------------
1572
getPrimaryOutputSamplingRate()1573 uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
1574 {
1575 Mutex::Autolock _l(mLock);
1576 PlaybackThread *thread = primaryPlaybackThread_l();
1577 return thread != NULL ? thread->sampleRate() : 0;
1578 }
1579
getPrimaryOutputFrameCount()1580 size_t AudioFlinger::getPrimaryOutputFrameCount()
1581 {
1582 Mutex::Autolock _l(mLock);
1583 PlaybackThread *thread = primaryPlaybackThread_l();
1584 return thread != NULL ? thread->frameCountHAL() : 0;
1585 }
1586
1587 // ----------------------------------------------------------------------------
1588
setLowRamDevice(bool isLowRamDevice)1589 status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1590 {
1591 uid_t uid = IPCThreadState::self()->getCallingUid();
1592 if (uid != AID_SYSTEM) {
1593 return PERMISSION_DENIED;
1594 }
1595 Mutex::Autolock _l(mLock);
1596 if (mIsDeviceTypeKnown) {
1597 return INVALID_OPERATION;
1598 }
1599 mIsLowRamDevice = isLowRamDevice;
1600 mIsDeviceTypeKnown = true;
1601 return NO_ERROR;
1602 }
1603
getAudioHwSyncForSession(audio_session_t sessionId)1604 audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1605 {
1606 Mutex::Autolock _l(mLock);
1607 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1608 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1609 if ((thread->hasAudioSession(sessionId) & ThreadBase::TRACK_SESSION) != 0) {
1610 // A session can only be on one thread, so exit after first match
1611 String8 reply = thread->getParameters(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC));
1612 AudioParameter param = AudioParameter(reply);
1613 int value;
1614 if (param.getInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value) == NO_ERROR) {
1615 return value;
1616 }
1617 break;
1618 }
1619 }
1620 return AUDIO_HW_SYNC_INVALID;
1621 }
1622
1623 // ----------------------------------------------------------------------------
1624
1625
openOutput_l(audio_module_handle_t module,audio_io_handle_t * output,audio_config_t * config,audio_devices_t devices,const String8 & address,audio_output_flags_t flags)1626 sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
1627 audio_io_handle_t *output,
1628 audio_config_t *config,
1629 audio_devices_t devices,
1630 const String8& address,
1631 audio_output_flags_t flags)
1632 {
1633 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
1634 if (outHwDev == NULL) {
1635 return 0;
1636 }
1637
1638 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
1639 if (*output == AUDIO_IO_HANDLE_NONE) {
1640 *output = nextUniqueId();
1641 }
1642
1643 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1644
1645 audio_stream_out_t *outStream = NULL;
1646
1647 // FOR TESTING ONLY:
1648 // This if statement allows overriding the audio policy settings
1649 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1650 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1651 // Check only for Normal Mixing mode
1652 if (kEnableExtendedPrecision) {
1653 // Specify format (uncomment one below to choose)
1654 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1655 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1656 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1657 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
1658 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
1659 }
1660 if (kEnableExtendedChannels) {
1661 // Specify channel mask (uncomment one below to choose)
1662 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1663 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1664 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1665 }
1666 }
1667
1668 status_t status = hwDevHal->open_output_stream(hwDevHal,
1669 *output,
1670 devices,
1671 flags,
1672 config,
1673 &outStream,
1674 address.string());
1675
1676 mHardwareStatus = AUDIO_HW_IDLE;
1677 ALOGV("openOutput_l() openOutputStream returned output %p, sampleRate %d, Format %#x, "
1678 "channelMask %#x, status %d",
1679 outStream,
1680 config->sample_rate,
1681 config->format,
1682 config->channel_mask,
1683 status);
1684
1685 if (status == NO_ERROR && outStream != NULL) {
1686 AudioStreamOut *outputStream = new AudioStreamOut(outHwDev, outStream, flags);
1687
1688 PlaybackThread *thread;
1689 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1690 thread = new OffloadThread(this, outputStream, *output, devices);
1691 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
1692 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1693 || !isValidPcmSinkFormat(config->format)
1694 || !isValidPcmSinkChannelMask(config->channel_mask)) {
1695 thread = new DirectOutputThread(this, outputStream, *output, devices);
1696 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
1697 } else {
1698 thread = new MixerThread(this, outputStream, *output, devices);
1699 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
1700 }
1701 mPlaybackThreads.add(*output, thread);
1702 return thread;
1703 }
1704
1705 return 0;
1706 }
1707
openOutput(audio_module_handle_t module,audio_io_handle_t * output,audio_config_t * config,audio_devices_t * devices,const String8 & address,uint32_t * latencyMs,audio_output_flags_t flags)1708 status_t AudioFlinger::openOutput(audio_module_handle_t module,
1709 audio_io_handle_t *output,
1710 audio_config_t *config,
1711 audio_devices_t *devices,
1712 const String8& address,
1713 uint32_t *latencyMs,
1714 audio_output_flags_t flags)
1715 {
1716 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
1717 module,
1718 (devices != NULL) ? *devices : 0,
1719 config->sample_rate,
1720 config->format,
1721 config->channel_mask,
1722 flags);
1723
1724 if (*devices == AUDIO_DEVICE_NONE) {
1725 return BAD_VALUE;
1726 }
1727
1728 Mutex::Autolock _l(mLock);
1729
1730 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
1731 if (thread != 0) {
1732 *latencyMs = thread->latency();
1733
1734 // notify client processes of the new output creation
1735 thread->audioConfigChanged(AudioSystem::OUTPUT_OPENED);
1736
1737 // the first primary output opened designates the primary hw device
1738 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
1739 ALOGI("Using module %d has the primary audio interface", module);
1740 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
1741
1742 AutoMutex lock(mHardwareLock);
1743 mHardwareStatus = AUDIO_HW_SET_MODE;
1744 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
1745 mHardwareStatus = AUDIO_HW_IDLE;
1746
1747 mPrimaryOutputSampleRate = config->sample_rate;
1748 }
1749 return NO_ERROR;
1750 }
1751
1752 return NO_INIT;
1753 }
1754
openDuplicateOutput(audio_io_handle_t output1,audio_io_handle_t output2)1755 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1756 audio_io_handle_t output2)
1757 {
1758 Mutex::Autolock _l(mLock);
1759 MixerThread *thread1 = checkMixerThread_l(output1);
1760 MixerThread *thread2 = checkMixerThread_l(output2);
1761
1762 if (thread1 == NULL || thread2 == NULL) {
1763 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1764 output2);
1765 return AUDIO_IO_HANDLE_NONE;
1766 }
1767
1768 audio_io_handle_t id = nextUniqueId();
1769 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
1770 thread->addOutputTrack(thread2);
1771 mPlaybackThreads.add(id, thread);
1772 // notify client processes of the new output creation
1773 thread->audioConfigChanged(AudioSystem::OUTPUT_OPENED);
1774 return id;
1775 }
1776
closeOutput(audio_io_handle_t output)1777 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
1778 {
1779 return closeOutput_nonvirtual(output);
1780 }
1781
closeOutput_nonvirtual(audio_io_handle_t output)1782 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1783 {
1784 // keep strong reference on the playback thread so that
1785 // it is not destroyed while exit() is executed
1786 sp<PlaybackThread> thread;
1787 {
1788 Mutex::Autolock _l(mLock);
1789 thread = checkPlaybackThread_l(output);
1790 if (thread == NULL) {
1791 return BAD_VALUE;
1792 }
1793
1794 ALOGV("closeOutput() %d", output);
1795
1796 if (thread->type() == ThreadBase::MIXER) {
1797 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1798 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
1799 DuplicatingThread *dupThread =
1800 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
1801 dupThread->removeOutputTrack((MixerThread *)thread.get());
1802
1803 }
1804 }
1805 }
1806
1807
1808 mPlaybackThreads.removeItem(output);
1809 // save all effects to the default thread
1810 if (mPlaybackThreads.size()) {
1811 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1812 if (dstThread != NULL) {
1813 // audioflinger lock is held here so the acquisition order of thread locks does not
1814 // matter
1815 Mutex::Autolock _dl(dstThread->mLock);
1816 Mutex::Autolock _sl(thread->mLock);
1817 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1818 for (size_t i = 0; i < effectChains.size(); i ++) {
1819 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
1820 }
1821 }
1822 }
1823 audioConfigChanged(AudioSystem::OUTPUT_CLOSED, output, NULL);
1824 }
1825 thread->exit();
1826 // The thread entity (active unit of execution) is no longer running here,
1827 // but the ThreadBase container still exists.
1828
1829 if (thread->type() != ThreadBase::DUPLICATING) {
1830 closeOutputFinish(thread);
1831 }
1832
1833 return NO_ERROR;
1834 }
1835
closeOutputFinish(sp<PlaybackThread> thread)1836 void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
1837 {
1838 AudioStreamOut *out = thread->clearOutput();
1839 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1840 // from now on thread->mOutput is NULL
1841 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1842 delete out;
1843 }
1844
closeOutputInternal_l(sp<PlaybackThread> thread)1845 void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
1846 {
1847 mPlaybackThreads.removeItem(thread->mId);
1848 thread->exit();
1849 closeOutputFinish(thread);
1850 }
1851
suspendOutput(audio_io_handle_t output)1852 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
1853 {
1854 Mutex::Autolock _l(mLock);
1855 PlaybackThread *thread = checkPlaybackThread_l(output);
1856
1857 if (thread == NULL) {
1858 return BAD_VALUE;
1859 }
1860
1861 ALOGV("suspendOutput() %d", output);
1862 thread->suspend();
1863
1864 return NO_ERROR;
1865 }
1866
restoreOutput(audio_io_handle_t output)1867 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
1868 {
1869 Mutex::Autolock _l(mLock);
1870 PlaybackThread *thread = checkPlaybackThread_l(output);
1871
1872 if (thread == NULL) {
1873 return BAD_VALUE;
1874 }
1875
1876 ALOGV("restoreOutput() %d", output);
1877
1878 thread->restore();
1879
1880 return NO_ERROR;
1881 }
1882
openInput(audio_module_handle_t module,audio_io_handle_t * input,audio_config_t * config,audio_devices_t * device,const String8 & address,audio_source_t source,audio_input_flags_t flags)1883 status_t AudioFlinger::openInput(audio_module_handle_t module,
1884 audio_io_handle_t *input,
1885 audio_config_t *config,
1886 audio_devices_t *device,
1887 const String8& address,
1888 audio_source_t source,
1889 audio_input_flags_t flags)
1890 {
1891 Mutex::Autolock _l(mLock);
1892
1893 if (*device == AUDIO_DEVICE_NONE) {
1894 return BAD_VALUE;
1895 }
1896
1897 sp<RecordThread> thread = openInput_l(module, input, config, *device, address, source, flags);
1898
1899 if (thread != 0) {
1900 // notify client processes of the new input creation
1901 thread->audioConfigChanged(AudioSystem::INPUT_OPENED);
1902 return NO_ERROR;
1903 }
1904 return NO_INIT;
1905 }
1906
openInput_l(audio_module_handle_t module,audio_io_handle_t * input,audio_config_t * config,audio_devices_t device,const String8 & address,audio_source_t source,audio_input_flags_t flags)1907 sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
1908 audio_io_handle_t *input,
1909 audio_config_t *config,
1910 audio_devices_t device,
1911 const String8& address,
1912 audio_source_t source,
1913 audio_input_flags_t flags)
1914 {
1915 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, device);
1916 if (inHwDev == NULL) {
1917 *input = AUDIO_IO_HANDLE_NONE;
1918 return 0;
1919 }
1920
1921 if (*input == AUDIO_IO_HANDLE_NONE) {
1922 *input = nextUniqueId();
1923 }
1924
1925 audio_config_t halconfig = *config;
1926 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
1927 audio_stream_in_t *inStream = NULL;
1928 status_t status = inHwHal->open_input_stream(inHwHal, *input, device, &halconfig,
1929 &inStream, flags, address.string(), source);
1930 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
1931 ", Format %#x, Channels %x, flags %#x, status %d",
1932 inStream,
1933 halconfig.sample_rate,
1934 halconfig.format,
1935 halconfig.channel_mask,
1936 flags,
1937 status);
1938
1939 // If the input could not be opened with the requested parameters and we can handle the
1940 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
1941 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
1942 if (status == BAD_VALUE &&
1943 config->format == halconfig.format && halconfig.format == AUDIO_FORMAT_PCM_16_BIT &&
1944 (halconfig.sample_rate <= 2 * config->sample_rate) &&
1945 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_2) &&
1946 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_2)) {
1947 // FIXME describe the change proposed by HAL (save old values so we can log them here)
1948 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
1949 inStream = NULL;
1950 status = inHwHal->open_input_stream(inHwHal, *input, device, &halconfig,
1951 &inStream, flags, address.string(), source);
1952 // FIXME log this new status; HAL should not propose any further changes
1953 }
1954
1955 if (status == NO_ERROR && inStream != NULL) {
1956
1957 #ifdef TEE_SINK
1958 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
1959 // or (re-)create if current Pipe is idle and does not match the new format
1960 sp<NBAIO_Sink> teeSink;
1961 enum {
1962 TEE_SINK_NO, // don't copy input
1963 TEE_SINK_NEW, // copy input using a new pipe
1964 TEE_SINK_OLD, // copy input using an existing pipe
1965 } kind;
1966 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
1967 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
1968 if (!mTeeSinkInputEnabled) {
1969 kind = TEE_SINK_NO;
1970 } else if (!Format_isValid(format)) {
1971 kind = TEE_SINK_NO;
1972 } else if (mRecordTeeSink == 0) {
1973 kind = TEE_SINK_NEW;
1974 } else if (mRecordTeeSink->getStrongCount() != 1) {
1975 kind = TEE_SINK_NO;
1976 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
1977 kind = TEE_SINK_OLD;
1978 } else {
1979 kind = TEE_SINK_NEW;
1980 }
1981 switch (kind) {
1982 case TEE_SINK_NEW: {
1983 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
1984 size_t numCounterOffers = 0;
1985 const NBAIO_Format offers[1] = {format};
1986 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
1987 ALOG_ASSERT(index == 0);
1988 PipeReader *pipeReader = new PipeReader(*pipe);
1989 numCounterOffers = 0;
1990 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
1991 ALOG_ASSERT(index == 0);
1992 mRecordTeeSink = pipe;
1993 mRecordTeeSource = pipeReader;
1994 teeSink = pipe;
1995 }
1996 break;
1997 case TEE_SINK_OLD:
1998 teeSink = mRecordTeeSink;
1999 break;
2000 case TEE_SINK_NO:
2001 default:
2002 break;
2003 }
2004 #endif
2005
2006 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
2007
2008 // Start record thread
2009 // RecordThread requires both input and output device indication to forward to audio
2010 // pre processing modules
2011 sp<RecordThread> thread = new RecordThread(this,
2012 inputStream,
2013 *input,
2014 primaryOutputDevice_l(),
2015 device
2016 #ifdef TEE_SINK
2017 , teeSink
2018 #endif
2019 );
2020 mRecordThreads.add(*input, thread);
2021 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2022 return thread;
2023 }
2024
2025 *input = AUDIO_IO_HANDLE_NONE;
2026 return 0;
2027 }
2028
closeInput(audio_io_handle_t input)2029 status_t AudioFlinger::closeInput(audio_io_handle_t input)
2030 {
2031 return closeInput_nonvirtual(input);
2032 }
2033
closeInput_nonvirtual(audio_io_handle_t input)2034 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2035 {
2036 // keep strong reference on the record thread so that
2037 // it is not destroyed while exit() is executed
2038 sp<RecordThread> thread;
2039 {
2040 Mutex::Autolock _l(mLock);
2041 thread = checkRecordThread_l(input);
2042 if (thread == 0) {
2043 return BAD_VALUE;
2044 }
2045
2046 ALOGV("closeInput() %d", input);
2047
2048 // If we still have effect chains, it means that a client still holds a handle
2049 // on at least one effect. We must either move the chain to an existing thread with the
2050 // same session ID or put it aside in case a new record thread is opened for a
2051 // new capture on the same session
2052 sp<EffectChain> chain;
2053 {
2054 Mutex::Autolock _sl(thread->mLock);
2055 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2056 // Note: maximum one chain per record thread
2057 if (effectChains.size() != 0) {
2058 chain = effectChains[0];
2059 }
2060 }
2061 if (chain != 0) {
2062 // first check if a record thread is already opened with a client on the same session.
2063 // This should only happen in case of overlap between one thread tear down and the
2064 // creation of its replacement
2065 size_t i;
2066 for (i = 0; i < mRecordThreads.size(); i++) {
2067 sp<RecordThread> t = mRecordThreads.valueAt(i);
2068 if (t == thread) {
2069 continue;
2070 }
2071 if (t->hasAudioSession(chain->sessionId()) != 0) {
2072 Mutex::Autolock _l(t->mLock);
2073 ALOGV("closeInput() found thread %d for effect session %d",
2074 t->id(), chain->sessionId());
2075 t->addEffectChain_l(chain);
2076 break;
2077 }
2078 }
2079 // put the chain aside if we could not find a record thread with the same session id.
2080 if (i == mRecordThreads.size()) {
2081 putOrphanEffectChain_l(chain);
2082 }
2083 }
2084 audioConfigChanged(AudioSystem::INPUT_CLOSED, input, NULL);
2085 mRecordThreads.removeItem(input);
2086 }
2087 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2088 // we have a different lock for notification client
2089 closeInputFinish(thread);
2090 return NO_ERROR;
2091 }
2092
closeInputFinish(sp<RecordThread> thread)2093 void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2094 {
2095 thread->exit();
2096 AudioStreamIn *in = thread->clearInput();
2097 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2098 // from now on thread->mInput is NULL
2099 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
2100 delete in;
2101 }
2102
closeInputInternal_l(sp<RecordThread> thread)2103 void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2104 {
2105 mRecordThreads.removeItem(thread->mId);
2106 closeInputFinish(thread);
2107 }
2108
invalidateStream(audio_stream_type_t stream)2109 status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
2110 {
2111 Mutex::Autolock _l(mLock);
2112 ALOGV("invalidateStream() stream %d", stream);
2113
2114 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2115 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2116 thread->invalidateTracks(stream);
2117 }
2118
2119 return NO_ERROR;
2120 }
2121
2122
newAudioUniqueId()2123 audio_unique_id_t AudioFlinger::newAudioUniqueId()
2124 {
2125 return nextUniqueId();
2126 }
2127
acquireAudioSessionId(int audioSession,pid_t pid)2128 void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
2129 {
2130 Mutex::Autolock _l(mLock);
2131 pid_t caller = IPCThreadState::self()->getCallingPid();
2132 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2133 if (pid != -1 && (caller == getpid_cached)) {
2134 caller = pid;
2135 }
2136
2137 {
2138 Mutex::Autolock _cl(mClientLock);
2139 // Ignore requests received from processes not known as notification client. The request
2140 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2141 // called from a different pid leaving a stale session reference. Also we don't know how
2142 // to clear this reference if the client process dies.
2143 if (mNotificationClients.indexOfKey(caller) < 0) {
2144 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2145 return;
2146 }
2147 }
2148
2149 size_t num = mAudioSessionRefs.size();
2150 for (size_t i = 0; i< num; i++) {
2151 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
2152 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2153 ref->mCnt++;
2154 ALOGV(" incremented refcount to %d", ref->mCnt);
2155 return;
2156 }
2157 }
2158 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2159 ALOGV(" added new entry for %d", audioSession);
2160 }
2161
releaseAudioSessionId(int audioSession,pid_t pid)2162 void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
2163 {
2164 Mutex::Autolock _l(mLock);
2165 pid_t caller = IPCThreadState::self()->getCallingPid();
2166 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2167 if (pid != -1 && (caller == getpid_cached)) {
2168 caller = pid;
2169 }
2170 size_t num = mAudioSessionRefs.size();
2171 for (size_t i = 0; i< num; i++) {
2172 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2173 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2174 ref->mCnt--;
2175 ALOGV(" decremented refcount to %d", ref->mCnt);
2176 if (ref->mCnt == 0) {
2177 mAudioSessionRefs.removeAt(i);
2178 delete ref;
2179 purgeStaleEffects_l();
2180 }
2181 return;
2182 }
2183 }
2184 // If the caller is mediaserver it is likely that the session being released was acquired
2185 // on behalf of a process not in notification clients and we ignore the warning.
2186 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
2187 }
2188
purgeStaleEffects_l()2189 void AudioFlinger::purgeStaleEffects_l() {
2190
2191 ALOGV("purging stale effects");
2192
2193 Vector< sp<EffectChain> > chains;
2194
2195 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2196 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2197 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2198 sp<EffectChain> ec = t->mEffectChains[j];
2199 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2200 chains.push(ec);
2201 }
2202 }
2203 }
2204 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2205 sp<RecordThread> t = mRecordThreads.valueAt(i);
2206 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2207 sp<EffectChain> ec = t->mEffectChains[j];
2208 chains.push(ec);
2209 }
2210 }
2211
2212 for (size_t i = 0; i < chains.size(); i++) {
2213 sp<EffectChain> ec = chains[i];
2214 int sessionid = ec->sessionId();
2215 sp<ThreadBase> t = ec->mThread.promote();
2216 if (t == 0) {
2217 continue;
2218 }
2219 size_t numsessionrefs = mAudioSessionRefs.size();
2220 bool found = false;
2221 for (size_t k = 0; k < numsessionrefs; k++) {
2222 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
2223 if (ref->mSessionid == sessionid) {
2224 ALOGV(" session %d still exists for %d with %d refs",
2225 sessionid, ref->mPid, ref->mCnt);
2226 found = true;
2227 break;
2228 }
2229 }
2230 if (!found) {
2231 Mutex::Autolock _l(t->mLock);
2232 // remove all effects from the chain
2233 while (ec->mEffects.size()) {
2234 sp<EffectModule> effect = ec->mEffects[0];
2235 effect->unPin();
2236 t->removeEffect_l(effect);
2237 if (effect->purgeHandles()) {
2238 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
2239 }
2240 AudioSystem::unregisterEffect(effect->id());
2241 }
2242 }
2243 }
2244 return;
2245 }
2246
2247 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
checkPlaybackThread_l(audio_io_handle_t output) const2248 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
2249 {
2250 return mPlaybackThreads.valueFor(output).get();
2251 }
2252
2253 // checkMixerThread_l() must be called with AudioFlinger::mLock held
checkMixerThread_l(audio_io_handle_t output) const2254 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
2255 {
2256 PlaybackThread *thread = checkPlaybackThread_l(output);
2257 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
2258 }
2259
2260 // checkRecordThread_l() must be called with AudioFlinger::mLock held
checkRecordThread_l(audio_io_handle_t input) const2261 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
2262 {
2263 return mRecordThreads.valueFor(input).get();
2264 }
2265
nextUniqueId()2266 uint32_t AudioFlinger::nextUniqueId()
2267 {
2268 return (uint32_t) android_atomic_inc(&mNextUniqueId);
2269 }
2270
primaryPlaybackThread_l() const2271 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
2272 {
2273 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2274 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2275 AudioStreamOut *output = thread->getOutput();
2276 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
2277 return thread;
2278 }
2279 }
2280 return NULL;
2281 }
2282
primaryOutputDevice_l() const2283 audio_devices_t AudioFlinger::primaryOutputDevice_l() const
2284 {
2285 PlaybackThread *thread = primaryPlaybackThread_l();
2286
2287 if (thread == NULL) {
2288 return 0;
2289 }
2290
2291 return thread->outDevice();
2292 }
2293
createSyncEvent(AudioSystem::sync_event_t type,int triggerSession,int listenerSession,sync_event_callback_t callBack,wp<RefBase> cookie)2294 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
2295 int triggerSession,
2296 int listenerSession,
2297 sync_event_callback_t callBack,
2298 wp<RefBase> cookie)
2299 {
2300 Mutex::Autolock _l(mLock);
2301
2302 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2303 status_t playStatus = NAME_NOT_FOUND;
2304 status_t recStatus = NAME_NOT_FOUND;
2305 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2306 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2307 if (playStatus == NO_ERROR) {
2308 return event;
2309 }
2310 }
2311 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2312 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2313 if (recStatus == NO_ERROR) {
2314 return event;
2315 }
2316 }
2317 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2318 mPendingSyncEvents.add(event);
2319 } else {
2320 ALOGV("createSyncEvent() invalid event %d", event->type());
2321 event.clear();
2322 }
2323 return event;
2324 }
2325
2326 // ----------------------------------------------------------------------------
2327 // Effect management
2328 // ----------------------------------------------------------------------------
2329
2330
queryNumberEffects(uint32_t * numEffects) const2331 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
2332 {
2333 Mutex::Autolock _l(mLock);
2334 return EffectQueryNumberEffects(numEffects);
2335 }
2336
queryEffect(uint32_t index,effect_descriptor_t * descriptor) const2337 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
2338 {
2339 Mutex::Autolock _l(mLock);
2340 return EffectQueryEffect(index, descriptor);
2341 }
2342
getEffectDescriptor(const effect_uuid_t * pUuid,effect_descriptor_t * descriptor) const2343 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
2344 effect_descriptor_t *descriptor) const
2345 {
2346 Mutex::Autolock _l(mLock);
2347 return EffectGetDescriptor(pUuid, descriptor);
2348 }
2349
2350
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)2351 sp<IEffect> AudioFlinger::createEffect(
2352 effect_descriptor_t *pDesc,
2353 const sp<IEffectClient>& effectClient,
2354 int32_t priority,
2355 audio_io_handle_t io,
2356 int sessionId,
2357 status_t *status,
2358 int *id,
2359 int *enabled)
2360 {
2361 status_t lStatus = NO_ERROR;
2362 sp<EffectHandle> handle;
2363 effect_descriptor_t desc;
2364
2365 pid_t pid = IPCThreadState::self()->getCallingPid();
2366 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
2367 pid, effectClient.get(), priority, sessionId, io);
2368
2369 if (pDesc == NULL) {
2370 lStatus = BAD_VALUE;
2371 goto Exit;
2372 }
2373
2374 // check audio settings permission for global effects
2375 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
2376 lStatus = PERMISSION_DENIED;
2377 goto Exit;
2378 }
2379
2380 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
2381 // that can only be created by audio policy manager (running in same process)
2382 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
2383 lStatus = PERMISSION_DENIED;
2384 goto Exit;
2385 }
2386
2387 {
2388 if (!EffectIsNullUuid(&pDesc->uuid)) {
2389 // if uuid is specified, request effect descriptor
2390 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2391 if (lStatus < 0) {
2392 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
2393 goto Exit;
2394 }
2395 } else {
2396 // if uuid is not specified, look for an available implementation
2397 // of the required type in effect factory
2398 if (EffectIsNullUuid(&pDesc->type)) {
2399 ALOGW("createEffect() no effect type");
2400 lStatus = BAD_VALUE;
2401 goto Exit;
2402 }
2403 uint32_t numEffects = 0;
2404 effect_descriptor_t d;
2405 d.flags = 0; // prevent compiler warning
2406 bool found = false;
2407
2408 lStatus = EffectQueryNumberEffects(&numEffects);
2409 if (lStatus < 0) {
2410 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
2411 goto Exit;
2412 }
2413 for (uint32_t i = 0; i < numEffects; i++) {
2414 lStatus = EffectQueryEffect(i, &desc);
2415 if (lStatus < 0) {
2416 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
2417 continue;
2418 }
2419 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2420 // If matching type found save effect descriptor. If the session is
2421 // 0 and the effect is not auxiliary, continue enumeration in case
2422 // an auxiliary version of this effect type is available
2423 found = true;
2424 d = desc;
2425 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
2426 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2427 break;
2428 }
2429 }
2430 }
2431 if (!found) {
2432 lStatus = BAD_VALUE;
2433 ALOGW("createEffect() effect not found");
2434 goto Exit;
2435 }
2436 // For same effect type, chose auxiliary version over insert version if
2437 // connect to output mix (Compliance to OpenSL ES)
2438 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
2439 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
2440 desc = d;
2441 }
2442 }
2443
2444 // Do not allow auxiliary effects on a session different from 0 (output mix)
2445 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
2446 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2447 lStatus = INVALID_OPERATION;
2448 goto Exit;
2449 }
2450
2451 // check recording permission for visualizer
2452 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
2453 !recordingAllowed()) {
2454 lStatus = PERMISSION_DENIED;
2455 goto Exit;
2456 }
2457
2458 // return effect descriptor
2459 *pDesc = desc;
2460 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2461 // if the output returned by getOutputForEffect() is removed before we lock the
2462 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2463 // and we will exit safely
2464 io = AudioSystem::getOutputForEffect(&desc);
2465 ALOGV("createEffect got output %d", io);
2466 }
2467
2468 Mutex::Autolock _l(mLock);
2469
2470 // If output is not specified try to find a matching audio session ID in one of the
2471 // output threads.
2472 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2473 // because of code checking output when entering the function.
2474 // Note: io is never 0 when creating an effect on an input
2475 if (io == AUDIO_IO_HANDLE_NONE) {
2476 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2477 // output must be specified by AudioPolicyManager when using session
2478 // AUDIO_SESSION_OUTPUT_STAGE
2479 lStatus = BAD_VALUE;
2480 goto Exit;
2481 }
2482 // look for the thread where the specified audio session is present
2483 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2484 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2485 io = mPlaybackThreads.keyAt(i);
2486 break;
2487 }
2488 }
2489 if (io == 0) {
2490 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2491 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2492 io = mRecordThreads.keyAt(i);
2493 break;
2494 }
2495 }
2496 }
2497 // If no output thread contains the requested session ID, default to
2498 // first output. The effect chain will be moved to the correct output
2499 // thread when a track with the same session ID is created
2500 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
2501 io = mPlaybackThreads.keyAt(0);
2502 }
2503 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
2504 }
2505 ThreadBase *thread = checkRecordThread_l(io);
2506 if (thread == NULL) {
2507 thread = checkPlaybackThread_l(io);
2508 if (thread == NULL) {
2509 ALOGE("createEffect() unknown output thread");
2510 lStatus = BAD_VALUE;
2511 goto Exit;
2512 }
2513 } else {
2514 // Check if one effect chain was awaiting for an effect to be created on this
2515 // session and used it instead of creating a new one.
2516 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)sessionId);
2517 if (chain != 0) {
2518 Mutex::Autolock _l(thread->mLock);
2519 thread->addEffectChain_l(chain);
2520 }
2521 }
2522
2523 sp<Client> client = registerPid(pid);
2524
2525 // create effect on selected output thread
2526 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2527 &desc, enabled, &lStatus);
2528 if (handle != 0 && id != NULL) {
2529 *id = handle->id();
2530 }
2531 if (handle == 0) {
2532 // remove local strong reference to Client with mClientLock held
2533 Mutex::Autolock _cl(mClientLock);
2534 client.clear();
2535 }
2536 }
2537
2538 Exit:
2539 *status = lStatus;
2540 return handle;
2541 }
2542
moveEffects(int sessionId,audio_io_handle_t srcOutput,audio_io_handle_t dstOutput)2543 status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2544 audio_io_handle_t dstOutput)
2545 {
2546 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
2547 sessionId, srcOutput, dstOutput);
2548 Mutex::Autolock _l(mLock);
2549 if (srcOutput == dstOutput) {
2550 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
2551 return NO_ERROR;
2552 }
2553 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2554 if (srcThread == NULL) {
2555 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
2556 return BAD_VALUE;
2557 }
2558 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2559 if (dstThread == NULL) {
2560 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
2561 return BAD_VALUE;
2562 }
2563
2564 Mutex::Autolock _dl(dstThread->mLock);
2565 Mutex::Autolock _sl(srcThread->mLock);
2566 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
2567 }
2568
2569 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
moveEffectChain_l(int sessionId,AudioFlinger::PlaybackThread * srcThread,AudioFlinger::PlaybackThread * dstThread,bool reRegister)2570 status_t AudioFlinger::moveEffectChain_l(int sessionId,
2571 AudioFlinger::PlaybackThread *srcThread,
2572 AudioFlinger::PlaybackThread *dstThread,
2573 bool reRegister)
2574 {
2575 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
2576 sessionId, srcThread, dstThread);
2577
2578 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
2579 if (chain == 0) {
2580 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
2581 sessionId, srcThread);
2582 return INVALID_OPERATION;
2583 }
2584
2585 // Check whether the destination thread has a channel count of FCC_2, which is
2586 // currently required for (most) effects. Prevent moving the effect chain here rather
2587 // than disabling the addEffect_l() call in dstThread below.
2588 if (dstThread->mChannelCount != FCC_2) {
2589 ALOGW("moveEffectChain_l() effect chain failed because"
2590 " destination thread %p channel count(%u) != %u",
2591 dstThread, dstThread->mChannelCount, FCC_2);
2592 return INVALID_OPERATION;
2593 }
2594
2595 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
2596 // so that a new chain is created with correct parameters when first effect is added. This is
2597 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
2598 // removed.
2599 srcThread->removeEffectChain_l(chain);
2600
2601 // transfer all effects one by one so that new effect chain is created on new thread with
2602 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
2603 sp<EffectChain> dstChain;
2604 uint32_t strategy = 0; // prevent compiler warning
2605 sp<EffectModule> effect = chain->getEffectFromId_l(0);
2606 Vector< sp<EffectModule> > removed;
2607 status_t status = NO_ERROR;
2608 while (effect != 0) {
2609 srcThread->removeEffect_l(effect);
2610 removed.add(effect);
2611 status = dstThread->addEffect_l(effect);
2612 if (status != NO_ERROR) {
2613 break;
2614 }
2615 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2616 if (effect->state() == EffectModule::ACTIVE ||
2617 effect->state() == EffectModule::STOPPING) {
2618 effect->start();
2619 }
2620 // if the move request is not received from audio policy manager, the effect must be
2621 // re-registered with the new strategy and output
2622 if (dstChain == 0) {
2623 dstChain = effect->chain().promote();
2624 if (dstChain == 0) {
2625 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
2626 status = NO_INIT;
2627 break;
2628 }
2629 strategy = dstChain->strategy();
2630 }
2631 if (reRegister) {
2632 AudioSystem::unregisterEffect(effect->id());
2633 AudioSystem::registerEffect(&effect->desc(),
2634 dstThread->id(),
2635 strategy,
2636 sessionId,
2637 effect->id());
2638 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
2639 }
2640 effect = chain->getEffectFromId_l(0);
2641 }
2642
2643 if (status != NO_ERROR) {
2644 for (size_t i = 0; i < removed.size(); i++) {
2645 srcThread->addEffect_l(removed[i]);
2646 if (dstChain != 0 && reRegister) {
2647 AudioSystem::unregisterEffect(removed[i]->id());
2648 AudioSystem::registerEffect(&removed[i]->desc(),
2649 srcThread->id(),
2650 strategy,
2651 sessionId,
2652 removed[i]->id());
2653 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
2654 }
2655 }
2656 }
2657
2658 return status;
2659 }
2660
isNonOffloadableGlobalEffectEnabled_l()2661 bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
2662 {
2663 if (mGlobalEffectEnableTime != 0 &&
2664 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2665 return true;
2666 }
2667
2668 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2669 sp<EffectChain> ec =
2670 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2671 if (ec != 0 && ec->isNonOffloadableEnabled()) {
2672 return true;
2673 }
2674 }
2675 return false;
2676 }
2677
onNonOffloadableGlobalEffectEnable()2678 void AudioFlinger::onNonOffloadableGlobalEffectEnable()
2679 {
2680 Mutex::Autolock _l(mLock);
2681
2682 mGlobalEffectEnableTime = systemTime();
2683
2684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2685 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2686 if (t->mType == ThreadBase::OFFLOAD) {
2687 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2688 }
2689 }
2690
2691 }
2692
putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain> & chain)2693 status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2694 {
2695 audio_session_t session = (audio_session_t)chain->sessionId();
2696 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2697 ALOGV("putOrphanEffectChain_l session %d index %d", session, index);
2698 if (index >= 0) {
2699 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2700 return ALREADY_EXISTS;
2701 }
2702 mOrphanEffectChains.add(session, chain);
2703 return NO_ERROR;
2704 }
2705
getOrphanEffectChain_l(audio_session_t session)2706 sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2707 {
2708 sp<EffectChain> chain;
2709 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2710 ALOGV("getOrphanEffectChain_l session %d index %d", session, index);
2711 if (index >= 0) {
2712 chain = mOrphanEffectChains.valueAt(index);
2713 mOrphanEffectChains.removeItemsAt(index);
2714 }
2715 return chain;
2716 }
2717
updateOrphanEffectChains(const sp<AudioFlinger::EffectModule> & effect)2718 bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2719 {
2720 Mutex::Autolock _l(mLock);
2721 audio_session_t session = (audio_session_t)effect->sessionId();
2722 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2723 ALOGV("updateOrphanEffectChains session %d index %d", session, index);
2724 if (index >= 0) {
2725 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2726 if (chain->removeEffect_l(effect) == 0) {
2727 ALOGV("updateOrphanEffectChains removing effect chain at index %d", index);
2728 mOrphanEffectChains.removeItemsAt(index);
2729 }
2730 return true;
2731 }
2732 return false;
2733 }
2734
2735
2736 struct Entry {
2737 #define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav
2738 char mName[MAX_NAME];
2739 };
2740
comparEntry(const void * p1,const void * p2)2741 int comparEntry(const void *p1, const void *p2)
2742 {
2743 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName);
2744 }
2745
2746 #ifdef TEE_SINK
dumpTee(int fd,const sp<NBAIO_Source> & source,audio_io_handle_t id)2747 void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
2748 {
2749 NBAIO_Source *teeSource = source.get();
2750 if (teeSource != NULL) {
2751 // .wav rotation
2752 // There is a benign race condition if 2 threads call this simultaneously.
2753 // They would both traverse the directory, but the result would simply be
2754 // failures at unlink() which are ignored. It's also unlikely since
2755 // normally dumpsys is only done by bugreport or from the command line.
2756 char teePath[32+256];
2757 strcpy(teePath, "/data/misc/media");
2758 size_t teePathLen = strlen(teePath);
2759 DIR *dir = opendir(teePath);
2760 teePath[teePathLen++] = '/';
2761 if (dir != NULL) {
2762 #define MAX_SORT 20 // number of entries to sort
2763 #define MAX_KEEP 10 // number of entries to keep
2764 struct Entry entries[MAX_SORT];
2765 size_t entryCount = 0;
2766 while (entryCount < MAX_SORT) {
2767 struct dirent de;
2768 struct dirent *result = NULL;
2769 int rc = readdir_r(dir, &de, &result);
2770 if (rc != 0) {
2771 ALOGW("readdir_r failed %d", rc);
2772 break;
2773 }
2774 if (result == NULL) {
2775 break;
2776 }
2777 if (result != &de) {
2778 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2779 break;
2780 }
2781 // ignore non .wav file entries
2782 size_t nameLen = strlen(de.d_name);
2783 if (nameLen <= 4 || nameLen >= MAX_NAME ||
2784 strcmp(&de.d_name[nameLen - 4], ".wav")) {
2785 continue;
2786 }
2787 strcpy(entries[entryCount++].mName, de.d_name);
2788 }
2789 (void) closedir(dir);
2790 if (entryCount > MAX_KEEP) {
2791 qsort(entries, entryCount, sizeof(Entry), comparEntry);
2792 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) {
2793 strcpy(&teePath[teePathLen], entries[i].mName);
2794 (void) unlink(teePath);
2795 }
2796 }
2797 } else {
2798 if (fd >= 0) {
2799 dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
2800 }
2801 }
2802 char teeTime[16];
2803 struct timeval tv;
2804 gettimeofday(&tv, NULL);
2805 struct tm tm;
2806 localtime_r(&tv.tv_sec, &tm);
2807 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2808 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2809 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2810 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
2811 if (teeFd >= 0) {
2812 // FIXME use libsndfile
2813 char wavHeader[44];
2814 memcpy(wavHeader,
2815 "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",
2816 sizeof(wavHeader));
2817 NBAIO_Format format = teeSource->format();
2818 unsigned channelCount = Format_channelCount(format);
2819 uint32_t sampleRate = Format_sampleRate(format);
2820 size_t frameSize = Format_frameSize(format);
2821 wavHeader[22] = channelCount; // number of channels
2822 wavHeader[24] = sampleRate; // sample rate
2823 wavHeader[25] = sampleRate >> 8;
2824 wavHeader[32] = frameSize; // block alignment
2825 wavHeader[33] = frameSize >> 8;
2826 write(teeFd, wavHeader, sizeof(wavHeader));
2827 size_t total = 0;
2828 bool firstRead = true;
2829 #define TEE_SINK_READ 1024 // frames per I/O operation
2830 void *buffer = malloc(TEE_SINK_READ * frameSize);
2831 for (;;) {
2832 size_t count = TEE_SINK_READ;
2833 ssize_t actual = teeSource->read(buffer, count,
2834 AudioBufferProvider::kInvalidPTS);
2835 bool wasFirstRead = firstRead;
2836 firstRead = false;
2837 if (actual <= 0) {
2838 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2839 continue;
2840 }
2841 break;
2842 }
2843 ALOG_ASSERT(actual <= (ssize_t)count);
2844 write(teeFd, buffer, actual * frameSize);
2845 total += actual;
2846 }
2847 free(buffer);
2848 lseek(teeFd, (off_t) 4, SEEK_SET);
2849 uint32_t temp = 44 + total * frameSize - 8;
2850 // FIXME not big-endian safe
2851 write(teeFd, &temp, sizeof(temp));
2852 lseek(teeFd, (off_t) 40, SEEK_SET);
2853 temp = total * frameSize;
2854 // FIXME not big-endian safe
2855 write(teeFd, &temp, sizeof(temp));
2856 close(teeFd);
2857 if (fd >= 0) {
2858 dprintf(fd, "tee copied to %s\n", teePath);
2859 }
2860 } else {
2861 if (fd >= 0) {
2862 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
2863 }
2864 }
2865 }
2866 }
2867 #endif
2868
2869 // ----------------------------------------------------------------------------
2870
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)2871 status_t AudioFlinger::onTransact(
2872 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2873 {
2874 return BnAudioFlinger::onTransact(code, data, reply, flags);
2875 }
2876
2877 }; // namespace android
2878