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