AudioFlinger.cpp revision 9156ef3e11b68cc4b6d3cea77f1f63673855a6d1
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 504 // move effect chain to this output thread if an effect on same session was waiting 505 // for a track to be created 506 if (lStatus == NO_ERROR && effectThread != NULL) { 507 Mutex::Autolock _dl(thread->mLock); 508 Mutex::Autolock _sl(effectThread->mLock); 509 moveEffectChain_l(lSessionId, effectThread, thread, true); 510 } 511 512 // Look for sync events awaiting for a session to be used. 513 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 514 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 515 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 516 if (lStatus == NO_ERROR) { 517 (void) track->setSyncEvent(mPendingSyncEvents[i]); 518 } else { 519 mPendingSyncEvents[i]->cancel(); 520 } 521 mPendingSyncEvents.removeAt(i); 522 i--; 523 } 524 } 525 } 526 } 527 if (lStatus == NO_ERROR) { 528 // s for server's pid, n for normal mixer name, f for fast index 529 name = String8::format("s:%d;n:%d;f:%d", getpid_cached, track->name() - AudioMixer::TRACK0, 530 track->fastIndex()); 531 trackHandle = new TrackHandle(track); 532 } else { 533 // remove local strong reference to Client before deleting the Track so that the Client 534 // destructor is called by the TrackBase destructor with mLock held 535 client.clear(); 536 track.clear(); 537 } 538 539Exit: 540 *status = lStatus; 541 return trackHandle; 542} 543 544uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 545{ 546 Mutex::Autolock _l(mLock); 547 PlaybackThread *thread = checkPlaybackThread_l(output); 548 if (thread == NULL) { 549 ALOGW("sampleRate() unknown thread %d", output); 550 return 0; 551 } 552 return thread->sampleRate(); 553} 554 555int AudioFlinger::channelCount(audio_io_handle_t output) const 556{ 557 Mutex::Autolock _l(mLock); 558 PlaybackThread *thread = checkPlaybackThread_l(output); 559 if (thread == NULL) { 560 ALOGW("channelCount() unknown thread %d", output); 561 return 0; 562 } 563 return thread->channelCount(); 564} 565 566audio_format_t AudioFlinger::format(audio_io_handle_t output) const 567{ 568 Mutex::Autolock _l(mLock); 569 PlaybackThread *thread = checkPlaybackThread_l(output); 570 if (thread == NULL) { 571 ALOGW("format() unknown thread %d", output); 572 return AUDIO_FORMAT_INVALID; 573 } 574 return thread->format(); 575} 576 577size_t AudioFlinger::frameCount(audio_io_handle_t output) const 578{ 579 Mutex::Autolock _l(mLock); 580 PlaybackThread *thread = checkPlaybackThread_l(output); 581 if (thread == NULL) { 582 ALOGW("frameCount() unknown thread %d", output); 583 return 0; 584 } 585 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 586 // should examine all callers and fix them to handle smaller counts 587 return thread->frameCount(); 588} 589 590uint32_t AudioFlinger::latency(audio_io_handle_t output) const 591{ 592 Mutex::Autolock _l(mLock); 593 PlaybackThread *thread = checkPlaybackThread_l(output); 594 if (thread == NULL) { 595 ALOGW("latency(): no playback thread found for output handle %d", output); 596 return 0; 597 } 598 return thread->latency(); 599} 600 601status_t AudioFlinger::setMasterVolume(float value) 602{ 603 status_t ret = initCheck(); 604 if (ret != NO_ERROR) { 605 return ret; 606 } 607 608 // check calling permissions 609 if (!settingsAllowed()) { 610 return PERMISSION_DENIED; 611 } 612 613 Mutex::Autolock _l(mLock); 614 mMasterVolume = value; 615 616 // Set master volume in the HALs which support it. 617 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 618 AutoMutex lock(mHardwareLock); 619 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 620 621 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 622 if (dev->canSetMasterVolume()) { 623 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 624 } 625 mHardwareStatus = AUDIO_HW_IDLE; 626 } 627 628 // Now set the master volume in each playback thread. Playback threads 629 // assigned to HALs which do not have master volume support will apply 630 // master volume during the mix operation. Threads with HALs which do 631 // support master volume will simply ignore the setting. 632 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 633 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 634 635 return NO_ERROR; 636} 637 638status_t AudioFlinger::setMode(audio_mode_t mode) 639{ 640 status_t ret = initCheck(); 641 if (ret != NO_ERROR) { 642 return ret; 643 } 644 645 // check calling permissions 646 if (!settingsAllowed()) { 647 return PERMISSION_DENIED; 648 } 649 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 650 ALOGW("Illegal value: setMode(%d)", mode); 651 return BAD_VALUE; 652 } 653 654 { // scope for the lock 655 AutoMutex lock(mHardwareLock); 656 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 657 mHardwareStatus = AUDIO_HW_SET_MODE; 658 ret = dev->set_mode(dev, mode); 659 mHardwareStatus = AUDIO_HW_IDLE; 660 } 661 662 if (NO_ERROR == ret) { 663 Mutex::Autolock _l(mLock); 664 mMode = mode; 665 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 666 mPlaybackThreads.valueAt(i)->setMode(mode); 667 } 668 669 return ret; 670} 671 672status_t AudioFlinger::setMicMute(bool state) 673{ 674 status_t ret = initCheck(); 675 if (ret != NO_ERROR) { 676 return ret; 677 } 678 679 // check calling permissions 680 if (!settingsAllowed()) { 681 return PERMISSION_DENIED; 682 } 683 684 AutoMutex lock(mHardwareLock); 685 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 686 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 687 ret = dev->set_mic_mute(dev, state); 688 mHardwareStatus = AUDIO_HW_IDLE; 689 return ret; 690} 691 692bool AudioFlinger::getMicMute() const 693{ 694 status_t ret = initCheck(); 695 if (ret != NO_ERROR) { 696 return false; 697 } 698 699 bool state = AUDIO_MODE_INVALID; 700 AutoMutex lock(mHardwareLock); 701 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 702 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 703 dev->get_mic_mute(dev, &state); 704 mHardwareStatus = AUDIO_HW_IDLE; 705 return state; 706} 707 708status_t AudioFlinger::setMasterMute(bool muted) 709{ 710 status_t ret = initCheck(); 711 if (ret != NO_ERROR) { 712 return ret; 713 } 714 715 // check calling permissions 716 if (!settingsAllowed()) { 717 return PERMISSION_DENIED; 718 } 719 720 Mutex::Autolock _l(mLock); 721 mMasterMute = muted; 722 723 // Set master mute in the HALs which support it. 724 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 725 AutoMutex lock(mHardwareLock); 726 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 727 728 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 729 if (dev->canSetMasterMute()) { 730 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 731 } 732 mHardwareStatus = AUDIO_HW_IDLE; 733 } 734 735 // Now set the master mute in each playback thread. Playback threads 736 // assigned to HALs which do not have master mute support will apply master 737 // mute during the mix operation. Threads with HALs which do support master 738 // mute will simply ignore the setting. 739 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 740 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 741 742 return NO_ERROR; 743} 744 745float AudioFlinger::masterVolume() const 746{ 747 Mutex::Autolock _l(mLock); 748 return masterVolume_l(); 749} 750 751bool AudioFlinger::masterMute() const 752{ 753 Mutex::Autolock _l(mLock); 754 return masterMute_l(); 755} 756 757float AudioFlinger::masterVolume_l() const 758{ 759 return mMasterVolume; 760} 761 762bool AudioFlinger::masterMute_l() const 763{ 764 return mMasterMute; 765} 766 767status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 768 audio_io_handle_t output) 769{ 770 // check calling permissions 771 if (!settingsAllowed()) { 772 return PERMISSION_DENIED; 773 } 774 775 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 776 ALOGE("setStreamVolume() invalid stream %d", stream); 777 return BAD_VALUE; 778 } 779 780 AutoMutex lock(mLock); 781 PlaybackThread *thread = NULL; 782 if (output) { 783 thread = checkPlaybackThread_l(output); 784 if (thread == NULL) { 785 return BAD_VALUE; 786 } 787 } 788 789 mStreamTypes[stream].volume = value; 790 791 if (thread == NULL) { 792 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 793 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 794 } 795 } else { 796 thread->setStreamVolume(stream, value); 797 } 798 799 return NO_ERROR; 800} 801 802status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 803{ 804 // check calling permissions 805 if (!settingsAllowed()) { 806 return PERMISSION_DENIED; 807 } 808 809 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 810 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 811 ALOGE("setStreamMute() invalid stream %d", stream); 812 return BAD_VALUE; 813 } 814 815 AutoMutex lock(mLock); 816 mStreamTypes[stream].mute = muted; 817 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 818 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 819 820 return NO_ERROR; 821} 822 823float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 824{ 825 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 826 return 0.0f; 827 } 828 829 AutoMutex lock(mLock); 830 float volume; 831 if (output) { 832 PlaybackThread *thread = checkPlaybackThread_l(output); 833 if (thread == NULL) { 834 return 0.0f; 835 } 836 volume = thread->streamVolume(stream); 837 } else { 838 volume = streamVolume_l(stream); 839 } 840 841 return volume; 842} 843 844bool AudioFlinger::streamMute(audio_stream_type_t stream) const 845{ 846 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 847 return true; 848 } 849 850 AutoMutex lock(mLock); 851 return streamMute_l(stream); 852} 853 854status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 855{ 856 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 857 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 858 859 // check calling permissions 860 if (!settingsAllowed()) { 861 return PERMISSION_DENIED; 862 } 863 864 // ioHandle == 0 means the parameters are global to the audio hardware interface 865 if (ioHandle == 0) { 866 Mutex::Autolock _l(mLock); 867 status_t final_result = NO_ERROR; 868 { 869 AutoMutex lock(mHardwareLock); 870 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 871 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 872 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 873 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 874 final_result = result ?: final_result; 875 } 876 mHardwareStatus = AUDIO_HW_IDLE; 877 } 878 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 879 AudioParameter param = AudioParameter(keyValuePairs); 880 String8 value; 881 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 882 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 883 if (mBtNrecIsOff != btNrecIsOff) { 884 for (size_t i = 0; i < mRecordThreads.size(); i++) { 885 sp<RecordThread> thread = mRecordThreads.valueAt(i); 886 audio_devices_t device = thread->inDevice(); 887 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 888 // collect all of the thread's session IDs 889 KeyedVector<int, bool> ids = thread->sessionIds(); 890 // suspend effects associated with those session IDs 891 for (size_t j = 0; j < ids.size(); ++j) { 892 int sessionId = ids.keyAt(j); 893 thread->setEffectSuspended(FX_IID_AEC, 894 suspend, 895 sessionId); 896 thread->setEffectSuspended(FX_IID_NS, 897 suspend, 898 sessionId); 899 } 900 } 901 mBtNrecIsOff = btNrecIsOff; 902 } 903 } 904 String8 screenState; 905 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 906 bool isOff = screenState == "off"; 907 if (isOff != (AudioFlinger::mScreenState & 1)) { 908 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 909 } 910 } 911 return final_result; 912 } 913 914 // hold a strong ref on thread in case closeOutput() or closeInput() is called 915 // and the thread is exited once the lock is released 916 sp<ThreadBase> thread; 917 { 918 Mutex::Autolock _l(mLock); 919 thread = checkPlaybackThread_l(ioHandle); 920 if (thread == 0) { 921 thread = checkRecordThread_l(ioHandle); 922 } else if (thread == primaryPlaybackThread_l()) { 923 // indicate output device change to all input threads for pre processing 924 AudioParameter param = AudioParameter(keyValuePairs); 925 int value; 926 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 927 (value != 0)) { 928 for (size_t i = 0; i < mRecordThreads.size(); i++) { 929 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 930 } 931 } 932 } 933 } 934 if (thread != 0) { 935 return thread->setParameters(keyValuePairs); 936 } 937 return BAD_VALUE; 938} 939 940String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 941{ 942 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 943 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 944 945 Mutex::Autolock _l(mLock); 946 947 if (ioHandle == 0) { 948 String8 out_s8; 949 950 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 951 char *s; 952 { 953 AutoMutex lock(mHardwareLock); 954 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 955 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 956 s = dev->get_parameters(dev, keys.string()); 957 mHardwareStatus = AUDIO_HW_IDLE; 958 } 959 out_s8 += String8(s ? s : ""); 960 free(s); 961 } 962 return out_s8; 963 } 964 965 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 966 if (playbackThread != NULL) { 967 return playbackThread->getParameters(keys); 968 } 969 RecordThread *recordThread = checkRecordThread_l(ioHandle); 970 if (recordThread != NULL) { 971 return recordThread->getParameters(keys); 972 } 973 return String8(""); 974} 975 976size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 977 audio_channel_mask_t channelMask) const 978{ 979 status_t ret = initCheck(); 980 if (ret != NO_ERROR) { 981 return 0; 982 } 983 984 AutoMutex lock(mHardwareLock); 985 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 986 struct audio_config config; 987 memset(&config, 0, sizeof(config)); 988 config.sample_rate = sampleRate; 989 config.channel_mask = channelMask; 990 config.format = format; 991 992 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 993 size_t size = dev->get_input_buffer_size(dev, &config); 994 mHardwareStatus = AUDIO_HW_IDLE; 995 return size; 996} 997 998unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 999{ 1000 Mutex::Autolock _l(mLock); 1001 1002 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1003 if (recordThread != NULL) { 1004 return recordThread->getInputFramesLost(); 1005 } 1006 return 0; 1007} 1008 1009status_t AudioFlinger::setVoiceVolume(float value) 1010{ 1011 status_t ret = initCheck(); 1012 if (ret != NO_ERROR) { 1013 return ret; 1014 } 1015 1016 // check calling permissions 1017 if (!settingsAllowed()) { 1018 return PERMISSION_DENIED; 1019 } 1020 1021 AutoMutex lock(mHardwareLock); 1022 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1023 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1024 ret = dev->set_voice_volume(dev, value); 1025 mHardwareStatus = AUDIO_HW_IDLE; 1026 1027 return ret; 1028} 1029 1030status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames, 1031 audio_io_handle_t output) const 1032{ 1033 status_t status; 1034 1035 Mutex::Autolock _l(mLock); 1036 1037 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1038 if (playbackThread != NULL) { 1039 return playbackThread->getRenderPosition(halFrames, dspFrames); 1040 } 1041 1042 return BAD_VALUE; 1043} 1044 1045void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1046{ 1047 1048 Mutex::Autolock _l(mLock); 1049 1050 pid_t pid = IPCThreadState::self()->getCallingPid(); 1051 if (mNotificationClients.indexOfKey(pid) < 0) { 1052 sp<NotificationClient> notificationClient = new NotificationClient(this, 1053 client, 1054 pid); 1055 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1056 1057 mNotificationClients.add(pid, notificationClient); 1058 1059 sp<IBinder> binder = client->asBinder(); 1060 binder->linkToDeath(notificationClient); 1061 1062 // the config change is always sent from playback or record threads to avoid deadlock 1063 // with AudioSystem::gLock 1064 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1065 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1066 } 1067 1068 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1069 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1070 } 1071 } 1072} 1073 1074void AudioFlinger::removeNotificationClient(pid_t pid) 1075{ 1076 Mutex::Autolock _l(mLock); 1077 1078 mNotificationClients.removeItem(pid); 1079 1080 ALOGV("%d died, releasing its sessions", pid); 1081 size_t num = mAudioSessionRefs.size(); 1082 bool removed = false; 1083 for (size_t i = 0; i< num; ) { 1084 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1085 ALOGV(" pid %d @ %d", ref->mPid, i); 1086 if (ref->mPid == pid) { 1087 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1088 mAudioSessionRefs.removeAt(i); 1089 delete ref; 1090 removed = true; 1091 num--; 1092 } else { 1093 i++; 1094 } 1095 } 1096 if (removed) { 1097 purgeStaleEffects_l(); 1098 } 1099} 1100 1101// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1102void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1103{ 1104 size_t size = mNotificationClients.size(); 1105 for (size_t i = 0; i < size; i++) { 1106 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1107 param2); 1108 } 1109} 1110 1111// removeClient_l() must be called with AudioFlinger::mLock held 1112void AudioFlinger::removeClient_l(pid_t pid) 1113{ 1114 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1115 IPCThreadState::self()->getCallingPid()); 1116 mClients.removeItem(pid); 1117} 1118 1119// getEffectThread_l() must be called with AudioFlinger::mLock held 1120sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1121{ 1122 sp<PlaybackThread> thread; 1123 1124 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1125 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1126 ALOG_ASSERT(thread == 0); 1127 thread = mPlaybackThreads.valueAt(i); 1128 } 1129 } 1130 1131 return thread; 1132} 1133 1134 1135 1136// ---------------------------------------------------------------------------- 1137 1138AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1139 : RefBase(), 1140 mAudioFlinger(audioFlinger), 1141 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 1142 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 1143 mPid(pid), 1144 mTimedTrackCount(0) 1145{ 1146 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 1147} 1148 1149// Client destructor must be called with AudioFlinger::mLock held 1150AudioFlinger::Client::~Client() 1151{ 1152 mAudioFlinger->removeClient_l(mPid); 1153} 1154 1155sp<MemoryDealer> AudioFlinger::Client::heap() const 1156{ 1157 return mMemoryDealer; 1158} 1159 1160// Reserve one of the limited slots for a timed audio track associated 1161// with this client 1162bool AudioFlinger::Client::reserveTimedTrack() 1163{ 1164 const int kMaxTimedTracksPerClient = 4; 1165 1166 Mutex::Autolock _l(mTimedTrackLock); 1167 1168 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 1169 ALOGW("can not create timed track - pid %d has exceeded the limit", 1170 mPid); 1171 return false; 1172 } 1173 1174 mTimedTrackCount++; 1175 return true; 1176} 1177 1178// Release a slot for a timed audio track 1179void AudioFlinger::Client::releaseTimedTrack() 1180{ 1181 Mutex::Autolock _l(mTimedTrackLock); 1182 mTimedTrackCount--; 1183} 1184 1185// ---------------------------------------------------------------------------- 1186 1187AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1188 const sp<IAudioFlingerClient>& client, 1189 pid_t pid) 1190 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1191{ 1192} 1193 1194AudioFlinger::NotificationClient::~NotificationClient() 1195{ 1196} 1197 1198void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 1199{ 1200 sp<NotificationClient> keep(this); 1201 mAudioFlinger->removeNotificationClient(mPid); 1202} 1203 1204 1205// ---------------------------------------------------------------------------- 1206 1207sp<IAudioRecord> AudioFlinger::openRecord( 1208 audio_io_handle_t input, 1209 uint32_t sampleRate, 1210 audio_format_t format, 1211 audio_channel_mask_t channelMask, 1212 size_t frameCount, 1213 IAudioFlinger::track_flags_t *flags, 1214 pid_t tid, 1215 int *sessionId, 1216 status_t *status) 1217{ 1218 sp<RecordThread::RecordTrack> recordTrack; 1219 sp<RecordHandle> recordHandle; 1220 sp<Client> client; 1221 status_t lStatus; 1222 RecordThread *thread; 1223 size_t inFrameCount; 1224 int lSessionId; 1225 1226 // check calling permissions 1227 if (!recordingAllowed()) { 1228 lStatus = PERMISSION_DENIED; 1229 goto Exit; 1230 } 1231 1232 if (format != AUDIO_FORMAT_PCM_16_BIT) { 1233 ALOGE("openRecord() invalid format %d", format); 1234 lStatus = BAD_VALUE; 1235 goto Exit; 1236 } 1237 1238 // add client to list 1239 { // scope for mLock 1240 Mutex::Autolock _l(mLock); 1241 thread = checkRecordThread_l(input); 1242 if (thread == NULL) { 1243 lStatus = BAD_VALUE; 1244 goto Exit; 1245 } 1246 1247 pid_t pid = IPCThreadState::self()->getCallingPid(); 1248 client = registerPid_l(pid); 1249 1250 // If no audio session id is provided, create one here 1251 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 1252 lSessionId = *sessionId; 1253 } else { 1254 lSessionId = nextUniqueId(); 1255 if (sessionId != NULL) { 1256 *sessionId = lSessionId; 1257 } 1258 } 1259 // create new record track. 1260 // The record track uses one track in mHardwareMixerThread by convention. 1261 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1262 frameCount, lSessionId, flags, tid, &lStatus); 1263 } 1264 if (lStatus != NO_ERROR) { 1265 // remove local strong reference to Client before deleting the RecordTrack so that the 1266 // Client destructor is called by the TrackBase destructor with mLock held 1267 client.clear(); 1268 recordTrack.clear(); 1269 goto Exit; 1270 } 1271 1272 // return to handle to client 1273 recordHandle = new RecordHandle(recordTrack); 1274 lStatus = NO_ERROR; 1275 1276Exit: 1277 *status = lStatus; 1278 return recordHandle; 1279} 1280 1281 1282 1283// ---------------------------------------------------------------------------- 1284 1285audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 1286{ 1287 if (!settingsAllowed()) { 1288 return 0; 1289 } 1290 Mutex::Autolock _l(mLock); 1291 return loadHwModule_l(name); 1292} 1293 1294// loadHwModule_l() must be called with AudioFlinger::mLock held 1295audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 1296{ 1297 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1298 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 1299 ALOGW("loadHwModule() module %s already loaded", name); 1300 return mAudioHwDevs.keyAt(i); 1301 } 1302 } 1303 1304 audio_hw_device_t *dev; 1305 1306 int rc = load_audio_interface(name, &dev); 1307 if (rc) { 1308 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 1309 return 0; 1310 } 1311 1312 mHardwareStatus = AUDIO_HW_INIT; 1313 rc = dev->init_check(dev); 1314 mHardwareStatus = AUDIO_HW_IDLE; 1315 if (rc) { 1316 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 1317 return 0; 1318 } 1319 1320 // Check and cache this HAL's level of support for master mute and master 1321 // volume. If this is the first HAL opened, and it supports the get 1322 // methods, use the initial values provided by the HAL as the current 1323 // master mute and volume settings. 1324 1325 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 1326 { // scope for auto-lock pattern 1327 AutoMutex lock(mHardwareLock); 1328 1329 if (0 == mAudioHwDevs.size()) { 1330 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 1331 if (NULL != dev->get_master_volume) { 1332 float mv; 1333 if (OK == dev->get_master_volume(dev, &mv)) { 1334 mMasterVolume = mv; 1335 } 1336 } 1337 1338 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 1339 if (NULL != dev->get_master_mute) { 1340 bool mm; 1341 if (OK == dev->get_master_mute(dev, &mm)) { 1342 mMasterMute = mm; 1343 } 1344 } 1345 } 1346 1347 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 1348 if ((NULL != dev->set_master_volume) && 1349 (OK == dev->set_master_volume(dev, mMasterVolume))) { 1350 flags = static_cast<AudioHwDevice::Flags>(flags | 1351 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 1352 } 1353 1354 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 1355 if ((NULL != dev->set_master_mute) && 1356 (OK == dev->set_master_mute(dev, mMasterMute))) { 1357 flags = static_cast<AudioHwDevice::Flags>(flags | 1358 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 1359 } 1360 1361 mHardwareStatus = AUDIO_HW_IDLE; 1362 } 1363 1364 audio_module_handle_t handle = nextUniqueId(); 1365 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags)); 1366 1367 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 1368 name, dev->common.module->name, dev->common.module->id, handle); 1369 1370 return handle; 1371 1372} 1373 1374// ---------------------------------------------------------------------------- 1375 1376uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 1377{ 1378 Mutex::Autolock _l(mLock); 1379 PlaybackThread *thread = primaryPlaybackThread_l(); 1380 return thread != NULL ? thread->sampleRate() : 0; 1381} 1382 1383size_t AudioFlinger::getPrimaryOutputFrameCount() 1384{ 1385 Mutex::Autolock _l(mLock); 1386 PlaybackThread *thread = primaryPlaybackThread_l(); 1387 return thread != NULL ? thread->frameCountHAL() : 0; 1388} 1389 1390// ---------------------------------------------------------------------------- 1391 1392status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice) 1393{ 1394 uid_t uid = IPCThreadState::self()->getCallingUid(); 1395 if (uid != AID_SYSTEM) { 1396 return PERMISSION_DENIED; 1397 } 1398 Mutex::Autolock _l(mLock); 1399 if (mIsDeviceTypeKnown) { 1400 return INVALID_OPERATION; 1401 } 1402 mIsLowRamDevice = isLowRamDevice; 1403 mIsDeviceTypeKnown = true; 1404 return NO_ERROR; 1405} 1406 1407// ---------------------------------------------------------------------------- 1408 1409audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 1410 audio_devices_t *pDevices, 1411 uint32_t *pSamplingRate, 1412 audio_format_t *pFormat, 1413 audio_channel_mask_t *pChannelMask, 1414 uint32_t *pLatencyMs, 1415 audio_output_flags_t flags, 1416 const audio_offload_info_t *offloadInfo) 1417{ 1418 PlaybackThread *thread = NULL; 1419 struct audio_config config; 1420 memset(&config, 0, sizeof(config)); 1421 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1422 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1423 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1424 if (offloadInfo != NULL) { 1425 config.offload_info = *offloadInfo; 1426 } 1427 1428 audio_stream_out_t *outStream = NULL; 1429 AudioHwDevice *outHwDev; 1430 1431 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x", 1432 module, 1433 (pDevices != NULL) ? *pDevices : 0, 1434 config.sample_rate, 1435 config.format, 1436 config.channel_mask, 1437 flags); 1438 ALOGV("openOutput(), offloadInfo %p version 0x%04x", 1439 offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version ); 1440 1441 if (pDevices == NULL || *pDevices == 0) { 1442 return 0; 1443 } 1444 1445 Mutex::Autolock _l(mLock); 1446 1447 outHwDev = findSuitableHwDev_l(module, *pDevices); 1448 if (outHwDev == NULL) 1449 return 0; 1450 1451 audio_hw_device_t *hwDevHal = outHwDev->hwDevice(); 1452 audio_io_handle_t id = nextUniqueId(); 1453 1454 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 1455 1456 status_t status = hwDevHal->open_output_stream(hwDevHal, 1457 id, 1458 *pDevices, 1459 (audio_output_flags_t)flags, 1460 &config, 1461 &outStream); 1462 1463 mHardwareStatus = AUDIO_HW_IDLE; 1464 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, " 1465 "Channels %x, status %d", 1466 outStream, 1467 config.sample_rate, 1468 config.format, 1469 config.channel_mask, 1470 status); 1471 1472 if (status == NO_ERROR && outStream != NULL) { 1473 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags); 1474 1475 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1476 thread = new OffloadThread(this, output, id, *pDevices); 1477 ALOGV("openOutput() created offload output: ID %d thread %p", id, thread); 1478 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 1479 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 1480 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 1481 thread = new DirectOutputThread(this, output, id, *pDevices); 1482 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 1483 } else { 1484 thread = new MixerThread(this, output, id, *pDevices); 1485 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 1486 } 1487 mPlaybackThreads.add(id, thread); 1488 1489 if (pSamplingRate != NULL) { 1490 *pSamplingRate = config.sample_rate; 1491 } 1492 if (pFormat != NULL) { 1493 *pFormat = config.format; 1494 } 1495 if (pChannelMask != NULL) { 1496 *pChannelMask = config.channel_mask; 1497 } 1498 if (pLatencyMs != NULL) { 1499 *pLatencyMs = thread->latency(); 1500 } 1501 1502 // notify client processes of the new output creation 1503 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1504 1505 // the first primary output opened designates the primary hw device 1506 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 1507 ALOGI("Using module %d has the primary audio interface", module); 1508 mPrimaryHardwareDev = outHwDev; 1509 1510 AutoMutex lock(mHardwareLock); 1511 mHardwareStatus = AUDIO_HW_SET_MODE; 1512 hwDevHal->set_mode(hwDevHal, mMode); 1513 mHardwareStatus = AUDIO_HW_IDLE; 1514 } 1515 return id; 1516 } 1517 1518 return 0; 1519} 1520 1521audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 1522 audio_io_handle_t output2) 1523{ 1524 Mutex::Autolock _l(mLock); 1525 MixerThread *thread1 = checkMixerThread_l(output1); 1526 MixerThread *thread2 = checkMixerThread_l(output2); 1527 1528 if (thread1 == NULL || thread2 == NULL) { 1529 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 1530 output2); 1531 return 0; 1532 } 1533 1534 audio_io_handle_t id = nextUniqueId(); 1535 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 1536 thread->addOutputTrack(thread2); 1537 mPlaybackThreads.add(id, thread); 1538 // notify client processes of the new output creation 1539 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1540 return id; 1541} 1542 1543status_t AudioFlinger::closeOutput(audio_io_handle_t output) 1544{ 1545 return closeOutput_nonvirtual(output); 1546} 1547 1548status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 1549{ 1550 // keep strong reference on the playback thread so that 1551 // it is not destroyed while exit() is executed 1552 sp<PlaybackThread> thread; 1553 { 1554 Mutex::Autolock _l(mLock); 1555 thread = checkPlaybackThread_l(output); 1556 if (thread == NULL) { 1557 return BAD_VALUE; 1558 } 1559 1560 ALOGV("closeOutput() %d", output); 1561 1562 if (thread->type() == ThreadBase::MIXER) { 1563 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1564 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 1565 DuplicatingThread *dupThread = 1566 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 1567 dupThread->removeOutputTrack((MixerThread *)thread.get()); 1568 1569 } 1570 } 1571 } 1572 1573 1574 mPlaybackThreads.removeItem(output); 1575 // save all effects to the default thread 1576 if (mPlaybackThreads.size()) { 1577 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0)); 1578 if (dstThread != NULL) { 1579 // audioflinger lock is held here so the acquisition order of thread locks does not 1580 // matter 1581 Mutex::Autolock _dl(dstThread->mLock); 1582 Mutex::Autolock _sl(thread->mLock); 1583 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l(); 1584 for (size_t i = 0; i < effectChains.size(); i ++) { 1585 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true); 1586 } 1587 } 1588 } 1589 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 1590 } 1591 thread->exit(); 1592 // The thread entity (active unit of execution) is no longer running here, 1593 // but the ThreadBase container still exists. 1594 1595 if (thread->type() != ThreadBase::DUPLICATING) { 1596 AudioStreamOut *out = thread->clearOutput(); 1597 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 1598 // from now on thread->mOutput is NULL 1599 out->hwDev()->close_output_stream(out->hwDev(), out->stream); 1600 delete out; 1601 } 1602 return NO_ERROR; 1603} 1604 1605status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 1606{ 1607 Mutex::Autolock _l(mLock); 1608 PlaybackThread *thread = checkPlaybackThread_l(output); 1609 1610 if (thread == NULL) { 1611 return BAD_VALUE; 1612 } 1613 1614 ALOGV("suspendOutput() %d", output); 1615 thread->suspend(); 1616 1617 return NO_ERROR; 1618} 1619 1620status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 1621{ 1622 Mutex::Autolock _l(mLock); 1623 PlaybackThread *thread = checkPlaybackThread_l(output); 1624 1625 if (thread == NULL) { 1626 return BAD_VALUE; 1627 } 1628 1629 ALOGV("restoreOutput() %d", output); 1630 1631 thread->restore(); 1632 1633 return NO_ERROR; 1634} 1635 1636audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 1637 audio_devices_t *pDevices, 1638 uint32_t *pSamplingRate, 1639 audio_format_t *pFormat, 1640 audio_channel_mask_t *pChannelMask) 1641{ 1642 status_t status; 1643 RecordThread *thread = NULL; 1644 struct audio_config config; 1645 memset(&config, 0, sizeof(config)); 1646 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1647 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1648 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1649 1650 uint32_t reqSamplingRate = config.sample_rate; 1651 audio_format_t reqFormat = config.format; 1652 audio_channel_mask_t reqChannelMask = config.channel_mask; 1653 audio_stream_in_t *inStream = NULL; 1654 AudioHwDevice *inHwDev; 1655 1656 if (pDevices == NULL || *pDevices == 0) { 1657 return 0; 1658 } 1659 1660 Mutex::Autolock _l(mLock); 1661 1662 inHwDev = findSuitableHwDev_l(module, *pDevices); 1663 if (inHwDev == NULL) 1664 return 0; 1665 1666 audio_hw_device_t *inHwHal = inHwDev->hwDevice(); 1667 audio_io_handle_t id = nextUniqueId(); 1668 1669 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, 1670 &inStream); 1671 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, " 1672 "status %d", 1673 inStream, 1674 config.sample_rate, 1675 config.format, 1676 config.channel_mask, 1677 status); 1678 1679 // If the input could not be opened with the requested parameters and we can handle the 1680 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can 1681 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs. 1682 if (status == BAD_VALUE && 1683 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 1684 (config.sample_rate <= 2 * reqSamplingRate) && 1685 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannelMask) <= FCC_2)) { 1686 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 1687 inStream = NULL; 1688 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 1689 } 1690 1691 if (status == NO_ERROR && inStream != NULL) { 1692 1693#ifdef TEE_SINK 1694 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 1695 // or (re-)create if current Pipe is idle and does not match the new format 1696 sp<NBAIO_Sink> teeSink; 1697 enum { 1698 TEE_SINK_NO, // don't copy input 1699 TEE_SINK_NEW, // copy input using a new pipe 1700 TEE_SINK_OLD, // copy input using an existing pipe 1701 } kind; 1702 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 1703 popcount(inStream->common.get_channels(&inStream->common))); 1704 if (!mTeeSinkInputEnabled) { 1705 kind = TEE_SINK_NO; 1706 } else if (format == Format_Invalid) { 1707 kind = TEE_SINK_NO; 1708 } else if (mRecordTeeSink == 0) { 1709 kind = TEE_SINK_NEW; 1710 } else if (mRecordTeeSink->getStrongCount() != 1) { 1711 kind = TEE_SINK_NO; 1712 } else if (format == mRecordTeeSink->format()) { 1713 kind = TEE_SINK_OLD; 1714 } else { 1715 kind = TEE_SINK_NEW; 1716 } 1717 switch (kind) { 1718 case TEE_SINK_NEW: { 1719 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 1720 size_t numCounterOffers = 0; 1721 const NBAIO_Format offers[1] = {format}; 1722 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 1723 ALOG_ASSERT(index == 0); 1724 PipeReader *pipeReader = new PipeReader(*pipe); 1725 numCounterOffers = 0; 1726 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 1727 ALOG_ASSERT(index == 0); 1728 mRecordTeeSink = pipe; 1729 mRecordTeeSource = pipeReader; 1730 teeSink = pipe; 1731 } 1732 break; 1733 case TEE_SINK_OLD: 1734 teeSink = mRecordTeeSink; 1735 break; 1736 case TEE_SINK_NO: 1737 default: 1738 break; 1739 } 1740#endif 1741 1742 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 1743 1744 // Start record thread 1745 // RecordThread requires both input and output device indication to forward to audio 1746 // pre processing modules 1747 thread = new RecordThread(this, 1748 input, 1749 reqSamplingRate, 1750 reqChannelMask, 1751 id, 1752 primaryOutputDevice_l(), 1753 *pDevices 1754#ifdef TEE_SINK 1755 , teeSink 1756#endif 1757 ); 1758 mRecordThreads.add(id, thread); 1759 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 1760 if (pSamplingRate != NULL) { 1761 *pSamplingRate = reqSamplingRate; 1762 } 1763 if (pFormat != NULL) { 1764 *pFormat = config.format; 1765 } 1766 if (pChannelMask != NULL) { 1767 *pChannelMask = reqChannelMask; 1768 } 1769 1770 // notify client processes of the new input creation 1771 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 1772 return id; 1773 } 1774 1775 return 0; 1776} 1777 1778status_t AudioFlinger::closeInput(audio_io_handle_t input) 1779{ 1780 return closeInput_nonvirtual(input); 1781} 1782 1783status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 1784{ 1785 // keep strong reference on the record thread so that 1786 // it is not destroyed while exit() is executed 1787 sp<RecordThread> thread; 1788 { 1789 Mutex::Autolock _l(mLock); 1790 thread = checkRecordThread_l(input); 1791 if (thread == 0) { 1792 return BAD_VALUE; 1793 } 1794 1795 ALOGV("closeInput() %d", input); 1796 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 1797 mRecordThreads.removeItem(input); 1798 } 1799 thread->exit(); 1800 // The thread entity (active unit of execution) is no longer running here, 1801 // but the ThreadBase container still exists. 1802 1803 AudioStreamIn *in = thread->clearInput(); 1804 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 1805 // from now on thread->mInput is NULL 1806 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 1807 delete in; 1808 1809 return NO_ERROR; 1810} 1811 1812status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 1813{ 1814 Mutex::Autolock _l(mLock); 1815 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 1816 1817 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1818 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1819 thread->invalidateTracks(stream); 1820 } 1821 1822 return NO_ERROR; 1823} 1824 1825 1826int AudioFlinger::newAudioSessionId() 1827{ 1828 return nextUniqueId(); 1829} 1830 1831void AudioFlinger::acquireAudioSessionId(int audioSession) 1832{ 1833 Mutex::Autolock _l(mLock); 1834 pid_t caller = IPCThreadState::self()->getCallingPid(); 1835 ALOGV("acquiring %d from %d", audioSession, caller); 1836 size_t num = mAudioSessionRefs.size(); 1837 for (size_t i = 0; i< num; i++) { 1838 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 1839 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1840 ref->mCnt++; 1841 ALOGV(" incremented refcount to %d", ref->mCnt); 1842 return; 1843 } 1844 } 1845 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 1846 ALOGV(" added new entry for %d", audioSession); 1847} 1848 1849void AudioFlinger::releaseAudioSessionId(int audioSession) 1850{ 1851 Mutex::Autolock _l(mLock); 1852 pid_t caller = IPCThreadState::self()->getCallingPid(); 1853 ALOGV("releasing %d from %d", audioSession, caller); 1854 size_t num = mAudioSessionRefs.size(); 1855 for (size_t i = 0; i< num; i++) { 1856 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1857 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1858 ref->mCnt--; 1859 ALOGV(" decremented refcount to %d", ref->mCnt); 1860 if (ref->mCnt == 0) { 1861 mAudioSessionRefs.removeAt(i); 1862 delete ref; 1863 purgeStaleEffects_l(); 1864 } 1865 return; 1866 } 1867 } 1868 ALOGW("session id %d not found for pid %d", audioSession, caller); 1869} 1870 1871void AudioFlinger::purgeStaleEffects_l() { 1872 1873 ALOGV("purging stale effects"); 1874 1875 Vector< sp<EffectChain> > chains; 1876 1877 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1878 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 1879 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1880 sp<EffectChain> ec = t->mEffectChains[j]; 1881 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 1882 chains.push(ec); 1883 } 1884 } 1885 } 1886 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1887 sp<RecordThread> t = mRecordThreads.valueAt(i); 1888 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 1889 sp<EffectChain> ec = t->mEffectChains[j]; 1890 chains.push(ec); 1891 } 1892 } 1893 1894 for (size_t i = 0; i < chains.size(); i++) { 1895 sp<EffectChain> ec = chains[i]; 1896 int sessionid = ec->sessionId(); 1897 sp<ThreadBase> t = ec->mThread.promote(); 1898 if (t == 0) { 1899 continue; 1900 } 1901 size_t numsessionrefs = mAudioSessionRefs.size(); 1902 bool found = false; 1903 for (size_t k = 0; k < numsessionrefs; k++) { 1904 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 1905 if (ref->mSessionid == sessionid) { 1906 ALOGV(" session %d still exists for %d with %d refs", 1907 sessionid, ref->mPid, ref->mCnt); 1908 found = true; 1909 break; 1910 } 1911 } 1912 if (!found) { 1913 Mutex::Autolock _l (t->mLock); 1914 // remove all effects from the chain 1915 while (ec->mEffects.size()) { 1916 sp<EffectModule> effect = ec->mEffects[0]; 1917 effect->unPin(); 1918 t->removeEffect_l(effect); 1919 if (effect->purgeHandles()) { 1920 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 1921 } 1922 AudioSystem::unregisterEffect(effect->id()); 1923 } 1924 } 1925 } 1926 return; 1927} 1928 1929// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 1930AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 1931{ 1932 return mPlaybackThreads.valueFor(output).get(); 1933} 1934 1935// checkMixerThread_l() must be called with AudioFlinger::mLock held 1936AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 1937{ 1938 PlaybackThread *thread = checkPlaybackThread_l(output); 1939 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 1940} 1941 1942// checkRecordThread_l() must be called with AudioFlinger::mLock held 1943AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 1944{ 1945 return mRecordThreads.valueFor(input).get(); 1946} 1947 1948uint32_t AudioFlinger::nextUniqueId() 1949{ 1950 return android_atomic_inc(&mNextUniqueId); 1951} 1952 1953AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 1954{ 1955 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1956 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1957 AudioStreamOut *output = thread->getOutput(); 1958 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 1959 return thread; 1960 } 1961 } 1962 return NULL; 1963} 1964 1965audio_devices_t AudioFlinger::primaryOutputDevice_l() const 1966{ 1967 PlaybackThread *thread = primaryPlaybackThread_l(); 1968 1969 if (thread == NULL) { 1970 return 0; 1971 } 1972 1973 return thread->outDevice(); 1974} 1975 1976sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 1977 int triggerSession, 1978 int listenerSession, 1979 sync_event_callback_t callBack, 1980 void *cookie) 1981{ 1982 Mutex::Autolock _l(mLock); 1983 1984 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 1985 status_t playStatus = NAME_NOT_FOUND; 1986 status_t recStatus = NAME_NOT_FOUND; 1987 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1988 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 1989 if (playStatus == NO_ERROR) { 1990 return event; 1991 } 1992 } 1993 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1994 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 1995 if (recStatus == NO_ERROR) { 1996 return event; 1997 } 1998 } 1999 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2000 mPendingSyncEvents.add(event); 2001 } else { 2002 ALOGV("createSyncEvent() invalid event %d", event->type()); 2003 event.clear(); 2004 } 2005 return event; 2006} 2007 2008// ---------------------------------------------------------------------------- 2009// Effect management 2010// ---------------------------------------------------------------------------- 2011 2012 2013status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2014{ 2015 Mutex::Autolock _l(mLock); 2016 return EffectQueryNumberEffects(numEffects); 2017} 2018 2019status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2020{ 2021 Mutex::Autolock _l(mLock); 2022 return EffectQueryEffect(index, descriptor); 2023} 2024 2025status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2026 effect_descriptor_t *descriptor) const 2027{ 2028 Mutex::Autolock _l(mLock); 2029 return EffectGetDescriptor(pUuid, descriptor); 2030} 2031 2032 2033sp<IEffect> AudioFlinger::createEffect( 2034 effect_descriptor_t *pDesc, 2035 const sp<IEffectClient>& effectClient, 2036 int32_t priority, 2037 audio_io_handle_t io, 2038 int sessionId, 2039 status_t *status, 2040 int *id, 2041 int *enabled) 2042{ 2043 status_t lStatus = NO_ERROR; 2044 sp<EffectHandle> handle; 2045 effect_descriptor_t desc; 2046 2047 pid_t pid = IPCThreadState::self()->getCallingPid(); 2048 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 2049 pid, effectClient.get(), priority, sessionId, io); 2050 2051 if (pDesc == NULL) { 2052 lStatus = BAD_VALUE; 2053 goto Exit; 2054 } 2055 2056 // check audio settings permission for global effects 2057 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2058 lStatus = PERMISSION_DENIED; 2059 goto Exit; 2060 } 2061 2062 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2063 // that can only be created by audio policy manager (running in same process) 2064 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2065 lStatus = PERMISSION_DENIED; 2066 goto Exit; 2067 } 2068 2069 if (io == 0) { 2070 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2071 // output must be specified by AudioPolicyManager when using session 2072 // AUDIO_SESSION_OUTPUT_STAGE 2073 lStatus = BAD_VALUE; 2074 goto Exit; 2075 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2076 // if the output returned by getOutputForEffect() is removed before we lock the 2077 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2078 // and we will exit safely 2079 io = AudioSystem::getOutputForEffect(&desc); 2080 } 2081 } 2082 2083 { 2084 Mutex::Autolock _l(mLock); 2085 2086 2087 if (!EffectIsNullUuid(&pDesc->uuid)) { 2088 // if uuid is specified, request effect descriptor 2089 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 2090 if (lStatus < 0) { 2091 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2092 goto Exit; 2093 } 2094 } else { 2095 // if uuid is not specified, look for an available implementation 2096 // of the required type in effect factory 2097 if (EffectIsNullUuid(&pDesc->type)) { 2098 ALOGW("createEffect() no effect type"); 2099 lStatus = BAD_VALUE; 2100 goto Exit; 2101 } 2102 uint32_t numEffects = 0; 2103 effect_descriptor_t d; 2104 d.flags = 0; // prevent compiler warning 2105 bool found = false; 2106 2107 lStatus = EffectQueryNumberEffects(&numEffects); 2108 if (lStatus < 0) { 2109 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2110 goto Exit; 2111 } 2112 for (uint32_t i = 0; i < numEffects; i++) { 2113 lStatus = EffectQueryEffect(i, &desc); 2114 if (lStatus < 0) { 2115 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2116 continue; 2117 } 2118 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2119 // If matching type found save effect descriptor. If the session is 2120 // 0 and the effect is not auxiliary, continue enumeration in case 2121 // an auxiliary version of this effect type is available 2122 found = true; 2123 d = desc; 2124 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2125 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2126 break; 2127 } 2128 } 2129 } 2130 if (!found) { 2131 lStatus = BAD_VALUE; 2132 ALOGW("createEffect() effect not found"); 2133 goto Exit; 2134 } 2135 // For same effect type, chose auxiliary version over insert version if 2136 // connect to output mix (Compliance to OpenSL ES) 2137 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2138 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2139 desc = d; 2140 } 2141 } 2142 2143 // Do not allow auxiliary effects on a session different from 0 (output mix) 2144 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2145 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2146 lStatus = INVALID_OPERATION; 2147 goto Exit; 2148 } 2149 2150 // check recording permission for visualizer 2151 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2152 !recordingAllowed()) { 2153 lStatus = PERMISSION_DENIED; 2154 goto Exit; 2155 } 2156 2157 // return effect descriptor 2158 *pDesc = desc; 2159 2160 // If output is not specified try to find a matching audio session ID in one of the 2161 // output threads. 2162 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2163 // because of code checking output when entering the function. 2164 // Note: io is never 0 when creating an effect on an input 2165 if (io == 0) { 2166 // look for the thread where the specified audio session is present 2167 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2168 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2169 io = mPlaybackThreads.keyAt(i); 2170 break; 2171 } 2172 } 2173 if (io == 0) { 2174 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2175 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2176 io = mRecordThreads.keyAt(i); 2177 break; 2178 } 2179 } 2180 } 2181 // If no output thread contains the requested session ID, default to 2182 // first output. The effect chain will be moved to the correct output 2183 // thread when a track with the same session ID is created 2184 if (io == 0 && mPlaybackThreads.size()) { 2185 io = mPlaybackThreads.keyAt(0); 2186 } 2187 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2188 } 2189 ThreadBase *thread = checkRecordThread_l(io); 2190 if (thread == NULL) { 2191 thread = checkPlaybackThread_l(io); 2192 if (thread == NULL) { 2193 ALOGE("createEffect() unknown output thread"); 2194 lStatus = BAD_VALUE; 2195 goto Exit; 2196 } 2197 } 2198 2199 sp<Client> client = registerPid_l(pid); 2200 2201 // create effect on selected output thread 2202 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 2203 &desc, enabled, &lStatus); 2204 if (handle != 0 && id != NULL) { 2205 *id = handle->id(); 2206 } 2207 } 2208 2209Exit: 2210 *status = lStatus; 2211 return handle; 2212} 2213 2214status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2215 audio_io_handle_t dstOutput) 2216{ 2217 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2218 sessionId, srcOutput, dstOutput); 2219 Mutex::Autolock _l(mLock); 2220 if (srcOutput == dstOutput) { 2221 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2222 return NO_ERROR; 2223 } 2224 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2225 if (srcThread == NULL) { 2226 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2227 return BAD_VALUE; 2228 } 2229 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2230 if (dstThread == NULL) { 2231 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2232 return BAD_VALUE; 2233 } 2234 2235 Mutex::Autolock _dl(dstThread->mLock); 2236 Mutex::Autolock _sl(srcThread->mLock); 2237 moveEffectChain_l(sessionId, srcThread, dstThread, false); 2238 2239 return NO_ERROR; 2240} 2241 2242// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2243status_t AudioFlinger::moveEffectChain_l(int sessionId, 2244 AudioFlinger::PlaybackThread *srcThread, 2245 AudioFlinger::PlaybackThread *dstThread, 2246 bool reRegister) 2247{ 2248 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2249 sessionId, srcThread, dstThread); 2250 2251 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2252 if (chain == 0) { 2253 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2254 sessionId, srcThread); 2255 return INVALID_OPERATION; 2256 } 2257 2258 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2259 // so that a new chain is created with correct parameters when first effect is added. This is 2260 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2261 // removed. 2262 srcThread->removeEffectChain_l(chain); 2263 2264 // transfer all effects one by one so that new effect chain is created on new thread with 2265 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2266 audio_io_handle_t dstOutput = dstThread->id(); 2267 sp<EffectChain> dstChain; 2268 uint32_t strategy = 0; // prevent compiler warning 2269 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2270 while (effect != 0) { 2271 srcThread->removeEffect_l(effect); 2272 dstThread->addEffect_l(effect); 2273 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2274 if (effect->state() == EffectModule::ACTIVE || 2275 effect->state() == EffectModule::STOPPING) { 2276 effect->start(); 2277 } 2278 // if the move request is not received from audio policy manager, the effect must be 2279 // re-registered with the new strategy and output 2280 if (dstChain == 0) { 2281 dstChain = effect->chain().promote(); 2282 if (dstChain == 0) { 2283 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2284 srcThread->addEffect_l(effect); 2285 return NO_INIT; 2286 } 2287 strategy = dstChain->strategy(); 2288 } 2289 if (reRegister) { 2290 AudioSystem::unregisterEffect(effect->id()); 2291 AudioSystem::registerEffect(&effect->desc(), 2292 dstOutput, 2293 strategy, 2294 sessionId, 2295 effect->id()); 2296 } 2297 effect = chain->getEffectFromId_l(0); 2298 } 2299 2300 return NO_ERROR; 2301} 2302 2303struct Entry { 2304#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2305 char mName[MAX_NAME]; 2306}; 2307 2308int comparEntry(const void *p1, const void *p2) 2309{ 2310 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2311} 2312 2313#ifdef TEE_SINK 2314void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2315{ 2316 NBAIO_Source *teeSource = source.get(); 2317 if (teeSource != NULL) { 2318 // .wav rotation 2319 // There is a benign race condition if 2 threads call this simultaneously. 2320 // They would both traverse the directory, but the result would simply be 2321 // failures at unlink() which are ignored. It's also unlikely since 2322 // normally dumpsys is only done by bugreport or from the command line. 2323 char teePath[32+256]; 2324 strcpy(teePath, "/data/misc/media"); 2325 size_t teePathLen = strlen(teePath); 2326 DIR *dir = opendir(teePath); 2327 teePath[teePathLen++] = '/'; 2328 if (dir != NULL) { 2329#define MAX_SORT 20 // number of entries to sort 2330#define MAX_KEEP 10 // number of entries to keep 2331 struct Entry entries[MAX_SORT]; 2332 size_t entryCount = 0; 2333 while (entryCount < MAX_SORT) { 2334 struct dirent de; 2335 struct dirent *result = NULL; 2336 int rc = readdir_r(dir, &de, &result); 2337 if (rc != 0) { 2338 ALOGW("readdir_r failed %d", rc); 2339 break; 2340 } 2341 if (result == NULL) { 2342 break; 2343 } 2344 if (result != &de) { 2345 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2346 break; 2347 } 2348 // ignore non .wav file entries 2349 size_t nameLen = strlen(de.d_name); 2350 if (nameLen <= 4 || nameLen >= MAX_NAME || 2351 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2352 continue; 2353 } 2354 strcpy(entries[entryCount++].mName, de.d_name); 2355 } 2356 (void) closedir(dir); 2357 if (entryCount > MAX_KEEP) { 2358 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2359 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2360 strcpy(&teePath[teePathLen], entries[i].mName); 2361 (void) unlink(teePath); 2362 } 2363 } 2364 } else { 2365 if (fd >= 0) { 2366 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2367 } 2368 } 2369 char teeTime[16]; 2370 struct timeval tv; 2371 gettimeofday(&tv, NULL); 2372 struct tm tm; 2373 localtime_r(&tv.tv_sec, &tm); 2374 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2375 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2376 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2377 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2378 if (teeFd >= 0) { 2379 char wavHeader[44]; 2380 memcpy(wavHeader, 2381 "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", 2382 sizeof(wavHeader)); 2383 NBAIO_Format format = teeSource->format(); 2384 unsigned channelCount = Format_channelCount(format); 2385 ALOG_ASSERT(channelCount <= FCC_2); 2386 uint32_t sampleRate = Format_sampleRate(format); 2387 wavHeader[22] = channelCount; // number of channels 2388 wavHeader[24] = sampleRate; // sample rate 2389 wavHeader[25] = sampleRate >> 8; 2390 wavHeader[32] = channelCount * 2; // block alignment 2391 write(teeFd, wavHeader, sizeof(wavHeader)); 2392 size_t total = 0; 2393 bool firstRead = true; 2394 for (;;) { 2395#define TEE_SINK_READ 1024 2396 short buffer[TEE_SINK_READ * FCC_2]; 2397 size_t count = TEE_SINK_READ; 2398 ssize_t actual = teeSource->read(buffer, count, 2399 AudioBufferProvider::kInvalidPTS); 2400 bool wasFirstRead = firstRead; 2401 firstRead = false; 2402 if (actual <= 0) { 2403 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2404 continue; 2405 } 2406 break; 2407 } 2408 ALOG_ASSERT(actual <= (ssize_t)count); 2409 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2410 total += actual; 2411 } 2412 lseek(teeFd, (off_t) 4, SEEK_SET); 2413 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2414 write(teeFd, &temp, sizeof(temp)); 2415 lseek(teeFd, (off_t) 40, SEEK_SET); 2416 temp = total * channelCount * sizeof(short); 2417 write(teeFd, &temp, sizeof(temp)); 2418 close(teeFd); 2419 if (fd >= 0) { 2420 fdprintf(fd, "tee copied to %s\n", teePath); 2421 } 2422 } else { 2423 if (fd >= 0) { 2424 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2425 } 2426 } 2427 } 2428} 2429#endif 2430 2431// ---------------------------------------------------------------------------- 2432 2433status_t AudioFlinger::onTransact( 2434 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2435{ 2436 return BnAudioFlinger::onTransact(code, data, reply, flags); 2437} 2438 2439}; // namespace android 2440