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