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