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