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