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