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