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