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