AudioFlinger.cpp revision 5806b3533437e3d83208e8e9d6bd74ed304e51ec
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_MIN) { 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 dprintf(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 (audio_channel_count_from_in_mask(config.channel_mask) <= FCC_2) && 1841 (audio_channel_count_from_in_mask(reqChannelMask) <= FCC_2)) { 1842 // FIXME describe the change proposed by HAL (save old values so we can log them here) 1843 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 1844 inStream = NULL; 1845 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 1846 // FIXME log this new status; HAL should not propose any further changes 1847 } 1848 1849 if (status == NO_ERROR && inStream != NULL) { 1850 1851#ifdef TEE_SINK 1852 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 1853 // or (re-)create if current Pipe is idle and does not match the new format 1854 sp<NBAIO_Sink> teeSink; 1855 enum { 1856 TEE_SINK_NO, // don't copy input 1857 TEE_SINK_NEW, // copy input using a new pipe 1858 TEE_SINK_OLD, // copy input using an existing pipe 1859 } kind; 1860 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 1861 audio_channel_count_from_in_mask( 1862 inStream->common.get_channels(&inStream->common))); 1863 if (!mTeeSinkInputEnabled) { 1864 kind = TEE_SINK_NO; 1865 } else if (!Format_isValid(format)) { 1866 kind = TEE_SINK_NO; 1867 } else if (mRecordTeeSink == 0) { 1868 kind = TEE_SINK_NEW; 1869 } else if (mRecordTeeSink->getStrongCount() != 1) { 1870 kind = TEE_SINK_NO; 1871 } else if (Format_isEqual(format, mRecordTeeSink->format())) { 1872 kind = TEE_SINK_OLD; 1873 } else { 1874 kind = TEE_SINK_NEW; 1875 } 1876 switch (kind) { 1877 case TEE_SINK_NEW: { 1878 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 1879 size_t numCounterOffers = 0; 1880 const NBAIO_Format offers[1] = {format}; 1881 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 1882 ALOG_ASSERT(index == 0); 1883 PipeReader *pipeReader = new PipeReader(*pipe); 1884 numCounterOffers = 0; 1885 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 1886 ALOG_ASSERT(index == 0); 1887 mRecordTeeSink = pipe; 1888 mRecordTeeSource = pipeReader; 1889 teeSink = pipe; 1890 } 1891 break; 1892 case TEE_SINK_OLD: 1893 teeSink = mRecordTeeSink; 1894 break; 1895 case TEE_SINK_NO: 1896 default: 1897 break; 1898 } 1899#endif 1900 1901 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 1902 1903 // Start record thread 1904 // RecordThread requires both input and output device indication to forward to audio 1905 // pre processing modules 1906 RecordThread *thread = new RecordThread(this, 1907 input, 1908 id, 1909 primaryOutputDevice_l(), 1910 *pDevices 1911#ifdef TEE_SINK 1912 , teeSink 1913#endif 1914 ); 1915 mRecordThreads.add(id, thread); 1916 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 1917 if (pSamplingRate != NULL) { 1918 *pSamplingRate = reqSamplingRate; 1919 } 1920 if (pFormat != NULL) { 1921 *pFormat = config.format; 1922 } 1923 if (pChannelMask != NULL) { 1924 *pChannelMask = reqChannelMask; 1925 } 1926 1927 // notify client processes of the new input creation 1928 thread->audioConfigChanged(AudioSystem::INPUT_OPENED); 1929 return id; 1930 } 1931 1932 return 0; 1933} 1934 1935status_t AudioFlinger::closeInput(audio_io_handle_t input) 1936{ 1937 return closeInput_nonvirtual(input); 1938} 1939 1940status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 1941{ 1942 // keep strong reference on the record thread so that 1943 // it is not destroyed while exit() is executed 1944 sp<RecordThread> thread; 1945 { 1946 Mutex::Autolock _l(mLock); 1947 thread = checkRecordThread_l(input); 1948 if (thread == 0) { 1949 return BAD_VALUE; 1950 } 1951 1952 ALOGV("closeInput() %d", input); 1953 audioConfigChanged(AudioSystem::INPUT_CLOSED, input, NULL); 1954 mRecordThreads.removeItem(input); 1955 } 1956 thread->exit(); 1957 // The thread entity (active unit of execution) is no longer running here, 1958 // but the ThreadBase container still exists. 1959 1960 AudioStreamIn *in = thread->clearInput(); 1961 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 1962 // from now on thread->mInput is NULL 1963 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 1964 delete in; 1965 1966 return NO_ERROR; 1967} 1968 1969status_t AudioFlinger::invalidateStream(audio_stream_type_t stream) 1970{ 1971 Mutex::Autolock _l(mLock); 1972 ALOGV("invalidateStream() stream %d", stream); 1973 1974 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1975 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1976 thread->invalidateTracks(stream); 1977 } 1978 1979 return NO_ERROR; 1980} 1981 1982 1983int AudioFlinger::newAudioSessionId() 1984{ 1985 return nextUniqueId(); 1986} 1987 1988void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid) 1989{ 1990 Mutex::Autolock _l(mLock); 1991 pid_t caller = IPCThreadState::self()->getCallingPid(); 1992 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid); 1993 if (pid != -1 && (caller == getpid_cached)) { 1994 caller = pid; 1995 } 1996 1997 { 1998 Mutex::Autolock _cl(mClientLock); 1999 // Ignore requests received from processes not known as notification client. The request 2000 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be 2001 // called from a different pid leaving a stale session reference. Also we don't know how 2002 // to clear this reference if the client process dies. 2003 if (mNotificationClients.indexOfKey(caller) < 0) { 2004 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession); 2005 return; 2006 } 2007 } 2008 2009 size_t num = mAudioSessionRefs.size(); 2010 for (size_t i = 0; i< num; i++) { 2011 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 2012 if (ref->mSessionid == audioSession && ref->mPid == caller) { 2013 ref->mCnt++; 2014 ALOGV(" incremented refcount to %d", ref->mCnt); 2015 return; 2016 } 2017 } 2018 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 2019 ALOGV(" added new entry for %d", audioSession); 2020} 2021 2022void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid) 2023{ 2024 Mutex::Autolock _l(mLock); 2025 pid_t caller = IPCThreadState::self()->getCallingPid(); 2026 ALOGV("releasing %d from %d for %d", audioSession, caller, pid); 2027 if (pid != -1 && (caller == getpid_cached)) { 2028 caller = pid; 2029 } 2030 size_t num = mAudioSessionRefs.size(); 2031 for (size_t i = 0; i< num; i++) { 2032 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 2033 if (ref->mSessionid == audioSession && ref->mPid == caller) { 2034 ref->mCnt--; 2035 ALOGV(" decremented refcount to %d", ref->mCnt); 2036 if (ref->mCnt == 0) { 2037 mAudioSessionRefs.removeAt(i); 2038 delete ref; 2039 purgeStaleEffects_l(); 2040 } 2041 return; 2042 } 2043 } 2044 // If the caller is mediaserver it is likely that the session being released was acquired 2045 // on behalf of a process not in notification clients and we ignore the warning. 2046 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller); 2047} 2048 2049void AudioFlinger::purgeStaleEffects_l() { 2050 2051 ALOGV("purging stale effects"); 2052 2053 Vector< sp<EffectChain> > chains; 2054 2055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2056 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2057 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2058 sp<EffectChain> ec = t->mEffectChains[j]; 2059 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 2060 chains.push(ec); 2061 } 2062 } 2063 } 2064 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2065 sp<RecordThread> t = mRecordThreads.valueAt(i); 2066 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2067 sp<EffectChain> ec = t->mEffectChains[j]; 2068 chains.push(ec); 2069 } 2070 } 2071 2072 for (size_t i = 0; i < chains.size(); i++) { 2073 sp<EffectChain> ec = chains[i]; 2074 int sessionid = ec->sessionId(); 2075 sp<ThreadBase> t = ec->mThread.promote(); 2076 if (t == 0) { 2077 continue; 2078 } 2079 size_t numsessionrefs = mAudioSessionRefs.size(); 2080 bool found = false; 2081 for (size_t k = 0; k < numsessionrefs; k++) { 2082 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 2083 if (ref->mSessionid == sessionid) { 2084 ALOGV(" session %d still exists for %d with %d refs", 2085 sessionid, ref->mPid, ref->mCnt); 2086 found = true; 2087 break; 2088 } 2089 } 2090 if (!found) { 2091 Mutex::Autolock _l(t->mLock); 2092 // remove all effects from the chain 2093 while (ec->mEffects.size()) { 2094 sp<EffectModule> effect = ec->mEffects[0]; 2095 effect->unPin(); 2096 t->removeEffect_l(effect); 2097 if (effect->purgeHandles()) { 2098 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 2099 } 2100 AudioSystem::unregisterEffect(effect->id()); 2101 } 2102 } 2103 } 2104 return; 2105} 2106 2107// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2108AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 2109{ 2110 return mPlaybackThreads.valueFor(output).get(); 2111} 2112 2113// checkMixerThread_l() must be called with AudioFlinger::mLock held 2114AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 2115{ 2116 PlaybackThread *thread = checkPlaybackThread_l(output); 2117 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 2118} 2119 2120// checkRecordThread_l() must be called with AudioFlinger::mLock held 2121AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 2122{ 2123 return mRecordThreads.valueFor(input).get(); 2124} 2125 2126uint32_t AudioFlinger::nextUniqueId() 2127{ 2128 return (uint32_t) android_atomic_inc(&mNextUniqueId); 2129} 2130 2131AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 2132{ 2133 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2134 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2135 AudioStreamOut *output = thread->getOutput(); 2136 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 2137 return thread; 2138 } 2139 } 2140 return NULL; 2141} 2142 2143audio_devices_t AudioFlinger::primaryOutputDevice_l() const 2144{ 2145 PlaybackThread *thread = primaryPlaybackThread_l(); 2146 2147 if (thread == NULL) { 2148 return 0; 2149 } 2150 2151 return thread->outDevice(); 2152} 2153 2154sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 2155 int triggerSession, 2156 int listenerSession, 2157 sync_event_callback_t callBack, 2158 wp<RefBase> cookie) 2159{ 2160 Mutex::Autolock _l(mLock); 2161 2162 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 2163 status_t playStatus = NAME_NOT_FOUND; 2164 status_t recStatus = NAME_NOT_FOUND; 2165 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2166 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 2167 if (playStatus == NO_ERROR) { 2168 return event; 2169 } 2170 } 2171 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2172 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 2173 if (recStatus == NO_ERROR) { 2174 return event; 2175 } 2176 } 2177 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2178 mPendingSyncEvents.add(event); 2179 } else { 2180 ALOGV("createSyncEvent() invalid event %d", event->type()); 2181 event.clear(); 2182 } 2183 return event; 2184} 2185 2186// ---------------------------------------------------------------------------- 2187// Effect management 2188// ---------------------------------------------------------------------------- 2189 2190 2191status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2192{ 2193 Mutex::Autolock _l(mLock); 2194 return EffectQueryNumberEffects(numEffects); 2195} 2196 2197status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2198{ 2199 Mutex::Autolock _l(mLock); 2200 return EffectQueryEffect(index, descriptor); 2201} 2202 2203status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2204 effect_descriptor_t *descriptor) const 2205{ 2206 Mutex::Autolock _l(mLock); 2207 return EffectGetDescriptor(pUuid, descriptor); 2208} 2209 2210 2211sp<IEffect> AudioFlinger::createEffect( 2212 effect_descriptor_t *pDesc, 2213 const sp<IEffectClient>& effectClient, 2214 int32_t priority, 2215 audio_io_handle_t io, 2216 int sessionId, 2217 status_t *status, 2218 int *id, 2219 int *enabled) 2220{ 2221 status_t lStatus = NO_ERROR; 2222 sp<EffectHandle> handle; 2223 effect_descriptor_t desc; 2224 2225 pid_t pid = IPCThreadState::self()->getCallingPid(); 2226 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 2227 pid, effectClient.get(), priority, sessionId, io); 2228 2229 if (pDesc == NULL) { 2230 lStatus = BAD_VALUE; 2231 goto Exit; 2232 } 2233 2234 // check audio settings permission for global effects 2235 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2236 lStatus = PERMISSION_DENIED; 2237 goto Exit; 2238 } 2239 2240 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2241 // that can only be created by audio policy manager (running in same process) 2242 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2243 lStatus = PERMISSION_DENIED; 2244 goto Exit; 2245 } 2246 2247 { 2248 if (!EffectIsNullUuid(&pDesc->uuid)) { 2249 // if uuid is specified, request effect descriptor 2250 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 2251 if (lStatus < 0) { 2252 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2253 goto Exit; 2254 } 2255 } else { 2256 // if uuid is not specified, look for an available implementation 2257 // of the required type in effect factory 2258 if (EffectIsNullUuid(&pDesc->type)) { 2259 ALOGW("createEffect() no effect type"); 2260 lStatus = BAD_VALUE; 2261 goto Exit; 2262 } 2263 uint32_t numEffects = 0; 2264 effect_descriptor_t d; 2265 d.flags = 0; // prevent compiler warning 2266 bool found = false; 2267 2268 lStatus = EffectQueryNumberEffects(&numEffects); 2269 if (lStatus < 0) { 2270 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2271 goto Exit; 2272 } 2273 for (uint32_t i = 0; i < numEffects; i++) { 2274 lStatus = EffectQueryEffect(i, &desc); 2275 if (lStatus < 0) { 2276 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2277 continue; 2278 } 2279 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2280 // If matching type found save effect descriptor. If the session is 2281 // 0 and the effect is not auxiliary, continue enumeration in case 2282 // an auxiliary version of this effect type is available 2283 found = true; 2284 d = desc; 2285 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2286 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2287 break; 2288 } 2289 } 2290 } 2291 if (!found) { 2292 lStatus = BAD_VALUE; 2293 ALOGW("createEffect() effect not found"); 2294 goto Exit; 2295 } 2296 // For same effect type, chose auxiliary version over insert version if 2297 // connect to output mix (Compliance to OpenSL ES) 2298 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2299 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2300 desc = d; 2301 } 2302 } 2303 2304 // Do not allow auxiliary effects on a session different from 0 (output mix) 2305 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2306 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2307 lStatus = INVALID_OPERATION; 2308 goto Exit; 2309 } 2310 2311 // check recording permission for visualizer 2312 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2313 !recordingAllowed()) { 2314 lStatus = PERMISSION_DENIED; 2315 goto Exit; 2316 } 2317 2318 // return effect descriptor 2319 *pDesc = desc; 2320 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2321 // if the output returned by getOutputForEffect() is removed before we lock the 2322 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2323 // and we will exit safely 2324 io = AudioSystem::getOutputForEffect(&desc); 2325 ALOGV("createEffect got output %d", io); 2326 } 2327 2328 Mutex::Autolock _l(mLock); 2329 2330 // If output is not specified try to find a matching audio session ID in one of the 2331 // output threads. 2332 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2333 // because of code checking output when entering the function. 2334 // Note: io is never 0 when creating an effect on an input 2335 if (io == AUDIO_IO_HANDLE_NONE) { 2336 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2337 // output must be specified by AudioPolicyManager when using session 2338 // AUDIO_SESSION_OUTPUT_STAGE 2339 lStatus = BAD_VALUE; 2340 goto Exit; 2341 } 2342 // look for the thread where the specified audio session is present 2343 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2344 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2345 io = mPlaybackThreads.keyAt(i); 2346 break; 2347 } 2348 } 2349 if (io == 0) { 2350 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2351 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2352 io = mRecordThreads.keyAt(i); 2353 break; 2354 } 2355 } 2356 } 2357 // If no output thread contains the requested session ID, default to 2358 // first output. The effect chain will be moved to the correct output 2359 // thread when a track with the same session ID is created 2360 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) { 2361 io = mPlaybackThreads.keyAt(0); 2362 } 2363 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2364 } 2365 ThreadBase *thread = checkRecordThread_l(io); 2366 if (thread == NULL) { 2367 thread = checkPlaybackThread_l(io); 2368 if (thread == NULL) { 2369 ALOGE("createEffect() unknown output thread"); 2370 lStatus = BAD_VALUE; 2371 goto Exit; 2372 } 2373 } 2374 2375 sp<Client> client = registerPid(pid); 2376 2377 // create effect on selected output thread 2378 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 2379 &desc, enabled, &lStatus); 2380 if (handle != 0 && id != NULL) { 2381 *id = handle->id(); 2382 } 2383 } 2384 2385Exit: 2386 *status = lStatus; 2387 return handle; 2388} 2389 2390status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2391 audio_io_handle_t dstOutput) 2392{ 2393 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2394 sessionId, srcOutput, dstOutput); 2395 Mutex::Autolock _l(mLock); 2396 if (srcOutput == dstOutput) { 2397 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2398 return NO_ERROR; 2399 } 2400 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2401 if (srcThread == NULL) { 2402 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2403 return BAD_VALUE; 2404 } 2405 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2406 if (dstThread == NULL) { 2407 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2408 return BAD_VALUE; 2409 } 2410 2411 Mutex::Autolock _dl(dstThread->mLock); 2412 Mutex::Autolock _sl(srcThread->mLock); 2413 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 2414} 2415 2416// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2417status_t AudioFlinger::moveEffectChain_l(int sessionId, 2418 AudioFlinger::PlaybackThread *srcThread, 2419 AudioFlinger::PlaybackThread *dstThread, 2420 bool reRegister) 2421{ 2422 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2423 sessionId, srcThread, dstThread); 2424 2425 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2426 if (chain == 0) { 2427 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2428 sessionId, srcThread); 2429 return INVALID_OPERATION; 2430 } 2431 2432 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2433 // so that a new chain is created with correct parameters when first effect is added. This is 2434 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2435 // removed. 2436 srcThread->removeEffectChain_l(chain); 2437 2438 // transfer all effects one by one so that new effect chain is created on new thread with 2439 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2440 sp<EffectChain> dstChain; 2441 uint32_t strategy = 0; // prevent compiler warning 2442 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2443 Vector< sp<EffectModule> > removed; 2444 status_t status = NO_ERROR; 2445 while (effect != 0) { 2446 srcThread->removeEffect_l(effect); 2447 removed.add(effect); 2448 status = dstThread->addEffect_l(effect); 2449 if (status != NO_ERROR) { 2450 break; 2451 } 2452 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2453 if (effect->state() == EffectModule::ACTIVE || 2454 effect->state() == EffectModule::STOPPING) { 2455 effect->start(); 2456 } 2457 // if the move request is not received from audio policy manager, the effect must be 2458 // re-registered with the new strategy and output 2459 if (dstChain == 0) { 2460 dstChain = effect->chain().promote(); 2461 if (dstChain == 0) { 2462 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2463 status = NO_INIT; 2464 break; 2465 } 2466 strategy = dstChain->strategy(); 2467 } 2468 if (reRegister) { 2469 AudioSystem::unregisterEffect(effect->id()); 2470 AudioSystem::registerEffect(&effect->desc(), 2471 dstThread->id(), 2472 strategy, 2473 sessionId, 2474 effect->id()); 2475 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2476 } 2477 effect = chain->getEffectFromId_l(0); 2478 } 2479 2480 if (status != NO_ERROR) { 2481 for (size_t i = 0; i < removed.size(); i++) { 2482 srcThread->addEffect_l(removed[i]); 2483 if (dstChain != 0 && reRegister) { 2484 AudioSystem::unregisterEffect(removed[i]->id()); 2485 AudioSystem::registerEffect(&removed[i]->desc(), 2486 srcThread->id(), 2487 strategy, 2488 sessionId, 2489 removed[i]->id()); 2490 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2491 } 2492 } 2493 } 2494 2495 return status; 2496} 2497 2498bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 2499{ 2500 if (mGlobalEffectEnableTime != 0 && 2501 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 2502 return true; 2503 } 2504 2505 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2506 sp<EffectChain> ec = 2507 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2508 if (ec != 0 && ec->isNonOffloadableEnabled()) { 2509 return true; 2510 } 2511 } 2512 return false; 2513} 2514 2515void AudioFlinger::onNonOffloadableGlobalEffectEnable() 2516{ 2517 Mutex::Autolock _l(mLock); 2518 2519 mGlobalEffectEnableTime = systemTime(); 2520 2521 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2522 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2523 if (t->mType == ThreadBase::OFFLOAD) { 2524 t->invalidateTracks(AUDIO_STREAM_MUSIC); 2525 } 2526 } 2527 2528} 2529 2530struct Entry { 2531#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2532 char mName[MAX_NAME]; 2533}; 2534 2535int comparEntry(const void *p1, const void *p2) 2536{ 2537 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2538} 2539 2540#ifdef TEE_SINK 2541void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2542{ 2543 NBAIO_Source *teeSource = source.get(); 2544 if (teeSource != NULL) { 2545 // .wav rotation 2546 // There is a benign race condition if 2 threads call this simultaneously. 2547 // They would both traverse the directory, but the result would simply be 2548 // failures at unlink() which are ignored. It's also unlikely since 2549 // normally dumpsys is only done by bugreport or from the command line. 2550 char teePath[32+256]; 2551 strcpy(teePath, "/data/misc/media"); 2552 size_t teePathLen = strlen(teePath); 2553 DIR *dir = opendir(teePath); 2554 teePath[teePathLen++] = '/'; 2555 if (dir != NULL) { 2556#define MAX_SORT 20 // number of entries to sort 2557#define MAX_KEEP 10 // number of entries to keep 2558 struct Entry entries[MAX_SORT]; 2559 size_t entryCount = 0; 2560 while (entryCount < MAX_SORT) { 2561 struct dirent de; 2562 struct dirent *result = NULL; 2563 int rc = readdir_r(dir, &de, &result); 2564 if (rc != 0) { 2565 ALOGW("readdir_r failed %d", rc); 2566 break; 2567 } 2568 if (result == NULL) { 2569 break; 2570 } 2571 if (result != &de) { 2572 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2573 break; 2574 } 2575 // ignore non .wav file entries 2576 size_t nameLen = strlen(de.d_name); 2577 if (nameLen <= 4 || nameLen >= MAX_NAME || 2578 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2579 continue; 2580 } 2581 strcpy(entries[entryCount++].mName, de.d_name); 2582 } 2583 (void) closedir(dir); 2584 if (entryCount > MAX_KEEP) { 2585 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2586 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2587 strcpy(&teePath[teePathLen], entries[i].mName); 2588 (void) unlink(teePath); 2589 } 2590 } 2591 } else { 2592 if (fd >= 0) { 2593 dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2594 } 2595 } 2596 char teeTime[16]; 2597 struct timeval tv; 2598 gettimeofday(&tv, NULL); 2599 struct tm tm; 2600 localtime_r(&tv.tv_sec, &tm); 2601 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2602 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2603 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2604 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2605 if (teeFd >= 0) { 2606 char wavHeader[44]; 2607 memcpy(wavHeader, 2608 "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", 2609 sizeof(wavHeader)); 2610 NBAIO_Format format = teeSource->format(); 2611 unsigned channelCount = Format_channelCount(format); 2612 ALOG_ASSERT(channelCount <= FCC_2); 2613 uint32_t sampleRate = Format_sampleRate(format); 2614 wavHeader[22] = channelCount; // number of channels 2615 wavHeader[24] = sampleRate; // sample rate 2616 wavHeader[25] = sampleRate >> 8; 2617 wavHeader[32] = channelCount * 2; // block alignment 2618 write(teeFd, wavHeader, sizeof(wavHeader)); 2619 size_t total = 0; 2620 bool firstRead = true; 2621 for (;;) { 2622#define TEE_SINK_READ 1024 2623 short buffer[TEE_SINK_READ * FCC_2]; 2624 size_t count = TEE_SINK_READ; 2625 ssize_t actual = teeSource->read(buffer, count, 2626 AudioBufferProvider::kInvalidPTS); 2627 bool wasFirstRead = firstRead; 2628 firstRead = false; 2629 if (actual <= 0) { 2630 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2631 continue; 2632 } 2633 break; 2634 } 2635 ALOG_ASSERT(actual <= (ssize_t)count); 2636 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2637 total += actual; 2638 } 2639 lseek(teeFd, (off_t) 4, SEEK_SET); 2640 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2641 write(teeFd, &temp, sizeof(temp)); 2642 lseek(teeFd, (off_t) 40, SEEK_SET); 2643 temp = total * channelCount * sizeof(short); 2644 write(teeFd, &temp, sizeof(temp)); 2645 close(teeFd); 2646 if (fd >= 0) { 2647 dprintf(fd, "tee copied to %s\n", teePath); 2648 } 2649 } else { 2650 if (fd >= 0) { 2651 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2652 } 2653 } 2654 } 2655} 2656#endif 2657 2658// ---------------------------------------------------------------------------- 2659 2660status_t AudioFlinger::onTransact( 2661 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2662{ 2663 return BnAudioFlinger::onTransact(code, data, reply, flags); 2664} 2665 2666}; // namespace android 2667