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