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