AudioFlinger.cpp revision c5a17425986b4ce3384e6956762c86018b49c4a0
1/* 2** 3** Copyright 2007, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18 19#define LOG_TAG "AudioFlinger" 20//#define LOG_NDEBUG 0 21 22#include "Configuration.h" 23#include <dirent.h> 24#include <math.h> 25#include <signal.h> 26#include <sys/time.h> 27#include <sys/resource.h> 28 29#include <binder/IPCThreadState.h> 30#include <binder/IServiceManager.h> 31#include <utils/Log.h> 32#include <utils/Trace.h> 33#include <binder/Parcel.h> 34#include <utils/String16.h> 35#include <utils/threads.h> 36#include <utils/Atomic.h> 37 38#include <cutils/bitops.h> 39#include <cutils/properties.h> 40 41#include <system/audio.h> 42#include <hardware/audio.h> 43 44#include "AudioMixer.h" 45#include "AudioFlinger.h" 46#include "ServiceUtilities.h" 47 48#include <media/EffectsFactoryApi.h> 49#include <audio_effects/effect_visualizer.h> 50#include <audio_effects/effect_ns.h> 51#include <audio_effects/effect_aec.h> 52 53#include <audio_utils/primitives.h> 54 55#include <powermanager/PowerManager.h> 56 57#include <common_time/cc_helper.h> 58 59#include <media/IMediaLogService.h> 60 61#include <media/nbaio/Pipe.h> 62#include <media/nbaio/PipeReader.h> 63#include <media/AudioParameter.h> 64#include <private/android_filesystem_config.h> 65 66// ---------------------------------------------------------------------------- 67 68// Note: the following macro is used for extremely verbose logging message. In 69// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 70// 0; but one side effect of this is to turn all LOGV's as well. Some messages 71// are so verbose that we want to suppress them even when we have ALOG_ASSERT 72// turned on. Do not uncomment the #def below unless you really know what you 73// are doing and want to see all of the extremely verbose messages. 74//#define VERY_VERY_VERBOSE_LOGGING 75#ifdef VERY_VERY_VERBOSE_LOGGING 76#define ALOGVV ALOGV 77#else 78#define ALOGVV(a...) do { } while(0) 79#endif 80 81namespace android { 82 83static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 84static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 85 86 87nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 88 89uint32_t AudioFlinger::mScreenState; 90 91#ifdef TEE_SINK 92bool AudioFlinger::mTeeSinkInputEnabled = false; 93bool AudioFlinger::mTeeSinkOutputEnabled = false; 94bool AudioFlinger::mTeeSinkTrackEnabled = false; 95 96size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault; 97size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault; 98size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault; 99#endif 100 101// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off 102// we define a minimum time during which a global effect is considered enabled. 103static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200); 104 105// ---------------------------------------------------------------------------- 106 107const char *formatToString(audio_format_t format) { 108 switch(format) { 109 case AUDIO_FORMAT_PCM_SUB_8_BIT: return "pcm8"; 110 case AUDIO_FORMAT_PCM_SUB_16_BIT: return "pcm16"; 111 case AUDIO_FORMAT_PCM_SUB_32_BIT: return "pcm32"; 112 case AUDIO_FORMAT_PCM_SUB_8_24_BIT: return "pcm8.24"; 113 case AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED: return "pcm24"; 114 case AUDIO_FORMAT_PCM_SUB_FLOAT: return "pcmfloat"; 115 case AUDIO_FORMAT_MP3: return "mp3"; 116 case AUDIO_FORMAT_AMR_NB: return "amr-nb"; 117 case AUDIO_FORMAT_AMR_WB: return "amr-wb"; 118 case AUDIO_FORMAT_AAC: return "aac"; 119 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1"; 120 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2"; 121 case AUDIO_FORMAT_VORBIS: return "vorbis"; 122 default: 123 break; 124 } 125 return "unknown"; 126} 127 128static int load_audio_interface(const char *if_name, audio_hw_device_t **dev) 129{ 130 const hw_module_t *mod; 131 int rc; 132 133 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod); 134 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__, 135 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 136 if (rc) { 137 goto out; 138 } 139 rc = audio_hw_device_open(mod, dev); 140 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__, 141 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 142 if (rc) { 143 goto out; 144 } 145 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) { 146 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version); 147 rc = BAD_VALUE; 148 goto out; 149 } 150 return 0; 151 152out: 153 *dev = NULL; 154 return rc; 155} 156 157// ---------------------------------------------------------------------------- 158 159AudioFlinger::AudioFlinger() 160 : BnAudioFlinger(), 161 mPrimaryHardwareDev(NULL), 162 mHardwareStatus(AUDIO_HW_IDLE), 163 mMasterVolume(1.0f), 164 mMasterMute(false), 165 mNextUniqueId(1), 166 mMode(AUDIO_MODE_INVALID), 167 mBtNrecIsOff(false), 168 mIsLowRamDevice(true), 169 mIsDeviceTypeKnown(false), 170 mGlobalEffectEnableTime(0) 171{ 172 getpid_cached = getpid(); 173 char value[PROPERTY_VALUE_MAX]; 174 bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1); 175 if (doLog) { 176 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters"); 177 } 178#ifdef TEE_SINK 179 (void) property_get("ro.debuggable", value, "0"); 180 int debuggable = atoi(value); 181 int teeEnabled = 0; 182 if (debuggable) { 183 (void) property_get("af.tee", value, "0"); 184 teeEnabled = atoi(value); 185 } 186 // FIXME symbolic constants here 187 if (teeEnabled & 1) { 188 mTeeSinkInputEnabled = true; 189 } 190 if (teeEnabled & 2) { 191 mTeeSinkOutputEnabled = true; 192 } 193 if (teeEnabled & 4) { 194 mTeeSinkTrackEnabled = true; 195 } 196#endif 197} 198 199void AudioFlinger::onFirstRef() 200{ 201 int rc = 0; 202 203 Mutex::Autolock _l(mLock); 204 205 /* TODO: move all this work into an Init() function */ 206 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 207 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 208 uint32_t int_val; 209 if (1 == sscanf(val_str, "%u", &int_val)) { 210 mStandbyTimeInNsecs = milliseconds(int_val); 211 ALOGI("Using %u mSec as standby time.", int_val); 212 } else { 213 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 214 ALOGI("Using default %u mSec as standby time.", 215 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 216 } 217 } 218 219 mMode = AUDIO_MODE_NORMAL; 220} 221 222AudioFlinger::~AudioFlinger() 223{ 224 while (!mRecordThreads.isEmpty()) { 225 // closeInput_nonvirtual() will remove specified entry from mRecordThreads 226 closeInput_nonvirtual(mRecordThreads.keyAt(0)); 227 } 228 while (!mPlaybackThreads.isEmpty()) { 229 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads 230 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0)); 231 } 232 233 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 234 // no mHardwareLock needed, as there are no other references to this 235 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice()); 236 delete mAudioHwDevs.valueAt(i); 237 } 238 239 // Tell media.log service about any old writers that still need to be unregistered 240 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 241 if (binder != 0) { 242 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 243 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 244 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory()); 245 mUnregisteredWriters.pop(); 246 mediaLogService->unregisterWriter(iMemory); 247 } 248 } 249 250} 251 252static const char * const audio_interfaces[] = { 253 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 254 AUDIO_HARDWARE_MODULE_ID_A2DP, 255 AUDIO_HARDWARE_MODULE_ID_USB, 256}; 257#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 258 259AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l( 260 audio_module_handle_t module, 261 audio_devices_t devices) 262{ 263 // if module is 0, the request comes from an old policy manager and we should load 264 // well known modules 265 if (module == 0) { 266 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 267 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 268 loadHwModule_l(audio_interfaces[i]); 269 } 270 // then try to find a module supporting the requested device. 271 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 272 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i); 273 audio_hw_device_t *dev = audioHwDevice->hwDevice(); 274 if ((dev->get_supported_devices != NULL) && 275 (dev->get_supported_devices(dev) & devices) == devices) 276 return audioHwDevice; 277 } 278 } else { 279 // check a match for the requested module handle 280 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module); 281 if (audioHwDevice != NULL) { 282 return audioHwDevice; 283 } 284 } 285 286 return NULL; 287} 288 289void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused) 290{ 291 const size_t SIZE = 256; 292 char buffer[SIZE]; 293 String8 result; 294 295 result.append("Clients:\n"); 296 for (size_t i = 0; i < mClients.size(); ++i) { 297 sp<Client> client = mClients.valueAt(i).promote(); 298 if (client != 0) { 299 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 300 result.append(buffer); 301 } 302 } 303 304 result.append("Notification Clients:\n"); 305 for (size_t i = 0; i < mNotificationClients.size(); ++i) { 306 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i)); 307 result.append(buffer); 308 } 309 310 result.append("Global session refs:\n"); 311 result.append(" session pid count\n"); 312 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 313 AudioSessionRef *r = mAudioSessionRefs[i]; 314 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt); 315 result.append(buffer); 316 } 317 write(fd, result.string(), result.size()); 318} 319 320 321void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused) 322{ 323 const size_t SIZE = 256; 324 char buffer[SIZE]; 325 String8 result; 326 hardware_call_state hardwareStatus = mHardwareStatus; 327 328 snprintf(buffer, SIZE, "Hardware status: %d\n" 329 "Standby Time mSec: %u\n", 330 hardwareStatus, 331 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 332 result.append(buffer); 333 write(fd, result.string(), result.size()); 334} 335 336void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused) 337{ 338 const size_t SIZE = 256; 339 char buffer[SIZE]; 340 String8 result; 341 snprintf(buffer, SIZE, "Permission Denial: " 342 "can't dump AudioFlinger from pid=%d, uid=%d\n", 343 IPCThreadState::self()->getCallingPid(), 344 IPCThreadState::self()->getCallingUid()); 345 result.append(buffer); 346 write(fd, result.string(), result.size()); 347} 348 349bool AudioFlinger::dumpTryLock(Mutex& mutex) 350{ 351 bool locked = false; 352 for (int i = 0; i < kDumpLockRetries; ++i) { 353 if (mutex.tryLock() == NO_ERROR) { 354 locked = true; 355 break; 356 } 357 usleep(kDumpLockSleepUs); 358 } 359 return locked; 360} 361 362status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 363{ 364 if (!dumpAllowed()) { 365 dumpPermissionDenial(fd, args); 366 } else { 367 // get state of hardware lock 368 bool hardwareLocked = dumpTryLock(mHardwareLock); 369 if (!hardwareLocked) { 370 String8 result(kHardwareLockedString); 371 write(fd, result.string(), result.size()); 372 } else { 373 mHardwareLock.unlock(); 374 } 375 376 bool locked = dumpTryLock(mLock); 377 378 // failed to lock - AudioFlinger is probably deadlocked 379 if (!locked) { 380 String8 result(kDeadlockedString); 381 write(fd, result.string(), result.size()); 382 } 383 384 dumpClients(fd, args); 385 dumpInternals(fd, args); 386 387 // dump playback threads 388 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 389 mPlaybackThreads.valueAt(i)->dump(fd, args); 390 } 391 392 // dump record threads 393 for (size_t i = 0; i < mRecordThreads.size(); i++) { 394 mRecordThreads.valueAt(i)->dump(fd, args); 395 } 396 397 // dump all hardware devs 398 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 399 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 400 dev->dump(dev, fd); 401 } 402 403#ifdef TEE_SINK 404 // dump the serially shared record tee sink 405 if (mRecordTeeSource != 0) { 406 dumpTee(fd, mRecordTeeSource); 407 } 408#endif 409 410 if (locked) { 411 mLock.unlock(); 412 } 413 414 // append a copy of media.log here by forwarding fd to it, but don't attempt 415 // to lookup the service if it's not running, as it will block for a second 416 if (mLogMemoryDealer != 0) { 417 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 418 if (binder != 0) { 419 fdprintf(fd, "\nmedia.log:\n"); 420 Vector<String16> args; 421 binder->dump(fd, args); 422 } 423 } 424 } 425 return NO_ERROR; 426} 427 428sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid) 429{ 430 // If pid is already in the mClients wp<> map, then use that entry 431 // (for which promote() is always != 0), otherwise create a new entry and Client. 432 sp<Client> client = mClients.valueFor(pid).promote(); 433 if (client == 0) { 434 client = new Client(this, pid); 435 mClients.add(pid, client); 436 } 437 438 return client; 439} 440 441sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name) 442{ 443 // If there is no memory allocated for logs, return a dummy writer that does nothing 444 if (mLogMemoryDealer == 0) { 445 return new NBLog::Writer(); 446 } 447 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log")); 448 // Similarly if we can't contact the media.log service, also return a dummy writer 449 if (binder == 0) { 450 return new NBLog::Writer(); 451 } 452 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder)); 453 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 454 // If allocation fails, consult the vector of previously unregistered writers 455 // and garbage-collect one or more them until an allocation succeeds 456 if (shared == 0) { 457 Mutex::Autolock _l(mUnregisteredWritersLock); 458 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) { 459 { 460 // Pick the oldest stale writer to garbage-collect 461 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory()); 462 mUnregisteredWriters.removeAt(0); 463 mediaLogService->unregisterWriter(iMemory); 464 // Now the media.log remote reference to IMemory is gone. When our last local 465 // reference to IMemory also drops to zero at end of this block, 466 // the IMemory destructor will deallocate the region from mLogMemoryDealer. 467 } 468 // Re-attempt the allocation 469 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size)); 470 if (shared != 0) { 471 goto success; 472 } 473 } 474 // Even after garbage-collecting all old writers, there is still not enough memory, 475 // so return a dummy writer 476 return new NBLog::Writer(); 477 } 478success: 479 mediaLogService->registerWriter(shared, size, name); 480 return new NBLog::Writer(size, shared); 481} 482 483void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer) 484{ 485 if (writer == 0) { 486 return; 487 } 488 sp<IMemory> iMemory(writer->getIMemory()); 489 if (iMemory == 0) { 490 return; 491 } 492 // Rather than removing the writer immediately, append it to a queue of old writers to 493 // be garbage-collected later. This allows us to continue to view old logs for a while. 494 Mutex::Autolock _l(mUnregisteredWritersLock); 495 mUnregisteredWriters.push(writer); 496} 497 498// IAudioFlinger interface 499 500 501sp<IAudioTrack> AudioFlinger::createTrack( 502 audio_stream_type_t streamType, 503 uint32_t sampleRate, 504 audio_format_t format, 505 audio_channel_mask_t channelMask, 506 size_t *frameCount, 507 IAudioFlinger::track_flags_t *flags, 508 const sp<IMemory>& sharedBuffer, 509 audio_io_handle_t output, 510 pid_t tid, 511 int *sessionId, 512 int clientUid, 513 status_t *status) 514{ 515 sp<PlaybackThread::Track> track; 516 sp<TrackHandle> trackHandle; 517 sp<Client> client; 518 status_t lStatus; 519 int lSessionId; 520 521 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 522 // but if someone uses binder directly they could bypass that and cause us to crash 523 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 524 ALOGE("createTrack() invalid stream type %d", streamType); 525 lStatus = BAD_VALUE; 526 goto Exit; 527 } 528 529 // further sample rate checks are performed by createTrack_l() depending on the thread type 530 if (sampleRate == 0) { 531 ALOGE("createTrack() invalid sample rate %u", sampleRate); 532 lStatus = BAD_VALUE; 533 goto Exit; 534 } 535 536 // further channel mask checks are performed by createTrack_l() depending on the thread type 537 if (!audio_is_output_channel(channelMask)) { 538 ALOGE("createTrack() invalid channel mask %#x", channelMask); 539 lStatus = BAD_VALUE; 540 goto Exit; 541 } 542 543 // client is responsible for conversion of 8-bit PCM to 16-bit PCM, 544 // and we don't yet support 8.24 or 32-bit PCM 545 if (!audio_is_valid_format(format) || 546 (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT)) { 547 ALOGE("createTrack() invalid format %#x", format); 548 lStatus = BAD_VALUE; 549 goto Exit; 550 } 551 552 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) { 553 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()"); 554 lStatus = BAD_VALUE; 555 goto Exit; 556 } 557 558 { 559 Mutex::Autolock _l(mLock); 560 PlaybackThread *thread = checkPlaybackThread_l(output); 561 PlaybackThread *effectThread = NULL; 562 if (thread == NULL) { 563 ALOGE("no playback thread found for output handle %d", output); 564 lStatus = BAD_VALUE; 565 goto Exit; 566 } 567 568 pid_t pid = IPCThreadState::self()->getCallingPid(); 569 client = registerPid_l(pid); 570 571 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 572 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 573 // check if an effect chain with the same session ID is present on another 574 // output thread and move it here. 575 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 576 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 577 if (mPlaybackThreads.keyAt(i) != output) { 578 uint32_t sessions = t->hasAudioSession(*sessionId); 579 if (sessions & PlaybackThread::EFFECT_SESSION) { 580 effectThread = t.get(); 581 break; 582 } 583 } 584 } 585 lSessionId = *sessionId; 586 } else { 587 // if no audio session id is provided, create one here 588 lSessionId = nextUniqueId(); 589 if (sessionId != NULL) { 590 *sessionId = lSessionId; 591 } 592 } 593 ALOGV("createTrack() lSessionId: %d", lSessionId); 594 595 track = thread->createTrack_l(client, streamType, sampleRate, format, 596 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus); 597 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0)); 598 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless 599 600 // move effect chain to this output thread if an effect on same session was waiting 601 // for a track to be created 602 if (lStatus == NO_ERROR && effectThread != NULL) { 603 // no risk of deadlock because AudioFlinger::mLock is held 604 Mutex::Autolock _dl(thread->mLock); 605 Mutex::Autolock _sl(effectThread->mLock); 606 moveEffectChain_l(lSessionId, effectThread, thread, true); 607 } 608 609 // Look for sync events awaiting for a session to be used. 610 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 611 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 612 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 613 if (lStatus == NO_ERROR) { 614 (void) track->setSyncEvent(mPendingSyncEvents[i]); 615 } else { 616 mPendingSyncEvents[i]->cancel(); 617 } 618 mPendingSyncEvents.removeAt(i); 619 i--; 620 } 621 } 622 } 623 624 } 625 626 if (lStatus == NO_ERROR) { 627 trackHandle = new TrackHandle(track); 628 } else { 629 // remove local strong reference to Client before deleting the Track so that the Client 630 // destructor is called by the TrackBase destructor with mLock held 631 client.clear(); 632 track.clear(); 633 } 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) { 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 (uint32_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) { 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 // ioHandle == 0 means the parameters are global to the audio hardware interface 961 if (ioHandle == 0) { 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 == 0) { 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 status_t *status) 1317{ 1318 sp<RecordThread::RecordTrack> recordTrack; 1319 sp<RecordHandle> recordHandle; 1320 sp<Client> client; 1321 status_t lStatus; 1322 RecordThread *thread; 1323 size_t inFrameCount; 1324 int lSessionId; 1325 1326 // check calling permissions 1327 if (!recordingAllowed()) { 1328 ALOGE("openRecord() permission denied: recording not allowed"); 1329 lStatus = PERMISSION_DENIED; 1330 goto Exit; 1331 } 1332 1333 // further sample rate checks are performed by createRecordTrack_l() 1334 if (sampleRate == 0) { 1335 ALOGE("openRecord() invalid sample rate %u", sampleRate); 1336 lStatus = BAD_VALUE; 1337 goto Exit; 1338 } 1339 1340 // we don't yet support anything other than 16-bit PCM 1341 if (!(audio_is_valid_format(format) && 1342 audio_is_linear_pcm(format) && format == AUDIO_FORMAT_PCM_16_BIT)) { 1343 ALOGE("openRecord() invalid format %#x", format); 1344 lStatus = BAD_VALUE; 1345 goto Exit; 1346 } 1347 1348 // further channel mask checks are performed by createRecordTrack_l() 1349 if (!audio_is_input_channel(channelMask)) { 1350 ALOGE("openRecord() invalid channel mask %#x", channelMask); 1351 lStatus = BAD_VALUE; 1352 goto Exit; 1353 } 1354 1355 { 1356 Mutex::Autolock _l(mLock); 1357 thread = checkRecordThread_l(input); 1358 if (thread == NULL) { 1359 ALOGE("openRecord() checkRecordThread_l failed"); 1360 lStatus = BAD_VALUE; 1361 goto Exit; 1362 } 1363 1364 if (deviceRequiresCaptureAudioOutputPermission(thread->inDevice()) 1365 && !captureAudioOutputAllowed()) { 1366 ALOGE("openRecord() permission denied: capture not allowed"); 1367 lStatus = PERMISSION_DENIED; 1368 goto Exit; 1369 } 1370 1371 pid_t pid = IPCThreadState::self()->getCallingPid(); 1372 client = registerPid_l(pid); 1373 1374 // If no audio session id is provided, create one here 1375 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) { 1376 lSessionId = *sessionId; 1377 } else { 1378 lSessionId = nextUniqueId(); 1379 if (sessionId != NULL) { 1380 *sessionId = lSessionId; 1381 } 1382 } 1383 // create new record track. 1384 // The record track uses one track in mHardwareMixerThread by convention. 1385 // TODO: the uid should be passed in as a parameter to openRecord 1386 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 1387 frameCount, lSessionId, 1388 IPCThreadState::self()->getCallingUid(), 1389 flags, tid, &lStatus); 1390 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0)); 1391 } 1392 1393 if (lStatus != NO_ERROR) { 1394 // remove local strong reference to Client before deleting the RecordTrack so that the 1395 // Client destructor is called by the TrackBase destructor with mLock held 1396 client.clear(); 1397 recordTrack.clear(); 1398 goto Exit; 1399 } 1400 1401 // return handle to client 1402 recordHandle = new RecordHandle(recordTrack); 1403 1404Exit: 1405 *status = lStatus; 1406 return recordHandle; 1407} 1408 1409 1410 1411// ---------------------------------------------------------------------------- 1412 1413audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 1414{ 1415 if (!settingsAllowed()) { 1416 return 0; 1417 } 1418 Mutex::Autolock _l(mLock); 1419 return loadHwModule_l(name); 1420} 1421 1422// loadHwModule_l() must be called with AudioFlinger::mLock held 1423audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 1424{ 1425 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 1426 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 1427 ALOGW("loadHwModule() module %s already loaded", name); 1428 return mAudioHwDevs.keyAt(i); 1429 } 1430 } 1431 1432 audio_hw_device_t *dev; 1433 1434 int rc = load_audio_interface(name, &dev); 1435 if (rc) { 1436 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 1437 return 0; 1438 } 1439 1440 mHardwareStatus = AUDIO_HW_INIT; 1441 rc = dev->init_check(dev); 1442 mHardwareStatus = AUDIO_HW_IDLE; 1443 if (rc) { 1444 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 1445 return 0; 1446 } 1447 1448 // Check and cache this HAL's level of support for master mute and master 1449 // volume. If this is the first HAL opened, and it supports the get 1450 // methods, use the initial values provided by the HAL as the current 1451 // master mute and volume settings. 1452 1453 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 1454 { // scope for auto-lock pattern 1455 AutoMutex lock(mHardwareLock); 1456 1457 if (0 == mAudioHwDevs.size()) { 1458 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 1459 if (NULL != dev->get_master_volume) { 1460 float mv; 1461 if (OK == dev->get_master_volume(dev, &mv)) { 1462 mMasterVolume = mv; 1463 } 1464 } 1465 1466 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 1467 if (NULL != dev->get_master_mute) { 1468 bool mm; 1469 if (OK == dev->get_master_mute(dev, &mm)) { 1470 mMasterMute = mm; 1471 } 1472 } 1473 } 1474 1475 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 1476 if ((NULL != dev->set_master_volume) && 1477 (OK == dev->set_master_volume(dev, mMasterVolume))) { 1478 flags = static_cast<AudioHwDevice::Flags>(flags | 1479 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 1480 } 1481 1482 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 1483 if ((NULL != dev->set_master_mute) && 1484 (OK == dev->set_master_mute(dev, mMasterMute))) { 1485 flags = static_cast<AudioHwDevice::Flags>(flags | 1486 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 1487 } 1488 1489 mHardwareStatus = AUDIO_HW_IDLE; 1490 } 1491 1492 audio_module_handle_t handle = nextUniqueId(); 1493 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags)); 1494 1495 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 1496 name, dev->common.module->name, dev->common.module->id, handle); 1497 1498 return handle; 1499 1500} 1501 1502// ---------------------------------------------------------------------------- 1503 1504uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 1505{ 1506 Mutex::Autolock _l(mLock); 1507 PlaybackThread *thread = primaryPlaybackThread_l(); 1508 return thread != NULL ? thread->sampleRate() : 0; 1509} 1510 1511size_t AudioFlinger::getPrimaryOutputFrameCount() 1512{ 1513 Mutex::Autolock _l(mLock); 1514 PlaybackThread *thread = primaryPlaybackThread_l(); 1515 return thread != NULL ? thread->frameCountHAL() : 0; 1516} 1517 1518// ---------------------------------------------------------------------------- 1519 1520status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice) 1521{ 1522 uid_t uid = IPCThreadState::self()->getCallingUid(); 1523 if (uid != AID_SYSTEM) { 1524 return PERMISSION_DENIED; 1525 } 1526 Mutex::Autolock _l(mLock); 1527 if (mIsDeviceTypeKnown) { 1528 return INVALID_OPERATION; 1529 } 1530 mIsLowRamDevice = isLowRamDevice; 1531 mIsDeviceTypeKnown = true; 1532 return NO_ERROR; 1533} 1534 1535// ---------------------------------------------------------------------------- 1536 1537audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 1538 audio_devices_t *pDevices, 1539 uint32_t *pSamplingRate, 1540 audio_format_t *pFormat, 1541 audio_channel_mask_t *pChannelMask, 1542 uint32_t *pLatencyMs, 1543 audio_output_flags_t flags, 1544 const audio_offload_info_t *offloadInfo) 1545{ 1546 struct audio_config config; 1547 memset(&config, 0, sizeof(config)); 1548 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1549 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1550 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1551 if (offloadInfo != NULL) { 1552 config.offload_info = *offloadInfo; 1553 } 1554 1555 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x", 1556 module, 1557 (pDevices != NULL) ? *pDevices : 0, 1558 config.sample_rate, 1559 config.format, 1560 config.channel_mask, 1561 flags); 1562 ALOGV("openOutput(), offloadInfo %p version 0x%04x", 1563 offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version); 1564 1565 if (pDevices == NULL || *pDevices == 0) { 1566 return 0; 1567 } 1568 1569 Mutex::Autolock _l(mLock); 1570 1571 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, *pDevices); 1572 if (outHwDev == NULL) { 1573 return 0; 1574 } 1575 1576 audio_hw_device_t *hwDevHal = outHwDev->hwDevice(); 1577 audio_io_handle_t id = nextUniqueId(); 1578 1579 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 1580 1581 audio_stream_out_t *outStream = NULL; 1582 status_t status = hwDevHal->open_output_stream(hwDevHal, 1583 id, 1584 *pDevices, 1585 (audio_output_flags_t)flags, 1586 &config, 1587 &outStream); 1588 1589 mHardwareStatus = AUDIO_HW_IDLE; 1590 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, " 1591 "Channels %x, status %d", 1592 outStream, 1593 config.sample_rate, 1594 config.format, 1595 config.channel_mask, 1596 status); 1597 1598 if (status == NO_ERROR && outStream != NULL) { 1599 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags); 1600 1601 PlaybackThread *thread; 1602 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1603 thread = new OffloadThread(this, output, id, *pDevices); 1604 ALOGV("openOutput() created offload output: ID %d thread %p", id, thread); 1605 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 1606 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 1607 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 1608 thread = new DirectOutputThread(this, output, id, *pDevices); 1609 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 1610 } else { 1611 thread = new MixerThread(this, output, id, *pDevices); 1612 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 1613 } 1614 mPlaybackThreads.add(id, thread); 1615 1616 if (pSamplingRate != NULL) { 1617 *pSamplingRate = config.sample_rate; 1618 } 1619 if (pFormat != NULL) { 1620 *pFormat = config.format; 1621 } 1622 if (pChannelMask != NULL) { 1623 *pChannelMask = config.channel_mask; 1624 } 1625 if (pLatencyMs != NULL) { 1626 *pLatencyMs = thread->latency(); 1627 } 1628 1629 // notify client processes of the new output creation 1630 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1631 1632 // the first primary output opened designates the primary hw device 1633 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 1634 ALOGI("Using module %d has the primary audio interface", module); 1635 mPrimaryHardwareDev = outHwDev; 1636 1637 AutoMutex lock(mHardwareLock); 1638 mHardwareStatus = AUDIO_HW_SET_MODE; 1639 hwDevHal->set_mode(hwDevHal, mMode); 1640 mHardwareStatus = AUDIO_HW_IDLE; 1641 } 1642 return id; 1643 } 1644 1645 return 0; 1646} 1647 1648audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 1649 audio_io_handle_t output2) 1650{ 1651 Mutex::Autolock _l(mLock); 1652 MixerThread *thread1 = checkMixerThread_l(output1); 1653 MixerThread *thread2 = checkMixerThread_l(output2); 1654 1655 if (thread1 == NULL || thread2 == NULL) { 1656 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 1657 output2); 1658 return 0; 1659 } 1660 1661 audio_io_handle_t id = nextUniqueId(); 1662 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 1663 thread->addOutputTrack(thread2); 1664 mPlaybackThreads.add(id, thread); 1665 // notify client processes of the new output creation 1666 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 1667 return id; 1668} 1669 1670status_t AudioFlinger::closeOutput(audio_io_handle_t output) 1671{ 1672 return closeOutput_nonvirtual(output); 1673} 1674 1675status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 1676{ 1677 // keep strong reference on the playback thread so that 1678 // it is not destroyed while exit() is executed 1679 sp<PlaybackThread> thread; 1680 { 1681 Mutex::Autolock _l(mLock); 1682 thread = checkPlaybackThread_l(output); 1683 if (thread == NULL) { 1684 return BAD_VALUE; 1685 } 1686 1687 ALOGV("closeOutput() %d", output); 1688 1689 if (thread->type() == ThreadBase::MIXER) { 1690 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1691 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 1692 DuplicatingThread *dupThread = 1693 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 1694 dupThread->removeOutputTrack((MixerThread *)thread.get()); 1695 1696 } 1697 } 1698 } 1699 1700 1701 mPlaybackThreads.removeItem(output); 1702 // save all effects to the default thread 1703 if (mPlaybackThreads.size()) { 1704 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0)); 1705 if (dstThread != NULL) { 1706 // audioflinger lock is held here so the acquisition order of thread locks does not 1707 // matter 1708 Mutex::Autolock _dl(dstThread->mLock); 1709 Mutex::Autolock _sl(thread->mLock); 1710 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l(); 1711 for (size_t i = 0; i < effectChains.size(); i ++) { 1712 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true); 1713 } 1714 } 1715 } 1716 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 1717 } 1718 thread->exit(); 1719 // The thread entity (active unit of execution) is no longer running here, 1720 // but the ThreadBase container still exists. 1721 1722 if (thread->type() != ThreadBase::DUPLICATING) { 1723 AudioStreamOut *out = thread->clearOutput(); 1724 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 1725 // from now on thread->mOutput is NULL 1726 out->hwDev()->close_output_stream(out->hwDev(), out->stream); 1727 delete out; 1728 } 1729 return NO_ERROR; 1730} 1731 1732status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 1733{ 1734 Mutex::Autolock _l(mLock); 1735 PlaybackThread *thread = checkPlaybackThread_l(output); 1736 1737 if (thread == NULL) { 1738 return BAD_VALUE; 1739 } 1740 1741 ALOGV("suspendOutput() %d", output); 1742 thread->suspend(); 1743 1744 return NO_ERROR; 1745} 1746 1747status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 1748{ 1749 Mutex::Autolock _l(mLock); 1750 PlaybackThread *thread = checkPlaybackThread_l(output); 1751 1752 if (thread == NULL) { 1753 return BAD_VALUE; 1754 } 1755 1756 ALOGV("restoreOutput() %d", output); 1757 1758 thread->restore(); 1759 1760 return NO_ERROR; 1761} 1762 1763audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 1764 audio_devices_t *pDevices, 1765 uint32_t *pSamplingRate, 1766 audio_format_t *pFormat, 1767 audio_channel_mask_t *pChannelMask) 1768{ 1769 struct audio_config config; 1770 memset(&config, 0, sizeof(config)); 1771 config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0; 1772 config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0; 1773 config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT; 1774 1775 uint32_t reqSamplingRate = config.sample_rate; 1776 audio_format_t reqFormat = config.format; 1777 audio_channel_mask_t reqChannelMask = config.channel_mask; 1778 1779 if (pDevices == NULL || *pDevices == 0) { 1780 return 0; 1781 } 1782 1783 Mutex::Autolock _l(mLock); 1784 1785 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, *pDevices); 1786 if (inHwDev == NULL) { 1787 return 0; 1788 } 1789 1790 audio_hw_device_t *inHwHal = inHwDev->hwDevice(); 1791 audio_io_handle_t id = nextUniqueId(); 1792 1793 audio_stream_in_t *inStream = NULL; 1794 status_t status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, 1795 &inStream); 1796 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %#x, Channels %x, " 1797 "status %d", 1798 inStream, 1799 config.sample_rate, 1800 config.format, 1801 config.channel_mask, 1802 status); 1803 1804 // If the input could not be opened with the requested parameters and we can handle the 1805 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can 1806 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs. 1807 if (status == BAD_VALUE && 1808 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 1809 (config.sample_rate <= 2 * reqSamplingRate) && 1810 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannelMask) <= FCC_2)) { 1811 // FIXME describe the change proposed by HAL (save old values so we can log them here) 1812 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 1813 inStream = NULL; 1814 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 1815 // FIXME log this new status; HAL should not propose any further changes 1816 } 1817 1818 if (status == NO_ERROR && inStream != NULL) { 1819 1820#ifdef TEE_SINK 1821 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 1822 // or (re-)create if current Pipe is idle and does not match the new format 1823 sp<NBAIO_Sink> teeSink; 1824 enum { 1825 TEE_SINK_NO, // don't copy input 1826 TEE_SINK_NEW, // copy input using a new pipe 1827 TEE_SINK_OLD, // copy input using an existing pipe 1828 } kind; 1829 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 1830 popcount(inStream->common.get_channels(&inStream->common))); 1831 if (!mTeeSinkInputEnabled) { 1832 kind = TEE_SINK_NO; 1833 } else if (!Format_isValid(format)) { 1834 kind = TEE_SINK_NO; 1835 } else if (mRecordTeeSink == 0) { 1836 kind = TEE_SINK_NEW; 1837 } else if (mRecordTeeSink->getStrongCount() != 1) { 1838 kind = TEE_SINK_NO; 1839 } else if (Format_isEqual(format, mRecordTeeSink->format())) { 1840 kind = TEE_SINK_OLD; 1841 } else { 1842 kind = TEE_SINK_NEW; 1843 } 1844 switch (kind) { 1845 case TEE_SINK_NEW: { 1846 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format); 1847 size_t numCounterOffers = 0; 1848 const NBAIO_Format offers[1] = {format}; 1849 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 1850 ALOG_ASSERT(index == 0); 1851 PipeReader *pipeReader = new PipeReader(*pipe); 1852 numCounterOffers = 0; 1853 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 1854 ALOG_ASSERT(index == 0); 1855 mRecordTeeSink = pipe; 1856 mRecordTeeSource = pipeReader; 1857 teeSink = pipe; 1858 } 1859 break; 1860 case TEE_SINK_OLD: 1861 teeSink = mRecordTeeSink; 1862 break; 1863 case TEE_SINK_NO: 1864 default: 1865 break; 1866 } 1867#endif 1868 1869 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 1870 1871 // Start record thread 1872 // RecordThread requires both input and output device indication to forward to audio 1873 // pre processing modules 1874 RecordThread *thread = new RecordThread(this, 1875 input, 1876 id, 1877 primaryOutputDevice_l(), 1878 *pDevices 1879#ifdef TEE_SINK 1880 , teeSink 1881#endif 1882 ); 1883 mRecordThreads.add(id, thread); 1884 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 1885 if (pSamplingRate != NULL) { 1886 *pSamplingRate = reqSamplingRate; 1887 } 1888 if (pFormat != NULL) { 1889 *pFormat = config.format; 1890 } 1891 if (pChannelMask != NULL) { 1892 *pChannelMask = reqChannelMask; 1893 } 1894 1895 // notify client processes of the new input creation 1896 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 1897 return id; 1898 } 1899 1900 return 0; 1901} 1902 1903status_t AudioFlinger::closeInput(audio_io_handle_t input) 1904{ 1905 return closeInput_nonvirtual(input); 1906} 1907 1908status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 1909{ 1910 // keep strong reference on the record thread so that 1911 // it is not destroyed while exit() is executed 1912 sp<RecordThread> thread; 1913 { 1914 Mutex::Autolock _l(mLock); 1915 thread = checkRecordThread_l(input); 1916 if (thread == 0) { 1917 return BAD_VALUE; 1918 } 1919 1920 ALOGV("closeInput() %d", input); 1921 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 1922 mRecordThreads.removeItem(input); 1923 } 1924 thread->exit(); 1925 // The thread entity (active unit of execution) is no longer running here, 1926 // but the ThreadBase container still exists. 1927 1928 AudioStreamIn *in = thread->clearInput(); 1929 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 1930 // from now on thread->mInput is NULL 1931 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 1932 delete in; 1933 1934 return NO_ERROR; 1935} 1936 1937status_t AudioFlinger::invalidateStream(audio_stream_type_t stream) 1938{ 1939 Mutex::Autolock _l(mLock); 1940 ALOGV("invalidateStream() stream %d", stream); 1941 1942 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1943 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 1944 thread->invalidateTracks(stream); 1945 } 1946 1947 return NO_ERROR; 1948} 1949 1950 1951int AudioFlinger::newAudioSessionId() 1952{ 1953 return nextUniqueId(); 1954} 1955 1956void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid) 1957{ 1958 Mutex::Autolock _l(mLock); 1959 pid_t caller = IPCThreadState::self()->getCallingPid(); 1960 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid); 1961 if (pid != -1 && (caller == getpid_cached)) { 1962 caller = pid; 1963 } 1964 1965 // Ignore requests received from processes not known as notification client. The request 1966 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be 1967 // called from a different pid leaving a stale session reference. Also we don't know how 1968 // to clear this reference if the client process dies. 1969 if (mNotificationClients.indexOfKey(caller) < 0) { 1970 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession); 1971 return; 1972 } 1973 1974 size_t num = mAudioSessionRefs.size(); 1975 for (size_t i = 0; i< num; i++) { 1976 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 1977 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1978 ref->mCnt++; 1979 ALOGV(" incremented refcount to %d", ref->mCnt); 1980 return; 1981 } 1982 } 1983 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 1984 ALOGV(" added new entry for %d", audioSession); 1985} 1986 1987void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid) 1988{ 1989 Mutex::Autolock _l(mLock); 1990 pid_t caller = IPCThreadState::self()->getCallingPid(); 1991 ALOGV("releasing %d from %d for %d", audioSession, caller, pid); 1992 if (pid != -1 && (caller == getpid_cached)) { 1993 caller = pid; 1994 } 1995 size_t num = mAudioSessionRefs.size(); 1996 for (size_t i = 0; i< num; i++) { 1997 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1998 if (ref->mSessionid == audioSession && ref->mPid == caller) { 1999 ref->mCnt--; 2000 ALOGV(" decremented refcount to %d", ref->mCnt); 2001 if (ref->mCnt == 0) { 2002 mAudioSessionRefs.removeAt(i); 2003 delete ref; 2004 purgeStaleEffects_l(); 2005 } 2006 return; 2007 } 2008 } 2009 // If the caller is mediaserver it is likely that the session being released was acquired 2010 // on behalf of a process not in notification clients and we ignore the warning. 2011 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller); 2012} 2013 2014void AudioFlinger::purgeStaleEffects_l() { 2015 2016 ALOGV("purging stale effects"); 2017 2018 Vector< sp<EffectChain> > chains; 2019 2020 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2021 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2022 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2023 sp<EffectChain> ec = t->mEffectChains[j]; 2024 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 2025 chains.push(ec); 2026 } 2027 } 2028 } 2029 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2030 sp<RecordThread> t = mRecordThreads.valueAt(i); 2031 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 2032 sp<EffectChain> ec = t->mEffectChains[j]; 2033 chains.push(ec); 2034 } 2035 } 2036 2037 for (size_t i = 0; i < chains.size(); i++) { 2038 sp<EffectChain> ec = chains[i]; 2039 int sessionid = ec->sessionId(); 2040 sp<ThreadBase> t = ec->mThread.promote(); 2041 if (t == 0) { 2042 continue; 2043 } 2044 size_t numsessionrefs = mAudioSessionRefs.size(); 2045 bool found = false; 2046 for (size_t k = 0; k < numsessionrefs; k++) { 2047 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 2048 if (ref->mSessionid == sessionid) { 2049 ALOGV(" session %d still exists for %d with %d refs", 2050 sessionid, ref->mPid, ref->mCnt); 2051 found = true; 2052 break; 2053 } 2054 } 2055 if (!found) { 2056 Mutex::Autolock _l(t->mLock); 2057 // remove all effects from the chain 2058 while (ec->mEffects.size()) { 2059 sp<EffectModule> effect = ec->mEffects[0]; 2060 effect->unPin(); 2061 t->removeEffect_l(effect); 2062 if (effect->purgeHandles()) { 2063 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 2064 } 2065 AudioSystem::unregisterEffect(effect->id()); 2066 } 2067 } 2068 } 2069 return; 2070} 2071 2072// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 2073AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 2074{ 2075 return mPlaybackThreads.valueFor(output).get(); 2076} 2077 2078// checkMixerThread_l() must be called with AudioFlinger::mLock held 2079AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 2080{ 2081 PlaybackThread *thread = checkPlaybackThread_l(output); 2082 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 2083} 2084 2085// checkRecordThread_l() must be called with AudioFlinger::mLock held 2086AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 2087{ 2088 return mRecordThreads.valueFor(input).get(); 2089} 2090 2091uint32_t AudioFlinger::nextUniqueId() 2092{ 2093 return android_atomic_inc(&mNextUniqueId); 2094} 2095 2096AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 2097{ 2098 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2099 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 2100 AudioStreamOut *output = thread->getOutput(); 2101 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 2102 return thread; 2103 } 2104 } 2105 return NULL; 2106} 2107 2108audio_devices_t AudioFlinger::primaryOutputDevice_l() const 2109{ 2110 PlaybackThread *thread = primaryPlaybackThread_l(); 2111 2112 if (thread == NULL) { 2113 return 0; 2114 } 2115 2116 return thread->outDevice(); 2117} 2118 2119sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 2120 int triggerSession, 2121 int listenerSession, 2122 sync_event_callback_t callBack, 2123 wp<RefBase> cookie) 2124{ 2125 Mutex::Autolock _l(mLock); 2126 2127 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 2128 status_t playStatus = NAME_NOT_FOUND; 2129 status_t recStatus = NAME_NOT_FOUND; 2130 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2131 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 2132 if (playStatus == NO_ERROR) { 2133 return event; 2134 } 2135 } 2136 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2137 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 2138 if (recStatus == NO_ERROR) { 2139 return event; 2140 } 2141 } 2142 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 2143 mPendingSyncEvents.add(event); 2144 } else { 2145 ALOGV("createSyncEvent() invalid event %d", event->type()); 2146 event.clear(); 2147 } 2148 return event; 2149} 2150 2151// ---------------------------------------------------------------------------- 2152// Effect management 2153// ---------------------------------------------------------------------------- 2154 2155 2156status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 2157{ 2158 Mutex::Autolock _l(mLock); 2159 return EffectQueryNumberEffects(numEffects); 2160} 2161 2162status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 2163{ 2164 Mutex::Autolock _l(mLock); 2165 return EffectQueryEffect(index, descriptor); 2166} 2167 2168status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 2169 effect_descriptor_t *descriptor) const 2170{ 2171 Mutex::Autolock _l(mLock); 2172 return EffectGetDescriptor(pUuid, descriptor); 2173} 2174 2175 2176sp<IEffect> AudioFlinger::createEffect( 2177 effect_descriptor_t *pDesc, 2178 const sp<IEffectClient>& effectClient, 2179 int32_t priority, 2180 audio_io_handle_t io, 2181 int sessionId, 2182 status_t *status, 2183 int *id, 2184 int *enabled) 2185{ 2186 status_t lStatus = NO_ERROR; 2187 sp<EffectHandle> handle; 2188 effect_descriptor_t desc; 2189 2190 pid_t pid = IPCThreadState::self()->getCallingPid(); 2191 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 2192 pid, effectClient.get(), priority, sessionId, io); 2193 2194 if (pDesc == NULL) { 2195 lStatus = BAD_VALUE; 2196 goto Exit; 2197 } 2198 2199 // check audio settings permission for global effects 2200 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 2201 lStatus = PERMISSION_DENIED; 2202 goto Exit; 2203 } 2204 2205 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 2206 // that can only be created by audio policy manager (running in same process) 2207 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 2208 lStatus = PERMISSION_DENIED; 2209 goto Exit; 2210 } 2211 2212 { 2213 if (!EffectIsNullUuid(&pDesc->uuid)) { 2214 // if uuid is specified, request effect descriptor 2215 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 2216 if (lStatus < 0) { 2217 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 2218 goto Exit; 2219 } 2220 } else { 2221 // if uuid is not specified, look for an available implementation 2222 // of the required type in effect factory 2223 if (EffectIsNullUuid(&pDesc->type)) { 2224 ALOGW("createEffect() no effect type"); 2225 lStatus = BAD_VALUE; 2226 goto Exit; 2227 } 2228 uint32_t numEffects = 0; 2229 effect_descriptor_t d; 2230 d.flags = 0; // prevent compiler warning 2231 bool found = false; 2232 2233 lStatus = EffectQueryNumberEffects(&numEffects); 2234 if (lStatus < 0) { 2235 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 2236 goto Exit; 2237 } 2238 for (uint32_t i = 0; i < numEffects; i++) { 2239 lStatus = EffectQueryEffect(i, &desc); 2240 if (lStatus < 0) { 2241 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 2242 continue; 2243 } 2244 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 2245 // If matching type found save effect descriptor. If the session is 2246 // 0 and the effect is not auxiliary, continue enumeration in case 2247 // an auxiliary version of this effect type is available 2248 found = true; 2249 d = desc; 2250 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 2251 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2252 break; 2253 } 2254 } 2255 } 2256 if (!found) { 2257 lStatus = BAD_VALUE; 2258 ALOGW("createEffect() effect not found"); 2259 goto Exit; 2260 } 2261 // For same effect type, chose auxiliary version over insert version if 2262 // connect to output mix (Compliance to OpenSL ES) 2263 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 2264 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 2265 desc = d; 2266 } 2267 } 2268 2269 // Do not allow auxiliary effects on a session different from 0 (output mix) 2270 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 2271 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2272 lStatus = INVALID_OPERATION; 2273 goto Exit; 2274 } 2275 2276 // check recording permission for visualizer 2277 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 2278 !recordingAllowed()) { 2279 lStatus = PERMISSION_DENIED; 2280 goto Exit; 2281 } 2282 2283 // return effect descriptor 2284 *pDesc = desc; 2285 if (io == 0 && sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2286 // if the output returned by getOutputForEffect() is removed before we lock the 2287 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 2288 // and we will exit safely 2289 io = AudioSystem::getOutputForEffect(&desc); 2290 ALOGV("createEffect got output %d", io); 2291 } 2292 2293 Mutex::Autolock _l(mLock); 2294 2295 // If output is not specified try to find a matching audio session ID in one of the 2296 // output threads. 2297 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 2298 // because of code checking output when entering the function. 2299 // Note: io is never 0 when creating an effect on an input 2300 if (io == 0) { 2301 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 2302 // output must be specified by AudioPolicyManager when using session 2303 // AUDIO_SESSION_OUTPUT_STAGE 2304 lStatus = BAD_VALUE; 2305 goto Exit; 2306 } 2307 // look for the thread where the specified audio session is present 2308 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2309 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2310 io = mPlaybackThreads.keyAt(i); 2311 break; 2312 } 2313 } 2314 if (io == 0) { 2315 for (size_t i = 0; i < mRecordThreads.size(); i++) { 2316 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 2317 io = mRecordThreads.keyAt(i); 2318 break; 2319 } 2320 } 2321 } 2322 // If no output thread contains the requested session ID, default to 2323 // first output. The effect chain will be moved to the correct output 2324 // thread when a track with the same session ID is created 2325 if (io == 0 && mPlaybackThreads.size()) { 2326 io = mPlaybackThreads.keyAt(0); 2327 } 2328 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 2329 } 2330 ThreadBase *thread = checkRecordThread_l(io); 2331 if (thread == NULL) { 2332 thread = checkPlaybackThread_l(io); 2333 if (thread == NULL) { 2334 ALOGE("createEffect() unknown output thread"); 2335 lStatus = BAD_VALUE; 2336 goto Exit; 2337 } 2338 } 2339 2340 sp<Client> client = registerPid_l(pid); 2341 2342 // create effect on selected output thread 2343 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 2344 &desc, enabled, &lStatus); 2345 if (handle != 0 && id != NULL) { 2346 *id = handle->id(); 2347 } 2348 } 2349 2350Exit: 2351 *status = lStatus; 2352 return handle; 2353} 2354 2355status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 2356 audio_io_handle_t dstOutput) 2357{ 2358 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 2359 sessionId, srcOutput, dstOutput); 2360 Mutex::Autolock _l(mLock); 2361 if (srcOutput == dstOutput) { 2362 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 2363 return NO_ERROR; 2364 } 2365 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 2366 if (srcThread == NULL) { 2367 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 2368 return BAD_VALUE; 2369 } 2370 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 2371 if (dstThread == NULL) { 2372 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 2373 return BAD_VALUE; 2374 } 2375 2376 Mutex::Autolock _dl(dstThread->mLock); 2377 Mutex::Autolock _sl(srcThread->mLock); 2378 return moveEffectChain_l(sessionId, srcThread, dstThread, false); 2379} 2380 2381// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 2382status_t AudioFlinger::moveEffectChain_l(int sessionId, 2383 AudioFlinger::PlaybackThread *srcThread, 2384 AudioFlinger::PlaybackThread *dstThread, 2385 bool reRegister) 2386{ 2387 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 2388 sessionId, srcThread, dstThread); 2389 2390 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 2391 if (chain == 0) { 2392 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 2393 sessionId, srcThread); 2394 return INVALID_OPERATION; 2395 } 2396 2397 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 2398 // so that a new chain is created with correct parameters when first effect is added. This is 2399 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 2400 // removed. 2401 srcThread->removeEffectChain_l(chain); 2402 2403 // transfer all effects one by one so that new effect chain is created on new thread with 2404 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 2405 sp<EffectChain> dstChain; 2406 uint32_t strategy = 0; // prevent compiler warning 2407 sp<EffectModule> effect = chain->getEffectFromId_l(0); 2408 Vector< sp<EffectModule> > removed; 2409 status_t status = NO_ERROR; 2410 while (effect != 0) { 2411 srcThread->removeEffect_l(effect); 2412 removed.add(effect); 2413 status = dstThread->addEffect_l(effect); 2414 if (status != NO_ERROR) { 2415 break; 2416 } 2417 // removeEffect_l() has stopped the effect if it was active so it must be restarted 2418 if (effect->state() == EffectModule::ACTIVE || 2419 effect->state() == EffectModule::STOPPING) { 2420 effect->start(); 2421 } 2422 // if the move request is not received from audio policy manager, the effect must be 2423 // re-registered with the new strategy and output 2424 if (dstChain == 0) { 2425 dstChain = effect->chain().promote(); 2426 if (dstChain == 0) { 2427 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 2428 status = NO_INIT; 2429 break; 2430 } 2431 strategy = dstChain->strategy(); 2432 } 2433 if (reRegister) { 2434 AudioSystem::unregisterEffect(effect->id()); 2435 AudioSystem::registerEffect(&effect->desc(), 2436 dstThread->id(), 2437 strategy, 2438 sessionId, 2439 effect->id()); 2440 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2441 } 2442 effect = chain->getEffectFromId_l(0); 2443 } 2444 2445 if (status != NO_ERROR) { 2446 for (size_t i = 0; i < removed.size(); i++) { 2447 srcThread->addEffect_l(removed[i]); 2448 if (dstChain != 0 && reRegister) { 2449 AudioSystem::unregisterEffect(removed[i]->id()); 2450 AudioSystem::registerEffect(&removed[i]->desc(), 2451 srcThread->id(), 2452 strategy, 2453 sessionId, 2454 removed[i]->id()); 2455 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled()); 2456 } 2457 } 2458 } 2459 2460 return status; 2461} 2462 2463bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() 2464{ 2465 if (mGlobalEffectEnableTime != 0 && 2466 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) { 2467 return true; 2468 } 2469 2470 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2471 sp<EffectChain> ec = 2472 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2473 if (ec != 0 && ec->isNonOffloadableEnabled()) { 2474 return true; 2475 } 2476 } 2477 return false; 2478} 2479 2480void AudioFlinger::onNonOffloadableGlobalEffectEnable() 2481{ 2482 Mutex::Autolock _l(mLock); 2483 2484 mGlobalEffectEnableTime = systemTime(); 2485 2486 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 2487 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 2488 if (t->mType == ThreadBase::OFFLOAD) { 2489 t->invalidateTracks(AUDIO_STREAM_MUSIC); 2490 } 2491 } 2492 2493} 2494 2495struct Entry { 2496#define MAX_NAME 32 // %Y%m%d%H%M%S_%d.wav 2497 char mName[MAX_NAME]; 2498}; 2499 2500int comparEntry(const void *p1, const void *p2) 2501{ 2502 return strcmp(((const Entry *) p1)->mName, ((const Entry *) p2)->mName); 2503} 2504 2505#ifdef TEE_SINK 2506void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 2507{ 2508 NBAIO_Source *teeSource = source.get(); 2509 if (teeSource != NULL) { 2510 // .wav rotation 2511 // There is a benign race condition if 2 threads call this simultaneously. 2512 // They would both traverse the directory, but the result would simply be 2513 // failures at unlink() which are ignored. It's also unlikely since 2514 // normally dumpsys is only done by bugreport or from the command line. 2515 char teePath[32+256]; 2516 strcpy(teePath, "/data/misc/media"); 2517 size_t teePathLen = strlen(teePath); 2518 DIR *dir = opendir(teePath); 2519 teePath[teePathLen++] = '/'; 2520 if (dir != NULL) { 2521#define MAX_SORT 20 // number of entries to sort 2522#define MAX_KEEP 10 // number of entries to keep 2523 struct Entry entries[MAX_SORT]; 2524 size_t entryCount = 0; 2525 while (entryCount < MAX_SORT) { 2526 struct dirent de; 2527 struct dirent *result = NULL; 2528 int rc = readdir_r(dir, &de, &result); 2529 if (rc != 0) { 2530 ALOGW("readdir_r failed %d", rc); 2531 break; 2532 } 2533 if (result == NULL) { 2534 break; 2535 } 2536 if (result != &de) { 2537 ALOGW("readdir_r returned unexpected result %p != %p", result, &de); 2538 break; 2539 } 2540 // ignore non .wav file entries 2541 size_t nameLen = strlen(de.d_name); 2542 if (nameLen <= 4 || nameLen >= MAX_NAME || 2543 strcmp(&de.d_name[nameLen - 4], ".wav")) { 2544 continue; 2545 } 2546 strcpy(entries[entryCount++].mName, de.d_name); 2547 } 2548 (void) closedir(dir); 2549 if (entryCount > MAX_KEEP) { 2550 qsort(entries, entryCount, sizeof(Entry), comparEntry); 2551 for (size_t i = 0; i < entryCount - MAX_KEEP; ++i) { 2552 strcpy(&teePath[teePathLen], entries[i].mName); 2553 (void) unlink(teePath); 2554 } 2555 } 2556 } else { 2557 if (fd >= 0) { 2558 fdprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno)); 2559 } 2560 } 2561 char teeTime[16]; 2562 struct timeval tv; 2563 gettimeofday(&tv, NULL); 2564 struct tm tm; 2565 localtime_r(&tv.tv_sec, &tm); 2566 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm); 2567 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id); 2568 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd 2569 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR); 2570 if (teeFd >= 0) { 2571 char wavHeader[44]; 2572 memcpy(wavHeader, 2573 "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", 2574 sizeof(wavHeader)); 2575 NBAIO_Format format = teeSource->format(); 2576 unsigned channelCount = Format_channelCount(format); 2577 ALOG_ASSERT(channelCount <= FCC_2); 2578 uint32_t sampleRate = Format_sampleRate(format); 2579 wavHeader[22] = channelCount; // number of channels 2580 wavHeader[24] = sampleRate; // sample rate 2581 wavHeader[25] = sampleRate >> 8; 2582 wavHeader[32] = channelCount * 2; // block alignment 2583 write(teeFd, wavHeader, sizeof(wavHeader)); 2584 size_t total = 0; 2585 bool firstRead = true; 2586 for (;;) { 2587#define TEE_SINK_READ 1024 2588 short buffer[TEE_SINK_READ * FCC_2]; 2589 size_t count = TEE_SINK_READ; 2590 ssize_t actual = teeSource->read(buffer, count, 2591 AudioBufferProvider::kInvalidPTS); 2592 bool wasFirstRead = firstRead; 2593 firstRead = false; 2594 if (actual <= 0) { 2595 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 2596 continue; 2597 } 2598 break; 2599 } 2600 ALOG_ASSERT(actual <= (ssize_t)count); 2601 write(teeFd, buffer, actual * channelCount * sizeof(short)); 2602 total += actual; 2603 } 2604 lseek(teeFd, (off_t) 4, SEEK_SET); 2605 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 2606 write(teeFd, &temp, sizeof(temp)); 2607 lseek(teeFd, (off_t) 40, SEEK_SET); 2608 temp = total * channelCount * sizeof(short); 2609 write(teeFd, &temp, sizeof(temp)); 2610 close(teeFd); 2611 if (fd >= 0) { 2612 fdprintf(fd, "tee copied to %s\n", teePath); 2613 } 2614 } else { 2615 if (fd >= 0) { 2616 fdprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno)); 2617 } 2618 } 2619 } 2620} 2621#endif 2622 2623// ---------------------------------------------------------------------------- 2624 2625status_t AudioFlinger::onTransact( 2626 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2627{ 2628 return BnAudioFlinger::onTransact(code, data, reply, flags); 2629} 2630 2631}; // namespace android 2632