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