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