AudioFlinger.cpp revision d3bb645f0b7f567b033b8664499d685f8ec10628
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 <media/audiohal/DeviceHalInterface.h> 35#include <media/audiohal/DevicesFactoryHalInterface.h> 36#include <media/audiohal/EffectsFactoryHalInterface.h> 37#include <media/AudioParameter.h> 38#include <media/TypeConverter.h> 39#include <memunreachable/memunreachable.h> 40#include <utils/String16.h> 41#include <utils/threads.h> 42#include <utils/Atomic.h> 43 44#include <cutils/bitops.h> 45#include <cutils/properties.h> 46 47#include <system/audio.h> 48 49#include "AudioFlinger.h" 50#include "ServiceUtilities.h" 51 52#include <media/AudioResamplerPublic.h> 53 54#include <system/audio_effects/effect_visualizer.h> 55#include <system/audio_effects/effect_ns.h> 56#include <system/audio_effects/effect_aec.h> 57 58#include <audio_utils/primitives.h> 59 60#include <powermanager/PowerManager.h> 61 62#include <media/IMediaLogService.h> 63#include <media/MemoryLeakTrackUtil.h> 64#include <media/nbaio/Pipe.h> 65#include <media/nbaio/PipeReader.h> 66#include <media/AudioParameter.h> 67#include <mediautils/BatteryNotifier.h> 68#include <private/android_filesystem_config.h> 69 70//#define BUFLOG_NDEBUG 0 71#include <BufLog.h> 72 73#include "TypedLogger.h" 74 75// ---------------------------------------------------------------------------- 76 77// Note: the following macro is used for extremely verbose logging message. In 78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 79// 0; but one side effect of this is to turn all LOGV's as well. Some messages 80// are so verbose that we want to suppress them even when we have ALOG_ASSERT 81// turned on. Do not uncomment the #def below unless you really know what you 82// are doing and want to see all of the extremely verbose messages. 83//#define VERY_VERY_VERBOSE_LOGGING 84#ifdef VERY_VERY_VERBOSE_LOGGING 85#define ALOGVV ALOGV 86#else 87#define ALOGVV(a...) do { } while(0) 88#endif 89 90namespace android { 91 92static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 93static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 94static const char kClientLockedString[] = "Client lock is taken\n"; 95static const char kNoEffectsFactory[] = "Effects Factory is absent\n"; 96 97 98nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 99 100uint32_t AudioFlinger::mScreenState; 101 102 103#ifdef TEE_SINK 104bool AudioFlinger::mTeeSinkInputEnabled = false; 105bool AudioFlinger::mTeeSinkOutputEnabled = false; 106bool AudioFlinger::mTeeSinkTrackEnabled = false; 107 108size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault; 109size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault; 110size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault; 111#endif 112 113// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off 114// we define a minimum time during which a global effect is considered enabled. 115static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200); 116 117Mutex gLock; 118wp<AudioFlinger> gAudioFlinger; 119 120// ---------------------------------------------------------------------------- 121 122std::string formatToString(audio_format_t format) { 123 std::string result; 124 FormatConverter::toString(format, result); 125 return result; 126} 127 128// ---------------------------------------------------------------------------- 129 130AudioFlinger::AudioFlinger() 131 : BnAudioFlinger(), 132 mPrimaryHardwareDev(NULL), 133 mAudioHwDevs(NULL), 134 mHardwareStatus(AUDIO_HW_IDLE), 135 mMasterVolume(1.0f), 136 mMasterMute(false), 137 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX), 138 mMode(AUDIO_MODE_INVALID), 139 mBtNrecIsOff(false), 140 mIsLowRamDevice(true), 141 mIsDeviceTypeKnown(false), 142 mGlobalEffectEnableTime(0), 143 mSystemReady(false) 144{ 145 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum 146 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) { 147 // zero ID has a special meaning, so unavailable 148 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX; 149 } 150 151 getpid_cached = getpid(); 152 const bool doLog = property_get_bool("ro.test_harness", false); 153 if (doLog) { 154 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters", 155 MemoryHeapBase::READ_ONLY); 156 } 157 158 // reset battery stats. 159 // if the audio service has crashed, battery stats could be left 160 // in bad state, reset the state upon service start. 161 BatteryNotifier::getInstance().noteResetAudio(); 162 163 mDevicesFactoryHal = DevicesFactoryHalInterface::create(); 164 mEffectsFactoryHal = EffectsFactoryHalInterface::create(); 165 166#ifdef TEE_SINK 167 char value[PROPERTY_VALUE_MAX]; 168 (void) property_get("ro.debuggable", value, "0"); 169 int debuggable = atoi(value); 170 int teeEnabled = 0; 171 if (debuggable) { 172 (void) property_get("af.tee", value, "0"); 173 teeEnabled = atoi(value); 174 } 175 // FIXME symbolic constants here 176 if (teeEnabled & 1) { 177 mTeeSinkInputEnabled = true; 178 } 179 if (teeEnabled & 2) { 180 mTeeSinkOutputEnabled = true; 181 } 182 if (teeEnabled & 4) { 183 mTeeSinkTrackEnabled = true; 184 } 185#endif 186} 187 188void AudioFlinger::onFirstRef() 189{ 190 Mutex::Autolock _l(mLock); 191 192 /* TODO: move all this work into an Init() function */ 193 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 194 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 195 uint32_t int_val; 196 if (1 == sscanf(val_str, "%u", &int_val)) { 197 mStandbyTimeInNsecs = milliseconds(int_val); 198 ALOGI("Using %u mSec as standby time.", int_val); 199 } else { 200 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 201 ALOGI("Using default %u mSec as standby time.", 202 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 203 } 204 } 205 206 mPatchPanel = new PatchPanel(this); 207 208 mMode = AUDIO_MODE_NORMAL; 209 210 gAudioFlinger = this; 211} 212 213AudioFlinger::~AudioFlinger() 214{ 215 while (!mRecordThreads.isEmpty()) { 216 // closeInput_nonvirtual() will remove specified entry from mRecordThreads 217 closeInput_nonvirtual(mRecordThreads.keyAt(0)); 218 } 219 while (!mPlaybackThreads.isEmpty()) { 220 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads 221 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0)); 222 } 223 224 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 225 // no mHardwareLock needed, as there are no other references to this 226 delete mAudioHwDevs.valueAt(i); 227 } 228 229 // Tell media.log service about any old writers that still need to be unregistered 230 if (mLogMemoryDealer != 0) { 231 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 232 if (binder != 0) { 233 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 234 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 235 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory()); 236 mUnregisteredWriters.pop(); 237 mediaLogService->unregisterWriter(iMemory); 238 } 239 } 240 } 241} 242 243//static 244__attribute__ ((visibility ("default"))) 245status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction, 246 const audio_attributes_t *attr, 247 audio_config_base_t *config, 248 const MmapStreamInterface::Client& client, 249 audio_port_handle_t *deviceId, 250 const sp<MmapStreamCallback>& callback, 251 sp<MmapStreamInterface>& interface) 252{ 253 sp<AudioFlinger> af; 254 { 255 Mutex::Autolock _l(gLock); 256 af = gAudioFlinger.promote(); 257 } 258 status_t ret = NO_INIT; 259 if (af != 0) { 260 ret = af->openMmapStream( 261 direction, attr, config, client, deviceId, callback, interface); 262 } 263 return ret; 264} 265 266status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction, 267 const audio_attributes_t *attr, 268 audio_config_base_t *config, 269 const MmapStreamInterface::Client& client, 270 audio_port_handle_t *deviceId, 271 const sp<MmapStreamCallback>& callback, 272 sp<MmapStreamInterface>& interface) 273{ 274 status_t ret = initCheck(); 275 if (ret != NO_ERROR) { 276 return ret; 277 } 278 279 audio_session_t sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION); 280 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT; 281 audio_io_handle_t io; 282 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE; 283 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) { 284 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER; 285 fullConfig.sample_rate = config->sample_rate; 286 fullConfig.channel_mask = config->channel_mask; 287 fullConfig.format = config->format; 288 ret = AudioSystem::getOutputForAttr(attr, &io, 289 sessionId, 290 &streamType, client.clientUid, 291 &fullConfig, 292 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | 293 AUDIO_OUTPUT_FLAG_DIRECT), 294 *deviceId, &portId); 295 } else { 296 ret = AudioSystem::getInputForAttr(attr, &io, 297 sessionId, 298 client.clientPid, 299 client.clientUid, 300 config, 301 AUDIO_INPUT_FLAG_MMAP_NOIRQ, *deviceId, &portId); 302 } 303 if (ret != NO_ERROR) { 304 return ret; 305 } 306 307 // at this stage, a MmapThread was created when openOutput() or openInput() was called by 308 // audio policy manager and we can retrieve it 309 sp<MmapThread> thread = mMmapThreads.valueFor(io); 310 if (thread != 0) { 311 interface = new MmapThreadHandle(thread); 312 thread->configure(attr, streamType, sessionId, callback, portId); 313 } else { 314 ret = NO_INIT; 315 } 316 317 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId); 318 319 return ret; 320} 321 322static const char * const audio_interfaces[] = { 323 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 324 AUDIO_HARDWARE_MODULE_ID_A2DP, 325 AUDIO_HARDWARE_MODULE_ID_USB, 326}; 327#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 328 329AudioHwDevice* AudioFlinger::findSuitableHwDev_l( 330 audio_module_handle_t module, 331 audio_devices_t devices) 332{ 333 // if module is 0, the request comes from an old policy manager and we should load 334 // well known modules 335 if (module == 0) { 336 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 337 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 338 loadHwModule_l(audio_interfaces[i]); 339 } 340 // then try to find a module supporting the requested device. 341 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 342 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i); 343 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice(); 344 uint32_t supportedDevices; 345 if (dev->getSupportedDevices(&supportedDevices) == OK && 346 (supportedDevices & devices) == devices) { 347 return audioHwDevice; 348 } 349 } 350 } else { 351 // check a match for the requested module handle 352 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module); 353 if (audioHwDevice != NULL) { 354 return audioHwDevice; 355 } 356 } 357 358 return NULL; 359} 360 361void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused) 362{ 363 const size_t SIZE = 256; 364 char buffer[SIZE]; 365 String8 result; 366 367 result.append("Clients:\n"); 368 for (size_t i = 0; i < mClients.size(); ++i) { 369 sp<Client> client = mClients.valueAt(i).promote(); 370 if (client != 0) { 371 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 372 result.append(buffer); 373 } 374 } 375 376 result.append("Notification Clients:\n"); 377 for (size_t i = 0; i < mNotificationClients.size(); ++i) { 378 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i)); 379 result.append(buffer); 380 } 381 382 result.append("Global session refs:\n"); 383 result.append(" session pid count\n"); 384 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 385 AudioSessionRef *r = mAudioSessionRefs[i]; 386 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt); 387 result.append(buffer); 388 } 389 write(fd, result.string(), result.size()); 390} 391 392 393void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused) 394{ 395 const size_t SIZE = 256; 396 char buffer[SIZE]; 397 String8 result; 398 hardware_call_state hardwareStatus = mHardwareStatus; 399 400 snprintf(buffer, SIZE, "Hardware status: %d\n" 401 "Standby Time mSec: %u\n", 402 hardwareStatus, 403 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 404 result.append(buffer); 405 write(fd, result.string(), result.size()); 406} 407 408void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused) 409{ 410 const size_t SIZE = 256; 411 char buffer[SIZE]; 412 String8 result; 413 snprintf(buffer, SIZE, "Permission Denial: " 414 "can't dump AudioFlinger from pid=%d, uid=%d\n", 415 IPCThreadState::self()->getCallingPid(), 416 IPCThreadState::self()->getCallingUid()); 417 result.append(buffer); 418 write(fd, result.string(), result.size()); 419} 420 421bool AudioFlinger::dumpTryLock(Mutex& mutex) 422{ 423 bool locked = false; 424 for (int i = 0; i < kDumpLockRetries; ++i) { 425 if (mutex.tryLock() == NO_ERROR) { 426 locked = true; 427 break; 428 } 429 usleep(kDumpLockSleepUs); 430 } 431 return locked; 432} 433 434status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 435{ 436 if (!dumpAllowed()) { 437 dumpPermissionDenial(fd, args); 438 } else { 439 // get state of hardware lock 440 bool hardwareLocked = dumpTryLock(mHardwareLock); 441 if (!hardwareLocked) { 442 String8 result(kHardwareLockedString); 443 write(fd, result.string(), result.size()); 444 } else { 445 mHardwareLock.unlock(); 446 } 447 448 bool locked = dumpTryLock(mLock); 449 450 // failed to lock - AudioFlinger is probably deadlocked 451 if (!locked) { 452 String8 result(kDeadlockedString); 453 write(fd, result.string(), result.size()); 454 } 455 456 bool clientLocked = dumpTryLock(mClientLock); 457 if (!clientLocked) { 458 String8 result(kClientLockedString); 459 write(fd, result.string(), result.size()); 460 } 461 462 if (mEffectsFactoryHal != 0) { 463 mEffectsFactoryHal->dumpEffects(fd); 464 } else { 465 String8 result(kNoEffectsFactory); 466 write(fd, result.string(), result.size()); 467 } 468 469 dumpClients(fd, args); 470 if (clientLocked) { 471 mClientLock.unlock(); 472 } 473 474 dumpInternals(fd, args); 475 476 // dump playback threads 477 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 478 mPlaybackThreads.valueAt(i)->dump(fd, args); 479 } 480 481 // dump record threads 482 for (size_t i = 0; i < mRecordThreads.size(); i++) { 483 mRecordThreads.valueAt(i)->dump(fd, args); 484 } 485 486 // dump mmap threads 487 for (size_t i = 0; i < mMmapThreads.size(); i++) { 488 mMmapThreads.valueAt(i)->dump(fd, args); 489 } 490 491 // dump orphan effect chains 492 if (mOrphanEffectChains.size() != 0) { 493 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n")); 494 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) { 495 mOrphanEffectChains.valueAt(i)->dump(fd, args); 496 } 497 } 498 // dump all hardware devs 499 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 500 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice(); 501 dev->dump(fd); 502 } 503 504#ifdef TEE_SINK 505 // dump the serially shared record tee sink 506 if (mRecordTeeSource != 0) { 507 dumpTee(fd, mRecordTeeSource); 508 } 509#endif 510 511 BUFLOG_RESET; 512 513 if (locked) { 514 mLock.unlock(); 515 } 516 517 // append a copy of media.log here by forwarding fd to it, but don't attempt 518 // to lookup the service if it's not running, as it will block for a second 519 if (mLogMemoryDealer != 0) { 520 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 521 if (binder != 0) { 522 dprintf(fd, "\nmedia.log:\n"); 523 Vector<String16> args; 524 binder->dump(fd, args); 525 } 526 } 527 528 // check for optional arguments 529 bool dumpMem = false; 530 bool unreachableMemory = false; 531 for (const auto &arg : args) { 532 if (arg == String16("-m")) { 533 dumpMem = true; 534 } else if (arg == String16("--unreachable")) { 535 unreachableMemory = true; 536 } 537 } 538 539 if (dumpMem) { 540 dprintf(fd, "\nDumping memory:\n"); 541 std::string s = dumpMemoryAddresses(100 /* limit */); 542 write(fd, s.c_str(), s.size()); 543 } 544 if (unreachableMemory) { 545 dprintf(fd, "\nDumping unreachable memory:\n"); 546 // TODO - should limit be an argument parameter? 547 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */); 548 write(fd, s.c_str(), s.size()); 549 } 550 } 551 return NO_ERROR; 552} 553 554sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid) 555{ 556 Mutex::Autolock _cl(mClientLock); 557 // If pid is already in the mClients wp<> map, then use that entry 558 // (for which promote() is always != 0), otherwise create a new entry and Client. 559 sp<Client> client = mClients.valueFor(pid).promote(); 560 if (client == 0) { 561 client = new Client(this, pid); 562 mClients.add(pid, client); 563 } 564 565 return client; 566} 567 568sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name) 569{ 570 // If there is no memory allocated for logs, return a dummy writer that does nothing 571 if (mLogMemoryDealer == 0) { 572 return new NBLog::Writer(); 573 } 574 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 575 // Similarly if we can't contact the media.log service, also return a dummy writer 576 if (binder == 0) { 577 return new NBLog::Writer(); 578 } 579 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 580 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 581 // If allocation fails, consult the vector of previously unregistered writers 582 // and garbage-collect one or more them until an allocation succeeds 583 if (shared == 0) { 584 Mutex::Autolock _l(mUnregisteredWritersLock); 585 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 586 { 587 // Pick the oldest stale writer to garbage-collect 588 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory()); 589 mUnregisteredWriters.removeAt(0); 590 mediaLogService->unregisterWriter(iMemory); 591 // Now the media.log remote reference to IMemory is gone. When our last local 592 // reference to IMemory also drops to zero at end of this block, 593 // the IMemory destructor will deallocate the region from mLogMemoryDealer. 594 } 595 // Re-attempt the allocation 596 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 597 if (shared != 0) { 598 goto success; 599 } 600 } 601 // Even after garbage-collecting all old writers, there is still not enough memory, 602 // so return a dummy writer 603 return new NBLog::Writer(); 604 } 605success: 606 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer(); 607 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding 608 // explicit destructor not needed since it is POD 609 mediaLogService->registerWriter(shared, size, name); 610 return new NBLog::Writer(shared, size); 611} 612 613void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer) 614{ 615 if (writer == 0) { 616 return; 617 } 618 sp<IMemory> iMemory(writer->getIMemory()); 619 if (iMemory == 0) { 620 return; 621 } 622 // Rather than removing the writer immediately, append it to a queue of old writers to 623 // be garbage-collected later. This allows us to continue to view old logs for a while. 624 Mutex::Autolock _l(mUnregisteredWritersLock); 625 mUnregisteredWriters.push(writer); 626} 627 628// IAudioFlinger interface 629 630 631sp<IAudioTrack> AudioFlinger::createTrack( 632 audio_stream_type_t streamType, 633 uint32_t sampleRate, 634 audio_format_t format, 635 audio_channel_mask_t channelMask, 636 size_t *frameCount, 637 audio_output_flags_t *flags, 638 const sp<IMemory>& sharedBuffer, 639 audio_io_handle_t output, 640 pid_t pid, 641 pid_t tid, 642 audio_session_t *sessionId, 643 int clientUid, 644 status_t *status, 645 audio_port_handle_t portId) 646{ 647 sp<PlaybackThread::Track> track; 648 sp<TrackHandle> trackHandle; 649 sp<Client> client; 650 status_t lStatus; 651 audio_session_t lSessionId; 652 653 const uid_t callingUid = IPCThreadState::self()->getCallingUid(); 654 if (pid == -1 || !isTrustedCallingUid(callingUid)) { 655 const pid_t callingPid = IPCThreadState::self()->getCallingPid(); 656 ALOGW_IF(pid != -1 && pid != callingPid, 657 "%s uid %d pid %d tried to pass itself off as pid %d", 658 __func__, callingUid, callingPid, pid); 659 pid = callingPid; 660 } 661 662 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 663 // but if someone uses binder directly they could bypass that and cause us to crash 664 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 665 ALOGE("createTrack() invalid stream type %d", streamType); 666 lStatus = BAD_VALUE; 667 goto Exit; 668 } 669 670 // further sample rate checks are performed by createTrack_l() depending on the thread type 671 if (sampleRate == 0) { 672 ALOGE("createTrack() invalid sample rate %u", sampleRate); 673 lStatus = BAD_VALUE; 674 goto Exit; 675 } 676 677 // further channel mask checks are performed by createTrack_l() depending on the thread type 678 if (!audio_is_output_channel(channelMask)) { 679 ALOGE("createTrack() invalid channel mask %#x", channelMask); 680 lStatus = BAD_VALUE; 681 goto Exit; 682 } 683 684 // further format checks are performed by createTrack_l() depending on the thread type 685 if (!audio_is_valid_format(format)) { 686 ALOGE("createTrack() invalid format %#x", format); 687 lStatus = BAD_VALUE; 688 goto Exit; 689 } 690 691 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) { 692 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()"); 693 lStatus = BAD_VALUE; 694 goto Exit; 695 } 696 697 { 698 Mutex::Autolock _l(mLock); 699 PlaybackThread *thread = checkPlaybackThread_l(output); 700 if (thread == NULL) { 701 ALOGE("no playback thread found for output handle %d", output); 702 lStatus = BAD_VALUE; 703 goto Exit; 704 } 705 706 client = registerPid(pid); 707 708 PlaybackThread *effectThread = NULL; 709 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 710 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) { 711 ALOGE("createTrack() invalid session ID %d", *sessionId); 712 lStatus = BAD_VALUE; 713 goto Exit; 714 } 715 lSessionId = *sessionId; 716 // check if an effect chain with the same session ID is present on another 717 // output thread and move it here. 718 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 719 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 720 if (mPlaybackThreads.keyAt(i) != output) { 721 uint32_t sessions = t->hasAudioSession(lSessionId); 722 if (sessions & ThreadBase::EFFECT_SESSION) { 723 effectThread = t.get(); 724 break; 725 } 726 } 727 } 728 } else { 729 // if no audio session id is provided, create one here 730 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION); 731 if (sessionId != NULL) { 732 *sessionId = lSessionId; 733 } 734 } 735 ALOGV("createTrack() lSessionId: %d", lSessionId); 736 737 track = thread->createTrack_l(client, streamType, sampleRate, format, 738 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, 739 clientUid, &lStatus, portId); 740 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0)); 741 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 742 743 // move effect chain to this output thread if an effect on same session was waiting 744 // for a track to be created 745 if (lStatus == NO_ERROR && effectThread != NULL) { 746 // no risk of deadlock because AudioFlinger::mLock is held 747 Mutex::Autolock _dl(thread->mLock); 748 Mutex::Autolock _sl(effectThread->mLock); 749 moveEffectChain_l(lSessionId, effectThread, thread, true); 750 } 751 752 // Look for sync events awaiting for a session to be used. 753 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) { 754 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 755 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 756 if (lStatus == NO_ERROR) { 757 (void) track->setSyncEvent(mPendingSyncEvents[i]); 758 } else { 759 mPendingSyncEvents[i]->cancel(); 760 } 761 mPendingSyncEvents.removeAt(i); 762 i--; 763 } 764 } 765 } 766 767 setAudioHwSyncForSession_l(thread, lSessionId); 768 } 769 770 if (lStatus != NO_ERROR) { 771 // remove local strong reference to Client before deleting the Track so that the 772 // Client destructor is called by the TrackBase destructor with mClientLock held 773 // Don't hold mClientLock when releasing the reference on the track as the 774 // destructor will acquire it. 775 { 776 Mutex::Autolock _cl(mClientLock); 777 client.clear(); 778 } 779 track.clear(); 780 goto Exit; 781 } 782 783 // return handle to client 784 trackHandle = new TrackHandle(track); 785 786Exit: 787 *status = lStatus; 788 return trackHandle; 789} 790 791uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const 792{ 793 Mutex::Autolock _l(mLock); 794 ThreadBase *thread = checkThread_l(ioHandle); 795 if (thread == NULL) { 796 ALOGW("sampleRate() unknown thread %d", ioHandle); 797 return 0; 798 } 799 return thread->sampleRate(); 800} 801 802audio_format_t AudioFlinger::format(audio_io_handle_t output) const 803{ 804 Mutex::Autolock _l(mLock); 805 PlaybackThread *thread = checkPlaybackThread_l(output); 806 if (thread == NULL) { 807 ALOGW("format() unknown thread %d", output); 808 return AUDIO_FORMAT_INVALID; 809 } 810 return thread->format(); 811} 812 813size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const 814{ 815 Mutex::Autolock _l(mLock); 816 ThreadBase *thread = checkThread_l(ioHandle); 817 if (thread == NULL) { 818 ALOGW("frameCount() unknown thread %d", ioHandle); 819 return 0; 820 } 821 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 822 // should examine all callers and fix them to handle smaller counts 823 return thread->frameCount(); 824} 825 826size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const 827{ 828 Mutex::Autolock _l(mLock); 829 ThreadBase *thread = checkThread_l(ioHandle); 830 if (thread == NULL) { 831 ALOGW("frameCountHAL() unknown thread %d", ioHandle); 832 return 0; 833 } 834 return thread->frameCountHAL(); 835} 836 837uint32_t AudioFlinger::latency(audio_io_handle_t output) const 838{ 839 Mutex::Autolock _l(mLock); 840 PlaybackThread *thread = checkPlaybackThread_l(output); 841 if (thread == NULL) { 842 ALOGW("latency(): no playback thread found for output handle %d", output); 843 return 0; 844 } 845 return thread->latency(); 846} 847 848status_t AudioFlinger::setMasterVolume(float value) 849{ 850 status_t ret = initCheck(); 851 if (ret != NO_ERROR) { 852 return ret; 853 } 854 855 // check calling permissions 856 if (!settingsAllowed()) { 857 return PERMISSION_DENIED; 858 } 859 860 Mutex::Autolock _l(mLock); 861 mMasterVolume = value; 862 863 // Set master volume in the HALs which support it. 864 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 865 AutoMutex lock(mHardwareLock); 866 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 867 868 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 869 if (dev->canSetMasterVolume()) { 870 dev->hwDevice()->setMasterVolume(value); 871 } 872 mHardwareStatus = AUDIO_HW_IDLE; 873 } 874 875 // Now set the master volume in each playback thread. Playback threads 876 // assigned to HALs which do not have master volume support will apply 877 // master volume during the mix operation. Threads with HALs which do 878 // support master volume will simply ignore the setting. 879 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 880 if (mPlaybackThreads.valueAt(i)->isDuplicating()) { 881 continue; 882 } 883 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 884 } 885 886 return NO_ERROR; 887} 888 889status_t AudioFlinger::setMode(audio_mode_t mode) 890{ 891 status_t ret = initCheck(); 892 if (ret != NO_ERROR) { 893 return ret; 894 } 895 896 // check calling permissions 897 if (!settingsAllowed()) { 898 return PERMISSION_DENIED; 899 } 900 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 901 ALOGW("Illegal value: setMode(%d)", mode); 902 return BAD_VALUE; 903 } 904 905 { // scope for the lock 906 AutoMutex lock(mHardwareLock); 907 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice(); 908 mHardwareStatus = AUDIO_HW_SET_MODE; 909 ret = dev->setMode(mode); 910 mHardwareStatus = AUDIO_HW_IDLE; 911 } 912 913 if (NO_ERROR == ret) { 914 Mutex::Autolock _l(mLock); 915 mMode = mode; 916 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 917 mPlaybackThreads.valueAt(i)->setMode(mode); 918 } 919 920 return ret; 921} 922 923status_t AudioFlinger::setMicMute(bool state) 924{ 925 status_t ret = initCheck(); 926 if (ret != NO_ERROR) { 927 return ret; 928 } 929 930 // check calling permissions 931 if (!settingsAllowed()) { 932 return PERMISSION_DENIED; 933 } 934 935 AutoMutex lock(mHardwareLock); 936 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 937 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 938 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice(); 939 status_t result = dev->setMicMute(state); 940 if (result != NO_ERROR) { 941 ret = result; 942 } 943 } 944 mHardwareStatus = AUDIO_HW_IDLE; 945 return ret; 946} 947 948bool AudioFlinger::getMicMute() const 949{ 950 status_t ret = initCheck(); 951 if (ret != NO_ERROR) { 952 return false; 953 } 954 bool mute = true; 955 bool state = AUDIO_MODE_INVALID; 956 AutoMutex lock(mHardwareLock); 957 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 958 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 959 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice(); 960 status_t result = dev->getMicMute(&state); 961 if (result == NO_ERROR) { 962 mute = mute && state; 963 } 964 } 965 mHardwareStatus = AUDIO_HW_IDLE; 966 967 return mute; 968} 969 970status_t AudioFlinger::setMasterMute(bool muted) 971{ 972 status_t ret = initCheck(); 973 if (ret != NO_ERROR) { 974 return ret; 975 } 976 977 // check calling permissions 978 if (!settingsAllowed()) { 979 return PERMISSION_DENIED; 980 } 981 982 Mutex::Autolock _l(mLock); 983 mMasterMute = muted; 984 985 // Set master mute in the HALs which support it. 986 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 987 AutoMutex lock(mHardwareLock); 988 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 989 990 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 991 if (dev->canSetMasterMute()) { 992 dev->hwDevice()->setMasterMute(muted); 993 } 994 mHardwareStatus = AUDIO_HW_IDLE; 995 } 996 997 // Now set the master mute in each playback thread. Playback threads 998 // assigned to HALs which do not have master mute support will apply master 999 // mute during the mix operation. Threads with HALs which do support master 1000 // mute will simply ignore the setting. 1001 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l(); 1002 for (size_t i = 0; i < volumeInterfaces.size(); i++) { 1003 volumeInterfaces[i]->setMasterMute(muted); 1004 } 1005 1006 return NO_ERROR; 1007} 1008 1009float AudioFlinger::masterVolume() const 1010{ 1011 Mutex::Autolock _l(mLock); 1012 return masterVolume_l(); 1013} 1014 1015bool AudioFlinger::masterMute() const 1016{ 1017 Mutex::Autolock _l(mLock); 1018 return masterMute_l(); 1019} 1020 1021float AudioFlinger::masterVolume_l() const 1022{ 1023 return mMasterVolume; 1024} 1025 1026bool AudioFlinger::masterMute_l() const 1027{ 1028 return mMasterMute; 1029} 1030 1031status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const 1032{ 1033 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 1034 ALOGW("checkStreamType() invalid stream %d", stream); 1035 return BAD_VALUE; 1036 } 1037 pid_t caller = IPCThreadState::self()->getCallingPid(); 1038 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) { 1039 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream); 1040 return PERMISSION_DENIED; 1041 } 1042 1043 return NO_ERROR; 1044} 1045 1046status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 1047 audio_io_handle_t output) 1048{ 1049 // check calling permissions 1050 if (!settingsAllowed()) { 1051 return PERMISSION_DENIED; 1052 } 1053 1054 status_t status = checkStreamType(stream); 1055 if (status != NO_ERROR) { 1056 return status; 1057 } 1058 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume"); 1059 1060 AutoMutex lock(mLock); 1061 Vector<VolumeInterface *> volumeInterfaces; 1062 if (output != AUDIO_IO_HANDLE_NONE) { 1063 VolumeInterface *volumeInterface = getVolumeInterface_l(output); 1064 if (volumeInterface == NULL) { 1065 return BAD_VALUE; 1066 } 1067 volumeInterfaces.add(volumeInterface); 1068 } 1069 1070 mStreamTypes[stream].volume = value; 1071 1072 if (volumeInterfaces.size() == 0) { 1073 volumeInterfaces = getAllVolumeInterfaces_l(); 1074 } 1075 for (size_t i = 0; i < volumeInterfaces.size(); i++) { 1076 volumeInterfaces[i]->setStreamVolume(stream, value); 1077 } 1078 1079 return NO_ERROR; 1080} 1081 1082status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 1083{ 1084 // check calling permissions 1085 if (!settingsAllowed()) { 1086 return PERMISSION_DENIED; 1087 } 1088 1089 status_t status = checkStreamType(stream); 1090 if (status != NO_ERROR) { 1091 return status; 1092 } 1093 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH"); 1094 1095 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 1096 ALOGE("setStreamMute() invalid stream %d", stream); 1097 return BAD_VALUE; 1098 } 1099 1100 AutoMutex lock(mLock); 1101 mStreamTypes[stream].mute = muted; 1102 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l(); 1103 for (size_t i = 0; i < volumeInterfaces.size(); i++) { 1104 volumeInterfaces[i]->setStreamMute(stream, muted); 1105 } 1106 1107 return NO_ERROR; 1108} 1109 1110float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 1111{ 1112 status_t status = checkStreamType(stream); 1113 if (status != NO_ERROR) { 1114 return 0.0f; 1115 } 1116 1117 AutoMutex lock(mLock); 1118 float volume; 1119 if (output != AUDIO_IO_HANDLE_NONE) { 1120 VolumeInterface *volumeInterface = getVolumeInterface_l(output); 1121 if (volumeInterface != NULL) { 1122 volume = volumeInterface->streamVolume(stream); 1123 } else { 1124 volume = 0.0f; 1125 } 1126 } else { 1127 volume = streamVolume_l(stream); 1128 } 1129 1130 return volume; 1131} 1132 1133bool AudioFlinger::streamMute(audio_stream_type_t stream) const 1134{ 1135 status_t status = checkStreamType(stream); 1136 if (status != NO_ERROR) { 1137 return true; 1138 } 1139 1140 AutoMutex lock(mLock); 1141 return streamMute_l(stream); 1142} 1143 1144 1145void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs) 1146{ 1147 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1148 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 1149 } 1150} 1151 1152status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 1153{ 1154 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 1155 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 1156 1157 // check calling permissions 1158 if (!settingsAllowed()) { 1159 return PERMISSION_DENIED; 1160 } 1161 1162 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface 1163 if (ioHandle == AUDIO_IO_HANDLE_NONE) { 1164 Mutex::Autolock _l(mLock); 1165 // result will remain NO_INIT if no audio device is present 1166 status_t final_result = NO_INIT; 1167 { 1168 AutoMutex lock(mHardwareLock); 1169 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 1170 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1171 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1172 status_t result = dev->setParameters(keyValuePairs); 1173 // return success if at least one audio device accepts the parameters as not all 1174 // HALs are requested to support all parameters. If no audio device supports the 1175 // requested parameters, the last error is reported. 1176 if (final_result != NO_ERROR) { 1177 final_result = result; 1178 } 1179 } 1180 mHardwareStatus = AUDIO_HW_IDLE; 1181 } 1182 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 1183 AudioParameter param = AudioParameter(keyValuePairs); 1184 String8 value; 1185 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) { 1186 bool btNrecIsOff = (value == AudioParameter::valueOff); 1187 if (mBtNrecIsOff != btNrecIsOff) { 1188 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1189 sp<RecordThread> thread = mRecordThreads.valueAt(i); 1190 audio_devices_t device = thread->inDevice(); 1191 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 1192 // collect all of the thread's session IDs 1193 KeyedVector<audio_session_t, bool> ids = thread->sessionIds(); 1194 // suspend effects associated with those session IDs 1195 for (size_t j = 0; j < ids.size(); ++j) { 1196 audio_session_t sessionId = ids.keyAt(j); 1197 thread->setEffectSuspended(FX_IID_AEC, 1198 suspend, 1199 sessionId); 1200 thread->setEffectSuspended(FX_IID_NS, 1201 suspend, 1202 sessionId); 1203 } 1204 } 1205 mBtNrecIsOff = btNrecIsOff; 1206 } 1207 } 1208 String8 screenState; 1209 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 1210 bool isOff = (screenState == AudioParameter::valueOff); 1211 if (isOff != (AudioFlinger::mScreenState & 1)) { 1212 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 1213 } 1214 } 1215 return final_result; 1216 } 1217 1218 // hold a strong ref on thread in case closeOutput() or closeInput() is called 1219 // and the thread is exited once the lock is released 1220 sp<ThreadBase> thread; 1221 { 1222 Mutex::Autolock _l(mLock); 1223 thread = checkPlaybackThread_l(ioHandle); 1224 if (thread == 0) { 1225 thread = checkRecordThread_l(ioHandle); 1226 if (thread == 0) { 1227 thread = checkMmapThread_l(ioHandle); 1228 } 1229 } else if (thread == primaryPlaybackThread_l()) { 1230 // indicate output device change to all input threads for pre processing 1231 AudioParameter param = AudioParameter(keyValuePairs); 1232 int value; 1233 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 1234 (value != 0)) { 1235 broacastParametersToRecordThreads_l(keyValuePairs); 1236 } 1237 } 1238 } 1239 if (thread != 0) { 1240 return thread->setParameters(keyValuePairs); 1241 } 1242 return BAD_VALUE; 1243} 1244 1245String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 1246{ 1247 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 1248 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 1249 1250 Mutex::Autolock _l(mLock); 1251 1252 if (ioHandle == AUDIO_IO_HANDLE_NONE) { 1253 String8 out_s8; 1254 1255 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1256 String8 s; 1257 status_t result; 1258 { 1259 AutoMutex lock(mHardwareLock); 1260 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 1261 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1262 result = dev->getParameters(keys, &s); 1263 mHardwareStatus = AUDIO_HW_IDLE; 1264 } 1265 if (result == OK) out_s8 += s; 1266 } 1267 return out_s8; 1268 } 1269 1270 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle); 1271 if (thread == NULL) { 1272 thread = (ThreadBase *)checkRecordThread_l(ioHandle); 1273 if (thread == NULL) { 1274 thread = (ThreadBase *)checkMmapThread_l(ioHandle); 1275 if (thread == NULL) { 1276 String8(""); 1277 } 1278 } 1279 } 1280 return thread->getParameters(keys); 1281} 1282 1283size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 1284 audio_channel_mask_t channelMask) const 1285{ 1286 status_t ret = initCheck(); 1287 if (ret != NO_ERROR) { 1288 return 0; 1289 } 1290 if ((sampleRate == 0) || 1291 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) || 1292 !audio_is_input_channel(channelMask)) { 1293 return 0; 1294 } 1295 1296 AutoMutex lock(mHardwareLock); 1297 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1298 audio_config_t config, proposed; 1299 memset(&proposed, 0, sizeof(proposed)); 1300 proposed.sample_rate = sampleRate; 1301 proposed.channel_mask = channelMask; 1302 proposed.format = format; 1303 1304 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice(); 1305 size_t frames; 1306 for (;;) { 1307 // Note: config is currently a const parameter for get_input_buffer_size() 1308 // but we use a copy from proposed in case config changes from the call. 1309 config = proposed; 1310 status_t result = dev->getInputBufferSize(&config, &frames); 1311 if (result == OK && frames != 0) { 1312 break; // hal success, config is the result 1313 } 1314 // change one parameter of the configuration each iteration to a more "common" value 1315 // to see if the device will support it. 1316 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) { 1317 proposed.format = AUDIO_FORMAT_PCM_16_BIT; 1318 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as 1319 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw? 1320 } else { 1321 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, " 1322 "format %#x, channelMask 0x%X", 1323 sampleRate, format, channelMask); 1324 break; // retries failed, break out of loop with frames == 0. 1325 } 1326 } 1327 mHardwareStatus = AUDIO_HW_IDLE; 1328 if (frames > 0 && config.sample_rate != sampleRate) { 1329 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate); 1330 } 1331 return frames; // may be converted to bytes at the Java level. 1332} 1333 1334uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1335{ 1336 Mutex::Autolock _l(mLock); 1337 1338 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1339 if (recordThread != NULL) { 1340 return recordThread->getInputFramesLost(); 1341 } 1342 return 0; 1343} 1344 1345status_t AudioFlinger::setVoiceVolume(float value) 1346{ 1347 status_t ret = initCheck(); 1348 if (ret != NO_ERROR) { 1349 return ret; 1350 } 1351 1352 // check calling permissions 1353 if (!settingsAllowed()) { 1354 return PERMISSION_DENIED; 1355 } 1356 1357 AutoMutex lock(mHardwareLock); 1358 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice(); 1359 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1360 ret = dev->setVoiceVolume(value); 1361 mHardwareStatus = AUDIO_HW_IDLE; 1362 1363 return ret; 1364} 1365 1366status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 1367 audio_io_handle_t output) const 1368{ 1369 Mutex::Autolock _l(mLock); 1370 1371 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1372 if (playbackThread != NULL) { 1373 return playbackThread->getRenderPosition(halFrames, dspFrames); 1374 } 1375 1376 return BAD_VALUE; 1377} 1378 1379void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1380{ 1381 Mutex::Autolock _l(mLock); 1382 if (client == 0) { 1383 return; 1384 } 1385 pid_t pid = IPCThreadState::self()->getCallingPid(); 1386 { 1387 Mutex::Autolock _cl(mClientLock); 1388 if (mNotificationClients.indexOfKey(pid) < 0) { 1389 sp<NotificationClient> notificationClient = new NotificationClient(this, 1390 client, 1391 pid); 1392 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1393 1394 mNotificationClients.add(pid, notificationClient); 1395 1396 sp<IBinder> binder = IInterface::asBinder(client); 1397 binder->linkToDeath(notificationClient); 1398 } 1399 } 1400 1401 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the 1402 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock. 1403 // the config change is always sent from playback or record threads to avoid deadlock 1404 // with AudioSystem::gLock 1405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1406 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid); 1407 } 1408 1409 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1410 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid); 1411 } 1412} 1413 1414void AudioFlinger::removeNotificationClient(pid_t pid) 1415{ 1416 Mutex::Autolock _l(mLock); 1417 { 1418 Mutex::Autolock _cl(mClientLock); 1419 mNotificationClients.removeItem(pid); 1420 } 1421 1422 ALOGV("%d died, releasing its sessions", pid); 1423 size_t num = mAudioSessionRefs.size(); 1424 bool removed = false; 1425 for (size_t i = 0; i < num; ) { 1426 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1427 ALOGV(" pid %d @ %zu", ref->mPid, i); 1428 if (ref->mPid == pid) { 1429 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1430 mAudioSessionRefs.removeAt(i); 1431 delete ref; 1432 removed = true; 1433 num--; 1434 } else { 1435 i++; 1436 } 1437 } 1438 if (removed) { 1439 purgeStaleEffects_l(); 1440 } 1441} 1442 1443void AudioFlinger::ioConfigChanged(audio_io_config_event event, 1444 const sp<AudioIoDescriptor>& ioDesc, 1445 pid_t pid) 1446{ 1447 Mutex::Autolock _l(mClientLock); 1448 size_t size = mNotificationClients.size(); 1449 for (size_t i = 0; i < size; i++) { 1450 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) { 1451 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc); 1452 } 1453 } 1454} 1455 1456// removeClient_l() must be called with AudioFlinger::mClientLock held 1457void AudioFlinger::removeClient_l(pid_t pid) 1458{ 1459 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1460 IPCThreadState::self()->getCallingPid()); 1461 mClients.removeItem(pid); 1462} 1463 1464// getEffectThread_l() must be called with AudioFlinger::mLock held 1465sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId, 1466 int EffectId) 1467{ 1468 sp<PlaybackThread> thread; 1469 1470 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1471 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1472 ALOG_ASSERT(thread == 0); 1473 thread = mPlaybackThreads.valueAt(i); 1474 } 1475 } 1476 1477 return thread; 1478} 1479 1480 1481 1482// ---------------------------------------------------------------------------- 1483 1484AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1485 : RefBase(), 1486 mAudioFlinger(audioFlinger), 1487 mPid(pid) 1488{ 1489 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0); 1490 heapSize *= 1024; 1491 if (!heapSize) { 1492 heapSize = kClientSharedHeapSizeBytes; 1493 // Increase heap size on non low ram devices to limit risk of reconnection failure for 1494 // invalidated tracks 1495 if (!audioFlinger->isLowRamDevice()) { 1496 heapSize *= kClientSharedHeapSizeMultiplier; 1497 } 1498 } 1499 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client"); 1500} 1501 1502// Client destructor must be called with AudioFlinger::mClientLock held 1503AudioFlinger::Client::~Client() 1504{ 1505 mAudioFlinger->removeClient_l(mPid); 1506} 1507 1508sp<MemoryDealer> AudioFlinger::Client::heap() const 1509{ 1510 return mMemoryDealer; 1511} 1512 1513// ---------------------------------------------------------------------------- 1514 1515AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1516 const sp<IAudioFlingerClient>& client, 1517 pid_t pid) 1518 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1519{ 1520} 1521 1522AudioFlinger::NotificationClient::~NotificationClient() 1523{ 1524} 1525 1526void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused) 1527{ 1528 sp<NotificationClient> keep(this); 1529 mAudioFlinger->removeNotificationClient(mPid); 1530} 1531 1532 1533// ---------------------------------------------------------------------------- 1534 1535sp<IAudioRecord> AudioFlinger::openRecord( 1536 audio_io_handle_t input, 1537 uint32_t sampleRate, 1538 audio_format_t format, 1539 audio_channel_mask_t channelMask, 1540 const String16& opPackageName, 1541 size_t *frameCount, 1542 audio_input_flags_t *flags, 1543 pid_t pid, 1544 pid_t tid, 1545 int clientUid, 1546 audio_session_t *sessionId, 1547 size_t *notificationFrames, 1548 sp<IMemory>& cblk, 1549 sp<IMemory>& buffers, 1550 status_t *status, 1551 audio_port_handle_t portId) 1552{ 1553 sp<RecordThread::RecordTrack> recordTrack; 1554 sp<RecordHandle> recordHandle; 1555 sp<Client> client; 1556 status_t lStatus; 1557 audio_session_t lSessionId; 1558 1559 cblk.clear(); 1560 buffers.clear(); 1561 1562 bool updatePid = (pid == -1); 1563 const uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1564 if (!isTrustedCallingUid(callingUid)) { 1565 ALOGW_IF((uid_t)clientUid != callingUid, 1566 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid); 1567 clientUid = callingUid; 1568 updatePid = true; 1569 } 1570 1571 if (updatePid) { 1572 const pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1573 ALOGW_IF(pid != -1 && pid != callingPid, 1574 "%s uid %d pid %d tried to pass itself off as pid %d", 1575 __func__, callingUid, callingPid, pid); 1576 pid = callingPid; 1577 } 1578 1579 // check calling permissions 1580 if (!recordingAllowed(opPackageName, tid, clientUid)) { 1581 ALOGE("openRecord() permission denied: recording not allowed"); 1582 lStatus = PERMISSION_DENIED; 1583 goto Exit; 1584 } 1585 1586 // further sample rate checks are performed by createRecordTrack_l() 1587 if (sampleRate == 0) { 1588 ALOGE("openRecord() invalid sample rate %u", sampleRate); 1589 lStatus = BAD_VALUE; 1590 goto Exit; 1591 } 1592 1593 // we don't yet support anything other than linear PCM 1594 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) { 1595 ALOGE("openRecord() invalid format %#x", format); 1596 lStatus = BAD_VALUE; 1597 goto Exit; 1598 } 1599 1600 // further channel mask checks are performed by createRecordTrack_l() 1601 if (!audio_is_input_channel(channelMask)) { 1602 ALOGE("openRecord() invalid channel mask %#x", channelMask); 1603 lStatus = BAD_VALUE; 1604 goto Exit; 1605 } 1606 1607 { 1608 Mutex::Autolock _l(mLock); 1609 RecordThread *thread = checkRecordThread_l(input); 1610 if (thread == NULL) { 1611 ALOGE("openRecord() checkRecordThread_l failed"); 1612 lStatus = BAD_VALUE; 1613 goto Exit; 1614 } 1615 1616 client = registerPid(pid); 1617 1618 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 1619 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) { 1620 lStatus = BAD_VALUE; 1621 goto Exit; 1622 } 1623 lSessionId = *sessionId; 1624 } else { 1625 // if no audio session id is provided, create one here 1626 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION); 1627 if (sessionId != NULL) { 1628 *sessionId = lSessionId; 1629 } 1630 } 1631 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input); 1632 1633 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1634 frameCount, lSessionId, notificationFrames, 1635 clientUid, flags, tid, &lStatus, portId); 1636 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0)); 1637 1638 if (lStatus == NO_ERROR) { 1639 // Check if one effect chain was awaiting for an AudioRecord to be created on this 1640 // session and move it to this thread. 1641 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId); 1642 if (chain != 0) { 1643 Mutex::Autolock _l(thread->mLock); 1644 thread->addEffectChain_l(chain); 1645 } 1646 } 1647 } 1648 1649 if (lStatus != NO_ERROR) { 1650 // remove local strong reference to Client before deleting the RecordTrack so that the 1651 // Client destructor is called by the TrackBase destructor with mClientLock held 1652 // Don't hold mClientLock when releasing the reference on the track as the 1653 // destructor will acquire it. 1654 { 1655 Mutex::Autolock _cl(mClientLock); 1656 client.clear(); 1657 } 1658 recordTrack.clear(); 1659 goto Exit; 1660 } 1661 1662 cblk = recordTrack->getCblk(); 1663 buffers = recordTrack->getBuffers(); 1664 1665 // return handle to client 1666 recordHandle = new RecordHandle(recordTrack); 1667 1668Exit: 1669 *status = lStatus; 1670 return recordHandle; 1671} 1672 1673 1674 1675// ---------------------------------------------------------------------------- 1676 1677audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 1678{ 1679 if (name == NULL) { 1680 return AUDIO_MODULE_HANDLE_NONE; 1681 } 1682 if (!settingsAllowed()) { 1683 return AUDIO_MODULE_HANDLE_NONE; 1684 } 1685 Mutex::Autolock _l(mLock); 1686 return loadHwModule_l(name); 1687} 1688 1689// loadHwModule_l() must be called with AudioFlinger::mLock held 1690audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 1691{ 1692 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1693 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 1694 ALOGW("loadHwModule() module %s already loaded", name); 1695 return mAudioHwDevs.keyAt(i); 1696 } 1697 } 1698 1699 sp<DeviceHalInterface> dev; 1700 1701 int rc = mDevicesFactoryHal->openDevice(name, &dev); 1702 if (rc) { 1703 ALOGE("loadHwModule() error %d loading module %s", rc, name); 1704 return AUDIO_MODULE_HANDLE_NONE; 1705 } 1706 1707 mHardwareStatus = AUDIO_HW_INIT; 1708 rc = dev->initCheck(); 1709 mHardwareStatus = AUDIO_HW_IDLE; 1710 if (rc) { 1711 ALOGE("loadHwModule() init check error %d for module %s", rc, name); 1712 return AUDIO_MODULE_HANDLE_NONE; 1713 } 1714 1715 // Check and cache this HAL's level of support for master mute and master 1716 // volume. If this is the first HAL opened, and it supports the get 1717 // methods, use the initial values provided by the HAL as the current 1718 // master mute and volume settings. 1719 1720 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 1721 { // scope for auto-lock pattern 1722 AutoMutex lock(mHardwareLock); 1723 1724 if (0 == mAudioHwDevs.size()) { 1725 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 1726 float mv; 1727 if (OK == dev->getMasterVolume(&mv)) { 1728 mMasterVolume = mv; 1729 } 1730 1731 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 1732 bool mm; 1733 if (OK == dev->getMasterMute(&mm)) { 1734 mMasterMute = mm; 1735 } 1736 } 1737 1738 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 1739 if (OK == dev->setMasterVolume(mMasterVolume)) { 1740 flags = static_cast<AudioHwDevice::Flags>(flags | 1741 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 1742 } 1743 1744 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 1745 if (OK == dev->setMasterMute(mMasterMute)) { 1746 flags = static_cast<AudioHwDevice::Flags>(flags | 1747 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 1748 } 1749 1750 mHardwareStatus = AUDIO_HW_IDLE; 1751 } 1752 1753 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE); 1754 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags)); 1755 1756 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle); 1757 1758 return handle; 1759 1760} 1761 1762// ---------------------------------------------------------------------------- 1763 1764uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 1765{ 1766 Mutex::Autolock _l(mLock); 1767 PlaybackThread *thread = fastPlaybackThread_l(); 1768 return thread != NULL ? thread->sampleRate() : 0; 1769} 1770 1771size_t AudioFlinger::getPrimaryOutputFrameCount() 1772{ 1773 Mutex::Autolock _l(mLock); 1774 PlaybackThread *thread = fastPlaybackThread_l(); 1775 return thread != NULL ? thread->frameCountHAL() : 0; 1776} 1777 1778// ---------------------------------------------------------------------------- 1779 1780status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice) 1781{ 1782 uid_t uid = IPCThreadState::self()->getCallingUid(); 1783 if (uid != AID_SYSTEM) { 1784 return PERMISSION_DENIED; 1785 } 1786 Mutex::Autolock _l(mLock); 1787 if (mIsDeviceTypeKnown) { 1788 return INVALID_OPERATION; 1789 } 1790 mIsLowRamDevice = isLowRamDevice; 1791 mIsDeviceTypeKnown = true; 1792 return NO_ERROR; 1793} 1794 1795audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId) 1796{ 1797 Mutex::Autolock _l(mLock); 1798 1799 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId); 1800 if (index >= 0) { 1801 ALOGV("getAudioHwSyncForSession found ID %d for session %d", 1802 mHwAvSyncIds.valueAt(index), sessionId); 1803 return mHwAvSyncIds.valueAt(index); 1804 } 1805 1806 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice(); 1807 if (dev == NULL) { 1808 return AUDIO_HW_SYNC_INVALID; 1809 } 1810 String8 reply; 1811 AudioParameter param; 1812 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) { 1813 param = AudioParameter(reply); 1814 } 1815 1816 int value; 1817 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) { 1818 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId); 1819 return AUDIO_HW_SYNC_INVALID; 1820 } 1821 1822 // allow only one session for a given HW A/V sync ID. 1823 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) { 1824 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) { 1825 ALOGV("getAudioHwSyncForSession removing ID %d for session %d", 1826 value, mHwAvSyncIds.keyAt(i)); 1827 mHwAvSyncIds.removeItemsAt(i); 1828 break; 1829 } 1830 } 1831 1832 mHwAvSyncIds.add(sessionId, value); 1833 1834 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1835 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i); 1836 uint32_t sessions = thread->hasAudioSession(sessionId); 1837 if (sessions & ThreadBase::TRACK_SESSION) { 1838 AudioParameter param = AudioParameter(); 1839 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value); 1840 thread->setParameters(param.toString()); 1841 break; 1842 } 1843 } 1844 1845 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId); 1846 return (audio_hw_sync_t)value; 1847} 1848 1849status_t AudioFlinger::systemReady() 1850{ 1851 Mutex::Autolock _l(mLock); 1852 ALOGI("%s", __FUNCTION__); 1853 if (mSystemReady) { 1854 ALOGW("%s called twice", __FUNCTION__); 1855 return NO_ERROR; 1856 } 1857 mSystemReady = true; 1858 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1859 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get(); 1860 thread->systemReady(); 1861 } 1862 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1863 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get(); 1864 thread->systemReady(); 1865 } 1866 return NO_ERROR; 1867} 1868 1869// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held 1870void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId) 1871{ 1872 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId); 1873 if (index >= 0) { 1874 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index); 1875 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId); 1876 AudioParameter param = AudioParameter(); 1877 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId); 1878 thread->setParameters(param.toString()); 1879 } 1880} 1881 1882 1883// ---------------------------------------------------------------------------- 1884 1885 1886sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module, 1887 audio_io_handle_t *output, 1888 audio_config_t *config, 1889 audio_devices_t devices, 1890 const String8& address, 1891 audio_output_flags_t flags) 1892{ 1893 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices); 1894 if (outHwDev == NULL) { 1895 return 0; 1896 } 1897 1898 if (*output == AUDIO_IO_HANDLE_NONE) { 1899 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT); 1900 } else { 1901 // Audio Policy does not currently request a specific output handle. 1902 // If this is ever needed, see openInput_l() for example code. 1903 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output); 1904 return 0; 1905 } 1906 1907 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 1908 1909 // FOR TESTING ONLY: 1910 // This if statement allows overriding the audio policy settings 1911 // and forcing a specific format or channel mask to the HAL/Sink device for testing. 1912 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) { 1913 // Check only for Normal Mixing mode 1914 if (kEnableExtendedPrecision) { 1915 // Specify format (uncomment one below to choose) 1916 //config->format = AUDIO_FORMAT_PCM_FLOAT; 1917 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED; 1918 //config->format = AUDIO_FORMAT_PCM_32_BIT; 1919 //config->format = AUDIO_FORMAT_PCM_8_24_BIT; 1920 // ALOGV("openOutput_l() upgrading format to %#08x", config->format); 1921 } 1922 if (kEnableExtendedChannels) { 1923 // Specify channel mask (uncomment one below to choose) 1924 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch 1925 //config->channel_mask = audio_channel_mask_from_representation_and_bits( 1926 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example 1927 } 1928 } 1929 1930 AudioStreamOut *outputStream = NULL; 1931 status_t status = outHwDev->openOutputStream( 1932 &outputStream, 1933 *output, 1934 devices, 1935 flags, 1936 config, 1937 address.string()); 1938 1939 mHardwareStatus = AUDIO_HW_IDLE; 1940 1941 if (status == NO_ERROR) { 1942 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) { 1943 sp<MmapPlaybackThread> thread = 1944 new MmapPlaybackThread(this, *output, outHwDev, outputStream, 1945 devices, AUDIO_DEVICE_NONE, mSystemReady); 1946 mMmapThreads.add(*output, thread); 1947 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p", 1948 *output, thread.get()); 1949 return thread; 1950 } else { 1951 sp<PlaybackThread> thread; 1952 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1953 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady); 1954 ALOGV("openOutput_l() created offload output: ID %d thread %p", 1955 *output, thread.get()); 1956 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) 1957 || !isValidPcmSinkFormat(config->format) 1958 || !isValidPcmSinkChannelMask(config->channel_mask)) { 1959 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady); 1960 ALOGV("openOutput_l() created direct output: ID %d thread %p", 1961 *output, thread.get()); 1962 } else { 1963 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady); 1964 ALOGV("openOutput_l() created mixer output: ID %d thread %p", 1965 *output, thread.get()); 1966 } 1967 mPlaybackThreads.add(*output, thread); 1968 return thread; 1969 } 1970 } 1971 1972 return 0; 1973} 1974 1975status_t AudioFlinger::openOutput(audio_module_handle_t module, 1976 audio_io_handle_t *output, 1977 audio_config_t *config, 1978 audio_devices_t *devices, 1979 const String8& address, 1980 uint32_t *latencyMs, 1981 audio_output_flags_t flags) 1982{ 1983 ALOGI("openOutput() this %p, module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, " 1984 "flags %x", 1985 this, module, 1986 (devices != NULL) ? *devices : 0, 1987 config->sample_rate, 1988 config->format, 1989 config->channel_mask, 1990 flags); 1991 1992 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) { 1993 return BAD_VALUE; 1994 } 1995 1996 Mutex::Autolock _l(mLock); 1997 1998 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags); 1999 if (thread != 0) { 2000 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) { 2001 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 2002 *latencyMs = playbackThread->latency(); 2003 2004 // notify client processes of the new output creation 2005 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED); 2006 2007 // the first primary output opened designates the primary hw device 2008 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 2009 ALOGI("Using module %d has the primary audio interface", module); 2010 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev; 2011 2012 AutoMutex lock(mHardwareLock); 2013 mHardwareStatus = AUDIO_HW_SET_MODE; 2014 mPrimaryHardwareDev->hwDevice()->setMode(mMode); 2015 mHardwareStatus = AUDIO_HW_IDLE; 2016 } 2017 } else { 2018 MmapThread *mmapThread = (MmapThread *)thread.get(); 2019 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED); 2020 } 2021 return NO_ERROR; 2022 } 2023 2024 return NO_INIT; 2025} 2026 2027audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 2028 audio_io_handle_t output2) 2029{ 2030 Mutex::Autolock _l(mLock); 2031 MixerThread *thread1 = checkMixerThread_l(output1); 2032 MixerThread *thread2 = checkMixerThread_l(output2); 2033 2034 if (thread1 == NULL || thread2 == NULL) { 2035 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 2036 output2); 2037 return AUDIO_IO_HANDLE_NONE; 2038 } 2039 2040 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT); 2041 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady); 2042 thread->addOutputTrack(thread2); 2043 mPlaybackThreads.add(id, thread); 2044 // notify client processes of the new output creation 2045 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED); 2046 return id; 2047} 2048 2049status_t AudioFlinger::closeOutput(audio_io_handle_t output) 2050{ 2051 return closeOutput_nonvirtual(output); 2052} 2053 2054status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 2055{ 2056 // keep strong reference on the playback thread so that 2057 // it is not destroyed while exit() is executed 2058 sp<PlaybackThread> playbackThread; 2059 sp<MmapPlaybackThread> mmapThread; 2060 { 2061 Mutex::Autolock _l(mLock); 2062 playbackThread = checkPlaybackThread_l(output); 2063 if (playbackThread != NULL) { 2064 ALOGV("closeOutput() %d", output); 2065 2066 if (playbackThread->type() == ThreadBase::MIXER) { 2067 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2068 if (mPlaybackThreads.valueAt(i)->isDuplicating()) { 2069 DuplicatingThread *dupThread = 2070 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 2071 dupThread->removeOutputTrack((MixerThread *)playbackThread.get()); 2072 } 2073 } 2074 } 2075 2076 2077 mPlaybackThreads.removeItem(output); 2078 // save all effects to the default thread 2079 if (mPlaybackThreads.size()) { 2080 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0)); 2081 if (dstThread != NULL) { 2082 // audioflinger lock is held so order of thread lock acquisition doesn't matter 2083 Mutex::Autolock _dl(dstThread->mLock); 2084 Mutex::Autolock _sl(playbackThread->mLock); 2085 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l(); 2086 for (size_t i = 0; i < effectChains.size(); i ++) { 2087 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(), 2088 dstThread, true); 2089 } 2090 } 2091 } 2092 } else { 2093 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output); 2094 if (mmapThread == 0) { 2095 return BAD_VALUE; 2096 } 2097 mMmapThreads.removeItem(output); 2098 ALOGV("closing mmapThread %p", mmapThread.get()); 2099 } 2100 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor(); 2101 ioDesc->mIoHandle = output; 2102 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc); 2103 } 2104 // The thread entity (active unit of execution) is no longer running here, 2105 // but the ThreadBase container still exists. 2106 2107 if (playbackThread != 0) { 2108 playbackThread->exit(); 2109 if (!playbackThread->isDuplicating()) { 2110 closeOutputFinish(playbackThread); 2111 } 2112 } else if (mmapThread != 0) { 2113 ALOGV("mmapThread exit()"); 2114 mmapThread->exit(); 2115 AudioStreamOut *out = mmapThread->clearOutput(); 2116 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 2117 // from now on thread->mOutput is NULL 2118 delete out; 2119 } 2120 return NO_ERROR; 2121} 2122 2123void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread) 2124{ 2125 AudioStreamOut *out = thread->clearOutput(); 2126 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 2127 // from now on thread->mOutput is NULL 2128 delete out; 2129} 2130 2131void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread) 2132{ 2133 mPlaybackThreads.removeItem(thread->mId); 2134 thread->exit(); 2135 closeOutputFinish(thread); 2136} 2137 2138status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 2139{ 2140 Mutex::Autolock _l(mLock); 2141 PlaybackThread *thread = checkPlaybackThread_l(output); 2142 2143 if (thread == NULL) { 2144 return BAD_VALUE; 2145 } 2146 2147 ALOGV("suspendOutput() %d", output); 2148 thread->suspend(); 2149 2150 return NO_ERROR; 2151} 2152 2153status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 2154{ 2155 Mutex::Autolock _l(mLock); 2156 PlaybackThread *thread = checkPlaybackThread_l(output); 2157 2158 if (thread == NULL) { 2159 return BAD_VALUE; 2160 } 2161 2162 ALOGV("restoreOutput() %d", output); 2163 2164 thread->restore(); 2165 2166 return NO_ERROR; 2167} 2168 2169status_t AudioFlinger::openInput(audio_module_handle_t module, 2170 audio_io_handle_t *input, 2171 audio_config_t *config, 2172 audio_devices_t *devices, 2173 const String8& address, 2174 audio_source_t source, 2175 audio_input_flags_t flags) 2176{ 2177 Mutex::Autolock _l(mLock); 2178 2179 if (*devices == AUDIO_DEVICE_NONE) { 2180 return BAD_VALUE; 2181 } 2182 2183 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags); 2184 2185 if (thread != 0) { 2186 // notify client processes of the new input creation 2187 thread->ioConfigChanged(AUDIO_INPUT_OPENED); 2188 return NO_ERROR; 2189 } 2190 return NO_INIT; 2191} 2192 2193sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module, 2194 audio_io_handle_t *input, 2195 audio_config_t *config, 2196 audio_devices_t devices, 2197 const String8& address, 2198 audio_source_t source, 2199 audio_input_flags_t flags) 2200{ 2201 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices); 2202 if (inHwDev == NULL) { 2203 *input = AUDIO_IO_HANDLE_NONE; 2204 return 0; 2205 } 2206 2207 // Audio Policy can request a specific handle for hardware hotword. 2208 // The goal here is not to re-open an already opened input. 2209 // It is to use a pre-assigned I/O handle. 2210 if (*input == AUDIO_IO_HANDLE_NONE) { 2211 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT); 2212 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) { 2213 ALOGE("openInput_l() requested input handle %d is invalid", *input); 2214 return 0; 2215 } else if (mRecordThreads.indexOfKey(*input) >= 0) { 2216 // This should not happen in a transient state with current design. 2217 ALOGE("openInput_l() requested input handle %d is already assigned", *input); 2218 return 0; 2219 } 2220 2221 audio_config_t halconfig = *config; 2222 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice(); 2223 sp<StreamInHalInterface> inStream; 2224 status_t status = inHwHal->openInputStream( 2225 *input, devices, &halconfig, flags, address.string(), source, &inStream); 2226 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d" 2227 ", Format %#x, Channels %x, flags %#x, status %d addr %s", 2228 inStream.get(), 2229 devices, 2230 halconfig.sample_rate, 2231 halconfig.format, 2232 halconfig.channel_mask, 2233 flags, 2234 status, address.string()); 2235 2236 // If the input could not be opened with the requested parameters and we can handle the 2237 // conversion internally, try to open again with the proposed parameters. 2238 if (status == BAD_VALUE && 2239 audio_is_linear_pcm(config->format) && 2240 audio_is_linear_pcm(halconfig.format) && 2241 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) && 2242 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) && 2243 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) { 2244 // FIXME describe the change proposed by HAL (save old values so we can log them here) 2245 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask"); 2246 inStream.clear(); 2247 status = inHwHal->openInputStream( 2248 *input, devices, &halconfig, flags, address.string(), source, &inStream); 2249 // FIXME log this new status; HAL should not propose any further changes 2250 } 2251 2252 if (status == NO_ERROR && inStream != 0) { 2253 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags); 2254 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) { 2255 sp<MmapCaptureThread> thread = 2256 new MmapCaptureThread(this, *input, 2257 inHwDev, inputStream, 2258 primaryOutputDevice_l(), devices, mSystemReady); 2259 mMmapThreads.add(*input, thread); 2260 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input, 2261 thread.get()); 2262 return thread; 2263 } else { 2264#ifdef TEE_SINK 2265 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 2266 // or (re-)create if current Pipe is idle and does not match the new format 2267 sp<NBAIO_Sink> teeSink; 2268 enum { 2269 TEE_SINK_NO, // don't copy input 2270 TEE_SINK_NEW, // copy input using a new pipe 2271 TEE_SINK_OLD, // copy input using an existing pipe 2272 } kind; 2273 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate, 2274 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format); 2275 if (!mTeeSinkInputEnabled) { 2276 kind = TEE_SINK_NO; 2277 } else if (!Format_isValid(format)) { 2278 kind = TEE_SINK_NO; 2279 } else if (mRecordTeeSink == 0) { 2280 kind = TEE_SINK_NEW; 2281 } else if (mRecordTeeSink->getStrongCount() != 1) { 2282 kind = TEE_SINK_NO; 2283 } else if (Format_isEqual(format, mRecordTeeSink->format())) { 2284 kind = TEE_SINK_OLD; 2285 } else { 2286 kind = TEE_SINK_NEW; 2287 } 2288 switch (kind) { 2289 case TEE_SINK_NEW: { 2290 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 2291 size_t numCounterOffers = 0; 2292 const NBAIO_Format offers[1] = {format}; 2293 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 2294 ALOG_ASSERT(index == 0); 2295 PipeReader *pipeReader = new PipeReader(*pipe); 2296 numCounterOffers = 0; 2297 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 2298 ALOG_ASSERT(index == 0); 2299 mRecordTeeSink = pipe; 2300 mRecordTeeSource = pipeReader; 2301 teeSink = pipe; 2302 } 2303 break; 2304 case TEE_SINK_OLD: 2305 teeSink = mRecordTeeSink; 2306 break; 2307 case TEE_SINK_NO: 2308 default: 2309 break; 2310 } 2311#endif 2312 2313 // Start record thread 2314 // RecordThread requires both input and output device indication to forward to audio 2315 // pre processing modules 2316 sp<RecordThread> thread = new RecordThread(this, 2317 inputStream, 2318 *input, 2319 primaryOutputDevice_l(), 2320 devices, 2321 mSystemReady 2322#ifdef TEE_SINK 2323 , teeSink 2324#endif 2325 ); 2326 mRecordThreads.add(*input, thread); 2327 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get()); 2328 return thread; 2329 } 2330 } 2331 2332 *input = AUDIO_IO_HANDLE_NONE; 2333 return 0; 2334} 2335 2336status_t AudioFlinger::closeInput(audio_io_handle_t input) 2337{ 2338 return closeInput_nonvirtual(input); 2339} 2340 2341status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 2342{ 2343 // keep strong reference on the record thread so that 2344 // it is not destroyed while exit() is executed 2345 sp<RecordThread> recordThread; 2346 sp<MmapCaptureThread> mmapThread; 2347 { 2348 Mutex::Autolock _l(mLock); 2349 recordThread = checkRecordThread_l(input); 2350 if (recordThread != 0) { 2351 ALOGV("closeInput() %d", input); 2352 2353 // If we still have effect chains, it means that a client still holds a handle 2354 // on at least one effect. We must either move the chain to an existing thread with the 2355 // same session ID or put it aside in case a new record thread is opened for a 2356 // new capture on the same session 2357 sp<EffectChain> chain; 2358 { 2359 Mutex::Autolock _sl(recordThread->mLock); 2360 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l(); 2361 // Note: maximum one chain per record thread 2362 if (effectChains.size() != 0) { 2363 chain = effectChains[0]; 2364 } 2365 } 2366 if (chain != 0) { 2367 // first check if a record thread is already opened with a client on same session. 2368 // This should only happen in case of overlap between one thread tear down and the 2369 // creation of its replacement 2370 size_t i; 2371 for (i = 0; i < mRecordThreads.size(); i++) { 2372 sp<RecordThread> t = mRecordThreads.valueAt(i); 2373 if (t == recordThread) { 2374 continue; 2375 } 2376 if (t->hasAudioSession(chain->sessionId()) != 0) { 2377 Mutex::Autolock _l(t->mLock); 2378 ALOGV("closeInput() found thread %d for effect session %d", 2379 t->id(), chain->sessionId()); 2380 t->addEffectChain_l(chain); 2381 break; 2382 } 2383 } 2384 // put the chain aside if we could not find a record thread with the same session id 2385 if (i == mRecordThreads.size()) { 2386 putOrphanEffectChain_l(chain); 2387 } 2388 } 2389 mRecordThreads.removeItem(input); 2390 } else { 2391 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input); 2392 if (mmapThread == 0) { 2393 return BAD_VALUE; 2394 } 2395 mMmapThreads.removeItem(input); 2396 } 2397 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor(); 2398 ioDesc->mIoHandle = input; 2399 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc); 2400 } 2401 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that 2402 // we have a different lock for notification client 2403 if (recordThread != 0) { 2404 closeInputFinish(recordThread); 2405 } else if (mmapThread != 0) { 2406 mmapThread->exit(); 2407 AudioStreamIn *in = mmapThread->clearInput(); 2408 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 2409 // from now on thread->mInput is NULL 2410 delete in; 2411 } 2412 return NO_ERROR; 2413} 2414 2415void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread) 2416{ 2417 thread->exit(); 2418 AudioStreamIn *in = thread->clearInput(); 2419 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 2420 // from now on thread->mInput is NULL 2421 delete in; 2422} 2423 2424void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread) 2425{ 2426 mRecordThreads.removeItem(thread->mId); 2427 closeInputFinish(thread); 2428} 2429 2430status_t AudioFlinger::invalidateStream(audio_stream_type_t stream) 2431{ 2432 Mutex::Autolock _l(mLock); 2433 ALOGV("invalidateStream() stream %d", stream); 2434 2435 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2436 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2437 thread->invalidateTracks(stream); 2438 } 2439 for (size_t i = 0; i < mMmapThreads.size(); i++) { 2440 mMmapThreads[i]->invalidateTracks(stream); 2441 } 2442 return NO_ERROR; 2443} 2444 2445 2446audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use) 2447{ 2448 // This is a binder API, so a malicious client could pass in a bad parameter. 2449 // Check for that before calling the internal API nextUniqueId(). 2450 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) { 2451 ALOGE("newAudioUniqueId invalid use %d", use); 2452 return AUDIO_UNIQUE_ID_ALLOCATE; 2453 } 2454 return nextUniqueId(use); 2455} 2456 2457void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid) 2458{ 2459 Mutex::Autolock _l(mLock); 2460 pid_t caller = IPCThreadState::self()->getCallingPid(); 2461 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid); 2462 if (pid != -1 && (caller == getpid_cached)) { 2463 caller = pid; 2464 } 2465 2466 { 2467 Mutex::Autolock _cl(mClientLock); 2468 // Ignore requests received from processes not known as notification client. The request 2469 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be 2470 // called from a different pid leaving a stale session reference. Also we don't know how 2471 // to clear this reference if the client process dies. 2472 if (mNotificationClients.indexOfKey(caller) < 0) { 2473 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession); 2474 return; 2475 } 2476 } 2477 2478 size_t num = mAudioSessionRefs.size(); 2479 for (size_t i = 0; i < num; i++) { 2480 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 2481 if (ref->mSessionid == audioSession && ref->mPid == caller) { 2482 ref->mCnt++; 2483 ALOGV(" incremented refcount to %d", ref->mCnt); 2484 return; 2485 } 2486 } 2487 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 2488 ALOGV(" added new entry for %d", audioSession); 2489} 2490 2491void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid) 2492{ 2493 Mutex::Autolock _l(mLock); 2494 pid_t caller = IPCThreadState::self()->getCallingPid(); 2495 ALOGV("releasing %d from %d for %d", audioSession, caller, pid); 2496 if (pid != -1 && (caller == getpid_cached)) { 2497 caller = pid; 2498 } 2499 size_t num = mAudioSessionRefs.size(); 2500 for (size_t i = 0; i < num; i++) { 2501 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 2502 if (ref->mSessionid == audioSession && ref->mPid == caller) { 2503 ref->mCnt--; 2504 ALOGV(" decremented refcount to %d", ref->mCnt); 2505 if (ref->mCnt == 0) { 2506 mAudioSessionRefs.removeAt(i); 2507 delete ref; 2508 purgeStaleEffects_l(); 2509 } 2510 return; 2511 } 2512 } 2513 // If the caller is mediaserver it is likely that the session being released was acquired 2514 // on behalf of a process not in notification clients and we ignore the warning. 2515 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller); 2516} 2517 2518bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession) 2519{ 2520 size_t num = mAudioSessionRefs.size(); 2521 for (size_t i = 0; i < num; i++) { 2522 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 2523 if (ref->mSessionid == audioSession) { 2524 return true; 2525 } 2526 } 2527 return false; 2528} 2529 2530void AudioFlinger::purgeStaleEffects_l() { 2531 2532 ALOGV("purging stale effects"); 2533 2534 Vector< sp<EffectChain> > chains; 2535 2536 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2537 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2538 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2539 sp<EffectChain> ec = t->mEffectChains[j]; 2540 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 2541 chains.push(ec); 2542 } 2543 } 2544 } 2545 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2546 sp<RecordThread> t = mRecordThreads.valueAt(i); 2547 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2548 sp<EffectChain> ec = t->mEffectChains[j]; 2549 chains.push(ec); 2550 } 2551 } 2552 2553 for (size_t i = 0; i < chains.size(); i++) { 2554 sp<EffectChain> ec = chains[i]; 2555 int sessionid = ec->sessionId(); 2556 sp<ThreadBase> t = ec->mThread.promote(); 2557 if (t == 0) { 2558 continue; 2559 } 2560 size_t numsessionrefs = mAudioSessionRefs.size(); 2561 bool found = false; 2562 for (size_t k = 0; k < numsessionrefs; k++) { 2563 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 2564 if (ref->mSessionid == sessionid) { 2565 ALOGV(" session %d still exists for %d with %d refs", 2566 sessionid, ref->mPid, ref->mCnt); 2567 found = true; 2568 break; 2569 } 2570 } 2571 if (!found) { 2572 Mutex::Autolock _l(t->mLock); 2573 // remove all effects from the chain 2574 while (ec->mEffects.size()) { 2575 sp<EffectModule> effect = ec->mEffects[0]; 2576 effect->unPin(); 2577 t->removeEffect_l(effect); 2578 if (effect->purgeHandles()) { 2579 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 2580 } 2581 AudioSystem::unregisterEffect(effect->id()); 2582 } 2583 } 2584 } 2585 return; 2586} 2587 2588// checkThread_l() must be called with AudioFlinger::mLock held 2589AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const 2590{ 2591 ThreadBase *thread = checkMmapThread_l(ioHandle); 2592 if (thread == 0) { 2593 switch (audio_unique_id_get_use(ioHandle)) { 2594 case AUDIO_UNIQUE_ID_USE_OUTPUT: 2595 thread = checkPlaybackThread_l(ioHandle); 2596 break; 2597 case AUDIO_UNIQUE_ID_USE_INPUT: 2598 thread = checkRecordThread_l(ioHandle); 2599 break; 2600 default: 2601 break; 2602 } 2603 } 2604 return thread; 2605} 2606 2607// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2608AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 2609{ 2610 return mPlaybackThreads.valueFor(output).get(); 2611} 2612 2613// checkMixerThread_l() must be called with AudioFlinger::mLock held 2614AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 2615{ 2616 PlaybackThread *thread = checkPlaybackThread_l(output); 2617 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 2618} 2619 2620// checkRecordThread_l() must be called with AudioFlinger::mLock held 2621AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 2622{ 2623 return mRecordThreads.valueFor(input).get(); 2624} 2625 2626// checkMmapThread_l() must be called with AudioFlinger::mLock held 2627AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const 2628{ 2629 return mMmapThreads.valueFor(io).get(); 2630} 2631 2632 2633// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2634AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const 2635{ 2636 VolumeInterface *volumeInterface = (VolumeInterface *)mPlaybackThreads.valueFor(output).get(); 2637 if (volumeInterface == nullptr) { 2638 MmapThread *mmapThread = mMmapThreads.valueFor(output).get(); 2639 if (mmapThread != nullptr) { 2640 if (mmapThread->isOutput()) { 2641 volumeInterface = (VolumeInterface *)mmapThread; 2642 } 2643 } 2644 } 2645 return volumeInterface; 2646} 2647 2648Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const 2649{ 2650 Vector <VolumeInterface *> volumeInterfaces; 2651 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2652 volumeInterfaces.add((VolumeInterface *)mPlaybackThreads.valueAt(i).get()); 2653 } 2654 for (size_t i = 0; i < mMmapThreads.size(); i++) { 2655 if (mMmapThreads.valueAt(i)->isOutput()) { 2656 volumeInterfaces.add((VolumeInterface *)mMmapThreads.valueAt(i).get()); 2657 } 2658 } 2659 return volumeInterfaces; 2660} 2661 2662audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use) 2663{ 2664 // This is the internal API, so it is OK to assert on bad parameter. 2665 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX); 2666 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1; 2667 for (int retry = 0; retry < maxRetries; retry++) { 2668 // The cast allows wraparound from max positive to min negative instead of abort 2669 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use], 2670 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel); 2671 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED); 2672 // allow wrap by skipping 0 and -1 for session ids 2673 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) { 2674 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use); 2675 return (audio_unique_id_t) (base | use); 2676 } 2677 } 2678 // We have no way of recovering from wraparound 2679 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use); 2680 // TODO Use a floor after wraparound. This may need a mutex. 2681} 2682 2683AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 2684{ 2685 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2686 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2687 if(thread->isDuplicating()) { 2688 continue; 2689 } 2690 AudioStreamOut *output = thread->getOutput(); 2691 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 2692 return thread; 2693 } 2694 } 2695 return NULL; 2696} 2697 2698audio_devices_t AudioFlinger::primaryOutputDevice_l() const 2699{ 2700 PlaybackThread *thread = primaryPlaybackThread_l(); 2701 2702 if (thread == NULL) { 2703 return 0; 2704 } 2705 2706 return thread->outDevice(); 2707} 2708 2709AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const 2710{ 2711 size_t minFrameCount = 0; 2712 PlaybackThread *minThread = NULL; 2713 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2714 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2715 if (!thread->isDuplicating()) { 2716 size_t frameCount = thread->frameCountHAL(); 2717 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount || 2718 (frameCount == minFrameCount && thread->hasFastMixer() && 2719 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) { 2720 minFrameCount = frameCount; 2721 minThread = thread; 2722 } 2723 } 2724 } 2725 return minThread; 2726} 2727 2728sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 2729 audio_session_t triggerSession, 2730 audio_session_t listenerSession, 2731 sync_event_callback_t callBack, 2732 const wp<RefBase>& cookie) 2733{ 2734 Mutex::Autolock _l(mLock); 2735 2736 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 2737 status_t playStatus = NAME_NOT_FOUND; 2738 status_t recStatus = NAME_NOT_FOUND; 2739 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2740 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 2741 if (playStatus == NO_ERROR) { 2742 return event; 2743 } 2744 } 2745 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2746 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 2747 if (recStatus == NO_ERROR) { 2748 return event; 2749 } 2750 } 2751 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2752 mPendingSyncEvents.add(event); 2753 } else { 2754 ALOGV("createSyncEvent() invalid event %d", event->type()); 2755 event.clear(); 2756 } 2757 return event; 2758} 2759 2760// ---------------------------------------------------------------------------- 2761// Effect management 2762// ---------------------------------------------------------------------------- 2763 2764sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() { 2765 return mEffectsFactoryHal; 2766} 2767 2768status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2769{ 2770 Mutex::Autolock _l(mLock); 2771 if (mEffectsFactoryHal.get()) { 2772 return mEffectsFactoryHal->queryNumberEffects(numEffects); 2773 } else { 2774 return -ENODEV; 2775 } 2776} 2777 2778status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2779{ 2780 Mutex::Autolock _l(mLock); 2781 if (mEffectsFactoryHal.get()) { 2782 return mEffectsFactoryHal->getDescriptor(index, descriptor); 2783 } else { 2784 return -ENODEV; 2785 } 2786} 2787 2788status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2789 effect_descriptor_t *descriptor) const 2790{ 2791 Mutex::Autolock _l(mLock); 2792 if (mEffectsFactoryHal.get()) { 2793 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor); 2794 } else { 2795 return -ENODEV; 2796 } 2797} 2798 2799 2800sp<IEffect> AudioFlinger::createEffect( 2801 effect_descriptor_t *pDesc, 2802 const sp<IEffectClient>& effectClient, 2803 int32_t priority, 2804 audio_io_handle_t io, 2805 audio_session_t sessionId, 2806 const String16& opPackageName, 2807 pid_t pid, 2808 status_t *status, 2809 int *id, 2810 int *enabled) 2811{ 2812 status_t lStatus = NO_ERROR; 2813 sp<EffectHandle> handle; 2814 effect_descriptor_t desc; 2815 2816 const uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2817 if (pid == -1 || !isTrustedCallingUid(callingUid)) { 2818 const pid_t callingPid = IPCThreadState::self()->getCallingPid(); 2819 ALOGW_IF(pid != -1 && pid != callingPid, 2820 "%s uid %d pid %d tried to pass itself off as pid %d", 2821 __func__, callingUid, callingPid, pid); 2822 pid = callingPid; 2823 } 2824 2825 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p", 2826 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get()); 2827 2828 if (pDesc == NULL) { 2829 lStatus = BAD_VALUE; 2830 goto Exit; 2831 } 2832 2833 // check audio settings permission for global effects 2834 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2835 lStatus = PERMISSION_DENIED; 2836 goto Exit; 2837 } 2838 2839 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2840 // that can only be created by audio policy manager (running in same process) 2841 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2842 lStatus = PERMISSION_DENIED; 2843 goto Exit; 2844 } 2845 2846 if (mEffectsFactoryHal == 0) { 2847 lStatus = NO_INIT; 2848 goto Exit; 2849 } 2850 2851 { 2852 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) { 2853 // if uuid is specified, request effect descriptor 2854 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc); 2855 if (lStatus < 0) { 2856 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2857 goto Exit; 2858 } 2859 } else { 2860 // if uuid is not specified, look for an available implementation 2861 // of the required type in effect factory 2862 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) { 2863 ALOGW("createEffect() no effect type"); 2864 lStatus = BAD_VALUE; 2865 goto Exit; 2866 } 2867 uint32_t numEffects = 0; 2868 effect_descriptor_t d; 2869 d.flags = 0; // prevent compiler warning 2870 bool found = false; 2871 2872 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects); 2873 if (lStatus < 0) { 2874 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2875 goto Exit; 2876 } 2877 for (uint32_t i = 0; i < numEffects; i++) { 2878 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc); 2879 if (lStatus < 0) { 2880 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2881 continue; 2882 } 2883 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2884 // If matching type found save effect descriptor. If the session is 2885 // 0 and the effect is not auxiliary, continue enumeration in case 2886 // an auxiliary version of this effect type is available 2887 found = true; 2888 d = desc; 2889 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2890 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2891 break; 2892 } 2893 } 2894 } 2895 if (!found) { 2896 lStatus = BAD_VALUE; 2897 ALOGW("createEffect() effect not found"); 2898 goto Exit; 2899 } 2900 // For same effect type, chose auxiliary version over insert version if 2901 // connect to output mix (Compliance to OpenSL ES) 2902 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2903 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2904 desc = d; 2905 } 2906 } 2907 2908 // Do not allow auxiliary effects on a session different from 0 (output mix) 2909 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2910 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2911 lStatus = INVALID_OPERATION; 2912 goto Exit; 2913 } 2914 2915 // check recording permission for visualizer 2916 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2917 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) { 2918 lStatus = PERMISSION_DENIED; 2919 goto Exit; 2920 } 2921 2922 // return effect descriptor 2923 *pDesc = desc; 2924 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2925 // if the output returned by getOutputForEffect() is removed before we lock the 2926 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2927 // and we will exit safely 2928 io = AudioSystem::getOutputForEffect(&desc); 2929 ALOGV("createEffect got output %d", io); 2930 } 2931 2932 Mutex::Autolock _l(mLock); 2933 2934 // If output is not specified try to find a matching audio session ID in one of the 2935 // output threads. 2936 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2937 // because of code checking output when entering the function. 2938 // Note: io is never 0 when creating an effect on an input 2939 if (io == AUDIO_IO_HANDLE_NONE) { 2940 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2941 // output must be specified by AudioPolicyManager when using session 2942 // AUDIO_SESSION_OUTPUT_STAGE 2943 lStatus = BAD_VALUE; 2944 goto Exit; 2945 } 2946 // look for the thread where the specified audio session is present 2947 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2948 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2949 io = mPlaybackThreads.keyAt(i); 2950 break; 2951 } 2952 } 2953 if (io == AUDIO_IO_HANDLE_NONE) { 2954 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2955 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2956 io = mRecordThreads.keyAt(i); 2957 break; 2958 } 2959 } 2960 } 2961 if (io == AUDIO_IO_HANDLE_NONE) { 2962 for (size_t i = 0; i < mMmapThreads.size(); i++) { 2963 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2964 io = mMmapThreads.keyAt(i); 2965 break; 2966 } 2967 } 2968 } 2969 // If no output thread contains the requested session ID, default to 2970 // first output. The effect chain will be moved to the correct output 2971 // thread when a track with the same session ID is created 2972 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) { 2973 io = mPlaybackThreads.keyAt(0); 2974 } 2975 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2976 } 2977 ThreadBase *thread = checkRecordThread_l(io); 2978 if (thread == NULL) { 2979 thread = checkPlaybackThread_l(io); 2980 if (thread == NULL) { 2981 thread = checkMmapThread_l(io); 2982 if (thread == NULL) { 2983 ALOGE("createEffect() unknown output thread"); 2984 lStatus = BAD_VALUE; 2985 goto Exit; 2986 } 2987 } 2988 } else { 2989 // Check if one effect chain was awaiting for an effect to be created on this 2990 // session and used it instead of creating a new one. 2991 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId); 2992 if (chain != 0) { 2993 Mutex::Autolock _l(thread->mLock); 2994 thread->addEffectChain_l(chain); 2995 } 2996 } 2997 2998 sp<Client> client = registerPid(pid); 2999 3000 // create effect on selected output thread 3001 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId); 3002 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 3003 &desc, enabled, &lStatus, pinned); 3004 if (handle != 0 && id != NULL) { 3005 *id = handle->id(); 3006 } 3007 if (handle == 0) { 3008 // remove local strong reference to Client with mClientLock held 3009 Mutex::Autolock _cl(mClientLock); 3010 client.clear(); 3011 } 3012 } 3013 3014Exit: 3015 *status = lStatus; 3016 return handle; 3017} 3018 3019status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput, 3020 audio_io_handle_t dstOutput) 3021{ 3022 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 3023 sessionId, srcOutput, dstOutput); 3024 Mutex::Autolock _l(mLock); 3025 if (srcOutput == dstOutput) { 3026 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 3027 return NO_ERROR; 3028 } 3029 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 3030 if (srcThread == NULL) { 3031 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 3032 return BAD_VALUE; 3033 } 3034 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 3035 if (dstThread == NULL) { 3036 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 3037 return BAD_VALUE; 3038 } 3039 3040 Mutex::Autolock _dl(dstThread->mLock); 3041 Mutex::Autolock _sl(srcThread->mLock); 3042 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 3043} 3044 3045// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 3046status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId, 3047 AudioFlinger::PlaybackThread *srcThread, 3048 AudioFlinger::PlaybackThread *dstThread, 3049 bool reRegister) 3050{ 3051 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 3052 sessionId, srcThread, dstThread); 3053 3054 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 3055 if (chain == 0) { 3056 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 3057 sessionId, srcThread); 3058 return INVALID_OPERATION; 3059 } 3060 3061 // Check whether the destination thread and all effects in the chain are compatible 3062 if (!chain->isCompatibleWithThread_l(dstThread)) { 3063 ALOGW("moveEffectChain_l() effect chain failed because" 3064 " destination thread %p is not compatible with effects in the chain", 3065 dstThread); 3066 return INVALID_OPERATION; 3067 } 3068 3069 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 3070 // so that a new chain is created with correct parameters when first effect is added. This is 3071 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 3072 // removed. 3073 srcThread->removeEffectChain_l(chain); 3074 3075 // transfer all effects one by one so that new effect chain is created on new thread with 3076 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 3077 sp<EffectChain> dstChain; 3078 uint32_t strategy = 0; // prevent compiler warning 3079 sp<EffectModule> effect = chain->getEffectFromId_l(0); 3080 Vector< sp<EffectModule> > removed; 3081 status_t status = NO_ERROR; 3082 while (effect != 0) { 3083 srcThread->removeEffect_l(effect); 3084 removed.add(effect); 3085 status = dstThread->addEffect_l(effect); 3086 if (status != NO_ERROR) { 3087 break; 3088 } 3089 // removeEffect_l() has stopped the effect if it was active so it must be restarted 3090 if (effect->state() == EffectModule::ACTIVE || 3091 effect->state() == EffectModule::STOPPING) { 3092 effect->start(); 3093 } 3094 // if the move request is not received from audio policy manager, the effect must be 3095 // re-registered with the new strategy and output 3096 if (dstChain == 0) { 3097 dstChain = effect->chain().promote(); 3098 if (dstChain == 0) { 3099 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 3100 status = NO_INIT; 3101 break; 3102 } 3103 strategy = dstChain->strategy(); 3104 } 3105 if (reRegister) { 3106 AudioSystem::unregisterEffect(effect->id()); 3107 AudioSystem::registerEffect(&effect->desc(), 3108 dstThread->id(), 3109 strategy, 3110 sessionId, 3111 effect->id()); 3112 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 3113 } 3114 effect = chain->getEffectFromId_l(0); 3115 } 3116 3117 if (status != NO_ERROR) { 3118 for (size_t i = 0; i < removed.size(); i++) { 3119 srcThread->addEffect_l(removed[i]); 3120 if (dstChain != 0 && reRegister) { 3121 AudioSystem::unregisterEffect(removed[i]->id()); 3122 AudioSystem::registerEffect(&removed[i]->desc(), 3123 srcThread->id(), 3124 strategy, 3125 sessionId, 3126 removed[i]->id()); 3127 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 3128 } 3129 } 3130 } 3131 3132 return status; 3133} 3134 3135bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 3136{ 3137 if (mGlobalEffectEnableTime != 0 && 3138 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 3139 return true; 3140 } 3141 3142 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 3143 sp<EffectChain> ec = 3144 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 3145 if (ec != 0 && ec->isNonOffloadableEnabled()) { 3146 return true; 3147 } 3148 } 3149 return false; 3150} 3151 3152void AudioFlinger::onNonOffloadableGlobalEffectEnable() 3153{ 3154 Mutex::Autolock _l(mLock); 3155 3156 mGlobalEffectEnableTime = systemTime(); 3157 3158 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 3159 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 3160 if (t->mType == ThreadBase::OFFLOAD) { 3161 t->invalidateTracks(AUDIO_STREAM_MUSIC); 3162 } 3163 } 3164 3165} 3166 3167status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain) 3168{ 3169 audio_session_t session = chain->sessionId(); 3170 ssize_t index = mOrphanEffectChains.indexOfKey(session); 3171 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index); 3172 if (index >= 0) { 3173 ALOGW("putOrphanEffectChain_l chain for session %d already present", session); 3174 return ALREADY_EXISTS; 3175 } 3176 mOrphanEffectChains.add(session, chain); 3177 return NO_ERROR; 3178} 3179 3180sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session) 3181{ 3182 sp<EffectChain> chain; 3183 ssize_t index = mOrphanEffectChains.indexOfKey(session); 3184 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index); 3185 if (index >= 0) { 3186 chain = mOrphanEffectChains.valueAt(index); 3187 mOrphanEffectChains.removeItemsAt(index); 3188 } 3189 return chain; 3190} 3191 3192bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect) 3193{ 3194 Mutex::Autolock _l(mLock); 3195 audio_session_t session = effect->sessionId(); 3196 ssize_t index = mOrphanEffectChains.indexOfKey(session); 3197 ALOGV("updateOrphanEffectChains session %d index %zd", session, index); 3198 if (index >= 0) { 3199 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index); 3200 if (chain->removeEffect_l(effect, true) == 0) { 3201 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index); 3202 mOrphanEffectChains.removeItemsAt(index); 3203 } 3204 return true; 3205 } 3206 return false; 3207} 3208 3209 3210struct Entry { 3211#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21 3212 char mFileName[TEE_MAX_FILENAME]; 3213}; 3214 3215int comparEntry(const void *p1, const void *p2) 3216{ 3217 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName); 3218} 3219 3220#ifdef TEE_SINK 3221void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 3222{ 3223 NBAIO_Source *teeSource = source.get(); 3224 if (teeSource != NULL) { 3225 // .wav rotation 3226 // There is a benign race condition if 2 threads call this simultaneously. 3227 // They would both traverse the directory, but the result would simply be 3228 // failures at unlink() which are ignored. It's also unlikely since 3229 // normally dumpsys is only done by bugreport or from the command line. 3230 char teePath[32+256]; 3231 strcpy(teePath, "/data/misc/audioserver"); 3232 size_t teePathLen = strlen(teePath); 3233 DIR *dir = opendir(teePath); 3234 teePath[teePathLen++] = '/'; 3235 if (dir != NULL) { 3236#define TEE_MAX_SORT 20 // number of entries to sort 3237#define TEE_MAX_KEEP 10 // number of entries to keep 3238 struct Entry entries[TEE_MAX_SORT]; 3239 size_t entryCount = 0; 3240 while (entryCount < TEE_MAX_SORT) { 3241 struct dirent de; 3242 struct dirent *result = NULL; 3243 int rc = readdir_r(dir, &de, &result); 3244 if (rc != 0) { 3245 ALOGW("readdir_r failed %d", rc); 3246 break; 3247 } 3248 if (result == NULL) { 3249 break; 3250 } 3251 if (result != &de) { 3252 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 3253 break; 3254 } 3255 // ignore non .wav file entries 3256 size_t nameLen = strlen(de.d_name); 3257 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME || 3258 strcmp(&de.d_name[nameLen - 4], ".wav")) { 3259 continue; 3260 } 3261 strcpy(entries[entryCount++].mFileName, de.d_name); 3262 } 3263 (void) closedir(dir); 3264 if (entryCount > TEE_MAX_KEEP) { 3265 qsort(entries, entryCount, sizeof(Entry), comparEntry); 3266 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) { 3267 strcpy(&teePath[teePathLen], entries[i].mFileName); 3268 (void) unlink(teePath); 3269 } 3270 } 3271 } else { 3272 if (fd >= 0) { 3273 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath, 3274 strerror(errno)); 3275 } 3276 } 3277 char teeTime[16]; 3278 struct timeval tv; 3279 gettimeofday(&tv, NULL); 3280 struct tm tm; 3281 localtime_r(&tv.tv_sec, &tm); 3282 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 3283 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 3284 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 3285 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 3286 if (teeFd >= 0) { 3287 // FIXME use libsndfile 3288 char wavHeader[44]; 3289 memcpy(wavHeader, 3290 "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", 3291 sizeof(wavHeader)); 3292 NBAIO_Format format = teeSource->format(); 3293 unsigned channelCount = Format_channelCount(format); 3294 uint32_t sampleRate = Format_sampleRate(format); 3295 size_t frameSize = Format_frameSize(format); 3296 wavHeader[22] = channelCount; // number of channels 3297 wavHeader[24] = sampleRate; // sample rate 3298 wavHeader[25] = sampleRate >> 8; 3299 wavHeader[32] = frameSize; // block alignment 3300 wavHeader[33] = frameSize >> 8; 3301 write(teeFd, wavHeader, sizeof(wavHeader)); 3302 size_t total = 0; 3303 bool firstRead = true; 3304#define TEE_SINK_READ 1024 // frames per I/O operation 3305 void *buffer = malloc(TEE_SINK_READ * frameSize); 3306 for (;;) { 3307 size_t count = TEE_SINK_READ; 3308 ssize_t actual = teeSource->read(buffer, count); 3309 bool wasFirstRead = firstRead; 3310 firstRead = false; 3311 if (actual <= 0) { 3312 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 3313 continue; 3314 } 3315 break; 3316 } 3317 ALOG_ASSERT(actual <= (ssize_t)count); 3318 write(teeFd, buffer, actual * frameSize); 3319 total += actual; 3320 } 3321 free(buffer); 3322 lseek(teeFd, (off_t) 4, SEEK_SET); 3323 uint32_t temp = 44 + total * frameSize - 8; 3324 // FIXME not big-endian safe 3325 write(teeFd, &temp, sizeof(temp)); 3326 lseek(teeFd, (off_t) 40, SEEK_SET); 3327 temp = total * frameSize; 3328 // FIXME not big-endian safe 3329 write(teeFd, &temp, sizeof(temp)); 3330 close(teeFd); 3331 if (fd >= 0) { 3332 dprintf(fd, "tee copied to %s\n", teePath); 3333 } 3334 } else { 3335 if (fd >= 0) { 3336 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 3337 } 3338 } 3339 } 3340} 3341#endif 3342 3343// ---------------------------------------------------------------------------- 3344 3345status_t AudioFlinger::onTransact( 3346 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 3347{ 3348 return BnAudioFlinger::onTransact(code, data, reply, flags); 3349} 3350 3351} // namespace android 3352