AudioFlinger.cpp revision 0f11b51a57bc9062c4fe8af73747319cedabc5d6
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 __unused) 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 __unused) 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 __unused) 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_ALLOCATE) { 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 LOG_ALWAYS_FATAL_IF((track != 0) != (lStatus == NO_ERROR)); 563 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 564 565 // move effect chain to this output thread if an effect on same session was waiting 566 // for a track to be created 567 if (lStatus == NO_ERROR && effectThread != NULL) { 568 // no risk of deadlock because AudioFlinger::mLock is held 569 Mutex::Autolock _dl(thread->mLock); 570 Mutex::Autolock _sl(effectThread->mLock); 571 moveEffectChain_l(lSessionId, effectThread, thread, true); 572 } 573 574 // Look for sync events awaiting for a session to be used. 575 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 576 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 577 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 578 if (lStatus == NO_ERROR) { 579 (void) track->setSyncEvent(mPendingSyncEvents[i]); 580 } else { 581 mPendingSyncEvents[i]->cancel(); 582 } 583 mPendingSyncEvents.removeAt(i); 584 i--; 585 } 586 } 587 } 588 589 } 590 591 if (lStatus == NO_ERROR) { 592 // s for server's pid, n for normal mixer name, f for fast index 593 name = String8::format("s:%d;n:%d;f:%d", getpid_cached, track->name() - AudioMixer::TRACK0, 594 track->fastIndex()); 595 trackHandle = new TrackHandle(track); 596 } else { 597 // remove local strong reference to Client before deleting the Track so that the Client 598 // destructor is called by the TrackBase destructor with mLock held 599 client.clear(); 600 track.clear(); 601 } 602 603Exit: 604 *status = lStatus; 605 return trackHandle; 606} 607 608uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 609{ 610 Mutex::Autolock _l(mLock); 611 PlaybackThread *thread = checkPlaybackThread_l(output); 612 if (thread == NULL) { 613 ALOGW("sampleRate() unknown thread %d", output); 614 return 0; 615 } 616 return thread->sampleRate(); 617} 618 619int AudioFlinger::channelCount(audio_io_handle_t output) const 620{ 621 Mutex::Autolock _l(mLock); 622 PlaybackThread *thread = checkPlaybackThread_l(output); 623 if (thread == NULL) { 624 ALOGW("channelCount() unknown thread %d", output); 625 return 0; 626 } 627 return thread->channelCount(); 628} 629 630audio_format_t AudioFlinger::format(audio_io_handle_t output) const 631{ 632 Mutex::Autolock _l(mLock); 633 PlaybackThread *thread = checkPlaybackThread_l(output); 634 if (thread == NULL) { 635 ALOGW("format() unknown thread %d", output); 636 return AUDIO_FORMAT_INVALID; 637 } 638 return thread->format(); 639} 640 641size_t AudioFlinger::frameCount(audio_io_handle_t output) const 642{ 643 Mutex::Autolock _l(mLock); 644 PlaybackThread *thread = checkPlaybackThread_l(output); 645 if (thread == NULL) { 646 ALOGW("frameCount() unknown thread %d", output); 647 return 0; 648 } 649 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 650 // should examine all callers and fix them to handle smaller counts 651 return thread->frameCount(); 652} 653 654uint32_t AudioFlinger::latency(audio_io_handle_t output) const 655{ 656 Mutex::Autolock _l(mLock); 657 PlaybackThread *thread = checkPlaybackThread_l(output); 658 if (thread == NULL) { 659 ALOGW("latency(): no playback thread found for output handle %d", output); 660 return 0; 661 } 662 return thread->latency(); 663} 664 665status_t AudioFlinger::setMasterVolume(float value) 666{ 667 status_t ret = initCheck(); 668 if (ret != NO_ERROR) { 669 return ret; 670 } 671 672 // check calling permissions 673 if (!settingsAllowed()) { 674 return PERMISSION_DENIED; 675 } 676 677 Mutex::Autolock _l(mLock); 678 mMasterVolume = value; 679 680 // Set master volume in the HALs which support it. 681 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 682 AutoMutex lock(mHardwareLock); 683 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 684 685 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 686 if (dev->canSetMasterVolume()) { 687 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 688 } 689 mHardwareStatus = AUDIO_HW_IDLE; 690 } 691 692 // Now set the master volume in each playback thread. Playback threads 693 // assigned to HALs which do not have master volume support will apply 694 // master volume during the mix operation. Threads with HALs which do 695 // support master volume will simply ignore the setting. 696 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 697 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 698 699 return NO_ERROR; 700} 701 702status_t AudioFlinger::setMode(audio_mode_t mode) 703{ 704 status_t ret = initCheck(); 705 if (ret != NO_ERROR) { 706 return ret; 707 } 708 709 // check calling permissions 710 if (!settingsAllowed()) { 711 return PERMISSION_DENIED; 712 } 713 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 714 ALOGW("Illegal value: setMode(%d)", mode); 715 return BAD_VALUE; 716 } 717 718 { // scope for the lock 719 AutoMutex lock(mHardwareLock); 720 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 721 mHardwareStatus = AUDIO_HW_SET_MODE; 722 ret = dev->set_mode(dev, mode); 723 mHardwareStatus = AUDIO_HW_IDLE; 724 } 725 726 if (NO_ERROR == ret) { 727 Mutex::Autolock _l(mLock); 728 mMode = mode; 729 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 730 mPlaybackThreads.valueAt(i)->setMode(mode); 731 } 732 733 return ret; 734} 735 736status_t AudioFlinger::setMicMute(bool state) 737{ 738 status_t ret = initCheck(); 739 if (ret != NO_ERROR) { 740 return ret; 741 } 742 743 // check calling permissions 744 if (!settingsAllowed()) { 745 return PERMISSION_DENIED; 746 } 747 748 AutoMutex lock(mHardwareLock); 749 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 750 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 751 ret = dev->set_mic_mute(dev, state); 752 mHardwareStatus = AUDIO_HW_IDLE; 753 return ret; 754} 755 756bool AudioFlinger::getMicMute() const 757{ 758 status_t ret = initCheck(); 759 if (ret != NO_ERROR) { 760 return false; 761 } 762 763 bool state = AUDIO_MODE_INVALID; 764 AutoMutex lock(mHardwareLock); 765 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 766 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 767 dev->get_mic_mute(dev, &state); 768 mHardwareStatus = AUDIO_HW_IDLE; 769 return state; 770} 771 772status_t AudioFlinger::setMasterMute(bool muted) 773{ 774 status_t ret = initCheck(); 775 if (ret != NO_ERROR) { 776 return ret; 777 } 778 779 // check calling permissions 780 if (!settingsAllowed()) { 781 return PERMISSION_DENIED; 782 } 783 784 Mutex::Autolock _l(mLock); 785 mMasterMute = muted; 786 787 // Set master mute in the HALs which support it. 788 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 789 AutoMutex lock(mHardwareLock); 790 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 791 792 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 793 if (dev->canSetMasterMute()) { 794 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 795 } 796 mHardwareStatus = AUDIO_HW_IDLE; 797 } 798 799 // Now set the master mute in each playback thread. Playback threads 800 // assigned to HALs which do not have master mute support will apply master 801 // mute during the mix operation. Threads with HALs which do support master 802 // mute will simply ignore the setting. 803 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 804 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 805 806 return NO_ERROR; 807} 808 809float AudioFlinger::masterVolume() const 810{ 811 Mutex::Autolock _l(mLock); 812 return masterVolume_l(); 813} 814 815bool AudioFlinger::masterMute() const 816{ 817 Mutex::Autolock _l(mLock); 818 return masterMute_l(); 819} 820 821float AudioFlinger::masterVolume_l() const 822{ 823 return mMasterVolume; 824} 825 826bool AudioFlinger::masterMute_l() const 827{ 828 return mMasterMute; 829} 830 831status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 832 audio_io_handle_t output) 833{ 834 // check calling permissions 835 if (!settingsAllowed()) { 836 return PERMISSION_DENIED; 837 } 838 839 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 840 ALOGE("setStreamVolume() invalid stream %d", stream); 841 return BAD_VALUE; 842 } 843 844 AutoMutex lock(mLock); 845 PlaybackThread *thread = NULL; 846 if (output) { 847 thread = checkPlaybackThread_l(output); 848 if (thread == NULL) { 849 return BAD_VALUE; 850 } 851 } 852 853 mStreamTypes[stream].volume = value; 854 855 if (thread == NULL) { 856 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 857 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 858 } 859 } else { 860 thread->setStreamVolume(stream, value); 861 } 862 863 return NO_ERROR; 864} 865 866status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 867{ 868 // check calling permissions 869 if (!settingsAllowed()) { 870 return PERMISSION_DENIED; 871 } 872 873 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 874 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 875 ALOGE("setStreamMute() invalid stream %d", stream); 876 return BAD_VALUE; 877 } 878 879 AutoMutex lock(mLock); 880 mStreamTypes[stream].mute = muted; 881 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 882 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 883 884 return NO_ERROR; 885} 886 887float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 888{ 889 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 890 return 0.0f; 891 } 892 893 AutoMutex lock(mLock); 894 float volume; 895 if (output) { 896 PlaybackThread *thread = checkPlaybackThread_l(output); 897 if (thread == NULL) { 898 return 0.0f; 899 } 900 volume = thread->streamVolume(stream); 901 } else { 902 volume = streamVolume_l(stream); 903 } 904 905 return volume; 906} 907 908bool AudioFlinger::streamMute(audio_stream_type_t stream) const 909{ 910 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 911 return true; 912 } 913 914 AutoMutex lock(mLock); 915 return streamMute_l(stream); 916} 917 918status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 919{ 920 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 921 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 922 923 // check calling permissions 924 if (!settingsAllowed()) { 925 return PERMISSION_DENIED; 926 } 927 928 // ioHandle == 0 means the parameters are global to the audio hardware interface 929 if (ioHandle == 0) { 930 Mutex::Autolock _l(mLock); 931 status_t final_result = NO_ERROR; 932 { 933 AutoMutex lock(mHardwareLock); 934 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 935 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 936 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 937 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 938 final_result = result ?: final_result; 939 } 940 mHardwareStatus = AUDIO_HW_IDLE; 941 } 942 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 943 AudioParameter param = AudioParameter(keyValuePairs); 944 String8 value; 945 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 946 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 947 if (mBtNrecIsOff != btNrecIsOff) { 948 for (size_t i = 0; i < mRecordThreads.size(); i++) { 949 sp<RecordThread> thread = mRecordThreads.valueAt(i); 950 audio_devices_t device = thread->inDevice(); 951 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 952 // collect all of the thread's session IDs 953 KeyedVector<int, bool> ids = thread->sessionIds(); 954 // suspend effects associated with those session IDs 955 for (size_t j = 0; j < ids.size(); ++j) { 956 int sessionId = ids.keyAt(j); 957 thread->setEffectSuspended(FX_IID_AEC, 958 suspend, 959 sessionId); 960 thread->setEffectSuspended(FX_IID_NS, 961 suspend, 962 sessionId); 963 } 964 } 965 mBtNrecIsOff = btNrecIsOff; 966 } 967 } 968 String8 screenState; 969 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 970 bool isOff = screenState == "off"; 971 if (isOff != (AudioFlinger::mScreenState & 1)) { 972 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 973 } 974 } 975 return final_result; 976 } 977 978 // hold a strong ref on thread in case closeOutput() or closeInput() is called 979 // and the thread is exited once the lock is released 980 sp<ThreadBase> thread; 981 { 982 Mutex::Autolock _l(mLock); 983 thread = checkPlaybackThread_l(ioHandle); 984 if (thread == 0) { 985 thread = checkRecordThread_l(ioHandle); 986 } else if (thread == primaryPlaybackThread_l()) { 987 // indicate output device change to all input threads for pre processing 988 AudioParameter param = AudioParameter(keyValuePairs); 989 int value; 990 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 991 (value != 0)) { 992 for (size_t i = 0; i < mRecordThreads.size(); i++) { 993 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 994 } 995 } 996 } 997 } 998 if (thread != 0) { 999 return thread->setParameters(keyValuePairs); 1000 } 1001 return BAD_VALUE; 1002} 1003 1004String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 1005{ 1006 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 1007 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 1008 1009 Mutex::Autolock _l(mLock); 1010 1011 if (ioHandle == 0) { 1012 String8 out_s8; 1013 1014 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1015 char *s; 1016 { 1017 AutoMutex lock(mHardwareLock); 1018 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 1019 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1020 s = dev->get_parameters(dev, keys.string()); 1021 mHardwareStatus = AUDIO_HW_IDLE; 1022 } 1023 out_s8 += String8(s ? s : ""); 1024 free(s); 1025 } 1026 return out_s8; 1027 } 1028 1029 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 1030 if (playbackThread != NULL) { 1031 return playbackThread->getParameters(keys); 1032 } 1033 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1034 if (recordThread != NULL) { 1035 return recordThread->getParameters(keys); 1036 } 1037 return String8(""); 1038} 1039 1040size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 1041 audio_channel_mask_t channelMask) const 1042{ 1043 status_t ret = initCheck(); 1044 if (ret != NO_ERROR) { 1045 return 0; 1046 } 1047 1048 AutoMutex lock(mHardwareLock); 1049 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1050 struct audio_config config; 1051 memset(&config, 0, sizeof(config)); 1052 config.sample_rate = sampleRate; 1053 config.channel_mask = channelMask; 1054 config.format = format; 1055 1056 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1057 size_t size = dev->get_input_buffer_size(dev, &config); 1058 mHardwareStatus = AUDIO_HW_IDLE; 1059 return size; 1060} 1061 1062uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1063{ 1064 Mutex::Autolock _l(mLock); 1065 1066 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1067 if (recordThread != NULL) { 1068 return recordThread->getInputFramesLost(); 1069 } 1070 return 0; 1071} 1072 1073status_t AudioFlinger::setVoiceVolume(float value) 1074{ 1075 status_t ret = initCheck(); 1076 if (ret != NO_ERROR) { 1077 return ret; 1078 } 1079 1080 // check calling permissions 1081 if (!settingsAllowed()) { 1082 return PERMISSION_DENIED; 1083 } 1084 1085 AutoMutex lock(mHardwareLock); 1086 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1087 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1088 ret = dev->set_voice_volume(dev, value); 1089 mHardwareStatus = AUDIO_HW_IDLE; 1090 1091 return ret; 1092} 1093 1094status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames, 1095 audio_io_handle_t output) const 1096{ 1097 status_t status; 1098 1099 Mutex::Autolock _l(mLock); 1100 1101 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1102 if (playbackThread != NULL) { 1103 return playbackThread->getRenderPosition(halFrames, dspFrames); 1104 } 1105 1106 return BAD_VALUE; 1107} 1108 1109void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1110{ 1111 1112 Mutex::Autolock _l(mLock); 1113 1114 pid_t pid = IPCThreadState::self()->getCallingPid(); 1115 if (mNotificationClients.indexOfKey(pid) < 0) { 1116 sp<NotificationClient> notificationClient = new NotificationClient(this, 1117 client, 1118 pid); 1119 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1120 1121 mNotificationClients.add(pid, notificationClient); 1122 1123 sp<IBinder> binder = client->asBinder(); 1124 binder->linkToDeath(notificationClient); 1125 1126 // the config change is always sent from playback or record threads to avoid deadlock 1127 // with AudioSystem::gLock 1128 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1129 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1130 } 1131 1132 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1133 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1134 } 1135 } 1136} 1137 1138void AudioFlinger::removeNotificationClient(pid_t pid) 1139{ 1140 Mutex::Autolock _l(mLock); 1141 1142 mNotificationClients.removeItem(pid); 1143 1144 ALOGV("%d died, releasing its sessions", pid); 1145 size_t num = mAudioSessionRefs.size(); 1146 bool removed = false; 1147 for (size_t i = 0; i< num; ) { 1148 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1149 ALOGV(" pid %d @ %d", ref->mPid, i); 1150 if (ref->mPid == pid) { 1151 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1152 mAudioSessionRefs.removeAt(i); 1153 delete ref; 1154 removed = true; 1155 num--; 1156 } else { 1157 i++; 1158 } 1159 } 1160 if (removed) { 1161 purgeStaleEffects_l(); 1162 } 1163} 1164 1165// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1166void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1167{ 1168 size_t size = mNotificationClients.size(); 1169 for (size_t i = 0; i < size; i++) { 1170 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1171 param2); 1172 } 1173} 1174 1175// removeClient_l() must be called with AudioFlinger::mLock held 1176void AudioFlinger::removeClient_l(pid_t pid) 1177{ 1178 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1179 IPCThreadState::self()->getCallingPid()); 1180 mClients.removeItem(pid); 1181} 1182 1183// getEffectThread_l() must be called with AudioFlinger::mLock held 1184sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1185{ 1186 sp<PlaybackThread> thread; 1187 1188 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1189 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1190 ALOG_ASSERT(thread == 0); 1191 thread = mPlaybackThreads.valueAt(i); 1192 } 1193 } 1194 1195 return thread; 1196} 1197 1198 1199 1200// ---------------------------------------------------------------------------- 1201 1202AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1203 : RefBase(), 1204 mAudioFlinger(audioFlinger), 1205 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 1206 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 1207 mPid(pid), 1208 mTimedTrackCount(0) 1209{ 1210 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 1211} 1212 1213// Client destructor must be called with AudioFlinger::mLock held 1214AudioFlinger::Client::~Client() 1215{ 1216 mAudioFlinger->removeClient_l(mPid); 1217} 1218 1219sp<MemoryDealer> AudioFlinger::Client::heap() const 1220{ 1221 return mMemoryDealer; 1222} 1223 1224// Reserve one of the limited slots for a timed audio track associated 1225// with this client 1226bool AudioFlinger::Client::reserveTimedTrack() 1227{ 1228 const int kMaxTimedTracksPerClient = 4; 1229 1230 Mutex::Autolock _l(mTimedTrackLock); 1231 1232 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 1233 ALOGW("can not create timed track - pid %d has exceeded the limit", 1234 mPid); 1235 return false; 1236 } 1237 1238 mTimedTrackCount++; 1239 return true; 1240} 1241 1242// Release a slot for a timed audio track 1243void AudioFlinger::Client::releaseTimedTrack() 1244{ 1245 Mutex::Autolock _l(mTimedTrackLock); 1246 mTimedTrackCount--; 1247} 1248 1249// ---------------------------------------------------------------------------- 1250 1251AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1252 const sp<IAudioFlingerClient>& client, 1253 pid_t pid) 1254 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1255{ 1256} 1257 1258AudioFlinger::NotificationClient::~NotificationClient() 1259{ 1260} 1261 1262void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused) 1263{ 1264 sp<NotificationClient> keep(this); 1265 mAudioFlinger->removeNotificationClient(mPid); 1266} 1267 1268 1269// ---------------------------------------------------------------------------- 1270 1271static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) { 1272 return audio_is_remote_submix_device(inDevice); 1273} 1274 1275sp<IAudioRecord> AudioFlinger::openRecord( 1276 audio_io_handle_t input, 1277 uint32_t sampleRate, 1278 audio_format_t format, 1279 audio_channel_mask_t channelMask, 1280 size_t *frameCount, 1281 IAudioFlinger::track_flags_t *flags, 1282 pid_t tid, 1283 int *sessionId, 1284 status_t *status) 1285{ 1286 sp<RecordThread::RecordTrack> recordTrack; 1287 sp<RecordHandle> recordHandle; 1288 sp<Client> client; 1289 status_t lStatus; 1290 RecordThread *thread; 1291 size_t inFrameCount; 1292 int lSessionId; 1293 1294 // check calling permissions 1295 if (!recordingAllowed()) { 1296 ALOGE("openRecord() permission denied: recording not allowed"); 1297 lStatus = PERMISSION_DENIED; 1298 goto Exit; 1299 } 1300 1301 if (format != AUDIO_FORMAT_PCM_16_BIT) { 1302 ALOGE("openRecord() invalid format %d", format); 1303 lStatus = BAD_VALUE; 1304 goto Exit; 1305 } 1306 1307 // add client to list 1308 { // scope for mLock 1309 Mutex::Autolock _l(mLock); 1310 thread = checkRecordThread_l(input); 1311 if (thread == NULL) { 1312 ALOGE("openRecord() checkRecordThread_l failed"); 1313 lStatus = BAD_VALUE; 1314 goto Exit; 1315 } 1316 1317 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice()) 1318 && !captureAudioOutputAllowed()) { 1319 ALOGE("openRecord() permission denied: capture not allowed"); 1320 lStatus = PERMISSION_DENIED; 1321 goto Exit; 1322 } 1323 1324 pid_t pid = IPCThreadState::self()->getCallingPid(); 1325 client = registerPid_l(pid); 1326 1327 // If no audio session id is provided, create one here 1328 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 1329 lSessionId = *sessionId; 1330 } else { 1331 lSessionId = nextUniqueId(); 1332 if (sessionId != NULL) { 1333 *sessionId = lSessionId; 1334 } 1335 } 1336 // create new record track. 1337 // The record track uses one track in mHardwareMixerThread by convention. 1338 // TODO: the uid should be passed in as a parameter to openRecord 1339 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1340 frameCount, lSessionId, 1341 IPCThreadState::self()->getCallingUid(), 1342 flags, tid, &lStatus); 1343 LOG_ALWAYS_FATAL_IF((recordTrack != 0) != (lStatus == NO_ERROR)); 1344 } 1345 1346 if (lStatus != NO_ERROR) { 1347 // remove local strong reference to Client before deleting the RecordTrack so that the 1348 // Client destructor is called by the TrackBase destructor with mLock held 1349 client.clear(); 1350 recordTrack.clear(); 1351 goto Exit; 1352 } 1353 1354 // return handle to client 1355 recordHandle = new RecordHandle(recordTrack); 1356 1357Exit: 1358 *status = lStatus; 1359 return recordHandle; 1360} 1361 1362 1363 1364// ---------------------------------------------------------------------------- 1365 1366audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 1367{ 1368 if (!settingsAllowed()) { 1369 return 0; 1370 } 1371 Mutex::Autolock _l(mLock); 1372 return loadHwModule_l(name); 1373} 1374 1375// loadHwModule_l() must be called with AudioFlinger::mLock held 1376audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 1377{ 1378 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1379 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 1380 ALOGW("loadHwModule() module %s already loaded", name); 1381 return mAudioHwDevs.keyAt(i); 1382 } 1383 } 1384 1385 audio_hw_device_t *dev; 1386 1387 int rc = load_audio_interface(name, &dev); 1388 if (rc) { 1389 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 1390 return 0; 1391 } 1392 1393 mHardwareStatus = AUDIO_HW_INIT; 1394 rc = dev->init_check(dev); 1395 mHardwareStatus = AUDIO_HW_IDLE; 1396 if (rc) { 1397 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 1398 return 0; 1399 } 1400 1401 // Check and cache this HAL's level of support for master mute and master 1402 // volume. If this is the first HAL opened, and it supports the get 1403 // methods, use the initial values provided by the HAL as the current 1404 // master mute and volume settings. 1405 1406 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 1407 { // scope for auto-lock pattern 1408 AutoMutex lock(mHardwareLock); 1409 1410 if (0 == mAudioHwDevs.size()) { 1411 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 1412 if (NULL != dev->get_master_volume) { 1413 float mv; 1414 if (OK == dev->get_master_volume(dev, &mv)) { 1415 mMasterVolume = mv; 1416 } 1417 } 1418 1419 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 1420 if (NULL != dev->get_master_mute) { 1421 bool mm; 1422 if (OK == dev->get_master_mute(dev, &mm)) { 1423 mMasterMute = mm; 1424 } 1425 } 1426 } 1427 1428 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 1429 if ((NULL != dev->set_master_volume) && 1430 (OK == dev->set_master_volume(dev, mMasterVolume))) { 1431 flags = static_cast<AudioHwDevice::Flags>(flags | 1432 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 1433 } 1434 1435 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 1436 if ((NULL != dev->set_master_mute) && 1437 (OK == dev->set_master_mute(dev, mMasterMute))) { 1438 flags = static_cast<AudioHwDevice::Flags>(flags | 1439 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 1440 } 1441 1442 mHardwareStatus = AUDIO_HW_IDLE; 1443 } 1444 1445 audio_module_handle_t handle = nextUniqueId(); 1446 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags)); 1447 1448 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 1449 name, dev->common.module->name, dev->common.module->id, handle); 1450 1451 return handle; 1452 1453} 1454 1455// ---------------------------------------------------------------------------- 1456 1457uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 1458{ 1459 Mutex::Autolock _l(mLock); 1460 PlaybackThread *thread = primaryPlaybackThread_l(); 1461 return thread != NULL ? thread->sampleRate() : 0; 1462} 1463 1464size_t AudioFlinger::getPrimaryOutputFrameCount() 1465{ 1466 Mutex::Autolock _l(mLock); 1467 PlaybackThread *thread = primaryPlaybackThread_l(); 1468 return thread != NULL ? thread->frameCountHAL() : 0; 1469} 1470 1471// ---------------------------------------------------------------------------- 1472 1473status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice) 1474{ 1475 uid_t uid = IPCThreadState::self()->getCallingUid(); 1476 if (uid != AID_SYSTEM) { 1477 return PERMISSION_DENIED; 1478 } 1479 Mutex::Autolock _l(mLock); 1480 if (mIsDeviceTypeKnown) { 1481 return INVALID_OPERATION; 1482 } 1483 mIsLowRamDevice = isLowRamDevice; 1484 mIsDeviceTypeKnown = true; 1485 return NO_ERROR; 1486} 1487 1488// ---------------------------------------------------------------------------- 1489 1490audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 1491 audio_devices_t *pDevices, 1492 uint32_t *pSamplingRate, 1493 audio_format_t *pFormat, 1494 audio_channel_mask_t *pChannelMask, 1495 uint32_t *pLatencyMs, 1496 audio_output_flags_t flags, 1497 const audio_offload_info_t *offloadInfo) 1498{ 1499 struct audio_config config; 1500 memset(&config, 0, sizeof(config)); 1501 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1502 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1503 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1504 if (offloadInfo != NULL) { 1505 config.offload_info = *offloadInfo; 1506 } 1507 1508 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x", 1509 module, 1510 (pDevices != NULL) ? *pDevices : 0, 1511 config.sample_rate, 1512 config.format, 1513 config.channel_mask, 1514 flags); 1515 ALOGV("openOutput(), offloadInfo %p version 0x%04x", 1516 offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version); 1517 1518 if (pDevices == NULL || *pDevices == 0) { 1519 return 0; 1520 } 1521 1522 Mutex::Autolock _l(mLock); 1523 1524 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, *pDevices); 1525 if (outHwDev == NULL) { 1526 return 0; 1527 } 1528 1529 audio_hw_device_t *hwDevHal = outHwDev->hwDevice(); 1530 audio_io_handle_t id = nextUniqueId(); 1531 1532 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 1533 1534 audio_stream_out_t *outStream = NULL; 1535 status_t status = hwDevHal->open_output_stream(hwDevHal, 1536 id, 1537 *pDevices, 1538 (audio_output_flags_t)flags, 1539 &config, 1540 &outStream); 1541 1542 mHardwareStatus = AUDIO_HW_IDLE; 1543 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, " 1544 "Channels %x, status %d", 1545 outStream, 1546 config.sample_rate, 1547 config.format, 1548 config.channel_mask, 1549 status); 1550 1551 if (status == NO_ERROR && outStream != NULL) { 1552 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags); 1553 1554 PlaybackThread *thread; 1555 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1556 thread = new OffloadThread(this, output, id, *pDevices); 1557 ALOGV("openOutput() created offload output: ID %d thread %p", id, thread); 1558 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 1559 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 1560 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 1561 thread = new DirectOutputThread(this, output, id, *pDevices); 1562 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 1563 } else { 1564 thread = new MixerThread(this, output, id, *pDevices); 1565 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 1566 } 1567 mPlaybackThreads.add(id, thread); 1568 1569 if (pSamplingRate != NULL) { 1570 *pSamplingRate = config.sample_rate; 1571 } 1572 if (pFormat != NULL) { 1573 *pFormat = config.format; 1574 } 1575 if (pChannelMask != NULL) { 1576 *pChannelMask = config.channel_mask; 1577 } 1578 if (pLatencyMs != NULL) { 1579 *pLatencyMs = thread->latency(); 1580 } 1581 1582 // notify client processes of the new output creation 1583 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1584 1585 // the first primary output opened designates the primary hw device 1586 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 1587 ALOGI("Using module %d has the primary audio interface", module); 1588 mPrimaryHardwareDev = outHwDev; 1589 1590 AutoMutex lock(mHardwareLock); 1591 mHardwareStatus = AUDIO_HW_SET_MODE; 1592 hwDevHal->set_mode(hwDevHal, mMode); 1593 mHardwareStatus = AUDIO_HW_IDLE; 1594 } 1595 return id; 1596 } 1597 1598 return 0; 1599} 1600 1601audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 1602 audio_io_handle_t output2) 1603{ 1604 Mutex::Autolock _l(mLock); 1605 MixerThread *thread1 = checkMixerThread_l(output1); 1606 MixerThread *thread2 = checkMixerThread_l(output2); 1607 1608 if (thread1 == NULL || thread2 == NULL) { 1609 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 1610 output2); 1611 return 0; 1612 } 1613 1614 audio_io_handle_t id = nextUniqueId(); 1615 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 1616 thread->addOutputTrack(thread2); 1617 mPlaybackThreads.add(id, thread); 1618 // notify client processes of the new output creation 1619 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1620 return id; 1621} 1622 1623status_t AudioFlinger::closeOutput(audio_io_handle_t output) 1624{ 1625 return closeOutput_nonvirtual(output); 1626} 1627 1628status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 1629{ 1630 // keep strong reference on the playback thread so that 1631 // it is not destroyed while exit() is executed 1632 sp<PlaybackThread> thread; 1633 { 1634 Mutex::Autolock _l(mLock); 1635 thread = checkPlaybackThread_l(output); 1636 if (thread == NULL) { 1637 return BAD_VALUE; 1638 } 1639 1640 ALOGV("closeOutput() %d", output); 1641 1642 if (thread->type() == ThreadBase::MIXER) { 1643 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1644 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 1645 DuplicatingThread *dupThread = 1646 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 1647 dupThread->removeOutputTrack((MixerThread *)thread.get()); 1648 1649 } 1650 } 1651 } 1652 1653 1654 mPlaybackThreads.removeItem(output); 1655 // save all effects to the default thread 1656 if (mPlaybackThreads.size()) { 1657 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0)); 1658 if (dstThread != NULL) { 1659 // audioflinger lock is held here so the acquisition order of thread locks does not 1660 // matter 1661 Mutex::Autolock _dl(dstThread->mLock); 1662 Mutex::Autolock _sl(thread->mLock); 1663 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l(); 1664 for (size_t i = 0; i < effectChains.size(); i ++) { 1665 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true); 1666 } 1667 } 1668 } 1669 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 1670 } 1671 thread->exit(); 1672 // The thread entity (active unit of execution) is no longer running here, 1673 // but the ThreadBase container still exists. 1674 1675 if (thread->type() != ThreadBase::DUPLICATING) { 1676 AudioStreamOut *out = thread->clearOutput(); 1677 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 1678 // from now on thread->mOutput is NULL 1679 out->hwDev()->close_output_stream(out->hwDev(), out->stream); 1680 delete out; 1681 } 1682 return NO_ERROR; 1683} 1684 1685status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 1686{ 1687 Mutex::Autolock _l(mLock); 1688 PlaybackThread *thread = checkPlaybackThread_l(output); 1689 1690 if (thread == NULL) { 1691 return BAD_VALUE; 1692 } 1693 1694 ALOGV("suspendOutput() %d", output); 1695 thread->suspend(); 1696 1697 return NO_ERROR; 1698} 1699 1700status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 1701{ 1702 Mutex::Autolock _l(mLock); 1703 PlaybackThread *thread = checkPlaybackThread_l(output); 1704 1705 if (thread == NULL) { 1706 return BAD_VALUE; 1707 } 1708 1709 ALOGV("restoreOutput() %d", output); 1710 1711 thread->restore(); 1712 1713 return NO_ERROR; 1714} 1715 1716audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 1717 audio_devices_t *pDevices, 1718 uint32_t *pSamplingRate, 1719 audio_format_t *pFormat, 1720 audio_channel_mask_t *pChannelMask) 1721{ 1722 struct audio_config config; 1723 memset(&config, 0, sizeof(config)); 1724 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1725 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1726 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1727 1728 uint32_t reqSamplingRate = config.sample_rate; 1729 audio_format_t reqFormat = config.format; 1730 audio_channel_mask_t reqChannelMask = config.channel_mask; 1731 1732 if (pDevices == NULL || *pDevices == 0) { 1733 return 0; 1734 } 1735 1736 Mutex::Autolock _l(mLock); 1737 1738 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, *pDevices); 1739 if (inHwDev == NULL) { 1740 return 0; 1741 } 1742 1743 audio_hw_device_t *inHwHal = inHwDev->hwDevice(); 1744 audio_io_handle_t id = nextUniqueId(); 1745 1746 audio_stream_in_t *inStream = NULL; 1747 status_t status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, 1748 &inStream); 1749 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, " 1750 "status %d", 1751 inStream, 1752 config.sample_rate, 1753 config.format, 1754 config.channel_mask, 1755 status); 1756 1757 // If the input could not be opened with the requested parameters and we can handle the 1758 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can 1759 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs. 1760 if (status == BAD_VALUE && 1761 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 1762 (config.sample_rate <= 2 * reqSamplingRate) && 1763 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannelMask) <= FCC_2)) { 1764 // FIXME describe the change proposed by HAL (save old values so we can log them here) 1765 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 1766 inStream = NULL; 1767 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 1768 // FIXME log this new status; HAL should not propose any further changes 1769 } 1770 1771 if (status == NO_ERROR && inStream != NULL) { 1772 1773#ifdef TEE_SINK 1774 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 1775 // or (re-)create if current Pipe is idle and does not match the new format 1776 sp<NBAIO_Sink> teeSink; 1777 enum { 1778 TEE_SINK_NO, // don't copy input 1779 TEE_SINK_NEW, // copy input using a new pipe 1780 TEE_SINK_OLD, // copy input using an existing pipe 1781 } kind; 1782 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 1783 popcount(inStream->common.get_channels(&inStream->common))); 1784 if (!mTeeSinkInputEnabled) { 1785 kind = TEE_SINK_NO; 1786 } else if (format == Format_Invalid) { 1787 kind = TEE_SINK_NO; 1788 } else if (mRecordTeeSink == 0) { 1789 kind = TEE_SINK_NEW; 1790 } else if (mRecordTeeSink->getStrongCount() != 1) { 1791 kind = TEE_SINK_NO; 1792 } else if (format == mRecordTeeSink->format()) { 1793 kind = TEE_SINK_OLD; 1794 } else { 1795 kind = TEE_SINK_NEW; 1796 } 1797 switch (kind) { 1798 case TEE_SINK_NEW: { 1799 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 1800 size_t numCounterOffers = 0; 1801 const NBAIO_Format offers[1] = {format}; 1802 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 1803 ALOG_ASSERT(index == 0); 1804 PipeReader *pipeReader = new PipeReader(*pipe); 1805 numCounterOffers = 0; 1806 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 1807 ALOG_ASSERT(index == 0); 1808 mRecordTeeSink = pipe; 1809 mRecordTeeSource = pipeReader; 1810 teeSink = pipe; 1811 } 1812 break; 1813 case TEE_SINK_OLD: 1814 teeSink = mRecordTeeSink; 1815 break; 1816 case TEE_SINK_NO: 1817 default: 1818 break; 1819 } 1820#endif 1821 1822 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 1823 1824 // Start record thread 1825 // RecordThread requires both input and output device indication to forward to audio 1826 // pre processing modules 1827 RecordThread *thread = new RecordThread(this, 1828 input, 1829 reqSamplingRate, 1830 reqChannelMask, 1831 id, 1832 primaryOutputDevice_l(), 1833 *pDevices 1834#ifdef TEE_SINK 1835 , teeSink 1836#endif 1837 ); 1838 mRecordThreads.add(id, thread); 1839 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 1840 if (pSamplingRate != NULL) { 1841 *pSamplingRate = reqSamplingRate; 1842 } 1843 if (pFormat != NULL) { 1844 *pFormat = config.format; 1845 } 1846 if (pChannelMask != NULL) { 1847 *pChannelMask = reqChannelMask; 1848 } 1849 1850 // notify client processes of the new input creation 1851 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 1852 return id; 1853 } 1854 1855 return 0; 1856} 1857 1858status_t AudioFlinger::closeInput(audio_io_handle_t input) 1859{ 1860 return closeInput_nonvirtual(input); 1861} 1862 1863status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 1864{ 1865 // keep strong reference on the record thread so that 1866 // it is not destroyed while exit() is executed 1867 sp<RecordThread> thread; 1868 { 1869 Mutex::Autolock _l(mLock); 1870 thread = checkRecordThread_l(input); 1871 if (thread == 0) { 1872 return BAD_VALUE; 1873 } 1874 1875 ALOGV("closeInput() %d", input); 1876 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 1877 mRecordThreads.removeItem(input); 1878 } 1879 thread->exit(); 1880 // The thread entity (active unit of execution) is no longer running here, 1881 // but the ThreadBase container still exists. 1882 1883 AudioStreamIn *in = thread->clearInput(); 1884 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 1885 // from now on thread->mInput is NULL 1886 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 1887 delete in; 1888 1889 return NO_ERROR; 1890} 1891 1892status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 1893{ 1894 Mutex::Autolock _l(mLock); 1895 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 1896 1897 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1898 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1899 thread->invalidateTracks(stream); 1900 } 1901 1902 return NO_ERROR; 1903} 1904 1905 1906int AudioFlinger::newAudioSessionId() 1907{ 1908 return nextUniqueId(); 1909} 1910 1911void AudioFlinger::acquireAudioSessionId(int audioSession) 1912{ 1913 Mutex::Autolock _l(mLock); 1914 pid_t caller = IPCThreadState::self()->getCallingPid(); 1915 ALOGV("acquiring %d from %d", audioSession, caller); 1916 1917 // Ignore requests received from processes not known as notification client. The request 1918 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be 1919 // called from a different pid leaving a stale session reference. Also we don't know how 1920 // to clear this reference if the client process dies. 1921 if (mNotificationClients.indexOfKey(caller) < 0) { 1922 ALOGV("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession); 1923 return; 1924 } 1925 1926 size_t num = mAudioSessionRefs.size(); 1927 for (size_t i = 0; i< num; i++) { 1928 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 1929 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1930 ref->mCnt++; 1931 ALOGV(" incremented refcount to %d", ref->mCnt); 1932 return; 1933 } 1934 } 1935 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 1936 ALOGV(" added new entry for %d", audioSession); 1937} 1938 1939void AudioFlinger::releaseAudioSessionId(int audioSession) 1940{ 1941 Mutex::Autolock _l(mLock); 1942 pid_t caller = IPCThreadState::self()->getCallingPid(); 1943 ALOGV("releasing %d from %d", audioSession, caller); 1944 size_t num = mAudioSessionRefs.size(); 1945 for (size_t i = 0; i< num; i++) { 1946 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1947 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1948 ref->mCnt--; 1949 ALOGV(" decremented refcount to %d", ref->mCnt); 1950 if (ref->mCnt == 0) { 1951 mAudioSessionRefs.removeAt(i); 1952 delete ref; 1953 purgeStaleEffects_l(); 1954 } 1955 return; 1956 } 1957 } 1958 // If the caller is mediaserver it is likely that the session being released was acquired 1959 // on behalf of a process not in notification clients and we ignore the warning. 1960 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller); 1961} 1962 1963void AudioFlinger::purgeStaleEffects_l() { 1964 1965 ALOGV("purging stale effects"); 1966 1967 Vector< sp<EffectChain> > chains; 1968 1969 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1970 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 1971 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1972 sp<EffectChain> ec = t->mEffectChains[j]; 1973 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 1974 chains.push(ec); 1975 } 1976 } 1977 } 1978 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1979 sp<RecordThread> t = mRecordThreads.valueAt(i); 1980 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1981 sp<EffectChain> ec = t->mEffectChains[j]; 1982 chains.push(ec); 1983 } 1984 } 1985 1986 for (size_t i = 0; i < chains.size(); i++) { 1987 sp<EffectChain> ec = chains[i]; 1988 int sessionid = ec->sessionId(); 1989 sp<ThreadBase> t = ec->mThread.promote(); 1990 if (t == 0) { 1991 continue; 1992 } 1993 size_t numsessionrefs = mAudioSessionRefs.size(); 1994 bool found = false; 1995 for (size_t k = 0; k < numsessionrefs; k++) { 1996 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 1997 if (ref->mSessionid == sessionid) { 1998 ALOGV(" session %d still exists for %d with %d refs", 1999 sessionid, ref->mPid, ref->mCnt); 2000 found = true; 2001 break; 2002 } 2003 } 2004 if (!found) { 2005 Mutex::Autolock _l(t->mLock); 2006 // remove all effects from the chain 2007 while (ec->mEffects.size()) { 2008 sp<EffectModule> effect = ec->mEffects[0]; 2009 effect->unPin(); 2010 t->removeEffect_l(effect); 2011 if (effect->purgeHandles()) { 2012 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 2013 } 2014 AudioSystem::unregisterEffect(effect->id()); 2015 } 2016 } 2017 } 2018 return; 2019} 2020 2021// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2022AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 2023{ 2024 return mPlaybackThreads.valueFor(output).get(); 2025} 2026 2027// checkMixerThread_l() must be called with AudioFlinger::mLock held 2028AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 2029{ 2030 PlaybackThread *thread = checkPlaybackThread_l(output); 2031 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 2032} 2033 2034// checkRecordThread_l() must be called with AudioFlinger::mLock held 2035AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 2036{ 2037 return mRecordThreads.valueFor(input).get(); 2038} 2039 2040uint32_t AudioFlinger::nextUniqueId() 2041{ 2042 return android_atomic_inc(&mNextUniqueId); 2043} 2044 2045AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 2046{ 2047 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2048 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2049 AudioStreamOut *output = thread->getOutput(); 2050 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 2051 return thread; 2052 } 2053 } 2054 return NULL; 2055} 2056 2057audio_devices_t AudioFlinger::primaryOutputDevice_l() const 2058{ 2059 PlaybackThread *thread = primaryPlaybackThread_l(); 2060 2061 if (thread == NULL) { 2062 return 0; 2063 } 2064 2065 return thread->outDevice(); 2066} 2067 2068sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 2069 int triggerSession, 2070 int listenerSession, 2071 sync_event_callback_t callBack, 2072 void *cookie) 2073{ 2074 Mutex::Autolock _l(mLock); 2075 2076 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 2077 status_t playStatus = NAME_NOT_FOUND; 2078 status_t recStatus = NAME_NOT_FOUND; 2079 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2080 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 2081 if (playStatus == NO_ERROR) { 2082 return event; 2083 } 2084 } 2085 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2086 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 2087 if (recStatus == NO_ERROR) { 2088 return event; 2089 } 2090 } 2091 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2092 mPendingSyncEvents.add(event); 2093 } else { 2094 ALOGV("createSyncEvent() invalid event %d", event->type()); 2095 event.clear(); 2096 } 2097 return event; 2098} 2099 2100// ---------------------------------------------------------------------------- 2101// Effect management 2102// ---------------------------------------------------------------------------- 2103 2104 2105status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2106{ 2107 Mutex::Autolock _l(mLock); 2108 return EffectQueryNumberEffects(numEffects); 2109} 2110 2111status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2112{ 2113 Mutex::Autolock _l(mLock); 2114 return EffectQueryEffect(index, descriptor); 2115} 2116 2117status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2118 effect_descriptor_t *descriptor) const 2119{ 2120 Mutex::Autolock _l(mLock); 2121 return EffectGetDescriptor(pUuid, descriptor); 2122} 2123 2124 2125sp<IEffect> AudioFlinger::createEffect( 2126 effect_descriptor_t *pDesc, 2127 const sp<IEffectClient>& effectClient, 2128 int32_t priority, 2129 audio_io_handle_t io, 2130 int sessionId, 2131 status_t *status, 2132 int *id, 2133 int *enabled) 2134{ 2135 status_t lStatus = NO_ERROR; 2136 sp<EffectHandle> handle; 2137 effect_descriptor_t desc; 2138 2139 pid_t pid = IPCThreadState::self()->getCallingPid(); 2140 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 2141 pid, effectClient.get(), priority, sessionId, io); 2142 2143 if (pDesc == NULL) { 2144 lStatus = BAD_VALUE; 2145 goto Exit; 2146 } 2147 2148 // check audio settings permission for global effects 2149 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2150 lStatus = PERMISSION_DENIED; 2151 goto Exit; 2152 } 2153 2154 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2155 // that can only be created by audio policy manager (running in same process) 2156 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2157 lStatus = PERMISSION_DENIED; 2158 goto Exit; 2159 } 2160 2161 { 2162 if (!EffectIsNullUuid(&pDesc->uuid)) { 2163 // if uuid is specified, request effect descriptor 2164 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 2165 if (lStatus < 0) { 2166 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2167 goto Exit; 2168 } 2169 } else { 2170 // if uuid is not specified, look for an available implementation 2171 // of the required type in effect factory 2172 if (EffectIsNullUuid(&pDesc->type)) { 2173 ALOGW("createEffect() no effect type"); 2174 lStatus = BAD_VALUE; 2175 goto Exit; 2176 } 2177 uint32_t numEffects = 0; 2178 effect_descriptor_t d; 2179 d.flags = 0; // prevent compiler warning 2180 bool found = false; 2181 2182 lStatus = EffectQueryNumberEffects(&numEffects); 2183 if (lStatus < 0) { 2184 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2185 goto Exit; 2186 } 2187 for (uint32_t i = 0; i < numEffects; i++) { 2188 lStatus = EffectQueryEffect(i, &desc); 2189 if (lStatus < 0) { 2190 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2191 continue; 2192 } 2193 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2194 // If matching type found save effect descriptor. If the session is 2195 // 0 and the effect is not auxiliary, continue enumeration in case 2196 // an auxiliary version of this effect type is available 2197 found = true; 2198 d = desc; 2199 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2200 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2201 break; 2202 } 2203 } 2204 } 2205 if (!found) { 2206 lStatus = BAD_VALUE; 2207 ALOGW("createEffect() effect not found"); 2208 goto Exit; 2209 } 2210 // For same effect type, chose auxiliary version over insert version if 2211 // connect to output mix (Compliance to OpenSL ES) 2212 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2213 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2214 desc = d; 2215 } 2216 } 2217 2218 // Do not allow auxiliary effects on a session different from 0 (output mix) 2219 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2220 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2221 lStatus = INVALID_OPERATION; 2222 goto Exit; 2223 } 2224 2225 // check recording permission for visualizer 2226 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2227 !recordingAllowed()) { 2228 lStatus = PERMISSION_DENIED; 2229 goto Exit; 2230 } 2231 2232 // return effect descriptor 2233 *pDesc = desc; 2234 if (io == 0 && sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2235 // if the output returned by getOutputForEffect() is removed before we lock the 2236 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2237 // and we will exit safely 2238 io = AudioSystem::getOutputForEffect(&desc); 2239 ALOGV("createEffect got output %d", io); 2240 } 2241 2242 Mutex::Autolock _l(mLock); 2243 2244 // If output is not specified try to find a matching audio session ID in one of the 2245 // output threads. 2246 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2247 // because of code checking output when entering the function. 2248 // Note: io is never 0 when creating an effect on an input 2249 if (io == 0) { 2250 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2251 // output must be specified by AudioPolicyManager when using session 2252 // AUDIO_SESSION_OUTPUT_STAGE 2253 lStatus = BAD_VALUE; 2254 goto Exit; 2255 } 2256 // look for the thread where the specified audio session is present 2257 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2258 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2259 io = mPlaybackThreads.keyAt(i); 2260 break; 2261 } 2262 } 2263 if (io == 0) { 2264 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2265 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2266 io = mRecordThreads.keyAt(i); 2267 break; 2268 } 2269 } 2270 } 2271 // If no output thread contains the requested session ID, default to 2272 // first output. The effect chain will be moved to the correct output 2273 // thread when a track with the same session ID is created 2274 if (io == 0 && mPlaybackThreads.size()) { 2275 io = mPlaybackThreads.keyAt(0); 2276 } 2277 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2278 } 2279 ThreadBase *thread = checkRecordThread_l(io); 2280 if (thread == NULL) { 2281 thread = checkPlaybackThread_l(io); 2282 if (thread == NULL) { 2283 ALOGE("createEffect() unknown output thread"); 2284 lStatus = BAD_VALUE; 2285 goto Exit; 2286 } 2287 } 2288 2289 sp<Client> client = registerPid_l(pid); 2290 2291 // create effect on selected output thread 2292 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 2293 &desc, enabled, &lStatus); 2294 if (handle != 0 && id != NULL) { 2295 *id = handle->id(); 2296 } 2297 } 2298 2299Exit: 2300 *status = lStatus; 2301 return handle; 2302} 2303 2304status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2305 audio_io_handle_t dstOutput) 2306{ 2307 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2308 sessionId, srcOutput, dstOutput); 2309 Mutex::Autolock _l(mLock); 2310 if (srcOutput == dstOutput) { 2311 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2312 return NO_ERROR; 2313 } 2314 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2315 if (srcThread == NULL) { 2316 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2317 return BAD_VALUE; 2318 } 2319 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2320 if (dstThread == NULL) { 2321 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2322 return BAD_VALUE; 2323 } 2324 2325 Mutex::Autolock _dl(dstThread->mLock); 2326 Mutex::Autolock _sl(srcThread->mLock); 2327 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 2328} 2329 2330// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2331status_t AudioFlinger::moveEffectChain_l(int sessionId, 2332 AudioFlinger::PlaybackThread *srcThread, 2333 AudioFlinger::PlaybackThread *dstThread, 2334 bool reRegister) 2335{ 2336 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2337 sessionId, srcThread, dstThread); 2338 2339 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2340 if (chain == 0) { 2341 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2342 sessionId, srcThread); 2343 return INVALID_OPERATION; 2344 } 2345 2346 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2347 // so that a new chain is created with correct parameters when first effect is added. This is 2348 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2349 // removed. 2350 srcThread->removeEffectChain_l(chain); 2351 2352 // transfer all effects one by one so that new effect chain is created on new thread with 2353 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2354 sp<EffectChain> dstChain; 2355 uint32_t strategy = 0; // prevent compiler warning 2356 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2357 Vector< sp<EffectModule> > removed; 2358 status_t status = NO_ERROR; 2359 while (effect != 0) { 2360 srcThread->removeEffect_l(effect); 2361 removed.add(effect); 2362 status = dstThread->addEffect_l(effect); 2363 if (status != NO_ERROR) { 2364 break; 2365 } 2366 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2367 if (effect->state() == EffectModule::ACTIVE || 2368 effect->state() == EffectModule::STOPPING) { 2369 effect->start(); 2370 } 2371 // if the move request is not received from audio policy manager, the effect must be 2372 // re-registered with the new strategy and output 2373 if (dstChain == 0) { 2374 dstChain = effect->chain().promote(); 2375 if (dstChain == 0) { 2376 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2377 status = NO_INIT; 2378 break; 2379 } 2380 strategy = dstChain->strategy(); 2381 } 2382 if (reRegister) { 2383 AudioSystem::unregisterEffect(effect->id()); 2384 AudioSystem::registerEffect(&effect->desc(), 2385 dstThread->id(), 2386 strategy, 2387 sessionId, 2388 effect->id()); 2389 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2390 } 2391 effect = chain->getEffectFromId_l(0); 2392 } 2393 2394 if (status != NO_ERROR) { 2395 for (size_t i = 0; i < removed.size(); i++) { 2396 srcThread->addEffect_l(removed[i]); 2397 if (dstChain != 0 && reRegister) { 2398 AudioSystem::unregisterEffect(removed[i]->id()); 2399 AudioSystem::registerEffect(&removed[i]->desc(), 2400 srcThread->id(), 2401 strategy, 2402 sessionId, 2403 removed[i]->id()); 2404 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2405 } 2406 } 2407 } 2408 2409 return status; 2410} 2411 2412bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 2413{ 2414 if (mGlobalEffectEnableTime != 0 && 2415 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 2416 return true; 2417 } 2418 2419 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2420 sp<EffectChain> ec = 2421 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2422 if (ec != 0 && ec->isNonOffloadableEnabled()) { 2423 return true; 2424 } 2425 } 2426 return false; 2427} 2428 2429void AudioFlinger::onNonOffloadableGlobalEffectEnable() 2430{ 2431 Mutex::Autolock _l(mLock); 2432 2433 mGlobalEffectEnableTime = systemTime(); 2434 2435 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2436 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2437 if (t->mType == ThreadBase::OFFLOAD) { 2438 t->invalidateTracks(AUDIO_STREAM_MUSIC); 2439 } 2440 } 2441 2442} 2443 2444struct Entry { 2445#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2446 char mName[MAX_NAME]; 2447}; 2448 2449int comparEntry(const void *p1, const void *p2) 2450{ 2451 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2452} 2453 2454#ifdef TEE_SINK 2455void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2456{ 2457 NBAIO_Source *teeSource = source.get(); 2458 if (teeSource != NULL) { 2459 // .wav rotation 2460 // There is a benign race condition if 2 threads call this simultaneously. 2461 // They would both traverse the directory, but the result would simply be 2462 // failures at unlink() which are ignored. It's also unlikely since 2463 // normally dumpsys is only done by bugreport or from the command line. 2464 char teePath[32+256]; 2465 strcpy(teePath, "/data/misc/media"); 2466 size_t teePathLen = strlen(teePath); 2467 DIR *dir = opendir(teePath); 2468 teePath[teePathLen++] = '/'; 2469 if (dir != NULL) { 2470#define MAX_SORT 20 // number of entries to sort 2471#define MAX_KEEP 10 // number of entries to keep 2472 struct Entry entries[MAX_SORT]; 2473 size_t entryCount = 0; 2474 while (entryCount < MAX_SORT) { 2475 struct dirent de; 2476 struct dirent *result = NULL; 2477 int rc = readdir_r(dir, &de, &result); 2478 if (rc != 0) { 2479 ALOGW("readdir_r failed %d", rc); 2480 break; 2481 } 2482 if (result == NULL) { 2483 break; 2484 } 2485 if (result != &de) { 2486 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2487 break; 2488 } 2489 // ignore non .wav file entries 2490 size_t nameLen = strlen(de.d_name); 2491 if (nameLen <= 4 || nameLen >= MAX_NAME || 2492 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2493 continue; 2494 } 2495 strcpy(entries[entryCount++].mName, de.d_name); 2496 } 2497 (void) closedir(dir); 2498 if (entryCount > MAX_KEEP) { 2499 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2500 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2501 strcpy(&teePath[teePathLen], entries[i].mName); 2502 (void) unlink(teePath); 2503 } 2504 } 2505 } else { 2506 if (fd >= 0) { 2507 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2508 } 2509 } 2510 char teeTime[16]; 2511 struct timeval tv; 2512 gettimeofday(&tv, NULL); 2513 struct tm tm; 2514 localtime_r(&tv.tv_sec, &tm); 2515 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2516 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2517 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2518 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2519 if (teeFd >= 0) { 2520 char wavHeader[44]; 2521 memcpy(wavHeader, 2522 "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", 2523 sizeof(wavHeader)); 2524 NBAIO_Format format = teeSource->format(); 2525 unsigned channelCount = Format_channelCount(format); 2526 ALOG_ASSERT(channelCount <= FCC_2); 2527 uint32_t sampleRate = Format_sampleRate(format); 2528 wavHeader[22] = channelCount; // number of channels 2529 wavHeader[24] = sampleRate; // sample rate 2530 wavHeader[25] = sampleRate >> 8; 2531 wavHeader[32] = channelCount * 2; // block alignment 2532 write(teeFd, wavHeader, sizeof(wavHeader)); 2533 size_t total = 0; 2534 bool firstRead = true; 2535 for (;;) { 2536#define TEE_SINK_READ 1024 2537 short buffer[TEE_SINK_READ * FCC_2]; 2538 size_t count = TEE_SINK_READ; 2539 ssize_t actual = teeSource->read(buffer, count, 2540 AudioBufferProvider::kInvalidPTS); 2541 bool wasFirstRead = firstRead; 2542 firstRead = false; 2543 if (actual <= 0) { 2544 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2545 continue; 2546 } 2547 break; 2548 } 2549 ALOG_ASSERT(actual <= (ssize_t)count); 2550 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2551 total += actual; 2552 } 2553 lseek(teeFd, (off_t) 4, SEEK_SET); 2554 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2555 write(teeFd, &temp, sizeof(temp)); 2556 lseek(teeFd, (off_t) 40, SEEK_SET); 2557 temp = total * channelCount * sizeof(short); 2558 write(teeFd, &temp, sizeof(temp)); 2559 close(teeFd); 2560 if (fd >= 0) { 2561 fdprintf(fd, "tee copied to %s\n", teePath); 2562 } 2563 } else { 2564 if (fd >= 0) { 2565 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2566 } 2567 } 2568 } 2569} 2570#endif 2571 2572// ---------------------------------------------------------------------------- 2573 2574status_t AudioFlinger::onTransact( 2575 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2576{ 2577 return BnAudioFlinger::onTransact(code, data, reply, flags); 2578} 2579 2580}; // namespace android 2581