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