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