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