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