AudioFlinger.cpp revision 481fb67a595f23c5b7f5be84b06db9b84a41a42f
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 <utils/String16.h> 35#include <utils/threads.h> 36#include <utils/Atomic.h> 37 38#include <cutils/bitops.h> 39#include <cutils/properties.h> 40 41#include <system/audio.h> 42#include <hardware/audio.h> 43 44#include "AudioMixer.h" 45#include "AudioFlinger.h" 46#include "ServiceUtilities.h" 47 48#include <media/EffectsFactoryApi.h> 49#include <audio_effects/effect_visualizer.h> 50#include <audio_effects/effect_ns.h> 51#include <audio_effects/effect_aec.h> 52 53#include <audio_utils/primitives.h> 54 55#include <powermanager/PowerManager.h> 56 57#include <common_time/cc_helper.h> 58 59#include <media/IMediaLogService.h> 60 61#include <media/nbaio/Pipe.h> 62#include <media/nbaio/PipeReader.h> 63#include <media/AudioParameter.h> 64#include <private/android_filesystem_config.h> 65 66// ---------------------------------------------------------------------------- 67 68// Note: the following macro is used for extremely verbose logging message. In 69// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 70// 0; but one side effect of this is to turn all LOGV's as well. Some messages 71// are so verbose that we want to suppress them even when we have ALOG_ASSERT 72// turned on. Do not uncomment the #def below unless you really know what you 73// are doing and want to see all of the extremely verbose messages. 74//#define VERY_VERY_VERBOSE_LOGGING 75#ifdef VERY_VERY_VERBOSE_LOGGING 76#define ALOGVV ALOGV 77#else 78#define ALOGVV(a...) do { } while(0) 79#endif 80 81namespace android { 82 83static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 84static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 85 86 87nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 88 89uint32_t AudioFlinger::mScreenState; 90 91#ifdef TEE_SINK 92bool AudioFlinger::mTeeSinkInputEnabled = false; 93bool AudioFlinger::mTeeSinkOutputEnabled = false; 94bool AudioFlinger::mTeeSinkTrackEnabled = false; 95 96size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault; 97size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault; 98size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault; 99#endif 100 101// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off 102// we define a minimum time during which a global effect is considered enabled. 103static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200); 104 105// ---------------------------------------------------------------------------- 106 107static int load_audio_interface(const char *if_name, audio_hw_device_t **dev) 108{ 109 const hw_module_t *mod; 110 int rc; 111 112 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod); 113 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__, 114 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 115 if (rc) { 116 goto out; 117 } 118 rc = audio_hw_device_open(mod, dev); 119 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__, 120 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 121 if (rc) { 122 goto out; 123 } 124 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) { 125 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version); 126 rc = BAD_VALUE; 127 goto out; 128 } 129 return 0; 130 131out: 132 *dev = NULL; 133 return rc; 134} 135 136// ---------------------------------------------------------------------------- 137 138AudioFlinger::AudioFlinger() 139 : BnAudioFlinger(), 140 mPrimaryHardwareDev(NULL), 141 mHardwareStatus(AUDIO_HW_IDLE), 142 mMasterVolume(1.0f), 143 mMasterMute(false), 144 mNextUniqueId(1), 145 mMode(AUDIO_MODE_INVALID), 146 mBtNrecIsOff(false), 147 mIsLowRamDevice(true), 148 mIsDeviceTypeKnown(false), 149 mGlobalEffectEnableTime(0) 150{ 151 getpid_cached = getpid(); 152 char value[PROPERTY_VALUE_MAX]; 153 bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1); 154 if (doLog) { 155 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters"); 156 } 157#ifdef TEE_SINK 158 (void) property_get("ro.debuggable", value, "0"); 159 int debuggable = atoi(value); 160 int teeEnabled = 0; 161 if (debuggable) { 162 (void) property_get("af.tee", value, "0"); 163 teeEnabled = atoi(value); 164 } 165 if (teeEnabled & 1) { 166 mTeeSinkInputEnabled = true; 167 } 168 if (teeEnabled & 2) { 169 mTeeSinkOutputEnabled = true; 170 } 171 if (teeEnabled & 4) { 172 mTeeSinkTrackEnabled = true; 173 } 174#endif 175} 176 177void AudioFlinger::onFirstRef() 178{ 179 int rc = 0; 180 181 Mutex::Autolock _l(mLock); 182 183 /* TODO: move all this work into an Init() function */ 184 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 185 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 186 uint32_t int_val; 187 if (1 == sscanf(val_str, "%u", &int_val)) { 188 mStandbyTimeInNsecs = milliseconds(int_val); 189 ALOGI("Using %u mSec as standby time.", int_val); 190 } else { 191 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 192 ALOGI("Using default %u mSec as standby time.", 193 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 194 } 195 } 196 197 mMode = AUDIO_MODE_NORMAL; 198} 199 200AudioFlinger::~AudioFlinger() 201{ 202 while (!mRecordThreads.isEmpty()) { 203 // closeInput_nonvirtual() will remove specified entry from mRecordThreads 204 closeInput_nonvirtual(mRecordThreads.keyAt(0)); 205 } 206 while (!mPlaybackThreads.isEmpty()) { 207 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads 208 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0)); 209 } 210 211 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 212 // no mHardwareLock needed, as there are no other references to this 213 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice()); 214 delete mAudioHwDevs.valueAt(i); 215 } 216 217 // Tell media.log service about any old writers that still need to be unregistered 218 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 219 if (binder != 0) { 220 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 221 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 222 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory()); 223 mUnregisteredWriters.pop(); 224 mediaLogService->unregisterWriter(iMemory); 225 } 226 } 227 228} 229 230static const char * const audio_interfaces[] = { 231 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 232 AUDIO_HARDWARE_MODULE_ID_A2DP, 233 AUDIO_HARDWARE_MODULE_ID_USB, 234}; 235#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 236 237AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l( 238 audio_module_handle_t module, 239 audio_devices_t devices) 240{ 241 // if module is 0, the request comes from an old policy manager and we should load 242 // well known modules 243 if (module == 0) { 244 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 245 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 246 loadHwModule_l(audio_interfaces[i]); 247 } 248 // then try to find a module supporting the requested device. 249 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 250 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i); 251 audio_hw_device_t *dev = audioHwDevice->hwDevice(); 252 if ((dev->get_supported_devices != NULL) && 253 (dev->get_supported_devices(dev) & devices) == devices) 254 return audioHwDevice; 255 } 256 } else { 257 // check a match for the requested module handle 258 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module); 259 if (audioHwDevice != NULL) { 260 return audioHwDevice; 261 } 262 } 263 264 return NULL; 265} 266 267void AudioFlinger::dumpClients(int fd, const Vector<String16>& args) 268{ 269 const size_t SIZE = 256; 270 char buffer[SIZE]; 271 String8 result; 272 273 result.append("Clients:\n"); 274 for (size_t i = 0; i < mClients.size(); ++i) { 275 sp<Client> client = mClients.valueAt(i).promote(); 276 if (client != 0) { 277 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 278 result.append(buffer); 279 } 280 } 281 282 result.append("Notification Clients:\n"); 283 for (size_t i = 0; i < mNotificationClients.size(); ++i) { 284 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i)); 285 result.append(buffer); 286 } 287 288 result.append("Global session refs:\n"); 289 result.append(" session pid count\n"); 290 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 291 AudioSessionRef *r = mAudioSessionRefs[i]; 292 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt); 293 result.append(buffer); 294 } 295 write(fd, result.string(), result.size()); 296} 297 298 299void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args) 300{ 301 const size_t SIZE = 256; 302 char buffer[SIZE]; 303 String8 result; 304 hardware_call_state hardwareStatus = mHardwareStatus; 305 306 snprintf(buffer, SIZE, "Hardware status: %d\n" 307 "Standby Time mSec: %u\n", 308 hardwareStatus, 309 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 310 result.append(buffer); 311 write(fd, result.string(), result.size()); 312} 313 314void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args) 315{ 316 const size_t SIZE = 256; 317 char buffer[SIZE]; 318 String8 result; 319 snprintf(buffer, SIZE, "Permission Denial: " 320 "can't dump AudioFlinger from pid=%d, uid=%d\n", 321 IPCThreadState::self()->getCallingPid(), 322 IPCThreadState::self()->getCallingUid()); 323 result.append(buffer); 324 write(fd, result.string(), result.size()); 325} 326 327bool AudioFlinger::dumpTryLock(Mutex& mutex) 328{ 329 bool locked = false; 330 for (int i = 0; i < kDumpLockRetries; ++i) { 331 if (mutex.tryLock() == NO_ERROR) { 332 locked = true; 333 break; 334 } 335 usleep(kDumpLockSleepUs); 336 } 337 return locked; 338} 339 340status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 341{ 342 if (!dumpAllowed()) { 343 dumpPermissionDenial(fd, args); 344 } else { 345 // get state of hardware lock 346 bool hardwareLocked = dumpTryLock(mHardwareLock); 347 if (!hardwareLocked) { 348 String8 result(kHardwareLockedString); 349 write(fd, result.string(), result.size()); 350 } else { 351 mHardwareLock.unlock(); 352 } 353 354 bool locked = dumpTryLock(mLock); 355 356 // failed to lock - AudioFlinger is probably deadlocked 357 if (!locked) { 358 String8 result(kDeadlockedString); 359 write(fd, result.string(), result.size()); 360 } 361 362 dumpClients(fd, args); 363 dumpInternals(fd, args); 364 365 // dump playback threads 366 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 367 mPlaybackThreads.valueAt(i)->dump(fd, args); 368 } 369 370 // dump record threads 371 for (size_t i = 0; i < mRecordThreads.size(); i++) { 372 mRecordThreads.valueAt(i)->dump(fd, args); 373 } 374 375 // dump all hardware devs 376 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 377 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 378 dev->dump(dev, fd); 379 } 380 381#ifdef TEE_SINK 382 // dump the serially shared record tee sink 383 if (mRecordTeeSource != 0) { 384 dumpTee(fd, mRecordTeeSource); 385 } 386#endif 387 388 if (locked) { 389 mLock.unlock(); 390 } 391 392 // append a copy of media.log here by forwarding fd to it, but don't attempt 393 // to lookup the service if it's not running, as it will block for a second 394 if (mLogMemoryDealer != 0) { 395 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 396 if (binder != 0) { 397 fdprintf(fd, "\nmedia.log:\n"); 398 Vector<String16> args; 399 binder->dump(fd, args); 400 } 401 } 402 } 403 return NO_ERROR; 404} 405 406sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid) 407{ 408 // If pid is already in the mClients wp<> map, then use that entry 409 // (for which promote() is always != 0), otherwise create a new entry and Client. 410 sp<Client> client = mClients.valueFor(pid).promote(); 411 if (client == 0) { 412 client = new Client(this, pid); 413 mClients.add(pid, client); 414 } 415 416 return client; 417} 418 419sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name) 420{ 421 // If there is no memory allocated for logs, return a dummy writer that does nothing 422 if (mLogMemoryDealer == 0) { 423 return new NBLog::Writer(); 424 } 425 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 426 // Similarly if we can't contact the media.log service, also return a dummy writer 427 if (binder == 0) { 428 return new NBLog::Writer(); 429 } 430 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 431 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 432 // If allocation fails, consult the vector of previously unregistered writers 433 // and garbage-collect one or more them until an allocation succeeds 434 if (shared == 0) { 435 Mutex::Autolock _l(mUnregisteredWritersLock); 436 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 437 { 438 // Pick the oldest stale writer to garbage-collect 439 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory()); 440 mUnregisteredWriters.removeAt(0); 441 mediaLogService->unregisterWriter(iMemory); 442 // Now the media.log remote reference to IMemory is gone. When our last local 443 // reference to IMemory also drops to zero at end of this block, 444 // the IMemory destructor will deallocate the region from mLogMemoryDealer. 445 } 446 // Re-attempt the allocation 447 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 448 if (shared != 0) { 449 goto success; 450 } 451 } 452 // Even after garbage-collecting all old writers, there is still not enough memory, 453 // so return a dummy writer 454 return new NBLog::Writer(); 455 } 456success: 457 mediaLogService->registerWriter(shared, size, name); 458 return new NBLog::Writer(size, shared); 459} 460 461void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer) 462{ 463 if (writer == 0) { 464 return; 465 } 466 sp<IMemory> iMemory(writer->getIMemory()); 467 if (iMemory == 0) { 468 return; 469 } 470 // Rather than removing the writer immediately, append it to a queue of old writers to 471 // be garbage-collected later. This allows us to continue to view old logs for a while. 472 Mutex::Autolock _l(mUnregisteredWritersLock); 473 mUnregisteredWriters.push(writer); 474} 475 476// IAudioFlinger interface 477 478 479sp<IAudioTrack> AudioFlinger::createTrack( 480 audio_stream_type_t streamType, 481 uint32_t sampleRate, 482 audio_format_t format, 483 audio_channel_mask_t channelMask, 484 size_t frameCount, 485 IAudioFlinger::track_flags_t *flags, 486 const sp<IMemory>& sharedBuffer, 487 audio_io_handle_t output, 488 pid_t tid, 489 int *sessionId, 490 String8& name, 491 int clientUid, 492 status_t *status) 493{ 494 sp<PlaybackThread::Track> track; 495 sp<TrackHandle> trackHandle; 496 sp<Client> client; 497 status_t lStatus; 498 int lSessionId; 499 500 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 501 // but if someone uses binder directly they could bypass that and cause us to crash 502 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 503 ALOGE("createTrack() invalid stream type %d", streamType); 504 lStatus = BAD_VALUE; 505 goto Exit; 506 } 507 508 // client is responsible for conversion of 8-bit PCM to 16-bit PCM, 509 // and we don't yet support 8.24 or 32-bit PCM 510 if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) { 511 ALOGE("createTrack() invalid format %d", format); 512 lStatus = BAD_VALUE; 513 goto Exit; 514 } 515 516 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) { 517 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()"); 518 lStatus = BAD_VALUE; 519 goto Exit; 520 } 521 522 { 523 Mutex::Autolock _l(mLock); 524 PlaybackThread *thread = checkPlaybackThread_l(output); 525 PlaybackThread *effectThread = NULL; 526 if (thread == NULL) { 527 ALOGE("no playback thread found for output handle %d", output); 528 lStatus = BAD_VALUE; 529 goto Exit; 530 } 531 532 pid_t pid = IPCThreadState::self()->getCallingPid(); 533 534 client = registerPid_l(pid); 535 536 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 537 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 538 // check if an effect chain with the same session ID is present on another 539 // output thread and move it here. 540 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 541 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 542 if (mPlaybackThreads.keyAt(i) != output) { 543 uint32_t sessions = t->hasAudioSession(*sessionId); 544 if (sessions & PlaybackThread::EFFECT_SESSION) { 545 effectThread = t.get(); 546 break; 547 } 548 } 549 } 550 lSessionId = *sessionId; 551 } else { 552 // if no audio session id is provided, create one here 553 lSessionId = nextUniqueId(); 554 if (sessionId != NULL) { 555 *sessionId = lSessionId; 556 } 557 } 558 ALOGV("createTrack() lSessionId: %d", lSessionId); 559 560 track = thread->createTrack_l(client, streamType, sampleRate, format, 561 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus); 562 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 563 564 // move effect chain to this output thread if an effect on same session was waiting 565 // for a track to be created 566 if (lStatus == NO_ERROR && effectThread != NULL) { 567 // no risk of deadlock because AudioFlinger::mLock is held 568 Mutex::Autolock _dl(thread->mLock); 569 Mutex::Autolock _sl(effectThread->mLock); 570 moveEffectChain_l(lSessionId, effectThread, thread, true); 571 } 572 573 // Look for sync events awaiting for a session to be used. 574 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 575 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 576 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 577 if (lStatus == NO_ERROR) { 578 (void) track->setSyncEvent(mPendingSyncEvents[i]); 579 } else { 580 mPendingSyncEvents[i]->cancel(); 581 } 582 mPendingSyncEvents.removeAt(i); 583 i--; 584 } 585 } 586 } 587 588 } 589 590 if (lStatus == NO_ERROR) { 591 // s for server's pid, n for normal mixer name, f for fast index 592 name = String8::format("s:%d;n:%d;f:%d", getpid_cached, track->name() - AudioMixer::TRACK0, 593 track->fastIndex()); 594 trackHandle = new TrackHandle(track); 595 } else { 596 // remove local strong reference to Client before deleting the Track so that the Client 597 // destructor is called by the TrackBase destructor with mLock held 598 client.clear(); 599 track.clear(); 600 } 601 602Exit: 603 *status = lStatus; 604 return trackHandle; 605} 606 607uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 608{ 609 Mutex::Autolock _l(mLock); 610 PlaybackThread *thread = checkPlaybackThread_l(output); 611 if (thread == NULL) { 612 ALOGW("sampleRate() unknown thread %d", output); 613 return 0; 614 } 615 return thread->sampleRate(); 616} 617 618int AudioFlinger::channelCount(audio_io_handle_t output) const 619{ 620 Mutex::Autolock _l(mLock); 621 PlaybackThread *thread = checkPlaybackThread_l(output); 622 if (thread == NULL) { 623 ALOGW("channelCount() unknown thread %d", output); 624 return 0; 625 } 626 return thread->channelCount(); 627} 628 629audio_format_t AudioFlinger::format(audio_io_handle_t output) const 630{ 631 Mutex::Autolock _l(mLock); 632 PlaybackThread *thread = checkPlaybackThread_l(output); 633 if (thread == NULL) { 634 ALOGW("format() unknown thread %d", output); 635 return AUDIO_FORMAT_INVALID; 636 } 637 return thread->format(); 638} 639 640size_t AudioFlinger::frameCount(audio_io_handle_t output) const 641{ 642 Mutex::Autolock _l(mLock); 643 PlaybackThread *thread = checkPlaybackThread_l(output); 644 if (thread == NULL) { 645 ALOGW("frameCount() unknown thread %d", output); 646 return 0; 647 } 648 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 649 // should examine all callers and fix them to handle smaller counts 650 return thread->frameCount(); 651} 652 653uint32_t AudioFlinger::latency(audio_io_handle_t output) const 654{ 655 Mutex::Autolock _l(mLock); 656 PlaybackThread *thread = checkPlaybackThread_l(output); 657 if (thread == NULL) { 658 ALOGW("latency(): no playback thread found for output handle %d", output); 659 return 0; 660 } 661 return thread->latency(); 662} 663 664status_t AudioFlinger::setMasterVolume(float value) 665{ 666 status_t ret = initCheck(); 667 if (ret != NO_ERROR) { 668 return ret; 669 } 670 671 // check calling permissions 672 if (!settingsAllowed()) { 673 return PERMISSION_DENIED; 674 } 675 676 Mutex::Autolock _l(mLock); 677 mMasterVolume = value; 678 679 // Set master volume in the HALs which support it. 680 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 681 AutoMutex lock(mHardwareLock); 682 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 683 684 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 685 if (dev->canSetMasterVolume()) { 686 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 687 } 688 mHardwareStatus = AUDIO_HW_IDLE; 689 } 690 691 // Now set the master volume in each playback thread. Playback threads 692 // assigned to HALs which do not have master volume support will apply 693 // master volume during the mix operation. Threads with HALs which do 694 // support master volume will simply ignore the setting. 695 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 696 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 697 698 return NO_ERROR; 699} 700 701status_t AudioFlinger::setMode(audio_mode_t mode) 702{ 703 status_t ret = initCheck(); 704 if (ret != NO_ERROR) { 705 return ret; 706 } 707 708 // check calling permissions 709 if (!settingsAllowed()) { 710 return PERMISSION_DENIED; 711 } 712 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 713 ALOGW("Illegal value: setMode(%d)", mode); 714 return BAD_VALUE; 715 } 716 717 { // scope for the lock 718 AutoMutex lock(mHardwareLock); 719 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 720 mHardwareStatus = AUDIO_HW_SET_MODE; 721 ret = dev->set_mode(dev, mode); 722 mHardwareStatus = AUDIO_HW_IDLE; 723 } 724 725 if (NO_ERROR == ret) { 726 Mutex::Autolock _l(mLock); 727 mMode = mode; 728 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 729 mPlaybackThreads.valueAt(i)->setMode(mode); 730 } 731 732 return ret; 733} 734 735status_t AudioFlinger::setMicMute(bool state) 736{ 737 status_t ret = initCheck(); 738 if (ret != NO_ERROR) { 739 return ret; 740 } 741 742 // check calling permissions 743 if (!settingsAllowed()) { 744 return PERMISSION_DENIED; 745 } 746 747 AutoMutex lock(mHardwareLock); 748 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 749 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 750 ret = dev->set_mic_mute(dev, state); 751 mHardwareStatus = AUDIO_HW_IDLE; 752 return ret; 753} 754 755bool AudioFlinger::getMicMute() const 756{ 757 status_t ret = initCheck(); 758 if (ret != NO_ERROR) { 759 return false; 760 } 761 762 bool state = AUDIO_MODE_INVALID; 763 AutoMutex lock(mHardwareLock); 764 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 765 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 766 dev->get_mic_mute(dev, &state); 767 mHardwareStatus = AUDIO_HW_IDLE; 768 return state; 769} 770 771status_t AudioFlinger::setMasterMute(bool muted) 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 mMasterMute = muted; 785 786 // Set master mute 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_MUTE; 792 if (dev->canSetMasterMute()) { 793 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 794 } 795 mHardwareStatus = AUDIO_HW_IDLE; 796 } 797 798 // Now set the master mute in each playback thread. Playback threads 799 // assigned to HALs which do not have master mute support will apply master 800 // mute during the mix operation. Threads with HALs which do support master 801 // mute will simply ignore the setting. 802 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 803 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 804 805 return NO_ERROR; 806} 807 808float AudioFlinger::masterVolume() const 809{ 810 Mutex::Autolock _l(mLock); 811 return masterVolume_l(); 812} 813 814bool AudioFlinger::masterMute() const 815{ 816 Mutex::Autolock _l(mLock); 817 return masterMute_l(); 818} 819 820float AudioFlinger::masterVolume_l() const 821{ 822 return mMasterVolume; 823} 824 825bool AudioFlinger::masterMute_l() const 826{ 827 return mMasterMute; 828} 829 830status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 831 audio_io_handle_t output) 832{ 833 // check calling permissions 834 if (!settingsAllowed()) { 835 return PERMISSION_DENIED; 836 } 837 838 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 839 ALOGE("setStreamVolume() invalid stream %d", stream); 840 return BAD_VALUE; 841 } 842 843 AutoMutex lock(mLock); 844 PlaybackThread *thread = NULL; 845 if (output) { 846 thread = checkPlaybackThread_l(output); 847 if (thread == NULL) { 848 return BAD_VALUE; 849 } 850 } 851 852 mStreamTypes[stream].volume = value; 853 854 if (thread == NULL) { 855 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 856 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 857 } 858 } else { 859 thread->setStreamVolume(stream, value); 860 } 861 862 return NO_ERROR; 863} 864 865status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 866{ 867 // check calling permissions 868 if (!settingsAllowed()) { 869 return PERMISSION_DENIED; 870 } 871 872 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 873 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 874 ALOGE("setStreamMute() invalid stream %d", stream); 875 return BAD_VALUE; 876 } 877 878 AutoMutex lock(mLock); 879 mStreamTypes[stream].mute = muted; 880 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 881 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 882 883 return NO_ERROR; 884} 885 886float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 887{ 888 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 889 return 0.0f; 890 } 891 892 AutoMutex lock(mLock); 893 float volume; 894 if (output) { 895 PlaybackThread *thread = checkPlaybackThread_l(output); 896 if (thread == NULL) { 897 return 0.0f; 898 } 899 volume = thread->streamVolume(stream); 900 } else { 901 volume = streamVolume_l(stream); 902 } 903 904 return volume; 905} 906 907bool AudioFlinger::streamMute(audio_stream_type_t stream) const 908{ 909 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 910 return true; 911 } 912 913 AutoMutex lock(mLock); 914 return streamMute_l(stream); 915} 916 917status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 918{ 919 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 920 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 921 922 // check calling permissions 923 if (!settingsAllowed()) { 924 return PERMISSION_DENIED; 925 } 926 927 // ioHandle == 0 means the parameters are global to the audio hardware interface 928 if (ioHandle == 0) { 929 Mutex::Autolock _l(mLock); 930 status_t final_result = NO_ERROR; 931 { 932 AutoMutex lock(mHardwareLock); 933 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 934 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 935 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 936 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 937 final_result = result ?: final_result; 938 } 939 mHardwareStatus = AUDIO_HW_IDLE; 940 } 941 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 942 AudioParameter param = AudioParameter(keyValuePairs); 943 String8 value; 944 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 945 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 946 if (mBtNrecIsOff != btNrecIsOff) { 947 for (size_t i = 0; i < mRecordThreads.size(); i++) { 948 sp<RecordThread> thread = mRecordThreads.valueAt(i); 949 audio_devices_t device = thread->inDevice(); 950 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 951 // collect all of the thread's session IDs 952 KeyedVector<int, bool> ids = thread->sessionIds(); 953 // suspend effects associated with those session IDs 954 for (size_t j = 0; j < ids.size(); ++j) { 955 int sessionId = ids.keyAt(j); 956 thread->setEffectSuspended(FX_IID_AEC, 957 suspend, 958 sessionId); 959 thread->setEffectSuspended(FX_IID_NS, 960 suspend, 961 sessionId); 962 } 963 } 964 mBtNrecIsOff = btNrecIsOff; 965 } 966 } 967 String8 screenState; 968 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 969 bool isOff = screenState == "off"; 970 if (isOff != (AudioFlinger::mScreenState & 1)) { 971 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 972 } 973 } 974 return final_result; 975 } 976 977 // hold a strong ref on thread in case closeOutput() or closeInput() is called 978 // and the thread is exited once the lock is released 979 sp<ThreadBase> thread; 980 { 981 Mutex::Autolock _l(mLock); 982 thread = checkPlaybackThread_l(ioHandle); 983 if (thread == 0) { 984 thread = checkRecordThread_l(ioHandle); 985 } else if (thread == primaryPlaybackThread_l()) { 986 // indicate output device change to all input threads for pre processing 987 AudioParameter param = AudioParameter(keyValuePairs); 988 int value; 989 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 990 (value != 0)) { 991 for (size_t i = 0; i < mRecordThreads.size(); i++) { 992 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 993 } 994 } 995 } 996 } 997 if (thread != 0) { 998 return thread->setParameters(keyValuePairs); 999 } 1000 return BAD_VALUE; 1001} 1002 1003String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 1004{ 1005 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 1006 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 1007 1008 Mutex::Autolock _l(mLock); 1009 1010 if (ioHandle == 0) { 1011 String8 out_s8; 1012 1013 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1014 char *s; 1015 { 1016 AutoMutex lock(mHardwareLock); 1017 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 1018 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1019 s = dev->get_parameters(dev, keys.string()); 1020 mHardwareStatus = AUDIO_HW_IDLE; 1021 } 1022 out_s8 += String8(s ? s : ""); 1023 free(s); 1024 } 1025 return out_s8; 1026 } 1027 1028 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 1029 if (playbackThread != NULL) { 1030 return playbackThread->getParameters(keys); 1031 } 1032 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1033 if (recordThread != NULL) { 1034 return recordThread->getParameters(keys); 1035 } 1036 return String8(""); 1037} 1038 1039size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 1040 audio_channel_mask_t channelMask) const 1041{ 1042 status_t ret = initCheck(); 1043 if (ret != NO_ERROR) { 1044 return 0; 1045 } 1046 1047 AutoMutex lock(mHardwareLock); 1048 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1049 struct audio_config config; 1050 memset(&config, 0, sizeof(config)); 1051 config.sample_rate = sampleRate; 1052 config.channel_mask = channelMask; 1053 config.format = format; 1054 1055 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1056 size_t size = dev->get_input_buffer_size(dev, &config); 1057 mHardwareStatus = AUDIO_HW_IDLE; 1058 return size; 1059} 1060 1061unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1062{ 1063 Mutex::Autolock _l(mLock); 1064 1065 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1066 if (recordThread != NULL) { 1067 return recordThread->getInputFramesLost(); 1068 } 1069 return 0; 1070} 1071 1072status_t AudioFlinger::setVoiceVolume(float value) 1073{ 1074 status_t ret = initCheck(); 1075 if (ret != NO_ERROR) { 1076 return ret; 1077 } 1078 1079 // check calling permissions 1080 if (!settingsAllowed()) { 1081 return PERMISSION_DENIED; 1082 } 1083 1084 AutoMutex lock(mHardwareLock); 1085 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1086 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1087 ret = dev->set_voice_volume(dev, value); 1088 mHardwareStatus = AUDIO_HW_IDLE; 1089 1090 return ret; 1091} 1092 1093status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames, 1094 audio_io_handle_t output) const 1095{ 1096 status_t status; 1097 1098 Mutex::Autolock _l(mLock); 1099 1100 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1101 if (playbackThread != NULL) { 1102 return playbackThread->getRenderPosition(halFrames, dspFrames); 1103 } 1104 1105 return BAD_VALUE; 1106} 1107 1108void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1109{ 1110 1111 Mutex::Autolock _l(mLock); 1112 1113 pid_t pid = IPCThreadState::self()->getCallingPid(); 1114 if (mNotificationClients.indexOfKey(pid) < 0) { 1115 sp<NotificationClient> notificationClient = new NotificationClient(this, 1116 client, 1117 pid); 1118 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1119 1120 mNotificationClients.add(pid, notificationClient); 1121 1122 sp<IBinder> binder = client->asBinder(); 1123 binder->linkToDeath(notificationClient); 1124 1125 // the config change is always sent from playback or record threads to avoid deadlock 1126 // with AudioSystem::gLock 1127 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1128 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1129 } 1130 1131 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1132 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1133 } 1134 } 1135} 1136 1137void AudioFlinger::removeNotificationClient(pid_t pid) 1138{ 1139 Mutex::Autolock _l(mLock); 1140 1141 mNotificationClients.removeItem(pid); 1142 1143 ALOGV("%d died, releasing its sessions", pid); 1144 size_t num = mAudioSessionRefs.size(); 1145 bool removed = false; 1146 for (size_t i = 0; i< num; ) { 1147 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1148 ALOGV(" pid %d @ %d", ref->mPid, i); 1149 if (ref->mPid == pid) { 1150 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1151 mAudioSessionRefs.removeAt(i); 1152 delete ref; 1153 removed = true; 1154 num--; 1155 } else { 1156 i++; 1157 } 1158 } 1159 if (removed) { 1160 purgeStaleEffects_l(); 1161 } 1162} 1163 1164// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1165void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1166{ 1167 size_t size = mNotificationClients.size(); 1168 for (size_t i = 0; i < size; i++) { 1169 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1170 param2); 1171 } 1172} 1173 1174// removeClient_l() must be called with AudioFlinger::mLock held 1175void AudioFlinger::removeClient_l(pid_t pid) 1176{ 1177 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1178 IPCThreadState::self()->getCallingPid()); 1179 mClients.removeItem(pid); 1180} 1181 1182// getEffectThread_l() must be called with AudioFlinger::mLock held 1183sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1184{ 1185 sp<PlaybackThread> thread; 1186 1187 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1188 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1189 ALOG_ASSERT(thread == 0); 1190 thread = mPlaybackThreads.valueAt(i); 1191 } 1192 } 1193 1194 return thread; 1195} 1196 1197 1198 1199// ---------------------------------------------------------------------------- 1200 1201AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1202 : RefBase(), 1203 mAudioFlinger(audioFlinger), 1204 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 1205 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 1206 mPid(pid), 1207 mTimedTrackCount(0) 1208{ 1209 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 1210} 1211 1212// Client destructor must be called with AudioFlinger::mLock held 1213AudioFlinger::Client::~Client() 1214{ 1215 mAudioFlinger->removeClient_l(mPid); 1216} 1217 1218sp<MemoryDealer> AudioFlinger::Client::heap() const 1219{ 1220 return mMemoryDealer; 1221} 1222 1223// Reserve one of the limited slots for a timed audio track associated 1224// with this client 1225bool AudioFlinger::Client::reserveTimedTrack() 1226{ 1227 const int kMaxTimedTracksPerClient = 4; 1228 1229 Mutex::Autolock _l(mTimedTrackLock); 1230 1231 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 1232 ALOGW("can not create timed track - pid %d has exceeded the limit", 1233 mPid); 1234 return false; 1235 } 1236 1237 mTimedTrackCount++; 1238 return true; 1239} 1240 1241// Release a slot for a timed audio track 1242void AudioFlinger::Client::releaseTimedTrack() 1243{ 1244 Mutex::Autolock _l(mTimedTrackLock); 1245 mTimedTrackCount--; 1246} 1247 1248// ---------------------------------------------------------------------------- 1249 1250AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1251 const sp<IAudioFlingerClient>& client, 1252 pid_t pid) 1253 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1254{ 1255} 1256 1257AudioFlinger::NotificationClient::~NotificationClient() 1258{ 1259} 1260 1261void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 1262{ 1263 sp<NotificationClient> keep(this); 1264 mAudioFlinger->removeNotificationClient(mPid); 1265} 1266 1267 1268// ---------------------------------------------------------------------------- 1269 1270static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) { 1271 return audio_is_remote_submix_device(inDevice); 1272} 1273 1274sp<IAudioRecord> AudioFlinger::openRecord( 1275 audio_io_handle_t input, 1276 uint32_t sampleRate, 1277 audio_format_t format, 1278 audio_channel_mask_t channelMask, 1279 size_t frameCount, 1280 IAudioFlinger::track_flags_t *flags, 1281 pid_t tid, 1282 int *sessionId, 1283 status_t *status) 1284{ 1285 sp<RecordThread::RecordTrack> recordTrack; 1286 sp<RecordHandle> recordHandle; 1287 sp<Client> client; 1288 status_t lStatus; 1289 RecordThread *thread; 1290 size_t inFrameCount; 1291 int lSessionId; 1292 1293 // check calling permissions 1294 if (!recordingAllowed()) { 1295 ALOGE("openRecord() permission denied: recording not allowed"); 1296 lStatus = PERMISSION_DENIED; 1297 goto Exit; 1298 } 1299 1300 if (format != AUDIO_FORMAT_PCM_16_BIT) { 1301 ALOGE("openRecord() invalid format %d", format); 1302 lStatus = BAD_VALUE; 1303 goto Exit; 1304 } 1305 1306 // add client to list 1307 { // scope for mLock 1308 Mutex::Autolock _l(mLock); 1309 thread = checkRecordThread_l(input); 1310 if (thread == NULL) { 1311 ALOGE("openRecord() checkRecordThread_l failed"); 1312 lStatus = BAD_VALUE; 1313 goto Exit; 1314 } 1315 1316 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice()) 1317 && !captureAudioOutputAllowed()) { 1318 ALOGE("openRecord() permission denied: capture not allowed"); 1319 lStatus = PERMISSION_DENIED; 1320 goto Exit; 1321 } 1322 1323 pid_t pid = IPCThreadState::self()->getCallingPid(); 1324 client = registerPid_l(pid); 1325 1326 // If no audio session id is provided, create one here 1327 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 1328 lSessionId = *sessionId; 1329 } else { 1330 lSessionId = nextUniqueId(); 1331 if (sessionId != NULL) { 1332 *sessionId = lSessionId; 1333 } 1334 } 1335 // create new record track. 1336 // The record track uses one track in mHardwareMixerThread by convention. 1337 // TODO: the uid should be passed in as a parameter to openRecord 1338 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1339 frameCount, lSessionId, 1340 IPCThreadState::self()->getCallingUid(), 1341 flags, tid, &lStatus); 1342 LOG_ALWAYS_FATAL_IF((recordTrack != 0) != (lStatus == NO_ERROR)); 1343 } 1344 1345 if (lStatus != NO_ERROR) { 1346 // remove local strong reference to Client before deleting the RecordTrack so that the 1347 // Client destructor is called by the TrackBase destructor with mLock held 1348 client.clear(); 1349 recordTrack.clear(); 1350 goto Exit; 1351 } 1352 1353 // return handle to client 1354 recordHandle = new RecordHandle(recordTrack); 1355 1356Exit: 1357 *status = lStatus; 1358 return recordHandle; 1359} 1360 1361 1362 1363// ---------------------------------------------------------------------------- 1364 1365audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 1366{ 1367 if (!settingsAllowed()) { 1368 return 0; 1369 } 1370 Mutex::Autolock _l(mLock); 1371 return loadHwModule_l(name); 1372} 1373 1374// loadHwModule_l() must be called with AudioFlinger::mLock held 1375audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 1376{ 1377 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1378 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 1379 ALOGW("loadHwModule() module %s already loaded", name); 1380 return mAudioHwDevs.keyAt(i); 1381 } 1382 } 1383 1384 audio_hw_device_t *dev; 1385 1386 int rc = load_audio_interface(name, &dev); 1387 if (rc) { 1388 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 1389 return 0; 1390 } 1391 1392 mHardwareStatus = AUDIO_HW_INIT; 1393 rc = dev->init_check(dev); 1394 mHardwareStatus = AUDIO_HW_IDLE; 1395 if (rc) { 1396 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 1397 return 0; 1398 } 1399 1400 // Check and cache this HAL's level of support for master mute and master 1401 // volume. If this is the first HAL opened, and it supports the get 1402 // methods, use the initial values provided by the HAL as the current 1403 // master mute and volume settings. 1404 1405 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 1406 { // scope for auto-lock pattern 1407 AutoMutex lock(mHardwareLock); 1408 1409 if (0 == mAudioHwDevs.size()) { 1410 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 1411 if (NULL != dev->get_master_volume) { 1412 float mv; 1413 if (OK == dev->get_master_volume(dev, &mv)) { 1414 mMasterVolume = mv; 1415 } 1416 } 1417 1418 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 1419 if (NULL != dev->get_master_mute) { 1420 bool mm; 1421 if (OK == dev->get_master_mute(dev, &mm)) { 1422 mMasterMute = mm; 1423 } 1424 } 1425 } 1426 1427 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 1428 if ((NULL != dev->set_master_volume) && 1429 (OK == dev->set_master_volume(dev, mMasterVolume))) { 1430 flags = static_cast<AudioHwDevice::Flags>(flags | 1431 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 1432 } 1433 1434 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 1435 if ((NULL != dev->set_master_mute) && 1436 (OK == dev->set_master_mute(dev, mMasterMute))) { 1437 flags = static_cast<AudioHwDevice::Flags>(flags | 1438 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 1439 } 1440 1441 mHardwareStatus = AUDIO_HW_IDLE; 1442 } 1443 1444 audio_module_handle_t handle = nextUniqueId(); 1445 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags)); 1446 1447 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 1448 name, dev->common.module->name, dev->common.module->id, handle); 1449 1450 return handle; 1451 1452} 1453 1454// ---------------------------------------------------------------------------- 1455 1456uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 1457{ 1458 Mutex::Autolock _l(mLock); 1459 PlaybackThread *thread = primaryPlaybackThread_l(); 1460 return thread != NULL ? thread->sampleRate() : 0; 1461} 1462 1463size_t AudioFlinger::getPrimaryOutputFrameCount() 1464{ 1465 Mutex::Autolock _l(mLock); 1466 PlaybackThread *thread = primaryPlaybackThread_l(); 1467 return thread != NULL ? thread->frameCountHAL() : 0; 1468} 1469 1470// ---------------------------------------------------------------------------- 1471 1472status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice) 1473{ 1474 uid_t uid = IPCThreadState::self()->getCallingUid(); 1475 if (uid != AID_SYSTEM) { 1476 return PERMISSION_DENIED; 1477 } 1478 Mutex::Autolock _l(mLock); 1479 if (mIsDeviceTypeKnown) { 1480 return INVALID_OPERATION; 1481 } 1482 mIsLowRamDevice = isLowRamDevice; 1483 mIsDeviceTypeKnown = true; 1484 return NO_ERROR; 1485} 1486 1487// ---------------------------------------------------------------------------- 1488 1489audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 1490 audio_devices_t *pDevices, 1491 uint32_t *pSamplingRate, 1492 audio_format_t *pFormat, 1493 audio_channel_mask_t *pChannelMask, 1494 uint32_t *pLatencyMs, 1495 audio_output_flags_t flags, 1496 const audio_offload_info_t *offloadInfo) 1497{ 1498 struct audio_config config; 1499 memset(&config, 0, sizeof(config)); 1500 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1501 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1502 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1503 if (offloadInfo != NULL) { 1504 config.offload_info = *offloadInfo; 1505 } 1506 1507 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x", 1508 module, 1509 (pDevices != NULL) ? *pDevices : 0, 1510 config.sample_rate, 1511 config.format, 1512 config.channel_mask, 1513 flags); 1514 ALOGV("openOutput(), offloadInfo %p version 0x%04x", 1515 offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version); 1516 1517 if (pDevices == NULL || *pDevices == 0) { 1518 return 0; 1519 } 1520 1521 Mutex::Autolock _l(mLock); 1522 1523 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, *pDevices); 1524 if (outHwDev == NULL) { 1525 return 0; 1526 } 1527 1528 audio_hw_device_t *hwDevHal = outHwDev->hwDevice(); 1529 audio_io_handle_t id = nextUniqueId(); 1530 1531 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 1532 1533 audio_stream_out_t *outStream = NULL; 1534 status_t status = hwDevHal->open_output_stream(hwDevHal, 1535 id, 1536 *pDevices, 1537 (audio_output_flags_t)flags, 1538 &config, 1539 &outStream); 1540 1541 mHardwareStatus = AUDIO_HW_IDLE; 1542 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, " 1543 "Channels %x, status %d", 1544 outStream, 1545 config.sample_rate, 1546 config.format, 1547 config.channel_mask, 1548 status); 1549 1550 if (status == NO_ERROR && outStream != NULL) { 1551 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags); 1552 1553 PlaybackThread *thread; 1554 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1555 thread = new OffloadThread(this, output, id, *pDevices); 1556 ALOGV("openOutput() created offload output: ID %d thread %p", id, thread); 1557 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 1558 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 1559 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 1560 thread = new DirectOutputThread(this, output, id, *pDevices); 1561 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 1562 } else { 1563 thread = new MixerThread(this, output, id, *pDevices); 1564 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 1565 } 1566 mPlaybackThreads.add(id, thread); 1567 1568 if (pSamplingRate != NULL) { 1569 *pSamplingRate = config.sample_rate; 1570 } 1571 if (pFormat != NULL) { 1572 *pFormat = config.format; 1573 } 1574 if (pChannelMask != NULL) { 1575 *pChannelMask = config.channel_mask; 1576 } 1577 if (pLatencyMs != NULL) { 1578 *pLatencyMs = thread->latency(); 1579 } 1580 1581 // notify client processes of the new output creation 1582 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1583 1584 // the first primary output opened designates the primary hw device 1585 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 1586 ALOGI("Using module %d has the primary audio interface", module); 1587 mPrimaryHardwareDev = outHwDev; 1588 1589 AutoMutex lock(mHardwareLock); 1590 mHardwareStatus = AUDIO_HW_SET_MODE; 1591 hwDevHal->set_mode(hwDevHal, mMode); 1592 mHardwareStatus = AUDIO_HW_IDLE; 1593 } 1594 return id; 1595 } 1596 1597 return 0; 1598} 1599 1600audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 1601 audio_io_handle_t output2) 1602{ 1603 Mutex::Autolock _l(mLock); 1604 MixerThread *thread1 = checkMixerThread_l(output1); 1605 MixerThread *thread2 = checkMixerThread_l(output2); 1606 1607 if (thread1 == NULL || thread2 == NULL) { 1608 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 1609 output2); 1610 return 0; 1611 } 1612 1613 audio_io_handle_t id = nextUniqueId(); 1614 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 1615 thread->addOutputTrack(thread2); 1616 mPlaybackThreads.add(id, thread); 1617 // notify client processes of the new output creation 1618 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1619 return id; 1620} 1621 1622status_t AudioFlinger::closeOutput(audio_io_handle_t output) 1623{ 1624 return closeOutput_nonvirtual(output); 1625} 1626 1627status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 1628{ 1629 // keep strong reference on the playback thread so that 1630 // it is not destroyed while exit() is executed 1631 sp<PlaybackThread> thread; 1632 { 1633 Mutex::Autolock _l(mLock); 1634 thread = checkPlaybackThread_l(output); 1635 if (thread == NULL) { 1636 return BAD_VALUE; 1637 } 1638 1639 ALOGV("closeOutput() %d", output); 1640 1641 if (thread->type() == ThreadBase::MIXER) { 1642 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1643 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 1644 DuplicatingThread *dupThread = 1645 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 1646 dupThread->removeOutputTrack((MixerThread *)thread.get()); 1647 1648 } 1649 } 1650 } 1651 1652 1653 mPlaybackThreads.removeItem(output); 1654 // save all effects to the default thread 1655 if (mPlaybackThreads.size()) { 1656 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0)); 1657 if (dstThread != NULL) { 1658 // audioflinger lock is held here so the acquisition order of thread locks does not 1659 // matter 1660 Mutex::Autolock _dl(dstThread->mLock); 1661 Mutex::Autolock _sl(thread->mLock); 1662 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l(); 1663 for (size_t i = 0; i < effectChains.size(); i ++) { 1664 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true); 1665 } 1666 } 1667 } 1668 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 1669 } 1670 thread->exit(); 1671 // The thread entity (active unit of execution) is no longer running here, 1672 // but the ThreadBase container still exists. 1673 1674 if (thread->type() != ThreadBase::DUPLICATING) { 1675 AudioStreamOut *out = thread->clearOutput(); 1676 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 1677 // from now on thread->mOutput is NULL 1678 out->hwDev()->close_output_stream(out->hwDev(), out->stream); 1679 delete out; 1680 } 1681 return NO_ERROR; 1682} 1683 1684status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 1685{ 1686 Mutex::Autolock _l(mLock); 1687 PlaybackThread *thread = checkPlaybackThread_l(output); 1688 1689 if (thread == NULL) { 1690 return BAD_VALUE; 1691 } 1692 1693 ALOGV("suspendOutput() %d", output); 1694 thread->suspend(); 1695 1696 return NO_ERROR; 1697} 1698 1699status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 1700{ 1701 Mutex::Autolock _l(mLock); 1702 PlaybackThread *thread = checkPlaybackThread_l(output); 1703 1704 if (thread == NULL) { 1705 return BAD_VALUE; 1706 } 1707 1708 ALOGV("restoreOutput() %d", output); 1709 1710 thread->restore(); 1711 1712 return NO_ERROR; 1713} 1714 1715audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 1716 audio_devices_t *pDevices, 1717 uint32_t *pSamplingRate, 1718 audio_format_t *pFormat, 1719 audio_channel_mask_t *pChannelMask) 1720{ 1721 struct audio_config config; 1722 memset(&config, 0, sizeof(config)); 1723 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1724 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1725 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1726 1727 uint32_t reqSamplingRate = config.sample_rate; 1728 audio_format_t reqFormat = config.format; 1729 audio_channel_mask_t reqChannelMask = config.channel_mask; 1730 1731 if (pDevices == NULL || *pDevices == 0) { 1732 return 0; 1733 } 1734 1735 Mutex::Autolock _l(mLock); 1736 1737 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, *pDevices); 1738 if (inHwDev == NULL) { 1739 return 0; 1740 } 1741 1742 audio_hw_device_t *inHwHal = inHwDev->hwDevice(); 1743 audio_io_handle_t id = nextUniqueId(); 1744 1745 audio_stream_in_t *inStream = NULL; 1746 status_t status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, 1747 &inStream); 1748 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, " 1749 "status %d", 1750 inStream, 1751 config.sample_rate, 1752 config.format, 1753 config.channel_mask, 1754 status); 1755 1756 // If the input could not be opened with the requested parameters and we can handle the 1757 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can 1758 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs. 1759 if (status == BAD_VALUE && 1760 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 1761 (config.sample_rate <= 2 * reqSamplingRate) && 1762 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannelMask) <= FCC_2)) { 1763 // FIXME describe the change proposed by HAL (save old values so we can log them here) 1764 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 1765 inStream = NULL; 1766 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 1767 // FIXME log this new status; HAL should not propose any further changes 1768 } 1769 1770 if (status == NO_ERROR && inStream != NULL) { 1771 1772#ifdef TEE_SINK 1773 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 1774 // or (re-)create if current Pipe is idle and does not match the new format 1775 sp<NBAIO_Sink> teeSink; 1776 enum { 1777 TEE_SINK_NO, // don't copy input 1778 TEE_SINK_NEW, // copy input using a new pipe 1779 TEE_SINK_OLD, // copy input using an existing pipe 1780 } kind; 1781 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 1782 popcount(inStream->common.get_channels(&inStream->common))); 1783 if (!mTeeSinkInputEnabled) { 1784 kind = TEE_SINK_NO; 1785 } else if (format == Format_Invalid) { 1786 kind = TEE_SINK_NO; 1787 } else if (mRecordTeeSink == 0) { 1788 kind = TEE_SINK_NEW; 1789 } else if (mRecordTeeSink->getStrongCount() != 1) { 1790 kind = TEE_SINK_NO; 1791 } else if (format == mRecordTeeSink->format()) { 1792 kind = TEE_SINK_OLD; 1793 } else { 1794 kind = TEE_SINK_NEW; 1795 } 1796 switch (kind) { 1797 case TEE_SINK_NEW: { 1798 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 1799 size_t numCounterOffers = 0; 1800 const NBAIO_Format offers[1] = {format}; 1801 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 1802 ALOG_ASSERT(index == 0); 1803 PipeReader *pipeReader = new PipeReader(*pipe); 1804 numCounterOffers = 0; 1805 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 1806 ALOG_ASSERT(index == 0); 1807 mRecordTeeSink = pipe; 1808 mRecordTeeSource = pipeReader; 1809 teeSink = pipe; 1810 } 1811 break; 1812 case TEE_SINK_OLD: 1813 teeSink = mRecordTeeSink; 1814 break; 1815 case TEE_SINK_NO: 1816 default: 1817 break; 1818 } 1819#endif 1820 1821 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 1822 1823 // Start record thread 1824 // RecordThread requires both input and output device indication to forward to audio 1825 // pre processing modules 1826 RecordThread *thread = new RecordThread(this, 1827 input, 1828 reqSamplingRate, 1829 reqChannelMask, 1830 id, 1831 primaryOutputDevice_l(), 1832 *pDevices 1833#ifdef TEE_SINK 1834 , teeSink 1835#endif 1836 ); 1837 mRecordThreads.add(id, thread); 1838 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 1839 if (pSamplingRate != NULL) { 1840 *pSamplingRate = reqSamplingRate; 1841 } 1842 if (pFormat != NULL) { 1843 *pFormat = config.format; 1844 } 1845 if (pChannelMask != NULL) { 1846 *pChannelMask = reqChannelMask; 1847 } 1848 1849 // notify client processes of the new input creation 1850 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 1851 return id; 1852 } 1853 1854 return 0; 1855} 1856 1857status_t AudioFlinger::closeInput(audio_io_handle_t input) 1858{ 1859 return closeInput_nonvirtual(input); 1860} 1861 1862status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 1863{ 1864 // keep strong reference on the record thread so that 1865 // it is not destroyed while exit() is executed 1866 sp<RecordThread> thread; 1867 { 1868 Mutex::Autolock _l(mLock); 1869 thread = checkRecordThread_l(input); 1870 if (thread == 0) { 1871 return BAD_VALUE; 1872 } 1873 1874 ALOGV("closeInput() %d", input); 1875 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 1876 mRecordThreads.removeItem(input); 1877 } 1878 thread->exit(); 1879 // The thread entity (active unit of execution) is no longer running here, 1880 // but the ThreadBase container still exists. 1881 1882 AudioStreamIn *in = thread->clearInput(); 1883 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 1884 // from now on thread->mInput is NULL 1885 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 1886 delete in; 1887 1888 return NO_ERROR; 1889} 1890 1891status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 1892{ 1893 Mutex::Autolock _l(mLock); 1894 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 1895 1896 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1897 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1898 thread->invalidateTracks(stream); 1899 } 1900 1901 return NO_ERROR; 1902} 1903 1904 1905int AudioFlinger::newAudioSessionId() 1906{ 1907 return nextUniqueId(); 1908} 1909 1910void AudioFlinger::acquireAudioSessionId(int audioSession) 1911{ 1912 Mutex::Autolock _l(mLock); 1913 pid_t caller = IPCThreadState::self()->getCallingPid(); 1914 ALOGV("acquiring %d from %d", audioSession, caller); 1915 1916 // Ignore requests received from processes not known as notification client. The request 1917 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be 1918 // called from a different pid leaving a stale session reference. Also we don't know how 1919 // to clear this reference if the client process dies. 1920 if (mNotificationClients.indexOfKey(caller) < 0) { 1921 ALOGV("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession); 1922 return; 1923 } 1924 1925 size_t num = mAudioSessionRefs.size(); 1926 for (size_t i = 0; i< num; i++) { 1927 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 1928 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1929 ref->mCnt++; 1930 ALOGV(" incremented refcount to %d", ref->mCnt); 1931 return; 1932 } 1933 } 1934 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 1935 ALOGV(" added new entry for %d", audioSession); 1936} 1937 1938void AudioFlinger::releaseAudioSessionId(int audioSession) 1939{ 1940 Mutex::Autolock _l(mLock); 1941 pid_t caller = IPCThreadState::self()->getCallingPid(); 1942 ALOGV("releasing %d from %d", audioSession, caller); 1943 size_t num = mAudioSessionRefs.size(); 1944 for (size_t i = 0; i< num; i++) { 1945 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1946 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1947 ref->mCnt--; 1948 ALOGV(" decremented refcount to %d", ref->mCnt); 1949 if (ref->mCnt == 0) { 1950 mAudioSessionRefs.removeAt(i); 1951 delete ref; 1952 purgeStaleEffects_l(); 1953 } 1954 return; 1955 } 1956 } 1957 // If the caller is mediaserver it is likely that the session being released was acquired 1958 // on behalf of a process not in notification clients and we ignore the warning. 1959 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller); 1960} 1961 1962void AudioFlinger::purgeStaleEffects_l() { 1963 1964 ALOGV("purging stale effects"); 1965 1966 Vector< sp<EffectChain> > chains; 1967 1968 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1969 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 1970 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1971 sp<EffectChain> ec = t->mEffectChains[j]; 1972 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 1973 chains.push(ec); 1974 } 1975 } 1976 } 1977 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1978 sp<RecordThread> t = mRecordThreads.valueAt(i); 1979 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1980 sp<EffectChain> ec = t->mEffectChains[j]; 1981 chains.push(ec); 1982 } 1983 } 1984 1985 for (size_t i = 0; i < chains.size(); i++) { 1986 sp<EffectChain> ec = chains[i]; 1987 int sessionid = ec->sessionId(); 1988 sp<ThreadBase> t = ec->mThread.promote(); 1989 if (t == 0) { 1990 continue; 1991 } 1992 size_t numsessionrefs = mAudioSessionRefs.size(); 1993 bool found = false; 1994 for (size_t k = 0; k < numsessionrefs; k++) { 1995 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 1996 if (ref->mSessionid == sessionid) { 1997 ALOGV(" session %d still exists for %d with %d refs", 1998 sessionid, ref->mPid, ref->mCnt); 1999 found = true; 2000 break; 2001 } 2002 } 2003 if (!found) { 2004 Mutex::Autolock _l(t->mLock); 2005 // remove all effects from the chain 2006 while (ec->mEffects.size()) { 2007 sp<EffectModule> effect = ec->mEffects[0]; 2008 effect->unPin(); 2009 t->removeEffect_l(effect); 2010 if (effect->purgeHandles()) { 2011 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 2012 } 2013 AudioSystem::unregisterEffect(effect->id()); 2014 } 2015 } 2016 } 2017 return; 2018} 2019 2020// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2021AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 2022{ 2023 return mPlaybackThreads.valueFor(output).get(); 2024} 2025 2026// checkMixerThread_l() must be called with AudioFlinger::mLock held 2027AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 2028{ 2029 PlaybackThread *thread = checkPlaybackThread_l(output); 2030 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 2031} 2032 2033// checkRecordThread_l() must be called with AudioFlinger::mLock held 2034AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 2035{ 2036 return mRecordThreads.valueFor(input).get(); 2037} 2038 2039uint32_t AudioFlinger::nextUniqueId() 2040{ 2041 return android_atomic_inc(&mNextUniqueId); 2042} 2043 2044AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 2045{ 2046 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2047 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2048 AudioStreamOut *output = thread->getOutput(); 2049 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 2050 return thread; 2051 } 2052 } 2053 return NULL; 2054} 2055 2056audio_devices_t AudioFlinger::primaryOutputDevice_l() const 2057{ 2058 PlaybackThread *thread = primaryPlaybackThread_l(); 2059 2060 if (thread == NULL) { 2061 return 0; 2062 } 2063 2064 return thread->outDevice(); 2065} 2066 2067sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 2068 int triggerSession, 2069 int listenerSession, 2070 sync_event_callback_t callBack, 2071 void *cookie) 2072{ 2073 Mutex::Autolock _l(mLock); 2074 2075 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 2076 status_t playStatus = NAME_NOT_FOUND; 2077 status_t recStatus = NAME_NOT_FOUND; 2078 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2079 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 2080 if (playStatus == NO_ERROR) { 2081 return event; 2082 } 2083 } 2084 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2085 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 2086 if (recStatus == NO_ERROR) { 2087 return event; 2088 } 2089 } 2090 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2091 mPendingSyncEvents.add(event); 2092 } else { 2093 ALOGV("createSyncEvent() invalid event %d", event->type()); 2094 event.clear(); 2095 } 2096 return event; 2097} 2098 2099// ---------------------------------------------------------------------------- 2100// Effect management 2101// ---------------------------------------------------------------------------- 2102 2103 2104status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2105{ 2106 Mutex::Autolock _l(mLock); 2107 return EffectQueryNumberEffects(numEffects); 2108} 2109 2110status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2111{ 2112 Mutex::Autolock _l(mLock); 2113 return EffectQueryEffect(index, descriptor); 2114} 2115 2116status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2117 effect_descriptor_t *descriptor) const 2118{ 2119 Mutex::Autolock _l(mLock); 2120 return EffectGetDescriptor(pUuid, descriptor); 2121} 2122 2123 2124sp<IEffect> AudioFlinger::createEffect( 2125 effect_descriptor_t *pDesc, 2126 const sp<IEffectClient>& effectClient, 2127 int32_t priority, 2128 audio_io_handle_t io, 2129 int sessionId, 2130 status_t *status, 2131 int *id, 2132 int *enabled) 2133{ 2134 status_t lStatus = NO_ERROR; 2135 sp<EffectHandle> handle; 2136 effect_descriptor_t desc; 2137 2138 pid_t pid = IPCThreadState::self()->getCallingPid(); 2139 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 2140 pid, effectClient.get(), priority, sessionId, io); 2141 2142 if (pDesc == NULL) { 2143 lStatus = BAD_VALUE; 2144 goto Exit; 2145 } 2146 2147 // check audio settings permission for global effects 2148 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2149 lStatus = PERMISSION_DENIED; 2150 goto Exit; 2151 } 2152 2153 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2154 // that can only be created by audio policy manager (running in same process) 2155 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2156 lStatus = PERMISSION_DENIED; 2157 goto Exit; 2158 } 2159 2160 { 2161 if (!EffectIsNullUuid(&pDesc->uuid)) { 2162 // if uuid is specified, request effect descriptor 2163 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 2164 if (lStatus < 0) { 2165 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2166 goto Exit; 2167 } 2168 } else { 2169 // if uuid is not specified, look for an available implementation 2170 // of the required type in effect factory 2171 if (EffectIsNullUuid(&pDesc->type)) { 2172 ALOGW("createEffect() no effect type"); 2173 lStatus = BAD_VALUE; 2174 goto Exit; 2175 } 2176 uint32_t numEffects = 0; 2177 effect_descriptor_t d; 2178 d.flags = 0; // prevent compiler warning 2179 bool found = false; 2180 2181 lStatus = EffectQueryNumberEffects(&numEffects); 2182 if (lStatus < 0) { 2183 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2184 goto Exit; 2185 } 2186 for (uint32_t i = 0; i < numEffects; i++) { 2187 lStatus = EffectQueryEffect(i, &desc); 2188 if (lStatus < 0) { 2189 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2190 continue; 2191 } 2192 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2193 // If matching type found save effect descriptor. If the session is 2194 // 0 and the effect is not auxiliary, continue enumeration in case 2195 // an auxiliary version of this effect type is available 2196 found = true; 2197 d = desc; 2198 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2199 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2200 break; 2201 } 2202 } 2203 } 2204 if (!found) { 2205 lStatus = BAD_VALUE; 2206 ALOGW("createEffect() effect not found"); 2207 goto Exit; 2208 } 2209 // For same effect type, chose auxiliary version over insert version if 2210 // connect to output mix (Compliance to OpenSL ES) 2211 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2212 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2213 desc = d; 2214 } 2215 } 2216 2217 // Do not allow auxiliary effects on a session different from 0 (output mix) 2218 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2219 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2220 lStatus = INVALID_OPERATION; 2221 goto Exit; 2222 } 2223 2224 // check recording permission for visualizer 2225 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2226 !recordingAllowed()) { 2227 lStatus = PERMISSION_DENIED; 2228 goto Exit; 2229 } 2230 2231 // return effect descriptor 2232 *pDesc = desc; 2233 if (io == 0 && sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2234 // if the output returned by getOutputForEffect() is removed before we lock the 2235 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2236 // and we will exit safely 2237 io = AudioSystem::getOutputForEffect(&desc); 2238 ALOGV("createEffect got output %d", io); 2239 } 2240 2241 Mutex::Autolock _l(mLock); 2242 2243 // If output is not specified try to find a matching audio session ID in one of the 2244 // output threads. 2245 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2246 // because of code checking output when entering the function. 2247 // Note: io is never 0 when creating an effect on an input 2248 if (io == 0) { 2249 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2250 // output must be specified by AudioPolicyManager when using session 2251 // AUDIO_SESSION_OUTPUT_STAGE 2252 lStatus = BAD_VALUE; 2253 goto Exit; 2254 } 2255 // look for the thread where the specified audio session is present 2256 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2257 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2258 io = mPlaybackThreads.keyAt(i); 2259 break; 2260 } 2261 } 2262 if (io == 0) { 2263 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2264 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2265 io = mRecordThreads.keyAt(i); 2266 break; 2267 } 2268 } 2269 } 2270 // If no output thread contains the requested session ID, default to 2271 // first output. The effect chain will be moved to the correct output 2272 // thread when a track with the same session ID is created 2273 if (io == 0 && mPlaybackThreads.size()) { 2274 io = mPlaybackThreads.keyAt(0); 2275 } 2276 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2277 } 2278 ThreadBase *thread = checkRecordThread_l(io); 2279 if (thread == NULL) { 2280 thread = checkPlaybackThread_l(io); 2281 if (thread == NULL) { 2282 ALOGE("createEffect() unknown output thread"); 2283 lStatus = BAD_VALUE; 2284 goto Exit; 2285 } 2286 } 2287 2288 sp<Client> client = registerPid_l(pid); 2289 2290 // create effect on selected output thread 2291 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 2292 &desc, enabled, &lStatus); 2293 if (handle != 0 && id != NULL) { 2294 *id = handle->id(); 2295 } 2296 } 2297 2298Exit: 2299 *status = lStatus; 2300 return handle; 2301} 2302 2303status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2304 audio_io_handle_t dstOutput) 2305{ 2306 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2307 sessionId, srcOutput, dstOutput); 2308 Mutex::Autolock _l(mLock); 2309 if (srcOutput == dstOutput) { 2310 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2311 return NO_ERROR; 2312 } 2313 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2314 if (srcThread == NULL) { 2315 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2316 return BAD_VALUE; 2317 } 2318 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2319 if (dstThread == NULL) { 2320 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2321 return BAD_VALUE; 2322 } 2323 2324 Mutex::Autolock _dl(dstThread->mLock); 2325 Mutex::Autolock _sl(srcThread->mLock); 2326 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 2327} 2328 2329// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2330status_t AudioFlinger::moveEffectChain_l(int sessionId, 2331 AudioFlinger::PlaybackThread *srcThread, 2332 AudioFlinger::PlaybackThread *dstThread, 2333 bool reRegister) 2334{ 2335 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2336 sessionId, srcThread, dstThread); 2337 2338 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2339 if (chain == 0) { 2340 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2341 sessionId, srcThread); 2342 return INVALID_OPERATION; 2343 } 2344 2345 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2346 // so that a new chain is created with correct parameters when first effect is added. This is 2347 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2348 // removed. 2349 srcThread->removeEffectChain_l(chain); 2350 2351 // transfer all effects one by one so that new effect chain is created on new thread with 2352 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2353 sp<EffectChain> dstChain; 2354 uint32_t strategy = 0; // prevent compiler warning 2355 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2356 Vector< sp<EffectModule> > removed; 2357 status_t status = NO_ERROR; 2358 while (effect != 0) { 2359 srcThread->removeEffect_l(effect); 2360 removed.add(effect); 2361 status = dstThread->addEffect_l(effect); 2362 if (status != NO_ERROR) { 2363 break; 2364 } 2365 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2366 if (effect->state() == EffectModule::ACTIVE || 2367 effect->state() == EffectModule::STOPPING) { 2368 effect->start(); 2369 } 2370 // if the move request is not received from audio policy manager, the effect must be 2371 // re-registered with the new strategy and output 2372 if (dstChain == 0) { 2373 dstChain = effect->chain().promote(); 2374 if (dstChain == 0) { 2375 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2376 status = NO_INIT; 2377 break; 2378 } 2379 strategy = dstChain->strategy(); 2380 } 2381 if (reRegister) { 2382 AudioSystem::unregisterEffect(effect->id()); 2383 AudioSystem::registerEffect(&effect->desc(), 2384 dstThread->id(), 2385 strategy, 2386 sessionId, 2387 effect->id()); 2388 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2389 } 2390 effect = chain->getEffectFromId_l(0); 2391 } 2392 2393 if (status != NO_ERROR) { 2394 for (size_t i = 0; i < removed.size(); i++) { 2395 srcThread->addEffect_l(removed[i]); 2396 if (dstChain != 0 && reRegister) { 2397 AudioSystem::unregisterEffect(removed[i]->id()); 2398 AudioSystem::registerEffect(&removed[i]->desc(), 2399 srcThread->id(), 2400 strategy, 2401 sessionId, 2402 removed[i]->id()); 2403 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2404 } 2405 } 2406 } 2407 2408 return status; 2409} 2410 2411bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 2412{ 2413 if (mGlobalEffectEnableTime != 0 && 2414 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 2415 return true; 2416 } 2417 2418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2419 sp<EffectChain> ec = 2420 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2421 if (ec != 0 && ec->isNonOffloadableEnabled()) { 2422 return true; 2423 } 2424 } 2425 return false; 2426} 2427 2428void AudioFlinger::onNonOffloadableGlobalEffectEnable() 2429{ 2430 Mutex::Autolock _l(mLock); 2431 2432 mGlobalEffectEnableTime = systemTime(); 2433 2434 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2435 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2436 if (t->mType == ThreadBase::OFFLOAD) { 2437 t->invalidateTracks(AUDIO_STREAM_MUSIC); 2438 } 2439 } 2440 2441} 2442 2443struct Entry { 2444#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2445 char mName[MAX_NAME]; 2446}; 2447 2448int comparEntry(const void *p1, const void *p2) 2449{ 2450 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2451} 2452 2453#ifdef TEE_SINK 2454void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2455{ 2456 NBAIO_Source *teeSource = source.get(); 2457 if (teeSource != NULL) { 2458 // .wav rotation 2459 // There is a benign race condition if 2 threads call this simultaneously. 2460 // They would both traverse the directory, but the result would simply be 2461 // failures at unlink() which are ignored. It's also unlikely since 2462 // normally dumpsys is only done by bugreport or from the command line. 2463 char teePath[32+256]; 2464 strcpy(teePath, "/data/misc/media"); 2465 size_t teePathLen = strlen(teePath); 2466 DIR *dir = opendir(teePath); 2467 teePath[teePathLen++] = '/'; 2468 if (dir != NULL) { 2469#define MAX_SORT 20 // number of entries to sort 2470#define MAX_KEEP 10 // number of entries to keep 2471 struct Entry entries[MAX_SORT]; 2472 size_t entryCount = 0; 2473 while (entryCount < MAX_SORT) { 2474 struct dirent de; 2475 struct dirent *result = NULL; 2476 int rc = readdir_r(dir, &de, &result); 2477 if (rc != 0) { 2478 ALOGW("readdir_r failed %d", rc); 2479 break; 2480 } 2481 if (result == NULL) { 2482 break; 2483 } 2484 if (result != &de) { 2485 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2486 break; 2487 } 2488 // ignore non .wav file entries 2489 size_t nameLen = strlen(de.d_name); 2490 if (nameLen <= 4 || nameLen >= MAX_NAME || 2491 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2492 continue; 2493 } 2494 strcpy(entries[entryCount++].mName, de.d_name); 2495 } 2496 (void) closedir(dir); 2497 if (entryCount > MAX_KEEP) { 2498 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2499 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2500 strcpy(&teePath[teePathLen], entries[i].mName); 2501 (void) unlink(teePath); 2502 } 2503 } 2504 } else { 2505 if (fd >= 0) { 2506 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2507 } 2508 } 2509 char teeTime[16]; 2510 struct timeval tv; 2511 gettimeofday(&tv, NULL); 2512 struct tm tm; 2513 localtime_r(&tv.tv_sec, &tm); 2514 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2515 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2516 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2517 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2518 if (teeFd >= 0) { 2519 char wavHeader[44]; 2520 memcpy(wavHeader, 2521 "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", 2522 sizeof(wavHeader)); 2523 NBAIO_Format format = teeSource->format(); 2524 unsigned channelCount = Format_channelCount(format); 2525 ALOG_ASSERT(channelCount <= FCC_2); 2526 uint32_t sampleRate = Format_sampleRate(format); 2527 wavHeader[22] = channelCount; // number of channels 2528 wavHeader[24] = sampleRate; // sample rate 2529 wavHeader[25] = sampleRate >> 8; 2530 wavHeader[32] = channelCount * 2; // block alignment 2531 write(teeFd, wavHeader, sizeof(wavHeader)); 2532 size_t total = 0; 2533 bool firstRead = true; 2534 for (;;) { 2535#define TEE_SINK_READ 1024 2536 short buffer[TEE_SINK_READ * FCC_2]; 2537 size_t count = TEE_SINK_READ; 2538 ssize_t actual = teeSource->read(buffer, count, 2539 AudioBufferProvider::kInvalidPTS); 2540 bool wasFirstRead = firstRead; 2541 firstRead = false; 2542 if (actual <= 0) { 2543 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2544 continue; 2545 } 2546 break; 2547 } 2548 ALOG_ASSERT(actual <= (ssize_t)count); 2549 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2550 total += actual; 2551 } 2552 lseek(teeFd, (off_t) 4, SEEK_SET); 2553 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2554 write(teeFd, &temp, sizeof(temp)); 2555 lseek(teeFd, (off_t) 40, SEEK_SET); 2556 temp = total * channelCount * sizeof(short); 2557 write(teeFd, &temp, sizeof(temp)); 2558 close(teeFd); 2559 if (fd >= 0) { 2560 fdprintf(fd, "tee copied to %s\n", teePath); 2561 } 2562 } else { 2563 if (fd >= 0) { 2564 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2565 } 2566 } 2567 } 2568} 2569#endif 2570 2571// ---------------------------------------------------------------------------- 2572 2573status_t AudioFlinger::onTransact( 2574 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2575{ 2576 return BnAudioFlinger::onTransact(code, data, reply, flags); 2577} 2578 2579}; // namespace android 2580