AudioFlinger.cpp revision d2304db2fcb5112292105a0949a55986a4c9875f
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 String8& name, 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 // client is responsible for conversion of 8-bit PCM to 16-bit PCM, 545 // and we don't yet support 8.24 or 32-bit PCM 546 if (!audio_is_valid_format(format) || 547 (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT)) { 548 ALOGE("createTrack() invalid format %#x", format); 549 lStatus = BAD_VALUE; 550 goto Exit; 551 } 552 553 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) { 554 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()"); 555 lStatus = BAD_VALUE; 556 goto Exit; 557 } 558 559 { 560 Mutex::Autolock _l(mLock); 561 PlaybackThread *thread = checkPlaybackThread_l(output); 562 PlaybackThread *effectThread = NULL; 563 if (thread == NULL) { 564 ALOGE("no playback thread found for output handle %d", output); 565 lStatus = BAD_VALUE; 566 goto Exit; 567 } 568 569 pid_t pid = IPCThreadState::self()->getCallingPid(); 570 571 client = registerPid_l(pid); 572 573 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 574 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 575 // check if an effect chain with the same session ID is present on another 576 // output thread and move it here. 577 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 578 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 579 if (mPlaybackThreads.keyAt(i) != output) { 580 uint32_t sessions = t->hasAudioSession(*sessionId); 581 if (sessions & PlaybackThread::EFFECT_SESSION) { 582 effectThread = t.get(); 583 break; 584 } 585 } 586 } 587 lSessionId = *sessionId; 588 } else { 589 // if no audio session id is provided, create one here 590 lSessionId = nextUniqueId(); 591 if (sessionId != NULL) { 592 *sessionId = lSessionId; 593 } 594 } 595 ALOGV("createTrack() lSessionId: %d", lSessionId); 596 597 track = thread->createTrack_l(client, streamType, sampleRate, format, 598 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus); 599 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0)); 600 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 601 602 // move effect chain to this output thread if an effect on same session was waiting 603 // for a track to be created 604 if (lStatus == NO_ERROR && effectThread != NULL) { 605 // no risk of deadlock because AudioFlinger::mLock is held 606 Mutex::Autolock _dl(thread->mLock); 607 Mutex::Autolock _sl(effectThread->mLock); 608 moveEffectChain_l(lSessionId, effectThread, thread, true); 609 } 610 611 // Look for sync events awaiting for a session to be used. 612 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 613 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 614 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 615 if (lStatus == NO_ERROR) { 616 (void) track->setSyncEvent(mPendingSyncEvents[i]); 617 } else { 618 mPendingSyncEvents[i]->cancel(); 619 } 620 mPendingSyncEvents.removeAt(i); 621 i--; 622 } 623 } 624 } 625 626 } 627 628 if (lStatus == NO_ERROR) { 629 // s for server's pid, n for normal mixer name, f for fast index 630 name = String8::format("s:%d;n:%d;f:%d", getpid_cached, track->name() - AudioMixer::TRACK0, 631 track->fastIndex()); 632 trackHandle = new TrackHandle(track); 633 } else { 634 // remove local strong reference to Client before deleting the Track so that the Client 635 // destructor is called by the TrackBase destructor with mLock held 636 client.clear(); 637 track.clear(); 638 } 639 640Exit: 641 *status = lStatus; 642 return trackHandle; 643} 644 645uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 646{ 647 Mutex::Autolock _l(mLock); 648 PlaybackThread *thread = checkPlaybackThread_l(output); 649 if (thread == NULL) { 650 ALOGW("sampleRate() unknown thread %d", output); 651 return 0; 652 } 653 return thread->sampleRate(); 654} 655 656int AudioFlinger::channelCount(audio_io_handle_t output) const 657{ 658 Mutex::Autolock _l(mLock); 659 PlaybackThread *thread = checkPlaybackThread_l(output); 660 if (thread == NULL) { 661 ALOGW("channelCount() unknown thread %d", output); 662 return 0; 663 } 664 return thread->channelCount(); 665} 666 667audio_format_t AudioFlinger::format(audio_io_handle_t output) const 668{ 669 Mutex::Autolock _l(mLock); 670 PlaybackThread *thread = checkPlaybackThread_l(output); 671 if (thread == NULL) { 672 ALOGW("format() unknown thread %d", output); 673 return AUDIO_FORMAT_INVALID; 674 } 675 return thread->format(); 676} 677 678size_t AudioFlinger::frameCount(audio_io_handle_t output) const 679{ 680 Mutex::Autolock _l(mLock); 681 PlaybackThread *thread = checkPlaybackThread_l(output); 682 if (thread == NULL) { 683 ALOGW("frameCount() unknown thread %d", output); 684 return 0; 685 } 686 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 687 // should examine all callers and fix them to handle smaller counts 688 return thread->frameCount(); 689} 690 691uint32_t AudioFlinger::latency(audio_io_handle_t output) const 692{ 693 Mutex::Autolock _l(mLock); 694 PlaybackThread *thread = checkPlaybackThread_l(output); 695 if (thread == NULL) { 696 ALOGW("latency(): no playback thread found for output handle %d", output); 697 return 0; 698 } 699 return thread->latency(); 700} 701 702status_t AudioFlinger::setMasterVolume(float value) 703{ 704 status_t ret = initCheck(); 705 if (ret != NO_ERROR) { 706 return ret; 707 } 708 709 // check calling permissions 710 if (!settingsAllowed()) { 711 return PERMISSION_DENIED; 712 } 713 714 Mutex::Autolock _l(mLock); 715 mMasterVolume = value; 716 717 // Set master volume in the HALs which support it. 718 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 719 AutoMutex lock(mHardwareLock); 720 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 721 722 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 723 if (dev->canSetMasterVolume()) { 724 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 725 } 726 mHardwareStatus = AUDIO_HW_IDLE; 727 } 728 729 // Now set the master volume in each playback thread. Playback threads 730 // assigned to HALs which do not have master volume support will apply 731 // master volume during the mix operation. Threads with HALs which do 732 // support master volume will simply ignore the setting. 733 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 734 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 735 736 return NO_ERROR; 737} 738 739status_t AudioFlinger::setMode(audio_mode_t mode) 740{ 741 status_t ret = initCheck(); 742 if (ret != NO_ERROR) { 743 return ret; 744 } 745 746 // check calling permissions 747 if (!settingsAllowed()) { 748 return PERMISSION_DENIED; 749 } 750 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 751 ALOGW("Illegal value: setMode(%d)", mode); 752 return BAD_VALUE; 753 } 754 755 { // scope for the lock 756 AutoMutex lock(mHardwareLock); 757 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 758 mHardwareStatus = AUDIO_HW_SET_MODE; 759 ret = dev->set_mode(dev, mode); 760 mHardwareStatus = AUDIO_HW_IDLE; 761 } 762 763 if (NO_ERROR == ret) { 764 Mutex::Autolock _l(mLock); 765 mMode = mode; 766 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 767 mPlaybackThreads.valueAt(i)->setMode(mode); 768 } 769 770 return ret; 771} 772 773status_t AudioFlinger::setMicMute(bool state) 774{ 775 status_t ret = initCheck(); 776 if (ret != NO_ERROR) { 777 return ret; 778 } 779 780 // check calling permissions 781 if (!settingsAllowed()) { 782 return PERMISSION_DENIED; 783 } 784 785 AutoMutex lock(mHardwareLock); 786 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 787 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 788 ret = dev->set_mic_mute(dev, state); 789 mHardwareStatus = AUDIO_HW_IDLE; 790 return ret; 791} 792 793bool AudioFlinger::getMicMute() const 794{ 795 status_t ret = initCheck(); 796 if (ret != NO_ERROR) { 797 return false; 798 } 799 800 bool state = AUDIO_MODE_INVALID; 801 AutoMutex lock(mHardwareLock); 802 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 803 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 804 dev->get_mic_mute(dev, &state); 805 mHardwareStatus = AUDIO_HW_IDLE; 806 return state; 807} 808 809status_t AudioFlinger::setMasterMute(bool muted) 810{ 811 status_t ret = initCheck(); 812 if (ret != NO_ERROR) { 813 return ret; 814 } 815 816 // check calling permissions 817 if (!settingsAllowed()) { 818 return PERMISSION_DENIED; 819 } 820 821 Mutex::Autolock _l(mLock); 822 mMasterMute = muted; 823 824 // Set master mute in the HALs which support it. 825 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 826 AutoMutex lock(mHardwareLock); 827 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 828 829 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 830 if (dev->canSetMasterMute()) { 831 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 832 } 833 mHardwareStatus = AUDIO_HW_IDLE; 834 } 835 836 // Now set the master mute in each playback thread. Playback threads 837 // assigned to HALs which do not have master mute support will apply master 838 // mute during the mix operation. Threads with HALs which do support master 839 // mute will simply ignore the setting. 840 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 841 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 842 843 return NO_ERROR; 844} 845 846float AudioFlinger::masterVolume() const 847{ 848 Mutex::Autolock _l(mLock); 849 return masterVolume_l(); 850} 851 852bool AudioFlinger::masterMute() const 853{ 854 Mutex::Autolock _l(mLock); 855 return masterMute_l(); 856} 857 858float AudioFlinger::masterVolume_l() const 859{ 860 return mMasterVolume; 861} 862 863bool AudioFlinger::masterMute_l() const 864{ 865 return mMasterMute; 866} 867 868status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 869 audio_io_handle_t output) 870{ 871 // check calling permissions 872 if (!settingsAllowed()) { 873 return PERMISSION_DENIED; 874 } 875 876 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 877 ALOGE("setStreamVolume() invalid stream %d", stream); 878 return BAD_VALUE; 879 } 880 881 AutoMutex lock(mLock); 882 PlaybackThread *thread = NULL; 883 if (output) { 884 thread = checkPlaybackThread_l(output); 885 if (thread == NULL) { 886 return BAD_VALUE; 887 } 888 } 889 890 mStreamTypes[stream].volume = value; 891 892 if (thread == NULL) { 893 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 894 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 895 } 896 } else { 897 thread->setStreamVolume(stream, value); 898 } 899 900 return NO_ERROR; 901} 902 903status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 904{ 905 // check calling permissions 906 if (!settingsAllowed()) { 907 return PERMISSION_DENIED; 908 } 909 910 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 911 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 912 ALOGE("setStreamMute() invalid stream %d", stream); 913 return BAD_VALUE; 914 } 915 916 AutoMutex lock(mLock); 917 mStreamTypes[stream].mute = muted; 918 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 919 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 920 921 return NO_ERROR; 922} 923 924float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 925{ 926 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 927 return 0.0f; 928 } 929 930 AutoMutex lock(mLock); 931 float volume; 932 if (output) { 933 PlaybackThread *thread = checkPlaybackThread_l(output); 934 if (thread == NULL) { 935 return 0.0f; 936 } 937 volume = thread->streamVolume(stream); 938 } else { 939 volume = streamVolume_l(stream); 940 } 941 942 return volume; 943} 944 945bool AudioFlinger::streamMute(audio_stream_type_t stream) const 946{ 947 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 948 return true; 949 } 950 951 AutoMutex lock(mLock); 952 return streamMute_l(stream); 953} 954 955status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 956{ 957 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d", 958 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid()); 959 960 // check calling permissions 961 if (!settingsAllowed()) { 962 return PERMISSION_DENIED; 963 } 964 965 // ioHandle == 0 means the parameters are global to the audio hardware interface 966 if (ioHandle == 0) { 967 Mutex::Autolock _l(mLock); 968 status_t final_result = NO_ERROR; 969 { 970 AutoMutex lock(mHardwareLock); 971 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 972 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 973 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 974 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 975 final_result = result ?: final_result; 976 } 977 mHardwareStatus = AUDIO_HW_IDLE; 978 } 979 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 980 AudioParameter param = AudioParameter(keyValuePairs); 981 String8 value; 982 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 983 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 984 if (mBtNrecIsOff != btNrecIsOff) { 985 for (size_t i = 0; i < mRecordThreads.size(); i++) { 986 sp<RecordThread> thread = mRecordThreads.valueAt(i); 987 audio_devices_t device = thread->inDevice(); 988 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 989 // collect all of the thread's session IDs 990 KeyedVector<int, bool> ids = thread->sessionIds(); 991 // suspend effects associated with those session IDs 992 for (size_t j = 0; j < ids.size(); ++j) { 993 int sessionId = ids.keyAt(j); 994 thread->setEffectSuspended(FX_IID_AEC, 995 suspend, 996 sessionId); 997 thread->setEffectSuspended(FX_IID_NS, 998 suspend, 999 sessionId); 1000 } 1001 } 1002 mBtNrecIsOff = btNrecIsOff; 1003 } 1004 } 1005 String8 screenState; 1006 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 1007 bool isOff = screenState == "off"; 1008 if (isOff != (AudioFlinger::mScreenState & 1)) { 1009 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff; 1010 } 1011 } 1012 return final_result; 1013 } 1014 1015 // hold a strong ref on thread in case closeOutput() or closeInput() is called 1016 // and the thread is exited once the lock is released 1017 sp<ThreadBase> thread; 1018 { 1019 Mutex::Autolock _l(mLock); 1020 thread = checkPlaybackThread_l(ioHandle); 1021 if (thread == 0) { 1022 thread = checkRecordThread_l(ioHandle); 1023 } else if (thread == primaryPlaybackThread_l()) { 1024 // indicate output device change to all input threads for pre processing 1025 AudioParameter param = AudioParameter(keyValuePairs); 1026 int value; 1027 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 1028 (value != 0)) { 1029 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1030 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 1031 } 1032 } 1033 } 1034 } 1035 if (thread != 0) { 1036 return thread->setParameters(keyValuePairs); 1037 } 1038 return BAD_VALUE; 1039} 1040 1041String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 1042{ 1043 ALOGVV("getParameters() io %d, keys %s, calling pid %d", 1044 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid()); 1045 1046 Mutex::Autolock _l(mLock); 1047 1048 if (ioHandle == 0) { 1049 String8 out_s8; 1050 1051 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1052 char *s; 1053 { 1054 AutoMutex lock(mHardwareLock); 1055 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 1056 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 1057 s = dev->get_parameters(dev, keys.string()); 1058 mHardwareStatus = AUDIO_HW_IDLE; 1059 } 1060 out_s8 += String8(s ? s : ""); 1061 free(s); 1062 } 1063 return out_s8; 1064 } 1065 1066 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 1067 if (playbackThread != NULL) { 1068 return playbackThread->getParameters(keys); 1069 } 1070 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1071 if (recordThread != NULL) { 1072 return recordThread->getParameters(keys); 1073 } 1074 return String8(""); 1075} 1076 1077size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 1078 audio_channel_mask_t channelMask) const 1079{ 1080 status_t ret = initCheck(); 1081 if (ret != NO_ERROR) { 1082 return 0; 1083 } 1084 1085 AutoMutex lock(mHardwareLock); 1086 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1087 struct audio_config config; 1088 memset(&config, 0, sizeof(config)); 1089 config.sample_rate = sampleRate; 1090 config.channel_mask = channelMask; 1091 config.format = format; 1092 1093 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1094 size_t size = dev->get_input_buffer_size(dev, &config); 1095 mHardwareStatus = AUDIO_HW_IDLE; 1096 return size; 1097} 1098 1099uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1100{ 1101 Mutex::Autolock _l(mLock); 1102 1103 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1104 if (recordThread != NULL) { 1105 return recordThread->getInputFramesLost(); 1106 } 1107 return 0; 1108} 1109 1110status_t AudioFlinger::setVoiceVolume(float value) 1111{ 1112 status_t ret = initCheck(); 1113 if (ret != NO_ERROR) { 1114 return ret; 1115 } 1116 1117 // check calling permissions 1118 if (!settingsAllowed()) { 1119 return PERMISSION_DENIED; 1120 } 1121 1122 AutoMutex lock(mHardwareLock); 1123 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1124 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1125 ret = dev->set_voice_volume(dev, value); 1126 mHardwareStatus = AUDIO_HW_IDLE; 1127 1128 return ret; 1129} 1130 1131status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 1132 audio_io_handle_t output) const 1133{ 1134 status_t status; 1135 1136 Mutex::Autolock _l(mLock); 1137 1138 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1139 if (playbackThread != NULL) { 1140 return playbackThread->getRenderPosition(halFrames, dspFrames); 1141 } 1142 1143 return BAD_VALUE; 1144} 1145 1146void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1147{ 1148 1149 Mutex::Autolock _l(mLock); 1150 1151 pid_t pid = IPCThreadState::self()->getCallingPid(); 1152 if (mNotificationClients.indexOfKey(pid) < 0) { 1153 sp<NotificationClient> notificationClient = new NotificationClient(this, 1154 client, 1155 pid); 1156 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1157 1158 mNotificationClients.add(pid, notificationClient); 1159 1160 sp<IBinder> binder = client->asBinder(); 1161 binder->linkToDeath(notificationClient); 1162 1163 // the config change is always sent from playback or record threads to avoid deadlock 1164 // with AudioSystem::gLock 1165 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1166 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1167 } 1168 1169 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1170 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1171 } 1172 } 1173} 1174 1175void AudioFlinger::removeNotificationClient(pid_t pid) 1176{ 1177 Mutex::Autolock _l(mLock); 1178 1179 mNotificationClients.removeItem(pid); 1180 1181 ALOGV("%d died, releasing its sessions", pid); 1182 size_t num = mAudioSessionRefs.size(); 1183 bool removed = false; 1184 for (size_t i = 0; i< num; ) { 1185 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1186 ALOGV(" pid %d @ %d", ref->mPid, i); 1187 if (ref->mPid == pid) { 1188 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1189 mAudioSessionRefs.removeAt(i); 1190 delete ref; 1191 removed = true; 1192 num--; 1193 } else { 1194 i++; 1195 } 1196 } 1197 if (removed) { 1198 purgeStaleEffects_l(); 1199 } 1200} 1201 1202// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1203void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1204{ 1205 size_t size = mNotificationClients.size(); 1206 for (size_t i = 0; i < size; i++) { 1207 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1208 param2); 1209 } 1210} 1211 1212// removeClient_l() must be called with AudioFlinger::mLock held 1213void AudioFlinger::removeClient_l(pid_t pid) 1214{ 1215 ALOGV("removeClient_l() pid %d, calling pid %d", pid, 1216 IPCThreadState::self()->getCallingPid()); 1217 mClients.removeItem(pid); 1218} 1219 1220// getEffectThread_l() must be called with AudioFlinger::mLock held 1221sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1222{ 1223 sp<PlaybackThread> thread; 1224 1225 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1226 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1227 ALOG_ASSERT(thread == 0); 1228 thread = mPlaybackThreads.valueAt(i); 1229 } 1230 } 1231 1232 return thread; 1233} 1234 1235 1236 1237// ---------------------------------------------------------------------------- 1238 1239AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 1240 : RefBase(), 1241 mAudioFlinger(audioFlinger), 1242 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 1243 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 1244 mPid(pid), 1245 mTimedTrackCount(0) 1246{ 1247 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 1248} 1249 1250// Client destructor must be called with AudioFlinger::mLock held 1251AudioFlinger::Client::~Client() 1252{ 1253 mAudioFlinger->removeClient_l(mPid); 1254} 1255 1256sp<MemoryDealer> AudioFlinger::Client::heap() const 1257{ 1258 return mMemoryDealer; 1259} 1260 1261// Reserve one of the limited slots for a timed audio track associated 1262// with this client 1263bool AudioFlinger::Client::reserveTimedTrack() 1264{ 1265 const int kMaxTimedTracksPerClient = 4; 1266 1267 Mutex::Autolock _l(mTimedTrackLock); 1268 1269 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 1270 ALOGW("can not create timed track - pid %d has exceeded the limit", 1271 mPid); 1272 return false; 1273 } 1274 1275 mTimedTrackCount++; 1276 return true; 1277} 1278 1279// Release a slot for a timed audio track 1280void AudioFlinger::Client::releaseTimedTrack() 1281{ 1282 Mutex::Autolock _l(mTimedTrackLock); 1283 mTimedTrackCount--; 1284} 1285 1286// ---------------------------------------------------------------------------- 1287 1288AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 1289 const sp<IAudioFlingerClient>& client, 1290 pid_t pid) 1291 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 1292{ 1293} 1294 1295AudioFlinger::NotificationClient::~NotificationClient() 1296{ 1297} 1298 1299void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused) 1300{ 1301 sp<NotificationClient> keep(this); 1302 mAudioFlinger->removeNotificationClient(mPid); 1303} 1304 1305 1306// ---------------------------------------------------------------------------- 1307 1308static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) { 1309 return audio_is_remote_submix_device(inDevice); 1310} 1311 1312sp<IAudioRecord> AudioFlinger::openRecord( 1313 audio_io_handle_t input, 1314 uint32_t sampleRate, 1315 audio_format_t format, 1316 audio_channel_mask_t channelMask, 1317 size_t *frameCount, 1318 IAudioFlinger::track_flags_t *flags, 1319 pid_t tid, 1320 int *sessionId, 1321 status_t *status) 1322{ 1323 sp<RecordThread::RecordTrack> recordTrack; 1324 sp<RecordHandle> recordHandle; 1325 sp<Client> client; 1326 status_t lStatus; 1327 RecordThread *thread; 1328 size_t inFrameCount; 1329 int lSessionId; 1330 1331 // check calling permissions 1332 if (!recordingAllowed()) { 1333 ALOGE("openRecord() permission denied: recording not allowed"); 1334 lStatus = PERMISSION_DENIED; 1335 goto Exit; 1336 } 1337 1338 // further sample rate checks are performed by createRecordTrack_l() 1339 if (sampleRate == 0) { 1340 ALOGE("openRecord() invalid sample rate %u", sampleRate); 1341 lStatus = BAD_VALUE; 1342 goto Exit; 1343 } 1344 1345 // FIXME when we support more formats, add audio_is_valid_format(format) 1346 // and any explicit restrictions if audio_is_linear_pcm(format) 1347 if (format != AUDIO_FORMAT_PCM_16_BIT) { 1348 ALOGE("openRecord() invalid format %#x", format); 1349 lStatus = BAD_VALUE; 1350 goto Exit; 1351 } 1352 1353 // further channel mask checks are performed by createRecordTrack_l() 1354 if (!audio_is_input_channel(channelMask)) { 1355 ALOGE("openRecord() invalid channel mask %#x", channelMask); 1356 lStatus = BAD_VALUE; 1357 goto Exit; 1358 } 1359 1360 // add client to list 1361 { // scope for mLock 1362 Mutex::Autolock _l(mLock); 1363 thread = checkRecordThread_l(input); 1364 if (thread == NULL) { 1365 ALOGE("openRecord() checkRecordThread_l failed"); 1366 lStatus = BAD_VALUE; 1367 goto Exit; 1368 } 1369 1370 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice()) 1371 && !captureAudioOutputAllowed()) { 1372 ALOGE("openRecord() permission denied: capture not allowed"); 1373 lStatus = PERMISSION_DENIED; 1374 goto Exit; 1375 } 1376 1377 pid_t pid = IPCThreadState::self()->getCallingPid(); 1378 client = registerPid_l(pid); 1379 1380 // If no audio session id is provided, create one here 1381 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 1382 lSessionId = *sessionId; 1383 } else { 1384 lSessionId = nextUniqueId(); 1385 if (sessionId != NULL) { 1386 *sessionId = lSessionId; 1387 } 1388 } 1389 // create new record track. 1390 // The record track uses one track in mHardwareMixerThread by convention. 1391 // TODO: the uid should be passed in as a parameter to openRecord 1392 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1393 frameCount, lSessionId, 1394 IPCThreadState::self()->getCallingUid(), 1395 flags, tid, &lStatus); 1396 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0)); 1397 } 1398 1399 if (lStatus != NO_ERROR) { 1400 // remove local strong reference to Client before deleting the RecordTrack so that the 1401 // Client destructor is called by the TrackBase destructor with mLock held 1402 client.clear(); 1403 recordTrack.clear(); 1404 goto Exit; 1405 } 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 == 0) { 1572 return 0; 1573 } 1574 1575 Mutex::Autolock _l(mLock); 1576 1577 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, *pDevices); 1578 if (outHwDev == NULL) { 1579 return 0; 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 0; 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 0; 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 == 0) { 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 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 == 0 && 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 == 0) { 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 == 0 && mPlaybackThreads.size()) { 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