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