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