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