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