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