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