AudioFlinger.cpp revision f947dbce4390f2c3c460325d37002a34f09c0b74
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 181#ifdef TEE_SINK 182 (void) property_get("ro.debuggable", value, "0"); 183 int debuggable = atoi(value); 184 int teeEnabled = 0; 185 if (debuggable) { 186 (void) property_get("af.tee", value, "0"); 187 teeEnabled = atoi(value); 188 } 189 // FIXME symbolic constants here 190 if (teeEnabled & 1) { 191 mTeeSinkInputEnabled = true; 192 } 193 if (teeEnabled & 2) { 194 mTeeSinkOutputEnabled = true; 195 } 196 if (teeEnabled & 4) { 197 mTeeSinkTrackEnabled = true; 198 } 199#endif 200} 201 202void AudioFlinger::onFirstRef() 203{ 204 int rc = 0; 205 206 Mutex::Autolock _l(mLock); 207 208 /* TODO: move all this work into an Init() function */ 209 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 210 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 211 uint32_t int_val; 212 if (1 == sscanf(val_str, "%u", &int_val)) { 213 mStandbyTimeInNsecs = milliseconds(int_val); 214 ALOGI("Using %u mSec as standby time.", int_val); 215 } else { 216 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 217 ALOGI("Using default %u mSec as standby time.", 218 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 219 } 220 } 221 222 mPatchPanel = new PatchPanel(this); 223 224 mMode = AUDIO_MODE_NORMAL; 225} 226 227AudioFlinger::~AudioFlinger() 228{ 229 while (!mRecordThreads.isEmpty()) { 230 // closeInput_nonvirtual() will remove specified entry from mRecordThreads 231 closeInput_nonvirtual(mRecordThreads.keyAt(0)); 232 } 233 while (!mPlaybackThreads.isEmpty()) { 234 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads 235 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0)); 236 } 237 238 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 239 // no mHardwareLock needed, as there are no other references to this 240 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice()); 241 delete mAudioHwDevs.valueAt(i); 242 } 243 244 // Tell media.log service about any old writers that still need to be unregistered 245 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 246 if (binder != 0) { 247 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 248 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 249 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory()); 250 mUnregisteredWriters.pop(); 251 mediaLogService->unregisterWriter(iMemory); 252 } 253 } 254 255} 256 257static const char * const audio_interfaces[] = { 258 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 259 AUDIO_HARDWARE_MODULE_ID_A2DP, 260 AUDIO_HARDWARE_MODULE_ID_USB, 261}; 262#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 263 264AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l( 265 audio_module_handle_t module, 266 audio_devices_t devices) 267{ 268 // if module is 0, the request comes from an old policy manager and we should load 269 // well known modules 270 if (module == 0) { 271 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 272 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 273 loadHwModule_l(audio_interfaces[i]); 274 } 275 // then try to find a module supporting the requested device. 276 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 277 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i); 278 audio_hw_device_t *dev = audioHwDevice->hwDevice(); 279 if ((dev->get_supported_devices != NULL) && 280 (dev->get_supported_devices(dev) & devices) == devices) 281 return audioHwDevice; 282 } 283 } else { 284 // check a match for the requested module handle 285 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module); 286 if (audioHwDevice != NULL) { 287 return audioHwDevice; 288 } 289 } 290 291 return NULL; 292} 293 294void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused) 295{ 296 const size_t SIZE = 256; 297 char buffer[SIZE]; 298 String8 result; 299 300 result.append("Clients:\n"); 301 for (size_t i = 0; i < mClients.size(); ++i) { 302 sp<Client> client = mClients.valueAt(i).promote(); 303 if (client != 0) { 304 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 305 result.append(buffer); 306 } 307 } 308 309 result.append("Notification Clients:\n"); 310 for (size_t i = 0; i < mNotificationClients.size(); ++i) { 311 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i)); 312 result.append(buffer); 313 } 314 315 result.append("Global session refs:\n"); 316 result.append(" session pid count\n"); 317 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 318 AudioSessionRef *r = mAudioSessionRefs[i]; 319 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt); 320 result.append(buffer); 321 } 322 write(fd, result.string(), result.size()); 323} 324 325 326void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused) 327{ 328 const size_t SIZE = 256; 329 char buffer[SIZE]; 330 String8 result; 331 hardware_call_state hardwareStatus = mHardwareStatus; 332 333 snprintf(buffer, SIZE, "Hardware status: %d\n" 334 "Standby Time mSec: %u\n", 335 hardwareStatus, 336 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 337 result.append(buffer); 338 write(fd, result.string(), result.size()); 339} 340 341void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused) 342{ 343 const size_t SIZE = 256; 344 char buffer[SIZE]; 345 String8 result; 346 snprintf(buffer, SIZE, "Permission Denial: " 347 "can't dump AudioFlinger from pid=%d, uid=%d\n", 348 IPCThreadState::self()->getCallingPid(), 349 IPCThreadState::self()->getCallingUid()); 350 result.append(buffer); 351 write(fd, result.string(), result.size()); 352} 353 354bool AudioFlinger::dumpTryLock(Mutex& mutex) 355{ 356 bool locked = false; 357 for (int i = 0; i < kDumpLockRetries; ++i) { 358 if (mutex.tryLock() == NO_ERROR) { 359 locked = true; 360 break; 361 } 362 usleep(kDumpLockSleepUs); 363 } 364 return locked; 365} 366 367status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 368{ 369 if (!dumpAllowed()) { 370 dumpPermissionDenial(fd, args); 371 } else { 372 // get state of hardware lock 373 bool hardwareLocked = dumpTryLock(mHardwareLock); 374 if (!hardwareLocked) { 375 String8 result(kHardwareLockedString); 376 write(fd, result.string(), result.size()); 377 } else { 378 mHardwareLock.unlock(); 379 } 380 381 bool locked = dumpTryLock(mLock); 382 383 // failed to lock - AudioFlinger is probably deadlocked 384 if (!locked) { 385 String8 result(kDeadlockedString); 386 write(fd, result.string(), result.size()); 387 } 388 389 bool clientLocked = dumpTryLock(mClientLock); 390 if (!clientLocked) { 391 String8 result(kClientLockedString); 392 write(fd, result.string(), result.size()); 393 } 394 dumpClients(fd, args); 395 if (clientLocked) { 396 mClientLock.unlock(); 397 } 398 399 dumpInternals(fd, args); 400 401 // dump playback threads 402 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 403 mPlaybackThreads.valueAt(i)->dump(fd, args); 404 } 405 406 // dump record threads 407 for (size_t i = 0; i < mRecordThreads.size(); i++) { 408 mRecordThreads.valueAt(i)->dump(fd, args); 409 } 410 411 // dump all hardware devs 412 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 413 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 414 dev->dump(dev, fd); 415 } 416 417#ifdef TEE_SINK 418 // dump the serially shared record tee sink 419 if (mRecordTeeSource != 0) { 420 dumpTee(fd, mRecordTeeSource); 421 } 422#endif 423 424 if (locked) { 425 mLock.unlock(); 426 } 427 428 // append a copy of media.log here by forwarding fd to it, but don't attempt 429 // to lookup the service if it's not running, as it will block for a second 430 if (mLogMemoryDealer != 0) { 431 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 432 if (binder != 0) { 433 dprintf(fd, "\nmedia.log:\n"); 434 Vector<String16> args; 435 binder->dump(fd, args); 436 } 437 } 438 } 439 return NO_ERROR; 440} 441 442sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid) 443{ 444 Mutex::Autolock _cl(mClientLock); 445 // If pid is already in the mClients wp<> map, then use that entry 446 // (for which promote() is always != 0), otherwise create a new entry and Client. 447 sp<Client> client = mClients.valueFor(pid).promote(); 448 if (client == 0) { 449 client = new Client(this, pid); 450 mClients.add(pid, client); 451 } 452 453 return client; 454} 455 456sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name) 457{ 458 // If there is no memory allocated for logs, return a dummy writer that does nothing 459 if (mLogMemoryDealer == 0) { 460 return new NBLog::Writer(); 461 } 462 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 463 // Similarly if we can't contact the media.log service, also return a dummy writer 464 if (binder == 0) { 465 return new NBLog::Writer(); 466 } 467 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 468 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 469 // If allocation fails, consult the vector of previously unregistered writers 470 // and garbage-collect one or more them until an allocation succeeds 471 if (shared == 0) { 472 Mutex::Autolock _l(mUnregisteredWritersLock); 473 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 474 { 475 // Pick the oldest stale writer to garbage-collect 476 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory()); 477 mUnregisteredWriters.removeAt(0); 478 mediaLogService->unregisterWriter(iMemory); 479 // Now the media.log remote reference to IMemory is gone. When our last local 480 // reference to IMemory also drops to zero at end of this block, 481 // the IMemory destructor will deallocate the region from mLogMemoryDealer. 482 } 483 // Re-attempt the allocation 484 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 485 if (shared != 0) { 486 goto success; 487 } 488 } 489 // Even after garbage-collecting all old writers, there is still not enough memory, 490 // so return a dummy writer 491 return new NBLog::Writer(); 492 } 493success: 494 mediaLogService->registerWriter(shared, size, name); 495 return new NBLog::Writer(size, shared); 496} 497 498void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer) 499{ 500 if (writer == 0) { 501 return; 502 } 503 sp<IMemory> iMemory(writer->getIMemory()); 504 if (iMemory == 0) { 505 return; 506 } 507 // Rather than removing the writer immediately, append it to a queue of old writers to 508 // be garbage-collected later. This allows us to continue to view old logs for a while. 509 Mutex::Autolock _l(mUnregisteredWritersLock); 510 mUnregisteredWriters.push(writer); 511} 512 513// IAudioFlinger interface 514 515 516sp<IAudioTrack> AudioFlinger::createTrack( 517 audio_stream_type_t streamType, 518 uint32_t sampleRate, 519 audio_format_t format, 520 audio_channel_mask_t channelMask, 521 size_t *frameCount, 522 IAudioFlinger::track_flags_t *flags, 523 const sp<IMemory>& sharedBuffer, 524 audio_io_handle_t output, 525 pid_t tid, 526 int *sessionId, 527 int clientUid, 528 status_t *status) 529{ 530 sp<PlaybackThread::Track> track; 531 sp<TrackHandle> trackHandle; 532 sp<Client> client; 533 status_t lStatus; 534 int lSessionId; 535 536 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 537 // but if someone uses binder directly they could bypass that and cause us to crash 538 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 539 ALOGE("createTrack() invalid stream type %d", streamType); 540 lStatus = BAD_VALUE; 541 goto Exit; 542 } 543 544 // further sample rate checks are performed by createTrack_l() depending on the thread type 545 if (sampleRate == 0) { 546 ALOGE("createTrack() invalid sample rate %u", sampleRate); 547 lStatus = BAD_VALUE; 548 goto Exit; 549 } 550 551 // further channel mask checks are performed by createTrack_l() depending on the thread type 552 if (!audio_is_output_channel(channelMask)) { 553 ALOGE("createTrack() invalid channel mask %#x", channelMask); 554 lStatus = BAD_VALUE; 555 goto Exit; 556 } 557 558 // further format checks are performed by createTrack_l() depending on the thread type 559 if (!audio_is_valid_format(format)) { 560 ALOGE("createTrack() invalid format %#x", format); 561 lStatus = BAD_VALUE; 562 goto Exit; 563 } 564 565 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) { 566 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()"); 567 lStatus = BAD_VALUE; 568 goto Exit; 569 } 570 571 { 572 Mutex::Autolock _l(mLock); 573 PlaybackThread *thread = checkPlaybackThread_l(output); 574 if (thread == NULL) { 575 ALOGE("no playback thread found for output handle %d", output); 576 lStatus = BAD_VALUE; 577 goto Exit; 578 } 579 580 pid_t pid = IPCThreadState::self()->getCallingPid(); 581 client = registerPid(pid); 582 583 PlaybackThread *effectThread = NULL; 584 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 585 lSessionId = *sessionId; 586 // check if an effect chain with the same session ID is present on another 587 // output thread and move it here. 588 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 589 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 590 if (mPlaybackThreads.keyAt(i) != output) { 591 uint32_t sessions = t->hasAudioSession(lSessionId); 592 if (sessions & PlaybackThread::EFFECT_SESSION) { 593 effectThread = t.get(); 594 break; 595 } 596 } 597 } 598 } else { 599 // if no audio session id is provided, create one here 600 lSessionId = nextUniqueId(); 601 if (sessionId != NULL) { 602 *sessionId = lSessionId; 603 } 604 } 605 ALOGV("createTrack() lSessionId: %d", lSessionId); 606 607 track = thread->createTrack_l(client, streamType, sampleRate, format, 608 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus); 609 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0)); 610 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 611 612 // move effect chain to this output thread if an effect on same session was waiting 613 // for a track to be created 614 if (lStatus == NO_ERROR && effectThread != NULL) { 615 // no risk of deadlock because AudioFlinger::mLock is held 616 Mutex::Autolock _dl(thread->mLock); 617 Mutex::Autolock _sl(effectThread->mLock); 618 moveEffectChain_l(lSessionId, effectThread, thread, true); 619 } 620 621 // Look for sync events awaiting for a session to be used. 622 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) { 623 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 624 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 625 if (lStatus == NO_ERROR) { 626 (void) track->setSyncEvent(mPendingSyncEvents[i]); 627 } else { 628 mPendingSyncEvents[i]->cancel(); 629 } 630 mPendingSyncEvents.removeAt(i); 631 i--; 632 } 633 } 634 } 635 636 } 637 638 if (lStatus != NO_ERROR) { 639 // remove local strong reference to Client before deleting the Track so that the 640 // Client destructor is called by the TrackBase destructor with mClientLock held 641 // Don't hold mClientLock when releasing the reference on the track as the 642 // destructor will acquire it. 643 { 644 Mutex::Autolock _cl(mClientLock); 645 client.clear(); 646 } 647 track.clear(); 648 goto Exit; 649 } 650 651 // return handle to client 652 trackHandle = new TrackHandle(track); 653 654Exit: 655 *status = lStatus; 656 return trackHandle; 657} 658 659uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 660{ 661 Mutex::Autolock _l(mLock); 662 PlaybackThread *thread = checkPlaybackThread_l(output); 663 if (thread == NULL) { 664 ALOGW("sampleRate() unknown thread %d", output); 665 return 0; 666 } 667 return thread->sampleRate(); 668} 669 670audio_format_t AudioFlinger::format(audio_io_handle_t output) const 671{ 672 Mutex::Autolock _l(mLock); 673 PlaybackThread *thread = checkPlaybackThread_l(output); 674 if (thread == NULL) { 675 ALOGW("format() unknown thread %d", output); 676 return AUDIO_FORMAT_INVALID; 677 } 678 return thread->format(); 679} 680 681size_t AudioFlinger::frameCount(audio_io_handle_t output) const 682{ 683 Mutex::Autolock _l(mLock); 684 PlaybackThread *thread = checkPlaybackThread_l(output); 685 if (thread == NULL) { 686 ALOGW("frameCount() unknown thread %d", output); 687 return 0; 688 } 689 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 690 // should examine all callers and fix them to handle smaller counts 691 return thread->frameCount(); 692} 693 694uint32_t AudioFlinger::latency(audio_io_handle_t output) const 695{ 696 Mutex::Autolock _l(mLock); 697 PlaybackThread *thread = checkPlaybackThread_l(output); 698 if (thread == NULL) { 699 ALOGW("latency(): no playback thread found for output handle %d", output); 700 return 0; 701 } 702 return thread->latency(); 703} 704 705status_t AudioFlinger::setMasterVolume(float value) 706{ 707 status_t ret = initCheck(); 708 if (ret != NO_ERROR) { 709 return ret; 710 } 711 712 // check calling permissions 713 if (!settingsAllowed()) { 714 return PERMISSION_DENIED; 715 } 716 717 Mutex::Autolock _l(mLock); 718 mMasterVolume = value; 719 720 // Set master volume in the HALs which support it. 721 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 722 AutoMutex lock(mHardwareLock); 723 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 724 725 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 726 if (dev->canSetMasterVolume()) { 727 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 728 } 729 mHardwareStatus = AUDIO_HW_IDLE; 730 } 731 732 // Now set the master volume in each playback thread. Playback threads 733 // assigned to HALs which do not have master volume support will apply 734 // master volume during the mix operation. Threads with HALs which do 735 // support master volume will simply ignore the setting. 736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 737 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 738 739 return NO_ERROR; 740} 741 742status_t AudioFlinger::setMode(audio_mode_t mode) 743{ 744 status_t ret = initCheck(); 745 if (ret != NO_ERROR) { 746 return ret; 747 } 748 749 // check calling permissions 750 if (!settingsAllowed()) { 751 return PERMISSION_DENIED; 752 } 753 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 754 ALOGW("Illegal value: setMode(%d)", mode); 755 return BAD_VALUE; 756 } 757 758 { // scope for the lock 759 AutoMutex lock(mHardwareLock); 760 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 761 mHardwareStatus = AUDIO_HW_SET_MODE; 762 ret = dev->set_mode(dev, mode); 763 mHardwareStatus = AUDIO_HW_IDLE; 764 } 765 766 if (NO_ERROR == ret) { 767 Mutex::Autolock _l(mLock); 768 mMode = mode; 769 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 770 mPlaybackThreads.valueAt(i)->setMode(mode); 771 } 772 773 return ret; 774} 775 776status_t AudioFlinger::setMicMute(bool state) 777{ 778 status_t ret = initCheck(); 779 if (ret != NO_ERROR) { 780 return ret; 781 } 782 783 // check calling permissions 784 if (!settingsAllowed()) { 785 return PERMISSION_DENIED; 786 } 787 788 AutoMutex lock(mHardwareLock); 789 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 790 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 791 ret = dev->set_mic_mute(dev, state); 792 mHardwareStatus = AUDIO_HW_IDLE; 793 return ret; 794} 795 796bool AudioFlinger::getMicMute() const 797{ 798 status_t ret = initCheck(); 799 if (ret != NO_ERROR) { 800 return false; 801 } 802 803 bool state = AUDIO_MODE_INVALID; 804 AutoMutex lock(mHardwareLock); 805 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 806 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 807 dev->get_mic_mute(dev, &state); 808 mHardwareStatus = AUDIO_HW_IDLE; 809 return state; 810} 811 812status_t AudioFlinger::setMasterMute(bool muted) 813{ 814 status_t ret = initCheck(); 815 if (ret != NO_ERROR) { 816 return ret; 817 } 818 819 // check calling permissions 820 if (!settingsAllowed()) { 821 return PERMISSION_DENIED; 822 } 823 824 Mutex::Autolock _l(mLock); 825 mMasterMute = muted; 826 827 // Set master mute in the HALs which support it. 828 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 829 AutoMutex lock(mHardwareLock); 830 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 831 832 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 833 if (dev->canSetMasterMute()) { 834 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 835 } 836 mHardwareStatus = AUDIO_HW_IDLE; 837 } 838 839 // Now set the master mute in each playback thread. Playback threads 840 // assigned to HALs which do not have master mute support will apply master 841 // mute during the mix operation. Threads with HALs which do support master 842 // mute will simply ignore the setting. 843 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 844 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 845 846 return NO_ERROR; 847} 848 849float AudioFlinger::masterVolume() const 850{ 851 Mutex::Autolock _l(mLock); 852 return masterVolume_l(); 853} 854 855bool AudioFlinger::masterMute() const 856{ 857 Mutex::Autolock _l(mLock); 858 return masterMute_l(); 859} 860 861float AudioFlinger::masterVolume_l() const 862{ 863 return mMasterVolume; 864} 865 866bool AudioFlinger::masterMute_l() const 867{ 868 return mMasterMute; 869} 870 871status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 872 audio_io_handle_t output) 873{ 874 // check calling permissions 875 if (!settingsAllowed()) { 876 return PERMISSION_DENIED; 877 } 878 879 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 880 ALOGE("setStreamVolume() invalid stream %d", stream); 881 return BAD_VALUE; 882 } 883 884 AutoMutex lock(mLock); 885 PlaybackThread *thread = NULL; 886 if (output != AUDIO_IO_HANDLE_NONE) { 887 thread = checkPlaybackThread_l(output); 888 if (thread == NULL) { 889 return BAD_VALUE; 890 } 891 } 892 893 mStreamTypes[stream].volume = value; 894 895 if (thread == NULL) { 896 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 897 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 898 } 899 } else { 900 thread->setStreamVolume(stream, value); 901 } 902 903 return NO_ERROR; 904} 905 906status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 907{ 908 // check calling permissions 909 if (!settingsAllowed()) { 910 return PERMISSION_DENIED; 911 } 912 913 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 914 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 915 ALOGE("setStreamMute() invalid stream %d", stream); 916 return BAD_VALUE; 917 } 918 919 AutoMutex lock(mLock); 920 mStreamTypes[stream].mute = muted; 921 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 922 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 923 924 return NO_ERROR; 925} 926 927float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 928{ 929 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 930 return 0.0f; 931 } 932 933 AutoMutex lock(mLock); 934 float volume; 935 if (output != AUDIO_IO_HANDLE_NONE) { 936 PlaybackThread *thread = checkPlaybackThread_l(output); 937 if (thread == NULL) { 938 return 0.0f; 939 } 940 volume = thread->streamVolume(stream); 941 } else { 942 volume = streamVolume_l(stream); 943 } 944 945 return volume; 946} 947 948bool AudioFlinger::streamMute(audio_stream_type_t stream) const 949{ 950 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 951 return true; 952 } 953 954 AutoMutex lock(mLock); 955 return streamMute_l(stream); 956} 957 958status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 959{ 960 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 961 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 962 963 // check calling permissions 964 if (!settingsAllowed()) { 965 return PERMISSION_DENIED; 966 } 967 968 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface 969 if (ioHandle == AUDIO_IO_HANDLE_NONE) { 970 Mutex::Autolock _l(mLock); 971 status_t final_result = NO_ERROR; 972 { 973 AutoMutex lock(mHardwareLock); 974 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 975 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 976 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 977 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 978 final_result = result ?: final_result; 979 } 980 mHardwareStatus = AUDIO_HW_IDLE; 981 } 982 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 983 AudioParameter param = AudioParameter(keyValuePairs); 984 String8 value; 985 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 986 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 987 if (mBtNrecIsOff != btNrecIsOff) { 988 for (size_t i = 0; i < mRecordThreads.size(); i++) { 989 sp<RecordThread> thread = mRecordThreads.valueAt(i); 990 audio_devices_t device = thread->inDevice(); 991 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 992 // collect all of the thread's session IDs 993 KeyedVector<int, bool> ids = thread->sessionIds(); 994 // suspend effects associated with those session IDs 995 for (size_t j = 0; j < ids.size(); ++j) { 996 int sessionId = ids.keyAt(j); 997 thread->setEffectSuspended(FX_IID_AEC, 998 suspend, 999 sessionId); 1000 thread->setEffectSuspended(FX_IID_NS, 1001 suspend, 1002 sessionId); 1003 } 1004 } 1005 mBtNrecIsOff = btNrecIsOff; 1006 } 1007 } 1008 String8 screenState; 1009 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 1010 bool isOff = screenState == "off"; 1011 if (isOff != (AudioFlinger::mScreenState & 1)) { 1012 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 1013 } 1014 } 1015 return final_result; 1016 } 1017 1018 // hold a strong ref on thread in case closeOutput() or closeInput() is called 1019 // and the thread is exited once the lock is released 1020 sp<ThreadBase> thread; 1021 { 1022 Mutex::Autolock _l(mLock); 1023 thread = checkPlaybackThread_l(ioHandle); 1024 if (thread == 0) { 1025 thread = checkRecordThread_l(ioHandle); 1026 } else if (thread == primaryPlaybackThread_l()) { 1027 // indicate output device change to all input threads for pre processing 1028 AudioParameter param = AudioParameter(keyValuePairs); 1029 int value; 1030 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 1031 (value != 0)) { 1032 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1033 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 1034 } 1035 } 1036 } 1037 } 1038 if (thread != 0) { 1039 return thread->setParameters(keyValuePairs); 1040 } 1041 return BAD_VALUE; 1042} 1043 1044String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 1045{ 1046 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 1047 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 1048 1049 Mutex::Autolock _l(mLock); 1050 1051 if (ioHandle == AUDIO_IO_HANDLE_NONE) { 1052 String8 out_s8; 1053 1054 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1055 char *s; 1056 { 1057 AutoMutex lock(mHardwareLock); 1058 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 1059 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1060 s = dev->get_parameters(dev, keys.string()); 1061 mHardwareStatus = AUDIO_HW_IDLE; 1062 } 1063 out_s8 += String8(s ? s : ""); 1064 free(s); 1065 } 1066 return out_s8; 1067 } 1068 1069 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 1070 if (playbackThread != NULL) { 1071 return playbackThread->getParameters(keys); 1072 } 1073 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1074 if (recordThread != NULL) { 1075 return recordThread->getParameters(keys); 1076 } 1077 return String8(""); 1078} 1079 1080size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 1081 audio_channel_mask_t channelMask) const 1082{ 1083 status_t ret = initCheck(); 1084 if (ret != NO_ERROR) { 1085 return 0; 1086 } 1087 1088 AutoMutex lock(mHardwareLock); 1089 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1090 struct audio_config config; 1091 memset(&config, 0, sizeof(config)); 1092 config.sample_rate = sampleRate; 1093 config.channel_mask = channelMask; 1094 config.format = format; 1095 1096 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1097 size_t size = dev->get_input_buffer_size(dev, &config); 1098 mHardwareStatus = AUDIO_HW_IDLE; 1099 return size; 1100} 1101 1102uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1103{ 1104 Mutex::Autolock _l(mLock); 1105 1106 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1107 if (recordThread != NULL) { 1108 return recordThread->getInputFramesLost(); 1109 } 1110 return 0; 1111} 1112 1113status_t AudioFlinger::setVoiceVolume(float value) 1114{ 1115 status_t ret = initCheck(); 1116 if (ret != NO_ERROR) { 1117 return ret; 1118 } 1119 1120 // check calling permissions 1121 if (!settingsAllowed()) { 1122 return PERMISSION_DENIED; 1123 } 1124 1125 AutoMutex lock(mHardwareLock); 1126 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1127 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1128 ret = dev->set_voice_volume(dev, value); 1129 mHardwareStatus = AUDIO_HW_IDLE; 1130 1131 return ret; 1132} 1133 1134status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 1135 audio_io_handle_t output) const 1136{ 1137 status_t status; 1138 1139 Mutex::Autolock _l(mLock); 1140 1141 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1142 if (playbackThread != NULL) { 1143 return playbackThread->getRenderPosition(halFrames, dspFrames); 1144 } 1145 1146 return BAD_VALUE; 1147} 1148 1149void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1150{ 1151 Mutex::Autolock _l(mLock); 1152 bool clientAdded = false; 1153 { 1154 Mutex::Autolock _cl(mClientLock); 1155 1156 pid_t pid = IPCThreadState::self()->getCallingPid(); 1157 if (mNotificationClients.indexOfKey(pid) < 0) { 1158 sp<NotificationClient> notificationClient = new NotificationClient(this, 1159 client, 1160 pid); 1161 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1162 1163 mNotificationClients.add(pid, notificationClient); 1164 1165 sp<IBinder> binder = client->asBinder(); 1166 binder->linkToDeath(notificationClient); 1167 clientAdded = true; 1168 } 1169 } 1170 1171 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the 1172 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock. 1173 if (clientAdded) { 1174 // the config change is always sent from playback or record threads to avoid deadlock 1175 // with AudioSystem::gLock 1176 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1177 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1178 } 1179 1180 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1181 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1182 } 1183 } 1184} 1185 1186void AudioFlinger::removeNotificationClient(pid_t pid) 1187{ 1188 Mutex::Autolock _l(mLock); 1189 { 1190 Mutex::Autolock _cl(mClientLock); 1191 mNotificationClients.removeItem(pid); 1192 } 1193 1194 ALOGV("%d died, releasing its sessions", pid); 1195 size_t num = mAudioSessionRefs.size(); 1196 bool removed = false; 1197 for (size_t i = 0; i< num; ) { 1198 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1199 ALOGV(" pid %d @ %d", ref->mPid, i); 1200 if (ref->mPid == pid) { 1201 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1202 mAudioSessionRefs.removeAt(i); 1203 delete ref; 1204 removed = true; 1205 num--; 1206 } else { 1207 i++; 1208 } 1209 } 1210 if (removed) { 1211 purgeStaleEffects_l(); 1212 } 1213} 1214 1215void AudioFlinger::audioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) 1216{ 1217 Mutex::Autolock _l(mClientLock); 1218 size_t size = mNotificationClients.size(); 1219 for (size_t i = 0; i < size; i++) { 1220 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, 1221 ioHandle, 1222 param2); 1223 } 1224} 1225 1226// removeClient_l() must be called with AudioFlinger::mClientLock held 1227void AudioFlinger::removeClient_l(pid_t pid) 1228{ 1229 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1230 IPCThreadState::self()->getCallingPid()); 1231 mClients.removeItem(pid); 1232} 1233 1234// getEffectThread_l() must be called with AudioFlinger::mLock held 1235sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1236{ 1237 sp<PlaybackThread> thread; 1238 1239 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1240 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1241 ALOG_ASSERT(thread == 0); 1242 thread = mPlaybackThreads.valueAt(i); 1243 } 1244 } 1245 1246 return thread; 1247} 1248 1249 1250 1251// ---------------------------------------------------------------------------- 1252 1253AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1254 : RefBase(), 1255 mAudioFlinger(audioFlinger), 1256 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 1257 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 1258 mPid(pid), 1259 mTimedTrackCount(0) 1260{ 1261 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 1262} 1263 1264// Client destructor must be called with AudioFlinger::mClientLock held 1265AudioFlinger::Client::~Client() 1266{ 1267 mAudioFlinger->removeClient_l(mPid); 1268} 1269 1270sp<MemoryDealer> AudioFlinger::Client::heap() const 1271{ 1272 return mMemoryDealer; 1273} 1274 1275// Reserve one of the limited slots for a timed audio track associated 1276// with this client 1277bool AudioFlinger::Client::reserveTimedTrack() 1278{ 1279 const int kMaxTimedTracksPerClient = 4; 1280 1281 Mutex::Autolock _l(mTimedTrackLock); 1282 1283 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 1284 ALOGW("can not create timed track - pid %d has exceeded the limit", 1285 mPid); 1286 return false; 1287 } 1288 1289 mTimedTrackCount++; 1290 return true; 1291} 1292 1293// Release a slot for a timed audio track 1294void AudioFlinger::Client::releaseTimedTrack() 1295{ 1296 Mutex::Autolock _l(mTimedTrackLock); 1297 mTimedTrackCount--; 1298} 1299 1300// ---------------------------------------------------------------------------- 1301 1302AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1303 const sp<IAudioFlingerClient>& client, 1304 pid_t pid) 1305 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1306{ 1307} 1308 1309AudioFlinger::NotificationClient::~NotificationClient() 1310{ 1311} 1312 1313void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused) 1314{ 1315 sp<NotificationClient> keep(this); 1316 mAudioFlinger->removeNotificationClient(mPid); 1317} 1318 1319 1320// ---------------------------------------------------------------------------- 1321 1322static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) { 1323 return audio_is_remote_submix_device(inDevice); 1324} 1325 1326sp<IAudioRecord> AudioFlinger::openRecord( 1327 audio_io_handle_t input, 1328 uint32_t sampleRate, 1329 audio_format_t format, 1330 audio_channel_mask_t channelMask, 1331 size_t *frameCount, 1332 IAudioFlinger::track_flags_t *flags, 1333 pid_t tid, 1334 int *sessionId, 1335 sp<IMemory>& cblk, 1336 sp<IMemory>& buffers, 1337 status_t *status) 1338{ 1339 sp<RecordThread::RecordTrack> recordTrack; 1340 sp<RecordHandle> recordHandle; 1341 sp<Client> client; 1342 status_t lStatus; 1343 int lSessionId; 1344 1345 cblk.clear(); 1346 buffers.clear(); 1347 1348 // check calling permissions 1349 if (!recordingAllowed()) { 1350 ALOGE("openRecord() permission denied: recording not allowed"); 1351 lStatus = PERMISSION_DENIED; 1352 goto Exit; 1353 } 1354 1355 // further sample rate checks are performed by createRecordTrack_l() 1356 if (sampleRate == 0) { 1357 ALOGE("openRecord() invalid sample rate %u", sampleRate); 1358 lStatus = BAD_VALUE; 1359 goto Exit; 1360 } 1361 1362 // we don't yet support anything other than 16-bit PCM 1363 if (!(audio_is_valid_format(format) && 1364 audio_is_linear_pcm(format) && format == AUDIO_FORMAT_PCM_16_BIT)) { 1365 ALOGE("openRecord() invalid format %#x", format); 1366 lStatus = BAD_VALUE; 1367 goto Exit; 1368 } 1369 1370 // further channel mask checks are performed by createRecordTrack_l() 1371 if (!audio_is_input_channel(channelMask)) { 1372 ALOGE("openRecord() invalid channel mask %#x", channelMask); 1373 lStatus = BAD_VALUE; 1374 goto Exit; 1375 } 1376 1377 { 1378 Mutex::Autolock _l(mLock); 1379 RecordThread *thread = checkRecordThread_l(input); 1380 if (thread == NULL) { 1381 ALOGE("openRecord() checkRecordThread_l failed"); 1382 lStatus = BAD_VALUE; 1383 goto Exit; 1384 } 1385 1386 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice()) 1387 && !captureAudioOutputAllowed()) { 1388 ALOGE("openRecord() permission denied: capture not allowed"); 1389 lStatus = PERMISSION_DENIED; 1390 goto Exit; 1391 } 1392 1393 pid_t pid = IPCThreadState::self()->getCallingPid(); 1394 client = registerPid(pid); 1395 1396 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 1397 lSessionId = *sessionId; 1398 } else { 1399 // if no audio session id is provided, create one here 1400 lSessionId = nextUniqueId(); 1401 if (sessionId != NULL) { 1402 *sessionId = lSessionId; 1403 } 1404 } 1405 ALOGV("openRecord() lSessionId: %d", lSessionId); 1406 1407 // TODO: the uid should be passed in as a parameter to openRecord 1408 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1409 frameCount, lSessionId, 1410 IPCThreadState::self()->getCallingUid(), 1411 flags, tid, &lStatus); 1412 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0)); 1413 } 1414 1415 if (lStatus != NO_ERROR) { 1416 // remove local strong reference to Client before deleting the RecordTrack so that the 1417 // Client destructor is called by the TrackBase destructor with mClientLock held 1418 // Don't hold mClientLock when releasing the reference on the track as the 1419 // destructor will acquire it. 1420 { 1421 Mutex::Autolock _cl(mClientLock); 1422 client.clear(); 1423 } 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 if (handle == 0) { 2384 // remove local strong reference to Client with mClientLock held 2385 Mutex::Autolock _cl(mClientLock); 2386 client.clear(); 2387 } 2388 } 2389 2390Exit: 2391 *status = lStatus; 2392 return handle; 2393} 2394 2395status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2396 audio_io_handle_t dstOutput) 2397{ 2398 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2399 sessionId, srcOutput, dstOutput); 2400 Mutex::Autolock _l(mLock); 2401 if (srcOutput == dstOutput) { 2402 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2403 return NO_ERROR; 2404 } 2405 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2406 if (srcThread == NULL) { 2407 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2408 return BAD_VALUE; 2409 } 2410 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2411 if (dstThread == NULL) { 2412 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2413 return BAD_VALUE; 2414 } 2415 2416 Mutex::Autolock _dl(dstThread->mLock); 2417 Mutex::Autolock _sl(srcThread->mLock); 2418 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 2419} 2420 2421// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2422status_t AudioFlinger::moveEffectChain_l(int sessionId, 2423 AudioFlinger::PlaybackThread *srcThread, 2424 AudioFlinger::PlaybackThread *dstThread, 2425 bool reRegister) 2426{ 2427 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2428 sessionId, srcThread, dstThread); 2429 2430 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2431 if (chain == 0) { 2432 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2433 sessionId, srcThread); 2434 return INVALID_OPERATION; 2435 } 2436 2437 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2438 // so that a new chain is created with correct parameters when first effect is added. This is 2439 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2440 // removed. 2441 srcThread->removeEffectChain_l(chain); 2442 2443 // transfer all effects one by one so that new effect chain is created on new thread with 2444 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2445 sp<EffectChain> dstChain; 2446 uint32_t strategy = 0; // prevent compiler warning 2447 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2448 Vector< sp<EffectModule> > removed; 2449 status_t status = NO_ERROR; 2450 while (effect != 0) { 2451 srcThread->removeEffect_l(effect); 2452 removed.add(effect); 2453 status = dstThread->addEffect_l(effect); 2454 if (status != NO_ERROR) { 2455 break; 2456 } 2457 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2458 if (effect->state() == EffectModule::ACTIVE || 2459 effect->state() == EffectModule::STOPPING) { 2460 effect->start(); 2461 } 2462 // if the move request is not received from audio policy manager, the effect must be 2463 // re-registered with the new strategy and output 2464 if (dstChain == 0) { 2465 dstChain = effect->chain().promote(); 2466 if (dstChain == 0) { 2467 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2468 status = NO_INIT; 2469 break; 2470 } 2471 strategy = dstChain->strategy(); 2472 } 2473 if (reRegister) { 2474 AudioSystem::unregisterEffect(effect->id()); 2475 AudioSystem::registerEffect(&effect->desc(), 2476 dstThread->id(), 2477 strategy, 2478 sessionId, 2479 effect->id()); 2480 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2481 } 2482 effect = chain->getEffectFromId_l(0); 2483 } 2484 2485 if (status != NO_ERROR) { 2486 for (size_t i = 0; i < removed.size(); i++) { 2487 srcThread->addEffect_l(removed[i]); 2488 if (dstChain != 0 && reRegister) { 2489 AudioSystem::unregisterEffect(removed[i]->id()); 2490 AudioSystem::registerEffect(&removed[i]->desc(), 2491 srcThread->id(), 2492 strategy, 2493 sessionId, 2494 removed[i]->id()); 2495 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2496 } 2497 } 2498 } 2499 2500 return status; 2501} 2502 2503bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 2504{ 2505 if (mGlobalEffectEnableTime != 0 && 2506 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 2507 return true; 2508 } 2509 2510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2511 sp<EffectChain> ec = 2512 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2513 if (ec != 0 && ec->isNonOffloadableEnabled()) { 2514 return true; 2515 } 2516 } 2517 return false; 2518} 2519 2520void AudioFlinger::onNonOffloadableGlobalEffectEnable() 2521{ 2522 Mutex::Autolock _l(mLock); 2523 2524 mGlobalEffectEnableTime = systemTime(); 2525 2526 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2527 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2528 if (t->mType == ThreadBase::OFFLOAD) { 2529 t->invalidateTracks(AUDIO_STREAM_MUSIC); 2530 } 2531 } 2532 2533} 2534 2535struct Entry { 2536#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2537 char mName[MAX_NAME]; 2538}; 2539 2540int comparEntry(const void *p1, const void *p2) 2541{ 2542 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2543} 2544 2545#ifdef TEE_SINK 2546void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2547{ 2548 NBAIO_Source *teeSource = source.get(); 2549 if (teeSource != NULL) { 2550 // .wav rotation 2551 // There is a benign race condition if 2 threads call this simultaneously. 2552 // They would both traverse the directory, but the result would simply be 2553 // failures at unlink() which are ignored. It's also unlikely since 2554 // normally dumpsys is only done by bugreport or from the command line. 2555 char teePath[32+256]; 2556 strcpy(teePath, "/data/misc/media"); 2557 size_t teePathLen = strlen(teePath); 2558 DIR *dir = opendir(teePath); 2559 teePath[teePathLen++] = '/'; 2560 if (dir != NULL) { 2561#define MAX_SORT 20 // number of entries to sort 2562#define MAX_KEEP 10 // number of entries to keep 2563 struct Entry entries[MAX_SORT]; 2564 size_t entryCount = 0; 2565 while (entryCount < MAX_SORT) { 2566 struct dirent de; 2567 struct dirent *result = NULL; 2568 int rc = readdir_r(dir, &de, &result); 2569 if (rc != 0) { 2570 ALOGW("readdir_r failed %d", rc); 2571 break; 2572 } 2573 if (result == NULL) { 2574 break; 2575 } 2576 if (result != &de) { 2577 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2578 break; 2579 } 2580 // ignore non .wav file entries 2581 size_t nameLen = strlen(de.d_name); 2582 if (nameLen <= 4 || nameLen >= MAX_NAME || 2583 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2584 continue; 2585 } 2586 strcpy(entries[entryCount++].mName, de.d_name); 2587 } 2588 (void) closedir(dir); 2589 if (entryCount > MAX_KEEP) { 2590 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2591 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2592 strcpy(&teePath[teePathLen], entries[i].mName); 2593 (void) unlink(teePath); 2594 } 2595 } 2596 } else { 2597 if (fd >= 0) { 2598 dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2599 } 2600 } 2601 char teeTime[16]; 2602 struct timeval tv; 2603 gettimeofday(&tv, NULL); 2604 struct tm tm; 2605 localtime_r(&tv.tv_sec, &tm); 2606 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2607 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2608 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2609 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2610 if (teeFd >= 0) { 2611 char wavHeader[44]; 2612 memcpy(wavHeader, 2613 "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", 2614 sizeof(wavHeader)); 2615 NBAIO_Format format = teeSource->format(); 2616 unsigned channelCount = Format_channelCount(format); 2617 ALOG_ASSERT(channelCount <= FCC_2); 2618 uint32_t sampleRate = Format_sampleRate(format); 2619 wavHeader[22] = channelCount; // number of channels 2620 wavHeader[24] = sampleRate; // sample rate 2621 wavHeader[25] = sampleRate >> 8; 2622 wavHeader[32] = channelCount * 2; // block alignment 2623 write(teeFd, wavHeader, sizeof(wavHeader)); 2624 size_t total = 0; 2625 bool firstRead = true; 2626 for (;;) { 2627#define TEE_SINK_READ 1024 2628 short buffer[TEE_SINK_READ * FCC_2]; 2629 size_t count = TEE_SINK_READ; 2630 ssize_t actual = teeSource->read(buffer, count, 2631 AudioBufferProvider::kInvalidPTS); 2632 bool wasFirstRead = firstRead; 2633 firstRead = false; 2634 if (actual <= 0) { 2635 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2636 continue; 2637 } 2638 break; 2639 } 2640 ALOG_ASSERT(actual <= (ssize_t)count); 2641 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2642 total += actual; 2643 } 2644 lseek(teeFd, (off_t) 4, SEEK_SET); 2645 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2646 write(teeFd, &temp, sizeof(temp)); 2647 lseek(teeFd, (off_t) 40, SEEK_SET); 2648 temp = total * channelCount * sizeof(short); 2649 write(teeFd, &temp, sizeof(temp)); 2650 close(teeFd); 2651 if (fd >= 0) { 2652 dprintf(fd, "tee copied to %s\n", teePath); 2653 } 2654 } else { 2655 if (fd >= 0) { 2656 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2657 } 2658 } 2659 } 2660} 2661#endif 2662 2663// ---------------------------------------------------------------------------- 2664 2665status_t AudioFlinger::onTransact( 2666 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2667{ 2668 return BnAudioFlinger::onTransact(code, data, reply, flags); 2669} 2670 2671}; // namespace android 2672