AudioFlinger.cpp revision 26c77556efc30800466b60b3975bc35a70c8c28b
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 <math.h> 23#include <signal.h> 24#include <sys/time.h> 25#include <sys/resource.h> 26 27#include <binder/IPCThreadState.h> 28#include <binder/IServiceManager.h> 29#include <utils/Log.h> 30#include <utils/Trace.h> 31#include <binder/Parcel.h> 32#include <binder/IPCThreadState.h> 33#include <utils/String16.h> 34#include <utils/threads.h> 35#include <utils/Atomic.h> 36 37#include <cutils/bitops.h> 38#include <cutils/properties.h> 39#include <cutils/compiler.h> 40 41#undef ADD_BATTERY_DATA 42 43#ifdef ADD_BATTERY_DATA 44#include <media/IMediaPlayerService.h> 45#include <media/IMediaDeathNotifier.h> 46#endif 47 48#include <private/media/AudioTrackShared.h> 49#include <private/media/AudioEffectShared.h> 50 51#include <system/audio.h> 52#include <hardware/audio.h> 53 54#include "AudioMixer.h" 55#include "AudioFlinger.h" 56#include "ServiceUtilities.h" 57 58#include <media/EffectsFactoryApi.h> 59#include <audio_effects/effect_visualizer.h> 60#include <audio_effects/effect_ns.h> 61#include <audio_effects/effect_aec.h> 62 63#include <audio_utils/primitives.h> 64 65#include <powermanager/PowerManager.h> 66 67// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds 68#ifdef DEBUG_CPU_USAGE 69#include <cpustats/CentralTendencyStatistics.h> 70#include <cpustats/ThreadCpuUsage.h> 71#endif 72 73#include <common_time/cc_helper.h> 74#include <common_time/local_clock.h> 75 76#include "FastMixer.h" 77 78// NBAIO implementations 79#include <media/nbaio/AudioStreamOutSink.h> 80#include <media/nbaio/MonoPipe.h> 81#include <media/nbaio/MonoPipeReader.h> 82#include <media/nbaio/Pipe.h> 83#include <media/nbaio/PipeReader.h> 84#include <media/nbaio/SourceAudioBufferProvider.h> 85 86#include "SchedulingPolicyService.h" 87 88// ---------------------------------------------------------------------------- 89 90// Note: the following macro is used for extremely verbose logging message. In 91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 92// 0; but one side effect of this is to turn all LOGV's as well. Some messages 93// are so verbose that we want to suppress them even when we have ALOG_ASSERT 94// turned on. Do not uncomment the #def below unless you really know what you 95// are doing and want to see all of the extremely verbose messages. 96//#define VERY_VERY_VERBOSE_LOGGING 97#ifdef VERY_VERY_VERBOSE_LOGGING 98#define ALOGVV ALOGV 99#else 100#define ALOGVV(a...) do { } while(0) 101#endif 102 103namespace android { 104 105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 106static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 107 108static const float MAX_GAIN = 4096.0f; 109static const uint32_t MAX_GAIN_INT = 0x1000; 110 111// retry counts for buffer fill timeout 112// 50 * ~20msecs = 1 second 113static const int8_t kMaxTrackRetries = 50; 114static const int8_t kMaxTrackStartupRetries = 50; 115// allow less retry attempts on direct output thread. 116// direct outputs can be a scarce resource in audio hardware and should 117// be released as quickly as possible. 118static const int8_t kMaxTrackRetriesDirect = 2; 119 120static const int kDumpLockRetries = 50; 121static const int kDumpLockSleepUs = 20000; 122 123// don't warn about blocked writes or record buffer overflows more often than this 124static const nsecs_t kWarningThrottleNs = seconds(5); 125 126// RecordThread loop sleep time upon application overrun or audio HAL read error 127static const int kRecordThreadSleepUs = 5000; 128 129// maximum time to wait for setParameters to complete 130static const nsecs_t kSetParametersTimeoutNs = seconds(2); 131 132// minimum sleep time for the mixer thread loop when tracks are active but in underrun 133static const uint32_t kMinThreadSleepTimeUs = 5000; 134// maximum divider applied to the active sleep time in the mixer thread loop 135static const uint32_t kMaxThreadSleepTimeShift = 2; 136 137// minimum normal mix buffer size, expressed in milliseconds rather than frames 138static const uint32_t kMinNormalMixBufferSizeMs = 20; 139// maximum normal mix buffer size 140static const uint32_t kMaxNormalMixBufferSizeMs = 24; 141 142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 143 144// Whether to use fast mixer 145static const enum { 146 FastMixer_Never, // never initialize or use: for debugging only 147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 148 // normal mixer multiplier is 1 149 FastMixer_Static, // initialize if needed, then use all the time if initialized, 150 // multiplier is calculated based on min & max normal mixer buffer size 151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 152 // multiplier is calculated based on min & max normal mixer buffer size 153 // FIXME for FastMixer_Dynamic: 154 // Supporting this option will require fixing HALs that can't handle large writes. 155 // For example, one HAL implementation returns an error from a large write, 156 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 157 // We could either fix the HAL implementations, or provide a wrapper that breaks 158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 159} kUseFastMixer = FastMixer_Static; 160 161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off" 162 // AudioFlinger::setParameters() updates, other threads read w/o lock 163 164// Priorities for requestPriority 165static const int kPriorityAudioApp = 2; 166static const int kPriorityFastMixer = 3; 167 168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area 169// for the track. The client then sub-divides this into smaller buffers for its use. 170// Currently the client uses double-buffering by default, but doesn't tell us about that. 171// So for now we just assume that client is double-buffered. 172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or 173// N-buffering, so AudioFlinger could allocate the right amount of memory. 174// See the client's minBufCount and mNotificationFramesAct calculations for details. 175static const int kFastTrackMultiplier = 2; 176 177// ---------------------------------------------------------------------------- 178 179#ifdef ADD_BATTERY_DATA 180// To collect the amplifier usage 181static void addBatteryData(uint32_t params) { 182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 183 if (service == NULL) { 184 // it already logged 185 return; 186 } 187 188 service->addBatteryData(params); 189} 190#endif 191 192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev) 193{ 194 const hw_module_t *mod; 195 int rc; 196 197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod); 198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__, 199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 200 if (rc) { 201 goto out; 202 } 203 rc = audio_hw_device_open(mod, dev); 204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__, 205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 206 if (rc) { 207 goto out; 208 } 209 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) { 210 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version); 211 rc = BAD_VALUE; 212 goto out; 213 } 214 return 0; 215 216out: 217 *dev = NULL; 218 return rc; 219} 220 221// ---------------------------------------------------------------------------- 222 223AudioFlinger::AudioFlinger() 224 : BnAudioFlinger(), 225 mPrimaryHardwareDev(NULL), 226 mHardwareStatus(AUDIO_HW_IDLE), 227 mMasterVolume(1.0f), 228 mMasterMute(false), 229 mNextUniqueId(1), 230 mMode(AUDIO_MODE_INVALID), 231 mBtNrecIsOff(false) 232{ 233} 234 235void AudioFlinger::onFirstRef() 236{ 237 int rc = 0; 238 239 Mutex::Autolock _l(mLock); 240 241 /* TODO: move all this work into an Init() function */ 242 char val_str[PROPERTY_VALUE_MAX] = { 0 }; 243 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) { 244 uint32_t int_val; 245 if (1 == sscanf(val_str, "%u", &int_val)) { 246 mStandbyTimeInNsecs = milliseconds(int_val); 247 ALOGI("Using %u mSec as standby time.", int_val); 248 } else { 249 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs; 250 ALOGI("Using default %u mSec as standby time.", 251 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 252 } 253 } 254 255 mMode = AUDIO_MODE_NORMAL; 256} 257 258AudioFlinger::~AudioFlinger() 259{ 260 while (!mRecordThreads.isEmpty()) { 261 // closeInput_nonvirtual() will remove specified entry from mRecordThreads 262 closeInput_nonvirtual(mRecordThreads.keyAt(0)); 263 } 264 while (!mPlaybackThreads.isEmpty()) { 265 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads 266 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0)); 267 } 268 269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 270 // no mHardwareLock needed, as there are no other references to this 271 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice()); 272 delete mAudioHwDevs.valueAt(i); 273 } 274} 275 276static const char * const audio_interfaces[] = { 277 AUDIO_HARDWARE_MODULE_ID_PRIMARY, 278 AUDIO_HARDWARE_MODULE_ID_A2DP, 279 AUDIO_HARDWARE_MODULE_ID_USB, 280}; 281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 282 283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l( 284 audio_module_handle_t module, 285 audio_devices_t devices) 286{ 287 // if module is 0, the request comes from an old policy manager and we should load 288 // well known modules 289 if (module == 0) { 290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules"); 291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 292 loadHwModule_l(audio_interfaces[i]); 293 } 294 // then try to find a module supporting the requested device. 295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i); 297 audio_hw_device_t *dev = audioHwDevice->hwDevice(); 298 if ((dev->get_supported_devices != NULL) && 299 (dev->get_supported_devices(dev) & devices) == devices) 300 return audioHwDevice; 301 } 302 } else { 303 // check a match for the requested module handle 304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module); 305 if (audioHwDevice != NULL) { 306 return audioHwDevice; 307 } 308 } 309 310 return NULL; 311} 312 313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args) 314{ 315 const size_t SIZE = 256; 316 char buffer[SIZE]; 317 String8 result; 318 319 result.append("Clients:\n"); 320 for (size_t i = 0; i < mClients.size(); ++i) { 321 sp<Client> client = mClients.valueAt(i).promote(); 322 if (client != 0) { 323 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 324 result.append(buffer); 325 } 326 } 327 328 result.append("Global session refs:\n"); 329 result.append(" session pid count\n"); 330 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 331 AudioSessionRef *r = mAudioSessionRefs[i]; 332 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt); 333 result.append(buffer); 334 } 335 write(fd, result.string(), result.size()); 336} 337 338 339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args) 340{ 341 const size_t SIZE = 256; 342 char buffer[SIZE]; 343 String8 result; 344 hardware_call_state hardwareStatus = mHardwareStatus; 345 346 snprintf(buffer, SIZE, "Hardware status: %d\n" 347 "Standby Time mSec: %u\n", 348 hardwareStatus, 349 (uint32_t)(mStandbyTimeInNsecs / 1000000)); 350 result.append(buffer); 351 write(fd, result.string(), result.size()); 352} 353 354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args) 355{ 356 const size_t SIZE = 256; 357 char buffer[SIZE]; 358 String8 result; 359 snprintf(buffer, SIZE, "Permission Denial: " 360 "can't dump AudioFlinger from pid=%d, uid=%d\n", 361 IPCThreadState::self()->getCallingPid(), 362 IPCThreadState::self()->getCallingUid()); 363 result.append(buffer); 364 write(fd, result.string(), result.size()); 365} 366 367static bool tryLock(Mutex& mutex) 368{ 369 bool locked = false; 370 for (int i = 0; i < kDumpLockRetries; ++i) { 371 if (mutex.tryLock() == NO_ERROR) { 372 locked = true; 373 break; 374 } 375 usleep(kDumpLockSleepUs); 376 } 377 return locked; 378} 379 380status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 381{ 382 if (!dumpAllowed()) { 383 dumpPermissionDenial(fd, args); 384 } else { 385 // get state of hardware lock 386 bool hardwareLocked = tryLock(mHardwareLock); 387 if (!hardwareLocked) { 388 String8 result(kHardwareLockedString); 389 write(fd, result.string(), result.size()); 390 } else { 391 mHardwareLock.unlock(); 392 } 393 394 bool locked = tryLock(mLock); 395 396 // failed to lock - AudioFlinger is probably deadlocked 397 if (!locked) { 398 String8 result(kDeadlockedString); 399 write(fd, result.string(), result.size()); 400 } 401 402 dumpClients(fd, args); 403 dumpInternals(fd, args); 404 405 // dump playback threads 406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 407 mPlaybackThreads.valueAt(i)->dump(fd, args); 408 } 409 410 // dump record threads 411 for (size_t i = 0; i < mRecordThreads.size(); i++) { 412 mRecordThreads.valueAt(i)->dump(fd, args); 413 } 414 415 // dump all hardware devs 416 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 417 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 418 dev->dump(dev, fd); 419 } 420 421 // dump the serially shared record tee sink 422 if (mRecordTeeSource != 0) { 423 dumpTee(fd, mRecordTeeSource); 424 } 425 426 if (locked) mLock.unlock(); 427 } 428 return NO_ERROR; 429} 430 431sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid) 432{ 433 // If pid is already in the mClients wp<> map, then use that entry 434 // (for which promote() is always != 0), otherwise create a new entry and Client. 435 sp<Client> client = mClients.valueFor(pid).promote(); 436 if (client == 0) { 437 client = new Client(this, pid); 438 mClients.add(pid, client); 439 } 440 441 return client; 442} 443 444// IAudioFlinger interface 445 446 447sp<IAudioTrack> AudioFlinger::createTrack( 448 pid_t pid, 449 audio_stream_type_t streamType, 450 uint32_t sampleRate, 451 audio_format_t format, 452 audio_channel_mask_t channelMask, 453 size_t frameCount, 454 IAudioFlinger::track_flags_t *flags, 455 const sp<IMemory>& sharedBuffer, 456 audio_io_handle_t output, 457 pid_t tid, 458 int *sessionId, 459 status_t *status) 460{ 461 sp<PlaybackThread::Track> track; 462 sp<TrackHandle> trackHandle; 463 sp<Client> client; 464 status_t lStatus; 465 int lSessionId; 466 467 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 468 // but if someone uses binder directly they could bypass that and cause us to crash 469 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 470 ALOGE("createTrack() invalid stream type %d", streamType); 471 lStatus = BAD_VALUE; 472 goto Exit; 473 } 474 475 // client is responsible for conversion of 8-bit PCM to 16-bit PCM, 476 // and we don't yet support 8.24 or 32-bit PCM 477 if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) { 478 ALOGE("createTrack() invalid format %d", format); 479 lStatus = BAD_VALUE; 480 goto Exit; 481 } 482 483 { 484 Mutex::Autolock _l(mLock); 485 PlaybackThread *thread = checkPlaybackThread_l(output); 486 PlaybackThread *effectThread = NULL; 487 if (thread == NULL) { 488 ALOGE("unknown output thread"); 489 lStatus = BAD_VALUE; 490 goto Exit; 491 } 492 493 client = registerPid_l(pid); 494 495 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 496 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 497 // check if an effect chain with the same session ID is present on another 498 // output thread and move it here. 499 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 500 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 501 if (mPlaybackThreads.keyAt(i) != output) { 502 uint32_t sessions = t->hasAudioSession(*sessionId); 503 if (sessions & PlaybackThread::EFFECT_SESSION) { 504 effectThread = t.get(); 505 break; 506 } 507 } 508 } 509 lSessionId = *sessionId; 510 } else { 511 // if no audio session id is provided, create one here 512 lSessionId = nextUniqueId(); 513 if (sessionId != NULL) { 514 *sessionId = lSessionId; 515 } 516 } 517 ALOGV("createTrack() lSessionId: %d", lSessionId); 518 519 track = thread->createTrack_l(client, streamType, sampleRate, format, 520 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus); 521 522 // move effect chain to this output thread if an effect on same session was waiting 523 // for a track to be created 524 if (lStatus == NO_ERROR && effectThread != NULL) { 525 Mutex::Autolock _dl(thread->mLock); 526 Mutex::Autolock _sl(effectThread->mLock); 527 moveEffectChain_l(lSessionId, effectThread, thread, true); 528 } 529 530 // Look for sync events awaiting for a session to be used. 531 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) { 532 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) { 533 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) { 534 if (lStatus == NO_ERROR) { 535 (void) track->setSyncEvent(mPendingSyncEvents[i]); 536 } else { 537 mPendingSyncEvents[i]->cancel(); 538 } 539 mPendingSyncEvents.removeAt(i); 540 i--; 541 } 542 } 543 } 544 } 545 if (lStatus == NO_ERROR) { 546 trackHandle = new TrackHandle(track); 547 } else { 548 // remove local strong reference to Client before deleting the Track so that the Client 549 // destructor is called by the TrackBase destructor with mLock held 550 client.clear(); 551 track.clear(); 552 } 553 554Exit: 555 if (status != NULL) { 556 *status = lStatus; 557 } 558 return trackHandle; 559} 560 561uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 562{ 563 Mutex::Autolock _l(mLock); 564 PlaybackThread *thread = checkPlaybackThread_l(output); 565 if (thread == NULL) { 566 ALOGW("sampleRate() unknown thread %d", output); 567 return 0; 568 } 569 return thread->sampleRate(); 570} 571 572int AudioFlinger::channelCount(audio_io_handle_t output) const 573{ 574 Mutex::Autolock _l(mLock); 575 PlaybackThread *thread = checkPlaybackThread_l(output); 576 if (thread == NULL) { 577 ALOGW("channelCount() unknown thread %d", output); 578 return 0; 579 } 580 return thread->channelCount(); 581} 582 583audio_format_t AudioFlinger::format(audio_io_handle_t output) const 584{ 585 Mutex::Autolock _l(mLock); 586 PlaybackThread *thread = checkPlaybackThread_l(output); 587 if (thread == NULL) { 588 ALOGW("format() unknown thread %d", output); 589 return AUDIO_FORMAT_INVALID; 590 } 591 return thread->format(); 592} 593 594size_t AudioFlinger::frameCount(audio_io_handle_t output) const 595{ 596 Mutex::Autolock _l(mLock); 597 PlaybackThread *thread = checkPlaybackThread_l(output); 598 if (thread == NULL) { 599 ALOGW("frameCount() unknown thread %d", output); 600 return 0; 601 } 602 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers; 603 // should examine all callers and fix them to handle smaller counts 604 return thread->frameCount(); 605} 606 607uint32_t AudioFlinger::latency(audio_io_handle_t output) const 608{ 609 Mutex::Autolock _l(mLock); 610 PlaybackThread *thread = checkPlaybackThread_l(output); 611 if (thread == NULL) { 612 ALOGW("latency() unknown thread %d", output); 613 return 0; 614 } 615 return thread->latency(); 616} 617 618status_t AudioFlinger::setMasterVolume(float value) 619{ 620 status_t ret = initCheck(); 621 if (ret != NO_ERROR) { 622 return ret; 623 } 624 625 // check calling permissions 626 if (!settingsAllowed()) { 627 return PERMISSION_DENIED; 628 } 629 630 Mutex::Autolock _l(mLock); 631 mMasterVolume = value; 632 633 // Set master volume in the HALs which support it. 634 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 635 AutoMutex lock(mHardwareLock); 636 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 637 638 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 639 if (dev->canSetMasterVolume()) { 640 dev->hwDevice()->set_master_volume(dev->hwDevice(), value); 641 } 642 mHardwareStatus = AUDIO_HW_IDLE; 643 } 644 645 // Now set the master volume in each playback thread. Playback threads 646 // assigned to HALs which do not have master volume support will apply 647 // master volume during the mix operation. Threads with HALs which do 648 // support master volume will simply ignore the setting. 649 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 650 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 651 652 return NO_ERROR; 653} 654 655status_t AudioFlinger::setMode(audio_mode_t mode) 656{ 657 status_t ret = initCheck(); 658 if (ret != NO_ERROR) { 659 return ret; 660 } 661 662 // check calling permissions 663 if (!settingsAllowed()) { 664 return PERMISSION_DENIED; 665 } 666 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 667 ALOGW("Illegal value: setMode(%d)", mode); 668 return BAD_VALUE; 669 } 670 671 { // scope for the lock 672 AutoMutex lock(mHardwareLock); 673 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 674 mHardwareStatus = AUDIO_HW_SET_MODE; 675 ret = dev->set_mode(dev, mode); 676 mHardwareStatus = AUDIO_HW_IDLE; 677 } 678 679 if (NO_ERROR == ret) { 680 Mutex::Autolock _l(mLock); 681 mMode = mode; 682 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 683 mPlaybackThreads.valueAt(i)->setMode(mode); 684 } 685 686 return ret; 687} 688 689status_t AudioFlinger::setMicMute(bool state) 690{ 691 status_t ret = initCheck(); 692 if (ret != NO_ERROR) { 693 return ret; 694 } 695 696 // check calling permissions 697 if (!settingsAllowed()) { 698 return PERMISSION_DENIED; 699 } 700 701 AutoMutex lock(mHardwareLock); 702 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 703 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 704 ret = dev->set_mic_mute(dev, state); 705 mHardwareStatus = AUDIO_HW_IDLE; 706 return ret; 707} 708 709bool AudioFlinger::getMicMute() const 710{ 711 status_t ret = initCheck(); 712 if (ret != NO_ERROR) { 713 return false; 714 } 715 716 bool state = AUDIO_MODE_INVALID; 717 AutoMutex lock(mHardwareLock); 718 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 719 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 720 dev->get_mic_mute(dev, &state); 721 mHardwareStatus = AUDIO_HW_IDLE; 722 return state; 723} 724 725status_t AudioFlinger::setMasterMute(bool muted) 726{ 727 status_t ret = initCheck(); 728 if (ret != NO_ERROR) { 729 return ret; 730 } 731 732 // check calling permissions 733 if (!settingsAllowed()) { 734 return PERMISSION_DENIED; 735 } 736 737 Mutex::Autolock _l(mLock); 738 mMasterMute = muted; 739 740 // Set master mute in the HALs which support it. 741 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 742 AutoMutex lock(mHardwareLock); 743 AudioHwDevice *dev = mAudioHwDevs.valueAt(i); 744 745 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 746 if (dev->canSetMasterMute()) { 747 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted); 748 } 749 mHardwareStatus = AUDIO_HW_IDLE; 750 } 751 752 // Now set the master mute in each playback thread. Playback threads 753 // assigned to HALs which do not have master mute support will apply master 754 // mute during the mix operation. Threads with HALs which do support master 755 // mute will simply ignore the setting. 756 for (size_t i = 0; i < mPlaybackThreads.size(); i++) 757 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 758 759 return NO_ERROR; 760} 761 762float AudioFlinger::masterVolume() const 763{ 764 Mutex::Autolock _l(mLock); 765 return masterVolume_l(); 766} 767 768bool AudioFlinger::masterMute() const 769{ 770 Mutex::Autolock _l(mLock); 771 return masterMute_l(); 772} 773 774float AudioFlinger::masterVolume_l() const 775{ 776 return mMasterVolume; 777} 778 779bool AudioFlinger::masterMute_l() const 780{ 781 return mMasterMute; 782} 783 784status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 785 audio_io_handle_t output) 786{ 787 // check calling permissions 788 if (!settingsAllowed()) { 789 return PERMISSION_DENIED; 790 } 791 792 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 793 ALOGE("setStreamVolume() invalid stream %d", stream); 794 return BAD_VALUE; 795 } 796 797 AutoMutex lock(mLock); 798 PlaybackThread *thread = NULL; 799 if (output) { 800 thread = checkPlaybackThread_l(output); 801 if (thread == NULL) { 802 return BAD_VALUE; 803 } 804 } 805 806 mStreamTypes[stream].volume = value; 807 808 if (thread == NULL) { 809 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 810 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 811 } 812 } else { 813 thread->setStreamVolume(stream, value); 814 } 815 816 return NO_ERROR; 817} 818 819status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 820{ 821 // check calling permissions 822 if (!settingsAllowed()) { 823 return PERMISSION_DENIED; 824 } 825 826 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 827 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 828 ALOGE("setStreamMute() invalid stream %d", stream); 829 return BAD_VALUE; 830 } 831 832 AutoMutex lock(mLock); 833 mStreamTypes[stream].mute = muted; 834 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 835 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 836 837 return NO_ERROR; 838} 839 840float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 841{ 842 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 843 return 0.0f; 844 } 845 846 AutoMutex lock(mLock); 847 float volume; 848 if (output) { 849 PlaybackThread *thread = checkPlaybackThread_l(output); 850 if (thread == NULL) { 851 return 0.0f; 852 } 853 volume = thread->streamVolume(stream); 854 } else { 855 volume = streamVolume_l(stream); 856 } 857 858 return volume; 859} 860 861bool AudioFlinger::streamMute(audio_stream_type_t stream) const 862{ 863 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 864 return true; 865 } 866 867 AutoMutex lock(mLock); 868 return streamMute_l(stream); 869} 870 871status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 872{ 873 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d", 874 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid()); 875 // check calling permissions 876 if (!settingsAllowed()) { 877 return PERMISSION_DENIED; 878 } 879 880 // ioHandle == 0 means the parameters are global to the audio hardware interface 881 if (ioHandle == 0) { 882 Mutex::Autolock _l(mLock); 883 status_t final_result = NO_ERROR; 884 { 885 AutoMutex lock(mHardwareLock); 886 mHardwareStatus = AUDIO_HW_SET_PARAMETER; 887 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 888 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 889 status_t result = dev->set_parameters(dev, keyValuePairs.string()); 890 final_result = result ?: final_result; 891 } 892 mHardwareStatus = AUDIO_HW_IDLE; 893 } 894 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 895 AudioParameter param = AudioParameter(keyValuePairs); 896 String8 value; 897 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 898 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 899 if (mBtNrecIsOff != btNrecIsOff) { 900 for (size_t i = 0; i < mRecordThreads.size(); i++) { 901 sp<RecordThread> thread = mRecordThreads.valueAt(i); 902 audio_devices_t device = thread->inDevice(); 903 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 904 // collect all of the thread's session IDs 905 KeyedVector<int, bool> ids = thread->sessionIds(); 906 // suspend effects associated with those session IDs 907 for (size_t j = 0; j < ids.size(); ++j) { 908 int sessionId = ids.keyAt(j); 909 thread->setEffectSuspended(FX_IID_AEC, 910 suspend, 911 sessionId); 912 thread->setEffectSuspended(FX_IID_NS, 913 suspend, 914 sessionId); 915 } 916 } 917 mBtNrecIsOff = btNrecIsOff; 918 } 919 } 920 String8 screenState; 921 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) { 922 bool isOff = screenState == "off"; 923 if (isOff != (gScreenState & 1)) { 924 gScreenState = ((gScreenState & ~1) + 2) | isOff; 925 } 926 } 927 return final_result; 928 } 929 930 // hold a strong ref on thread in case closeOutput() or closeInput() is called 931 // and the thread is exited once the lock is released 932 sp<ThreadBase> thread; 933 { 934 Mutex::Autolock _l(mLock); 935 thread = checkPlaybackThread_l(ioHandle); 936 if (thread == 0) { 937 thread = checkRecordThread_l(ioHandle); 938 } else if (thread == primaryPlaybackThread_l()) { 939 // indicate output device change to all input threads for pre processing 940 AudioParameter param = AudioParameter(keyValuePairs); 941 int value; 942 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) && 943 (value != 0)) { 944 for (size_t i = 0; i < mRecordThreads.size(); i++) { 945 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 946 } 947 } 948 } 949 } 950 if (thread != 0) { 951 return thread->setParameters(keyValuePairs); 952 } 953 return BAD_VALUE; 954} 955 956String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 957{ 958 ALOGVV("getParameters() io %d, keys %s, tid %d, calling pid %d", 959 ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid()); 960 961 Mutex::Autolock _l(mLock); 962 963 if (ioHandle == 0) { 964 String8 out_s8; 965 966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 967 char *s; 968 { 969 AutoMutex lock(mHardwareLock); 970 mHardwareStatus = AUDIO_HW_GET_PARAMETER; 971 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice(); 972 s = dev->get_parameters(dev, keys.string()); 973 mHardwareStatus = AUDIO_HW_IDLE; 974 } 975 out_s8 += String8(s ? s : ""); 976 free(s); 977 } 978 return out_s8; 979 } 980 981 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 982 if (playbackThread != NULL) { 983 return playbackThread->getParameters(keys); 984 } 985 RecordThread *recordThread = checkRecordThread_l(ioHandle); 986 if (recordThread != NULL) { 987 return recordThread->getParameters(keys); 988 } 989 return String8(""); 990} 991 992size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, 993 audio_channel_mask_t channelMask) const 994{ 995 status_t ret = initCheck(); 996 if (ret != NO_ERROR) { 997 return 0; 998 } 999 1000 AutoMutex lock(mHardwareLock); 1001 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE; 1002 struct audio_config config = { 1003 sample_rate: sampleRate, 1004 channel_mask: channelMask, 1005 format: format, 1006 }; 1007 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1008 size_t size = dev->get_input_buffer_size(dev, &config); 1009 mHardwareStatus = AUDIO_HW_IDLE; 1010 return size; 1011} 1012 1013unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 1014{ 1015 Mutex::Autolock _l(mLock); 1016 1017 RecordThread *recordThread = checkRecordThread_l(ioHandle); 1018 if (recordThread != NULL) { 1019 return recordThread->getInputFramesLost(); 1020 } 1021 return 0; 1022} 1023 1024status_t AudioFlinger::setVoiceVolume(float value) 1025{ 1026 status_t ret = initCheck(); 1027 if (ret != NO_ERROR) { 1028 return ret; 1029 } 1030 1031 // check calling permissions 1032 if (!settingsAllowed()) { 1033 return PERMISSION_DENIED; 1034 } 1035 1036 AutoMutex lock(mHardwareLock); 1037 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice(); 1038 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME; 1039 ret = dev->set_voice_volume(dev, value); 1040 mHardwareStatus = AUDIO_HW_IDLE; 1041 1042 return ret; 1043} 1044 1045status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames, 1046 audio_io_handle_t output) const 1047{ 1048 status_t status; 1049 1050 Mutex::Autolock _l(mLock); 1051 1052 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 1053 if (playbackThread != NULL) { 1054 return playbackThread->getRenderPosition(halFrames, dspFrames); 1055 } 1056 1057 return BAD_VALUE; 1058} 1059 1060void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 1061{ 1062 1063 Mutex::Autolock _l(mLock); 1064 1065 pid_t pid = IPCThreadState::self()->getCallingPid(); 1066 if (mNotificationClients.indexOfKey(pid) < 0) { 1067 sp<NotificationClient> notificationClient = new NotificationClient(this, 1068 client, 1069 pid); 1070 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 1071 1072 mNotificationClients.add(pid, notificationClient); 1073 1074 sp<IBinder> binder = client->asBinder(); 1075 binder->linkToDeath(notificationClient); 1076 1077 // the config change is always sent from playback or record threads to avoid deadlock 1078 // with AudioSystem::gLock 1079 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1080 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED); 1081 } 1082 1083 for (size_t i = 0; i < mRecordThreads.size(); i++) { 1084 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED); 1085 } 1086 } 1087} 1088 1089void AudioFlinger::removeNotificationClient(pid_t pid) 1090{ 1091 Mutex::Autolock _l(mLock); 1092 1093 mNotificationClients.removeItem(pid); 1094 1095 ALOGV("%d died, releasing its sessions", pid); 1096 size_t num = mAudioSessionRefs.size(); 1097 bool removed = false; 1098 for (size_t i = 0; i< num; ) { 1099 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 1100 ALOGV(" pid %d @ %d", ref->mPid, i); 1101 if (ref->mPid == pid) { 1102 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid); 1103 mAudioSessionRefs.removeAt(i); 1104 delete ref; 1105 removed = true; 1106 num--; 1107 } else { 1108 i++; 1109 } 1110 } 1111 if (removed) { 1112 purgeStaleEffects_l(); 1113 } 1114} 1115 1116// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1117void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2) 1118{ 1119 size_t size = mNotificationClients.size(); 1120 for (size_t i = 0; i < size; i++) { 1121 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 1122 param2); 1123 } 1124} 1125 1126// removeClient_l() must be called with AudioFlinger::mLock held 1127void AudioFlinger::removeClient_l(pid_t pid) 1128{ 1129 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), 1130 IPCThreadState::self()->getCallingPid()); 1131 mClients.removeItem(pid); 1132} 1133 1134// getEffectThread_l() must be called with AudioFlinger::mLock held 1135sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId) 1136{ 1137 sp<PlaybackThread> thread; 1138 1139 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 1140 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) { 1141 ALOG_ASSERT(thread == 0); 1142 thread = mPlaybackThreads.valueAt(i); 1143 } 1144 } 1145 1146 return thread; 1147} 1148 1149// ---------------------------------------------------------------------------- 1150 1151AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 1152 audio_devices_t outDevice, audio_devices_t inDevice, type_t type) 1153 : Thread(false /*canCallJava*/), 1154 mType(type), 1155 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0), 1156 // mChannelMask 1157 mChannelCount(0), 1158 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), 1159 mParamStatus(NO_ERROR), 1160 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 1161 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 1162 // mName will be set by concrete (non-virtual) subclass 1163 mDeathRecipient(new PMDeathRecipient(this)) 1164{ 1165} 1166 1167AudioFlinger::ThreadBase::~ThreadBase() 1168{ 1169 mParamCond.broadcast(); 1170 // do not lock the mutex in destructor 1171 releaseWakeLock_l(); 1172 if (mPowerManager != 0) { 1173 sp<IBinder> binder = mPowerManager->asBinder(); 1174 binder->unlinkToDeath(mDeathRecipient); 1175 } 1176} 1177 1178void AudioFlinger::ThreadBase::exit() 1179{ 1180 ALOGV("ThreadBase::exit"); 1181 // do any cleanup required for exit to succeed 1182 preExit(); 1183 { 1184 // This lock prevents the following race in thread (uniprocessor for illustration): 1185 // if (!exitPending()) { 1186 // // context switch from here to exit() 1187 // // exit() calls requestExit(), what exitPending() observes 1188 // // exit() calls signal(), which is dropped since no waiters 1189 // // context switch back from exit() to here 1190 // mWaitWorkCV.wait(...); 1191 // // now thread is hung 1192 // } 1193 AutoMutex lock(mLock); 1194 requestExit(); 1195 mWaitWorkCV.broadcast(); 1196 } 1197 // When Thread::requestExitAndWait is made virtual and this method is renamed to 1198 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 1199 requestExitAndWait(); 1200} 1201 1202status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 1203{ 1204 status_t status; 1205 1206 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 1207 Mutex::Autolock _l(mLock); 1208 1209 mNewParameters.add(keyValuePairs); 1210 mWaitWorkCV.signal(); 1211 // wait condition with timeout in case the thread loop has exited 1212 // before the request could be processed 1213 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { 1214 status = mParamStatus; 1215 mWaitWorkCV.signal(); 1216 } else { 1217 status = TIMED_OUT; 1218 } 1219 return status; 1220} 1221 1222void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param) 1223{ 1224 Mutex::Autolock _l(mLock); 1225 sendIoConfigEvent_l(event, param); 1226} 1227 1228// sendIoConfigEvent_l() must be called with ThreadBase::mLock held 1229void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param) 1230{ 1231 IoConfigEvent *ioEvent = new IoConfigEvent(event, param); 1232 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent)); 1233 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, 1234 param); 1235 mWaitWorkCV.signal(); 1236} 1237 1238// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 1239void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio) 1240{ 1241 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio); 1242 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent)); 1243 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d", 1244 mConfigEvents.size(), pid, tid, prio); 1245 mWaitWorkCV.signal(); 1246} 1247 1248void AudioFlinger::ThreadBase::processConfigEvents() 1249{ 1250 mLock.lock(); 1251 while (!mConfigEvents.isEmpty()) { 1252 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); 1253 ConfigEvent *event = mConfigEvents[0]; 1254 mConfigEvents.removeAt(0); 1255 // release mLock before locking AudioFlinger mLock: lock order is always 1256 // AudioFlinger then ThreadBase to avoid cross deadlock 1257 mLock.unlock(); 1258 switch(event->type()) { 1259 case CFG_EVENT_PRIO: { 1260 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event); 1261 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio()); 1262 if (err != 0) { 1263 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; " 1264 "error %d", 1265 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err); 1266 } 1267 } break; 1268 case CFG_EVENT_IO: { 1269 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event); 1270 mAudioFlinger->mLock.lock(); 1271 audioConfigChanged_l(ioEvent->event(), ioEvent->param()); 1272 mAudioFlinger->mLock.unlock(); 1273 } break; 1274 default: 1275 ALOGE("processConfigEvents() unknown event type %d", event->type()); 1276 break; 1277 } 1278 delete event; 1279 mLock.lock(); 1280 } 1281 mLock.unlock(); 1282} 1283 1284void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) 1285{ 1286 const size_t SIZE = 256; 1287 char buffer[SIZE]; 1288 String8 result; 1289 1290 bool locked = tryLock(mLock); 1291 if (!locked) { 1292 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); 1293 write(fd, buffer, strlen(buffer)); 1294 } 1295 1296 snprintf(buffer, SIZE, "io handle: %d\n", mId); 1297 result.append(buffer); 1298 snprintf(buffer, SIZE, "TID: %d\n", getTid()); 1299 result.append(buffer); 1300 snprintf(buffer, SIZE, "standby: %d\n", mStandby); 1301 result.append(buffer); 1302 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate); 1303 result.append(buffer); 1304 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount); 1305 result.append(buffer); 1306 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount); 1307 result.append(buffer); 1308 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount); 1309 result.append(buffer); 1310 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); 1311 result.append(buffer); 1312 snprintf(buffer, SIZE, "Format: %d\n", mFormat); 1313 result.append(buffer); 1314 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); 1315 result.append(buffer); 1316 1317 snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); 1318 result.append(buffer); 1319 result.append(" Index Command"); 1320 for (size_t i = 0; i < mNewParameters.size(); ++i) { 1321 snprintf(buffer, SIZE, "\n %02d ", i); 1322 result.append(buffer); 1323 result.append(mNewParameters[i]); 1324 } 1325 1326 snprintf(buffer, SIZE, "\n\nPending config events: \n"); 1327 result.append(buffer); 1328 for (size_t i = 0; i < mConfigEvents.size(); i++) { 1329 mConfigEvents[i]->dump(buffer, SIZE); 1330 result.append(buffer); 1331 } 1332 result.append("\n"); 1333 1334 write(fd, result.string(), result.size()); 1335 1336 if (locked) { 1337 mLock.unlock(); 1338 } 1339} 1340 1341void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 1342{ 1343 const size_t SIZE = 256; 1344 char buffer[SIZE]; 1345 String8 result; 1346 1347 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); 1348 write(fd, buffer, strlen(buffer)); 1349 1350 for (size_t i = 0; i < mEffectChains.size(); ++i) { 1351 sp<EffectChain> chain = mEffectChains[i]; 1352 if (chain != 0) { 1353 chain->dump(fd, args); 1354 } 1355 } 1356} 1357 1358void AudioFlinger::ThreadBase::acquireWakeLock() 1359{ 1360 Mutex::Autolock _l(mLock); 1361 acquireWakeLock_l(); 1362} 1363 1364void AudioFlinger::ThreadBase::acquireWakeLock_l() 1365{ 1366 if (mPowerManager == 0) { 1367 // use checkService() to avoid blocking if power service is not up yet 1368 sp<IBinder> binder = 1369 defaultServiceManager()->checkService(String16("power")); 1370 if (binder == 0) { 1371 ALOGW("Thread %s cannot connect to the power manager service", mName); 1372 } else { 1373 mPowerManager = interface_cast<IPowerManager>(binder); 1374 binder->linkToDeath(mDeathRecipient); 1375 } 1376 } 1377 if (mPowerManager != 0) { 1378 sp<IBinder> binder = new BBinder(); 1379 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 1380 binder, 1381 String16(mName)); 1382 if (status == NO_ERROR) { 1383 mWakeLockToken = binder; 1384 } 1385 ALOGV("acquireWakeLock_l() %s status %d", mName, status); 1386 } 1387} 1388 1389void AudioFlinger::ThreadBase::releaseWakeLock() 1390{ 1391 Mutex::Autolock _l(mLock); 1392 releaseWakeLock_l(); 1393} 1394 1395void AudioFlinger::ThreadBase::releaseWakeLock_l() 1396{ 1397 if (mWakeLockToken != 0) { 1398 ALOGV("releaseWakeLock_l() %s", mName); 1399 if (mPowerManager != 0) { 1400 mPowerManager->releaseWakeLock(mWakeLockToken, 0); 1401 } 1402 mWakeLockToken.clear(); 1403 } 1404} 1405 1406void AudioFlinger::ThreadBase::clearPowerManager() 1407{ 1408 Mutex::Autolock _l(mLock); 1409 releaseWakeLock_l(); 1410 mPowerManager.clear(); 1411} 1412 1413void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) 1414{ 1415 sp<ThreadBase> thread = mThread.promote(); 1416 if (thread != 0) { 1417 thread->clearPowerManager(); 1418 } 1419 ALOGW("power manager service died !!!"); 1420} 1421 1422void AudioFlinger::ThreadBase::setEffectSuspended( 1423 const effect_uuid_t *type, bool suspend, int sessionId) 1424{ 1425 Mutex::Autolock _l(mLock); 1426 setEffectSuspended_l(type, suspend, sessionId); 1427} 1428 1429void AudioFlinger::ThreadBase::setEffectSuspended_l( 1430 const effect_uuid_t *type, bool suspend, int sessionId) 1431{ 1432 sp<EffectChain> chain = getEffectChain_l(sessionId); 1433 if (chain != 0) { 1434 if (type != NULL) { 1435 chain->setEffectSuspended_l(type, suspend); 1436 } else { 1437 chain->setEffectSuspendedAll_l(suspend); 1438 } 1439 } 1440 1441 updateSuspendedSessions_l(type, suspend, sessionId); 1442} 1443 1444void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 1445{ 1446 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 1447 if (index < 0) { 1448 return; 1449 } 1450 1451 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 1452 mSuspendedSessions.valueAt(index); 1453 1454 for (size_t i = 0; i < sessionEffects.size(); i++) { 1455 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i); 1456 for (int j = 0; j < desc->mRefCount; j++) { 1457 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 1458 chain->setEffectSuspendedAll_l(true); 1459 } else { 1460 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 1461 desc->mType.timeLow); 1462 chain->setEffectSuspended_l(&desc->mType, true); 1463 } 1464 } 1465 } 1466} 1467 1468void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 1469 bool suspend, 1470 int sessionId) 1471{ 1472 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 1473 1474 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 1475 1476 if (suspend) { 1477 if (index >= 0) { 1478 sessionEffects = mSuspendedSessions.valueAt(index); 1479 } else { 1480 mSuspendedSessions.add(sessionId, sessionEffects); 1481 } 1482 } else { 1483 if (index < 0) { 1484 return; 1485 } 1486 sessionEffects = mSuspendedSessions.valueAt(index); 1487 } 1488 1489 1490 int key = EffectChain::kKeyForSuspendAll; 1491 if (type != NULL) { 1492 key = type->timeLow; 1493 } 1494 index = sessionEffects.indexOfKey(key); 1495 1496 sp<SuspendedSessionDesc> desc; 1497 if (suspend) { 1498 if (index >= 0) { 1499 desc = sessionEffects.valueAt(index); 1500 } else { 1501 desc = new SuspendedSessionDesc(); 1502 if (type != NULL) { 1503 desc->mType = *type; 1504 } 1505 sessionEffects.add(key, desc); 1506 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 1507 } 1508 desc->mRefCount++; 1509 } else { 1510 if (index < 0) { 1511 return; 1512 } 1513 desc = sessionEffects.valueAt(index); 1514 if (--desc->mRefCount == 0) { 1515 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 1516 sessionEffects.removeItemsAt(index); 1517 if (sessionEffects.isEmpty()) { 1518 ALOGV("updateSuspendedSessions_l() restore removing session %d", 1519 sessionId); 1520 mSuspendedSessions.removeItem(sessionId); 1521 } 1522 } 1523 } 1524 if (!sessionEffects.isEmpty()) { 1525 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 1526 } 1527} 1528 1529void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1530 bool enabled, 1531 int sessionId) 1532{ 1533 Mutex::Autolock _l(mLock); 1534 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 1535} 1536 1537void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 1538 bool enabled, 1539 int sessionId) 1540{ 1541 if (mType != RECORD) { 1542 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 1543 // another session. This gives the priority to well behaved effect control panels 1544 // and applications not using global effects. 1545 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 1546 // global effects 1547 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 1548 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 1549 } 1550 } 1551 1552 sp<EffectChain> chain = getEffectChain_l(sessionId); 1553 if (chain != 0) { 1554 chain->checkSuspendOnEffectEnabled(effect, enabled); 1555 } 1556} 1557 1558// ---------------------------------------------------------------------------- 1559 1560AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1561 AudioStreamOut* output, 1562 audio_io_handle_t id, 1563 audio_devices_t device, 1564 type_t type) 1565 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type), 1566 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), 1567 // mStreamTypes[] initialized in constructor body 1568 mOutput(output), 1569 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 1570 mMixerStatus(MIXER_IDLE), 1571 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 1572 standbyDelay(AudioFlinger::mStandbyTimeInNsecs), 1573 mScreenState(gScreenState), 1574 // index 0 is reserved for normal mixer's submix 1575 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1) 1576{ 1577 snprintf(mName, kNameLength, "AudioOut_%X", id); 1578 1579 // Assumes constructor is called by AudioFlinger with it's mLock held, but 1580 // it would be safer to explicitly pass initial masterVolume/masterMute as 1581 // parameter. 1582 // 1583 // If the HAL we are using has support for master volume or master mute, 1584 // then do not attenuate or mute during mixing (just leave the volume at 1.0 1585 // and the mute set to false). 1586 mMasterVolume = audioFlinger->masterVolume_l(); 1587 mMasterMute = audioFlinger->masterMute_l(); 1588 if (mOutput && mOutput->audioHwDev) { 1589 if (mOutput->audioHwDev->canSetMasterVolume()) { 1590 mMasterVolume = 1.0; 1591 } 1592 1593 if (mOutput->audioHwDev->canSetMasterMute()) { 1594 mMasterMute = false; 1595 } 1596 } 1597 1598 readOutputParameters(); 1599 1600 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 1601 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile 1602 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; 1603 stream = (audio_stream_type_t) (stream + 1)) { 1604 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 1605 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1606 } 1607 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, 1608 // because mAudioFlinger doesn't have one to copy from 1609} 1610 1611AudioFlinger::PlaybackThread::~PlaybackThread() 1612{ 1613 delete [] mMixBuffer; 1614} 1615 1616void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1617{ 1618 dumpInternals(fd, args); 1619 dumpTracks(fd, args); 1620 dumpEffectChains(fd, args); 1621} 1622 1623void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) 1624{ 1625 const size_t SIZE = 256; 1626 char buffer[SIZE]; 1627 String8 result; 1628 1629 result.appendFormat("Output thread %p stream volumes in dB:\n ", this); 1630 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1631 const stream_type_t *st = &mStreamTypes[i]; 1632 if (i > 0) { 1633 result.appendFormat(", "); 1634 } 1635 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1636 if (st->mute) { 1637 result.append("M"); 1638 } 1639 } 1640 result.append("\n"); 1641 write(fd, result.string(), result.length()); 1642 result.clear(); 1643 1644 snprintf(buffer, SIZE, "Output thread %p tracks\n", this); 1645 result.append(buffer); 1646 Track::appendDumpHeader(result); 1647 for (size_t i = 0; i < mTracks.size(); ++i) { 1648 sp<Track> track = mTracks[i]; 1649 if (track != 0) { 1650 track->dump(buffer, SIZE); 1651 result.append(buffer); 1652 } 1653 } 1654 1655 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); 1656 result.append(buffer); 1657 Track::appendDumpHeader(result); 1658 for (size_t i = 0; i < mActiveTracks.size(); ++i) { 1659 sp<Track> track = mActiveTracks[i].promote(); 1660 if (track != 0) { 1661 track->dump(buffer, SIZE); 1662 result.append(buffer); 1663 } 1664 } 1665 write(fd, result.string(), result.size()); 1666 1667 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1668 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1669 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n", 1670 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1671} 1672 1673void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1674{ 1675 const size_t SIZE = 256; 1676 char buffer[SIZE]; 1677 String8 result; 1678 1679 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); 1680 result.append(buffer); 1681 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", 1682 ns2ms(systemTime() - mLastWriteTime)); 1683 result.append(buffer); 1684 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); 1685 result.append(buffer); 1686 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); 1687 result.append(buffer); 1688 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); 1689 result.append(buffer); 1690 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); 1691 result.append(buffer); 1692 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); 1693 result.append(buffer); 1694 write(fd, result.string(), result.size()); 1695 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask); 1696 1697 dumpBase(fd, args); 1698} 1699 1700// Thread virtuals 1701status_t AudioFlinger::PlaybackThread::readyToRun() 1702{ 1703 status_t status = initCheck(); 1704 if (status == NO_ERROR) { 1705 ALOGI("AudioFlinger's thread %p ready to run", this); 1706 } else { 1707 ALOGE("No working audio driver found."); 1708 } 1709 return status; 1710} 1711 1712void AudioFlinger::PlaybackThread::onFirstRef() 1713{ 1714 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1715} 1716 1717// ThreadBase virtuals 1718void AudioFlinger::PlaybackThread::preExit() 1719{ 1720 ALOGV(" preExit()"); 1721 // FIXME this is using hard-coded strings but in the future, this functionality will be 1722 // converted to use audio HAL extensions required to support tunneling 1723 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1"); 1724} 1725 1726// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1727sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1728 const sp<AudioFlinger::Client>& client, 1729 audio_stream_type_t streamType, 1730 uint32_t sampleRate, 1731 audio_format_t format, 1732 audio_channel_mask_t channelMask, 1733 size_t frameCount, 1734 const sp<IMemory>& sharedBuffer, 1735 int sessionId, 1736 IAudioFlinger::track_flags_t *flags, 1737 pid_t tid, 1738 status_t *status) 1739{ 1740 sp<Track> track; 1741 status_t lStatus; 1742 1743 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0; 1744 1745 // client expresses a preference for FAST, but we get the final say 1746 if (*flags & IAudioFlinger::TRACK_FAST) { 1747 if ( 1748 // not timed 1749 (!isTimed) && 1750 // either of these use cases: 1751 ( 1752 // use case 1: shared buffer with any frame count 1753 ( 1754 (sharedBuffer != 0) 1755 ) || 1756 // use case 2: callback handler and frame count is default or at least as large as HAL 1757 ( 1758 (tid != -1) && 1759 ((frameCount == 0) || 1760 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier))) 1761 ) 1762 ) && 1763 // PCM data 1764 audio_is_linear_pcm(format) && 1765 // mono or stereo 1766 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 1767 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 1768#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE 1769 // hardware sample rate 1770 (sampleRate == mSampleRate) && 1771#endif 1772 // normal mixer has an associated fast mixer 1773 hasFastMixer() && 1774 // there are sufficient fast track slots available 1775 (mFastTrackAvailMask != 0) 1776 // FIXME test that MixerThread for this fast track has a capable output HAL 1777 // FIXME add a permission test also? 1778 ) { 1779 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count 1780 if (frameCount == 0) { 1781 frameCount = mFrameCount * kFastTrackMultiplier; 1782 } 1783 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 1784 frameCount, mFrameCount); 1785 } else { 1786 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " 1787 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 1788 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1789 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, 1790 audio_is_linear_pcm(format), 1791 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1792 *flags &= ~IAudioFlinger::TRACK_FAST; 1793 // For compatibility with AudioTrack calculation, buffer depth is forced 1794 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1795 // This is probably too conservative, but legacy application code may depend on it. 1796 // If you change this calculation, also review the start threshold which is related. 1797 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); 1798 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1799 if (minBufCount < 2) { 1800 minBufCount = 2; 1801 } 1802 size_t minFrameCount = mNormalFrameCount * minBufCount; 1803 if (frameCount < minFrameCount) { 1804 frameCount = minFrameCount; 1805 } 1806 } 1807 } 1808 1809 if (mType == DIRECT) { 1810 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { 1811 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1812 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x " 1813 "for output %p with format %d", 1814 sampleRate, format, channelMask, mOutput, mFormat); 1815 lStatus = BAD_VALUE; 1816 goto Exit; 1817 } 1818 } 1819 } else { 1820 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 1821 if (sampleRate > mSampleRate*2) { 1822 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1823 lStatus = BAD_VALUE; 1824 goto Exit; 1825 } 1826 } 1827 1828 lStatus = initCheck(); 1829 if (lStatus != NO_ERROR) { 1830 ALOGE("Audio driver not initialized."); 1831 goto Exit; 1832 } 1833 1834 { // scope for mLock 1835 Mutex::Autolock _l(mLock); 1836 1837 // all tracks in same audio session must share the same routing strategy otherwise 1838 // conflicts will happen when tracks are moved from one output to another by audio policy 1839 // manager 1840 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1841 for (size_t i = 0; i < mTracks.size(); ++i) { 1842 sp<Track> t = mTracks[i]; 1843 if (t != 0 && !t->isOutputTrack()) { 1844 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1845 if (sessionId == t->sessionId() && strategy != actual) { 1846 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1847 strategy, actual); 1848 lStatus = BAD_VALUE; 1849 goto Exit; 1850 } 1851 } 1852 } 1853 1854 if (!isTimed) { 1855 track = new Track(this, client, streamType, sampleRate, format, 1856 channelMask, frameCount, sharedBuffer, sessionId, *flags); 1857 } else { 1858 track = TimedTrack::create(this, client, streamType, sampleRate, format, 1859 channelMask, frameCount, sharedBuffer, sessionId); 1860 } 1861 if (track == 0 || track->getCblk() == NULL || track->name() < 0) { 1862 lStatus = NO_MEMORY; 1863 goto Exit; 1864 } 1865 mTracks.add(track); 1866 1867 sp<EffectChain> chain = getEffectChain_l(sessionId); 1868 if (chain != 0) { 1869 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1870 track->setMainBuffer(chain->inBuffer()); 1871 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 1872 chain->incTrackCnt(); 1873 } 1874 1875 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 1876 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1877 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 1878 // so ask activity manager to do this on our behalf 1879 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 1880 } 1881 } 1882 1883 lStatus = NO_ERROR; 1884 1885Exit: 1886 if (status) { 1887 *status = lStatus; 1888 } 1889 return track; 1890} 1891 1892uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 1893{ 1894 if (mFastMixer != NULL) { 1895 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 1896 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 1897 } 1898 return latency; 1899} 1900 1901uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 1902{ 1903 return latency; 1904} 1905 1906uint32_t AudioFlinger::PlaybackThread::latency() const 1907{ 1908 Mutex::Autolock _l(mLock); 1909 return latency_l(); 1910} 1911uint32_t AudioFlinger::PlaybackThread::latency_l() const 1912{ 1913 if (initCheck() == NO_ERROR) { 1914 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream)); 1915 } else { 1916 return 0; 1917 } 1918} 1919 1920void AudioFlinger::PlaybackThread::setMasterVolume(float value) 1921{ 1922 Mutex::Autolock _l(mLock); 1923 // Don't apply master volume in SW if our HAL can do it for us. 1924 if (mOutput && mOutput->audioHwDev && 1925 mOutput->audioHwDev->canSetMasterVolume()) { 1926 mMasterVolume = 1.0; 1927 } else { 1928 mMasterVolume = value; 1929 } 1930} 1931 1932void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1933{ 1934 Mutex::Autolock _l(mLock); 1935 // Don't apply master mute in SW if our HAL can do it for us. 1936 if (mOutput && mOutput->audioHwDev && 1937 mOutput->audioHwDev->canSetMasterMute()) { 1938 mMasterMute = false; 1939 } else { 1940 mMasterMute = muted; 1941 } 1942} 1943 1944void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1945{ 1946 Mutex::Autolock _l(mLock); 1947 mStreamTypes[stream].volume = value; 1948} 1949 1950void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1951{ 1952 Mutex::Autolock _l(mLock); 1953 mStreamTypes[stream].mute = muted; 1954} 1955 1956float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1957{ 1958 Mutex::Autolock _l(mLock); 1959 return mStreamTypes[stream].volume; 1960} 1961 1962// addTrack_l() must be called with ThreadBase::mLock held 1963status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1964{ 1965 status_t status = ALREADY_EXISTS; 1966 1967 // set retry count for buffer fill 1968 track->mRetryCount = kMaxTrackStartupRetries; 1969 if (mActiveTracks.indexOf(track) < 0) { 1970 // the track is newly added, make sure it fills up all its 1971 // buffers before playing. This is to ensure the client will 1972 // effectively get the latency it requested. 1973 track->mFillingUpStatus = Track::FS_FILLING; 1974 track->mResetDone = false; 1975 track->mPresentationCompleteFrames = 0; 1976 mActiveTracks.add(track); 1977 if (track->mainBuffer() != mMixBuffer) { 1978 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1979 if (chain != 0) { 1980 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 1981 track->sessionId()); 1982 chain->incActiveTrackCnt(); 1983 } 1984 } 1985 1986 status = NO_ERROR; 1987 } 1988 1989 ALOGV("mWaitWorkCV.broadcast"); 1990 mWaitWorkCV.broadcast(); 1991 1992 return status; 1993} 1994 1995// destroyTrack_l() must be called with ThreadBase::mLock held 1996void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 1997{ 1998 track->mState = TrackBase::TERMINATED; 1999 // active tracks are removed by threadLoop() 2000 if (mActiveTracks.indexOf(track) < 0) { 2001 removeTrack_l(track); 2002 } 2003} 2004 2005void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 2006{ 2007 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 2008 mTracks.remove(track); 2009 deleteTrackName_l(track->name()); 2010 // redundant as track is about to be destroyed, for dumpsys only 2011 track->mName = -1; 2012 if (track->isFastTrack()) { 2013 int index = track->mFastIndex; 2014 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks); 2015 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 2016 mFastTrackAvailMask |= 1 << index; 2017 // redundant as track is about to be destroyed, for dumpsys only 2018 track->mFastIndex = -1; 2019 } 2020 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2021 if (chain != 0) { 2022 chain->decTrackCnt(); 2023 } 2024} 2025 2026String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 2027{ 2028 String8 out_s8 = String8(""); 2029 char *s; 2030 2031 Mutex::Autolock _l(mLock); 2032 if (initCheck() != NO_ERROR) { 2033 return out_s8; 2034 } 2035 2036 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); 2037 out_s8 = String8(s); 2038 free(s); 2039 return out_s8; 2040} 2041 2042// audioConfigChanged_l() must be called with AudioFlinger::mLock held 2043void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { 2044 AudioSystem::OutputDescriptor desc; 2045 void *param2 = NULL; 2046 2047 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, 2048 param); 2049 2050 switch (event) { 2051 case AudioSystem::OUTPUT_OPENED: 2052 case AudioSystem::OUTPUT_CONFIG_CHANGED: 2053 desc.channels = mChannelMask; 2054 desc.samplingRate = mSampleRate; 2055 desc.format = mFormat; 2056 desc.frameCount = mNormalFrameCount; // FIXME see 2057 // AudioFlinger::frameCount(audio_io_handle_t) 2058 desc.latency = latency(); 2059 param2 = &desc; 2060 break; 2061 2062 case AudioSystem::STREAM_CONFIG_CHANGED: 2063 param2 = ¶m; 2064 case AudioSystem::OUTPUT_CLOSED: 2065 default: 2066 break; 2067 } 2068 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 2069} 2070 2071void AudioFlinger::PlaybackThread::readOutputParameters() 2072{ 2073 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); 2074 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); 2075 mChannelCount = (uint16_t)popcount(mChannelMask); 2076 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); 2077 mFrameSize = audio_stream_frame_size(&mOutput->stream->common); 2078 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize; 2079 if (mFrameCount & 15) { 2080 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames", 2081 mFrameCount); 2082 } 2083 2084 // Calculate size of normal mix buffer relative to the HAL output buffer size 2085 double multiplier = 1.0; 2086 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 2087 kUseFastMixer == FastMixer_Dynamic)) { 2088 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000; 2089 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000; 2090 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 2091 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 2092 maxNormalFrameCount = maxNormalFrameCount & ~15; 2093 if (maxNormalFrameCount < minNormalFrameCount) { 2094 maxNormalFrameCount = minNormalFrameCount; 2095 } 2096 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 2097 if (multiplier <= 1.0) { 2098 multiplier = 1.0; 2099 } else if (multiplier <= 2.0) { 2100 if (2 * mFrameCount <= maxNormalFrameCount) { 2101 multiplier = 2.0; 2102 } else { 2103 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 2104 } 2105 } else { 2106 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL 2107 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast 2108 // track, but we sometimes have to do this to satisfy the maximum frame count 2109 // constraint) 2110 // FIXME this rounding up should not be done if no HAL SRC 2111 uint32_t truncMult = (uint32_t) multiplier; 2112 if ((truncMult & 1)) { 2113 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { 2114 ++truncMult; 2115 } 2116 } 2117 multiplier = (double) truncMult; 2118 } 2119 } 2120 mNormalFrameCount = multiplier * mFrameCount; 2121 // round up to nearest 16 frames to satisfy AudioMixer 2122 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 2123 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, 2124 mNormalFrameCount); 2125 2126 delete[] mMixBuffer; 2127 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount]; 2128 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 2129 2130 // force reconfiguration of effect chains and engines to take new buffer size and audio 2131 // parameters into account 2132 // Note that mLock is not held when readOutputParameters() is called from the constructor 2133 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 2134 // matter. 2135 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 2136 Vector< sp<EffectChain> > effectChains = mEffectChains; 2137 for (size_t i = 0; i < effectChains.size(); i ++) { 2138 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 2139 } 2140} 2141 2142 2143status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames) 2144{ 2145 if (halFrames == NULL || dspFrames == NULL) { 2146 return BAD_VALUE; 2147 } 2148 Mutex::Autolock _l(mLock); 2149 if (initCheck() != NO_ERROR) { 2150 return INVALID_OPERATION; 2151 } 2152 size_t framesWritten = mBytesWritten / mFrameSize; 2153 *halFrames = framesWritten; 2154 2155 if (isSuspended()) { 2156 // return an estimation of rendered frames when the output is suspended 2157 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 2158 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; 2159 return NO_ERROR; 2160 } else { 2161 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 2162 } 2163} 2164 2165uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 2166{ 2167 Mutex::Autolock _l(mLock); 2168 uint32_t result = 0; 2169 if (getEffectChain_l(sessionId) != 0) { 2170 result = EFFECT_SESSION; 2171 } 2172 2173 for (size_t i = 0; i < mTracks.size(); ++i) { 2174 sp<Track> track = mTracks[i]; 2175 if (sessionId == track->sessionId() && 2176 !(track->mCblk->flags & CBLK_INVALID)) { 2177 result |= TRACK_SESSION; 2178 break; 2179 } 2180 } 2181 2182 return result; 2183} 2184 2185uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 2186{ 2187 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2188 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2189 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2190 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2191 } 2192 for (size_t i = 0; i < mTracks.size(); i++) { 2193 sp<Track> track = mTracks[i]; 2194 if (sessionId == track->sessionId() && 2195 !(track->mCblk->flags & CBLK_INVALID)) { 2196 return AudioSystem::getStrategyForStream(track->streamType()); 2197 } 2198 } 2199 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2200} 2201 2202 2203AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2204{ 2205 Mutex::Autolock _l(mLock); 2206 return mOutput; 2207} 2208 2209AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2210{ 2211 Mutex::Autolock _l(mLock); 2212 AudioStreamOut *output = mOutput; 2213 mOutput = NULL; 2214 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2215 // must push a NULL and wait for ack 2216 mOutputSink.clear(); 2217 mPipeSink.clear(); 2218 mNormalSink.clear(); 2219 return output; 2220} 2221 2222// this method must always be called either with ThreadBase mLock held or inside the thread loop 2223audio_stream_t* AudioFlinger::PlaybackThread::stream() const 2224{ 2225 if (mOutput == NULL) { 2226 return NULL; 2227 } 2228 return &mOutput->stream->common; 2229} 2230 2231uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2232{ 2233 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2234} 2235 2236status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2237{ 2238 if (!isValidSyncEvent(event)) { 2239 return BAD_VALUE; 2240 } 2241 2242 Mutex::Autolock _l(mLock); 2243 2244 for (size_t i = 0; i < mTracks.size(); ++i) { 2245 sp<Track> track = mTracks[i]; 2246 if (event->triggerSession() == track->sessionId()) { 2247 (void) track->setSyncEvent(event); 2248 return NO_ERROR; 2249 } 2250 } 2251 2252 return NAME_NOT_FOUND; 2253} 2254 2255bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 2256{ 2257 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 2258} 2259 2260void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 2261 const Vector< sp<Track> >& tracksToRemove) 2262{ 2263 size_t count = tracksToRemove.size(); 2264 if (CC_UNLIKELY(count)) { 2265 for (size_t i = 0 ; i < count ; i++) { 2266 const sp<Track>& track = tracksToRemove.itemAt(i); 2267 if ((track->sharedBuffer() != 0) && 2268 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) { 2269 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 2270 } 2271 } 2272 } 2273 2274} 2275 2276// ---------------------------------------------------------------------------- 2277 2278AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2279 audio_io_handle_t id, audio_devices_t device, type_t type) 2280 : PlaybackThread(audioFlinger, output, id, device, type), 2281 // mAudioMixer below 2282 // mFastMixer below 2283 mFastMixerFutex(0) 2284 // mOutputSink below 2285 // mPipeSink below 2286 // mNormalSink below 2287{ 2288 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2289 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, " 2290 "mFrameCount=%d, mNormalFrameCount=%d", 2291 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2292 mNormalFrameCount); 2293 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2294 2295 // FIXME - Current mixer implementation only supports stereo output 2296 if (mChannelCount != FCC_2) { 2297 ALOGE("Invalid audio hardware channel count %d", mChannelCount); 2298 } 2299 2300 // create an NBAIO sink for the HAL output stream, and negotiate 2301 mOutputSink = new AudioStreamOutSink(output->stream); 2302 size_t numCounterOffers = 0; 2303 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2304 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2305 ALOG_ASSERT(index == 0); 2306 2307 // initialize fast mixer depending on configuration 2308 bool initFastMixer; 2309 switch (kUseFastMixer) { 2310 case FastMixer_Never: 2311 initFastMixer = false; 2312 break; 2313 case FastMixer_Always: 2314 initFastMixer = true; 2315 break; 2316 case FastMixer_Static: 2317 case FastMixer_Dynamic: 2318 initFastMixer = mFrameCount < mNormalFrameCount; 2319 break; 2320 } 2321 if (initFastMixer) { 2322 2323 // create a MonoPipe to connect our submix to FastMixer 2324 NBAIO_Format format = mOutputSink->format(); 2325 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2326 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2327 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2328 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2329 const NBAIO_Format offers[1] = {format}; 2330 size_t numCounterOffers = 0; 2331 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2332 ALOG_ASSERT(index == 0); 2333 monoPipe->setAvgFrames((mScreenState & 1) ? 2334 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2335 mPipeSink = monoPipe; 2336 2337#ifdef TEE_SINK_FRAMES 2338 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2339 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format); 2340 numCounterOffers = 0; 2341 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2342 ALOG_ASSERT(index == 0); 2343 mTeeSink = teeSink; 2344 PipeReader *teeSource = new PipeReader(*teeSink); 2345 numCounterOffers = 0; 2346 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2347 ALOG_ASSERT(index == 0); 2348 mTeeSource = teeSource; 2349#endif 2350 2351 // create fast mixer and configure it initially with just one fast track for our submix 2352 mFastMixer = new FastMixer(); 2353 FastMixerStateQueue *sq = mFastMixer->sq(); 2354#ifdef STATE_QUEUE_DUMP 2355 sq->setObserverDump(&mStateQueueObserverDump); 2356 sq->setMutatorDump(&mStateQueueMutatorDump); 2357#endif 2358 FastMixerState *state = sq->begin(); 2359 FastTrack *fastTrack = &state->mFastTracks[0]; 2360 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2361 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2362 fastTrack->mVolumeProvider = NULL; 2363 fastTrack->mGeneration++; 2364 state->mFastTracksGen++; 2365 state->mTrackMask = 1; 2366 // fast mixer will use the HAL output sink 2367 state->mOutputSink = mOutputSink.get(); 2368 state->mOutputSinkGen++; 2369 state->mFrameCount = mFrameCount; 2370 state->mCommand = FastMixerState::COLD_IDLE; 2371 // already done in constructor initialization list 2372 //mFastMixerFutex = 0; 2373 state->mColdFutexAddr = &mFastMixerFutex; 2374 state->mColdGen++; 2375 state->mDumpState = &mFastMixerDumpState; 2376 state->mTeeSink = mTeeSink.get(); 2377 sq->end(); 2378 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2379 2380 // start the fast mixer 2381 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2382 pid_t tid = mFastMixer->getTid(); 2383 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2384 if (err != 0) { 2385 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2386 kPriorityFastMixer, getpid_cached, tid, err); 2387 } 2388 2389#ifdef AUDIO_WATCHDOG 2390 // create and start the watchdog 2391 mAudioWatchdog = new AudioWatchdog(); 2392 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2393 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2394 tid = mAudioWatchdog->getTid(); 2395 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2396 if (err != 0) { 2397 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2398 kPriorityFastMixer, getpid_cached, tid, err); 2399 } 2400#endif 2401 2402 } else { 2403 mFastMixer = NULL; 2404 } 2405 2406 switch (kUseFastMixer) { 2407 case FastMixer_Never: 2408 case FastMixer_Dynamic: 2409 mNormalSink = mOutputSink; 2410 break; 2411 case FastMixer_Always: 2412 mNormalSink = mPipeSink; 2413 break; 2414 case FastMixer_Static: 2415 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2416 break; 2417 } 2418} 2419 2420AudioFlinger::MixerThread::~MixerThread() 2421{ 2422 if (mFastMixer != NULL) { 2423 FastMixerStateQueue *sq = mFastMixer->sq(); 2424 FastMixerState *state = sq->begin(); 2425 if (state->mCommand == FastMixerState::COLD_IDLE) { 2426 int32_t old = android_atomic_inc(&mFastMixerFutex); 2427 if (old == -1) { 2428 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2429 } 2430 } 2431 state->mCommand = FastMixerState::EXIT; 2432 sq->end(); 2433 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2434 mFastMixer->join(); 2435 // Though the fast mixer thread has exited, it's state queue is still valid. 2436 // We'll use that extract the final state which contains one remaining fast track 2437 // corresponding to our sub-mix. 2438 state = sq->begin(); 2439 ALOG_ASSERT(state->mTrackMask == 1); 2440 FastTrack *fastTrack = &state->mFastTracks[0]; 2441 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2442 delete fastTrack->mBufferProvider; 2443 sq->end(false /*didModify*/); 2444 delete mFastMixer; 2445#ifdef AUDIO_WATCHDOG 2446 if (mAudioWatchdog != 0) { 2447 mAudioWatchdog->requestExit(); 2448 mAudioWatchdog->requestExitAndWait(); 2449 mAudioWatchdog.clear(); 2450 } 2451#endif 2452 } 2453 delete mAudioMixer; 2454} 2455 2456class CpuStats { 2457public: 2458 CpuStats(); 2459 void sample(const String8 &title); 2460#ifdef DEBUG_CPU_USAGE 2461private: 2462 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 2463 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 2464 2465 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 2466 2467 int mCpuNum; // thread's current CPU number 2468 int mCpukHz; // frequency of thread's current CPU in kHz 2469#endif 2470}; 2471 2472CpuStats::CpuStats() 2473#ifdef DEBUG_CPU_USAGE 2474 : mCpuNum(-1), mCpukHz(-1) 2475#endif 2476{ 2477} 2478 2479void CpuStats::sample(const String8 &title) { 2480#ifdef DEBUG_CPU_USAGE 2481 // get current thread's delta CPU time in wall clock ns 2482 double wcNs; 2483 bool valid = mCpuUsage.sampleAndEnable(wcNs); 2484 2485 // record sample for wall clock statistics 2486 if (valid) { 2487 mWcStats.sample(wcNs); 2488 } 2489 2490 // get the current CPU number 2491 int cpuNum = sched_getcpu(); 2492 2493 // get the current CPU frequency in kHz 2494 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 2495 2496 // check if either CPU number or frequency changed 2497 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 2498 mCpuNum = cpuNum; 2499 mCpukHz = cpukHz; 2500 // ignore sample for purposes of cycles 2501 valid = false; 2502 } 2503 2504 // if no change in CPU number or frequency, then record sample for cycle statistics 2505 if (valid && mCpukHz > 0) { 2506 double cycles = wcNs * cpukHz * 0.000001; 2507 mHzStats.sample(cycles); 2508 } 2509 2510 unsigned n = mWcStats.n(); 2511 // mCpuUsage.elapsed() is expensive, so don't call it every loop 2512 if ((n & 127) == 1) { 2513 long long elapsed = mCpuUsage.elapsed(); 2514 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 2515 double perLoop = elapsed / (double) n; 2516 double perLoop100 = perLoop * 0.01; 2517 double perLoop1k = perLoop * 0.001; 2518 double mean = mWcStats.mean(); 2519 double stddev = mWcStats.stddev(); 2520 double minimum = mWcStats.minimum(); 2521 double maximum = mWcStats.maximum(); 2522 double meanCycles = mHzStats.mean(); 2523 double stddevCycles = mHzStats.stddev(); 2524 double minCycles = mHzStats.minimum(); 2525 double maxCycles = mHzStats.maximum(); 2526 mCpuUsage.resetElapsed(); 2527 mWcStats.reset(); 2528 mHzStats.reset(); 2529 ALOGD("CPU usage for %s over past %.1f secs\n" 2530 " (%u mixer loops at %.1f mean ms per loop):\n" 2531 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 2532 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 2533 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 2534 title.string(), 2535 elapsed * .000000001, n, perLoop * .000001, 2536 mean * .001, 2537 stddev * .001, 2538 minimum * .001, 2539 maximum * .001, 2540 mean / perLoop100, 2541 stddev / perLoop100, 2542 minimum / perLoop100, 2543 maximum / perLoop100, 2544 meanCycles / perLoop1k, 2545 stddevCycles / perLoop1k, 2546 minCycles / perLoop1k, 2547 maxCycles / perLoop1k); 2548 2549 } 2550 } 2551#endif 2552}; 2553 2554void AudioFlinger::PlaybackThread::checkSilentMode_l() 2555{ 2556 if (!mMasterMute) { 2557 char value[PROPERTY_VALUE_MAX]; 2558 if (property_get("ro.audio.silent", value, "0") > 0) { 2559 char *endptr; 2560 unsigned long ul = strtoul(value, &endptr, 0); 2561 if (*endptr == '\0' && ul != 0) { 2562 ALOGD("Silence is golden"); 2563 // The setprop command will not allow a property to be changed after 2564 // the first time it is set, so we don't have to worry about un-muting. 2565 setMasterMute_l(true); 2566 } 2567 } 2568 } 2569} 2570 2571bool AudioFlinger::PlaybackThread::threadLoop() 2572{ 2573 Vector< sp<Track> > tracksToRemove; 2574 2575 standbyTime = systemTime(); 2576 2577 // MIXER 2578 nsecs_t lastWarning = 0; 2579 2580 // DUPLICATING 2581 // FIXME could this be made local to while loop? 2582 writeFrames = 0; 2583 2584 cacheParameters_l(); 2585 sleepTime = idleSleepTime; 2586 2587 if (mType == MIXER) { 2588 sleepTimeShift = 0; 2589 } 2590 2591 CpuStats cpuStats; 2592 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2593 2594 acquireWakeLock(); 2595 2596 while (!exitPending()) 2597 { 2598 cpuStats.sample(myName); 2599 2600 Vector< sp<EffectChain> > effectChains; 2601 2602 processConfigEvents(); 2603 2604 { // scope for mLock 2605 2606 Mutex::Autolock _l(mLock); 2607 2608 if (checkForNewParameters_l()) { 2609 cacheParameters_l(); 2610 } 2611 2612 saveOutputTracks(); 2613 2614 // put audio hardware into standby after short delay 2615 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) || 2616 isSuspended())) { 2617 if (!mStandby) { 2618 2619 threadLoop_standby(); 2620 2621 mStandby = true; 2622 } 2623 2624 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2625 // we're about to wait, flush the binder command buffer 2626 IPCThreadState::self()->flushCommands(); 2627 2628 clearOutputTracks(); 2629 2630 if (exitPending()) break; 2631 2632 releaseWakeLock_l(); 2633 // wait until we have something to do... 2634 ALOGV("%s going to sleep", myName.string()); 2635 mWaitWorkCV.wait(mLock); 2636 ALOGV("%s waking up", myName.string()); 2637 acquireWakeLock_l(); 2638 2639 mMixerStatus = MIXER_IDLE; 2640 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2641 mBytesWritten = 0; 2642 2643 checkSilentMode_l(); 2644 2645 standbyTime = systemTime() + standbyDelay; 2646 sleepTime = idleSleepTime; 2647 if (mType == MIXER) { 2648 sleepTimeShift = 0; 2649 } 2650 2651 continue; 2652 } 2653 } 2654 2655 // mMixerStatusIgnoringFastTracks is also updated internally 2656 mMixerStatus = prepareTracks_l(&tracksToRemove); 2657 2658 // prevent any changes in effect chain list and in each effect chain 2659 // during mixing and effect process as the audio buffers could be deleted 2660 // or modified if an effect is created or deleted 2661 lockEffectChains_l(effectChains); 2662 } 2663 2664 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) { 2665 threadLoop_mix(); 2666 } else { 2667 threadLoop_sleepTime(); 2668 } 2669 2670 if (isSuspended()) { 2671 sleepTime = suspendSleepTimeUs(); 2672 mBytesWritten += mixBufferSize; 2673 } 2674 2675 // only process effects if we're going to write 2676 if (sleepTime == 0) { 2677 for (size_t i = 0; i < effectChains.size(); i ++) { 2678 effectChains[i]->process_l(); 2679 } 2680 } 2681 2682 // enable changes in effect chain 2683 unlockEffectChains(effectChains); 2684 2685 // sleepTime == 0 means we must write to audio hardware 2686 if (sleepTime == 0) { 2687 2688 threadLoop_write(); 2689 2690if (mType == MIXER) { 2691 // write blocked detection 2692 nsecs_t now = systemTime(); 2693 nsecs_t delta = now - mLastWriteTime; 2694 if (!mStandby && delta > maxPeriod) { 2695 mNumDelayedWrites++; 2696 if ((now - lastWarning) > kWarningThrottleNs) { 2697#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) 2698 ScopedTrace st(ATRACE_TAG, "underrun"); 2699#endif 2700 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2701 ns2ms(delta), mNumDelayedWrites, this); 2702 lastWarning = now; 2703 } 2704 } 2705} 2706 2707 mStandby = false; 2708 } else { 2709 usleep(sleepTime); 2710 } 2711 2712 // Finally let go of removed track(s), without the lock held 2713 // since we can't guarantee the destructors won't acquire that 2714 // same lock. This will also mutate and push a new fast mixer state. 2715 threadLoop_removeTracks(tracksToRemove); 2716 tracksToRemove.clear(); 2717 2718 // FIXME I don't understand the need for this here; 2719 // it was in the original code but maybe the 2720 // assignment in saveOutputTracks() makes this unnecessary? 2721 clearOutputTracks(); 2722 2723 // Effect chains will be actually deleted here if they were removed from 2724 // mEffectChains list during mixing or effects processing 2725 effectChains.clear(); 2726 2727 // FIXME Note that the above .clear() is no longer necessary since effectChains 2728 // is now local to this block, but will keep it for now (at least until merge done). 2729 } 2730 2731 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ... 2732 if (mType == MIXER || mType == DIRECT) { 2733 // put output stream into standby mode 2734 if (!mStandby) { 2735 mOutput->stream->common.standby(&mOutput->stream->common); 2736 } 2737 } 2738 2739 releaseWakeLock(); 2740 2741 ALOGV("Thread %p type %d exiting", this, mType); 2742 return false; 2743} 2744 2745void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2746{ 2747 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2748} 2749 2750void AudioFlinger::MixerThread::threadLoop_write() 2751{ 2752 // FIXME we should only do one push per cycle; confirm this is true 2753 // Start the fast mixer if it's not already running 2754 if (mFastMixer != NULL) { 2755 FastMixerStateQueue *sq = mFastMixer->sq(); 2756 FastMixerState *state = sq->begin(); 2757 if (state->mCommand != FastMixerState::MIX_WRITE && 2758 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2759 if (state->mCommand == FastMixerState::COLD_IDLE) { 2760 int32_t old = android_atomic_inc(&mFastMixerFutex); 2761 if (old == -1) { 2762 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2763 } 2764#ifdef AUDIO_WATCHDOG 2765 if (mAudioWatchdog != 0) { 2766 mAudioWatchdog->resume(); 2767 } 2768#endif 2769 } 2770 state->mCommand = FastMixerState::MIX_WRITE; 2771 sq->end(); 2772 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2773 if (kUseFastMixer == FastMixer_Dynamic) { 2774 mNormalSink = mPipeSink; 2775 } 2776 } else { 2777 sq->end(false /*didModify*/); 2778 } 2779 } 2780 PlaybackThread::threadLoop_write(); 2781} 2782 2783// shared by MIXER and DIRECT, overridden by DUPLICATING 2784void AudioFlinger::PlaybackThread::threadLoop_write() 2785{ 2786 // FIXME rewrite to reduce number of system calls 2787 mLastWriteTime = systemTime(); 2788 mInWrite = true; 2789 int bytesWritten; 2790 2791 // If an NBAIO sink is present, use it to write the normal mixer's submix 2792 if (mNormalSink != 0) { 2793#define mBitShift 2 // FIXME 2794 size_t count = mixBufferSize >> mBitShift; 2795#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) 2796 Tracer::traceBegin(ATRACE_TAG, "write"); 2797#endif 2798 // update the setpoint when gScreenState changes 2799 uint32_t screenState = gScreenState; 2800 if (screenState != mScreenState) { 2801 mScreenState = screenState; 2802 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2803 if (pipe != NULL) { 2804 pipe->setAvgFrames((mScreenState & 1) ? 2805 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2806 } 2807 } 2808 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count); 2809#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) 2810 Tracer::traceEnd(ATRACE_TAG); 2811#endif 2812 if (framesWritten > 0) { 2813 bytesWritten = framesWritten << mBitShift; 2814 } else { 2815 bytesWritten = framesWritten; 2816 } 2817 // otherwise use the HAL / AudioStreamOut directly 2818 } else { 2819 // Direct output thread. 2820 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize); 2821 } 2822 2823 if (bytesWritten > 0) mBytesWritten += mixBufferSize; 2824 mNumWrites++; 2825 mInWrite = false; 2826} 2827 2828void AudioFlinger::MixerThread::threadLoop_standby() 2829{ 2830 // Idle the fast mixer if it's currently running 2831 if (mFastMixer != NULL) { 2832 FastMixerStateQueue *sq = mFastMixer->sq(); 2833 FastMixerState *state = sq->begin(); 2834 if (!(state->mCommand & FastMixerState::IDLE)) { 2835 state->mCommand = FastMixerState::COLD_IDLE; 2836 state->mColdFutexAddr = &mFastMixerFutex; 2837 state->mColdGen++; 2838 mFastMixerFutex = 0; 2839 sq->end(); 2840 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2841 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2842 if (kUseFastMixer == FastMixer_Dynamic) { 2843 mNormalSink = mOutputSink; 2844 } 2845#ifdef AUDIO_WATCHDOG 2846 if (mAudioWatchdog != 0) { 2847 mAudioWatchdog->pause(); 2848 } 2849#endif 2850 } else { 2851 sq->end(false /*didModify*/); 2852 } 2853 } 2854 PlaybackThread::threadLoop_standby(); 2855} 2856 2857// shared by MIXER and DIRECT, overridden by DUPLICATING 2858void AudioFlinger::PlaybackThread::threadLoop_standby() 2859{ 2860 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 2861 mOutput->stream->common.standby(&mOutput->stream->common); 2862} 2863 2864void AudioFlinger::MixerThread::threadLoop_mix() 2865{ 2866 // obtain the presentation timestamp of the next output buffer 2867 int64_t pts; 2868 status_t status = INVALID_OPERATION; 2869 2870 if (mNormalSink != 0) { 2871 status = mNormalSink->getNextWriteTimestamp(&pts); 2872 } else { 2873 status = mOutputSink->getNextWriteTimestamp(&pts); 2874 } 2875 2876 if (status != NO_ERROR) { 2877 pts = AudioBufferProvider::kInvalidPTS; 2878 } 2879 2880 // mix buffers... 2881 mAudioMixer->process(pts); 2882 // increase sleep time progressively when application underrun condition clears. 2883 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2884 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2885 // such that we would underrun the audio HAL. 2886 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2887 sleepTimeShift--; 2888 } 2889 sleepTime = 0; 2890 standbyTime = systemTime() + standbyDelay; 2891 //TODO: delay standby when effects have a tail 2892} 2893 2894void AudioFlinger::MixerThread::threadLoop_sleepTime() 2895{ 2896 // If no tracks are ready, sleep once for the duration of an output 2897 // buffer size, then write 0s to the output 2898 if (sleepTime == 0) { 2899 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2900 sleepTime = activeSleepTime >> sleepTimeShift; 2901 if (sleepTime < kMinThreadSleepTimeUs) { 2902 sleepTime = kMinThreadSleepTimeUs; 2903 } 2904 // reduce sleep time in case of consecutive application underruns to avoid 2905 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2906 // duration we would end up writing less data than needed by the audio HAL if 2907 // the condition persists. 2908 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2909 sleepTimeShift++; 2910 } 2911 } else { 2912 sleepTime = idleSleepTime; 2913 } 2914 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2915 memset (mMixBuffer, 0, mixBufferSize); 2916 sleepTime = 0; 2917 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 2918 "anticipated start"); 2919 } 2920 // TODO add standby time extension fct of effect tail 2921} 2922 2923// prepareTracks_l() must be called with ThreadBase::mLock held 2924AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2925 Vector< sp<Track> > *tracksToRemove) 2926{ 2927 2928 mixer_state mixerStatus = MIXER_IDLE; 2929 // find out which tracks need to be processed 2930 size_t count = mActiveTracks.size(); 2931 size_t mixedTracks = 0; 2932 size_t tracksWithEffect = 0; 2933 // counts only _active_ fast tracks 2934 size_t fastTracks = 0; 2935 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2936 2937 float masterVolume = mMasterVolume; 2938 bool masterMute = mMasterMute; 2939 2940 if (masterMute) { 2941 masterVolume = 0; 2942 } 2943 // Delegate master volume control to effect in output mix effect chain if needed 2944 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2945 if (chain != 0) { 2946 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2947 chain->setVolume_l(&v, &v); 2948 masterVolume = (float)((v + (1 << 23)) >> 24); 2949 chain.clear(); 2950 } 2951 2952 // prepare a new state to push 2953 FastMixerStateQueue *sq = NULL; 2954 FastMixerState *state = NULL; 2955 bool didModify = false; 2956 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2957 if (mFastMixer != NULL) { 2958 sq = mFastMixer->sq(); 2959 state = sq->begin(); 2960 } 2961 2962 for (size_t i=0 ; i<count ; i++) { 2963 sp<Track> t = mActiveTracks[i].promote(); 2964 if (t == 0) continue; 2965 2966 // this const just means the local variable doesn't change 2967 Track* const track = t.get(); 2968 2969 // process fast tracks 2970 if (track->isFastTrack()) { 2971 2972 // It's theoretically possible (though unlikely) for a fast track to be created 2973 // and then removed within the same normal mix cycle. This is not a problem, as 2974 // the track never becomes active so it's fast mixer slot is never touched. 2975 // The converse, of removing an (active) track and then creating a new track 2976 // at the identical fast mixer slot within the same normal mix cycle, 2977 // is impossible because the slot isn't marked available until the end of each cycle. 2978 int j = track->mFastIndex; 2979 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2980 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2981 FastTrack *fastTrack = &state->mFastTracks[j]; 2982 2983 // Determine whether the track is currently in underrun condition, 2984 // and whether it had a recent underrun. 2985 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2986 FastTrackUnderruns underruns = ftDump->mUnderruns; 2987 uint32_t recentFull = (underruns.mBitFields.mFull - 2988 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2989 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2990 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2991 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2992 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2993 uint32_t recentUnderruns = recentPartial + recentEmpty; 2994 track->mObservedUnderruns = underruns; 2995 // don't count underruns that occur while stopping or pausing 2996 // or stopped which can occur when flush() is called while active 2997 if (!(track->isStopping() || track->isPausing() || track->isStopped())) { 2998 track->mUnderrunCount += recentUnderruns; 2999 } 3000 3001 // This is similar to the state machine for normal tracks, 3002 // with a few modifications for fast tracks. 3003 bool isActive = true; 3004 switch (track->mState) { 3005 case TrackBase::STOPPING_1: 3006 // track stays active in STOPPING_1 state until first underrun 3007 if (recentUnderruns > 0) { 3008 track->mState = TrackBase::STOPPING_2; 3009 } 3010 break; 3011 case TrackBase::PAUSING: 3012 // ramp down is not yet implemented 3013 track->setPaused(); 3014 break; 3015 case TrackBase::RESUMING: 3016 // ramp up is not yet implemented 3017 track->mState = TrackBase::ACTIVE; 3018 break; 3019 case TrackBase::ACTIVE: 3020 if (recentFull > 0 || recentPartial > 0) { 3021 // track has provided at least some frames recently: reset retry count 3022 track->mRetryCount = kMaxTrackRetries; 3023 } 3024 if (recentUnderruns == 0) { 3025 // no recent underruns: stay active 3026 break; 3027 } 3028 // there has recently been an underrun of some kind 3029 if (track->sharedBuffer() == 0) { 3030 // were any of the recent underruns "empty" (no frames available)? 3031 if (recentEmpty == 0) { 3032 // no, then ignore the partial underruns as they are allowed indefinitely 3033 break; 3034 } 3035 // there has recently been an "empty" underrun: decrement the retry counter 3036 if (--(track->mRetryCount) > 0) { 3037 break; 3038 } 3039 // indicate to client process that the track was disabled because of underrun; 3040 // it will then automatically call start() when data is available 3041 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags); 3042 // remove from active list, but state remains ACTIVE [confusing but true] 3043 isActive = false; 3044 break; 3045 } 3046 // fall through 3047 case TrackBase::STOPPING_2: 3048 case TrackBase::PAUSED: 3049 case TrackBase::TERMINATED: 3050 case TrackBase::STOPPED: 3051 case TrackBase::FLUSHED: // flush() while active 3052 // Check for presentation complete if track is inactive 3053 // We have consumed all the buffers of this track. 3054 // This would be incomplete if we auto-paused on underrun 3055 { 3056 size_t audioHALFrames = 3057 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3058 size_t framesWritten = mBytesWritten / mFrameSize; 3059 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 3060 // track stays in active list until presentation is complete 3061 break; 3062 } 3063 } 3064 if (track->isStopping_2()) { 3065 track->mState = TrackBase::STOPPED; 3066 } 3067 if (track->isStopped()) { 3068 // Can't reset directly, as fast mixer is still polling this track 3069 // track->reset(); 3070 // So instead mark this track as needing to be reset after push with ack 3071 resetMask |= 1 << i; 3072 } 3073 isActive = false; 3074 break; 3075 case TrackBase::IDLE: 3076 default: 3077 LOG_FATAL("unexpected track state %d", track->mState); 3078 } 3079 3080 if (isActive) { 3081 // was it previously inactive? 3082 if (!(state->mTrackMask & (1 << j))) { 3083 ExtendedAudioBufferProvider *eabp = track; 3084 VolumeProvider *vp = track; 3085 fastTrack->mBufferProvider = eabp; 3086 fastTrack->mVolumeProvider = vp; 3087 fastTrack->mSampleRate = track->mSampleRate; 3088 fastTrack->mChannelMask = track->mChannelMask; 3089 fastTrack->mGeneration++; 3090 state->mTrackMask |= 1 << j; 3091 didModify = true; 3092 // no acknowledgement required for newly active tracks 3093 } 3094 // cache the combined master volume and stream type volume for fast mixer; this 3095 // lacks any synchronization or barrier so VolumeProvider may read a stale value 3096 track->mCachedVolume = track->isMuted() ? 3097 0 : masterVolume * mStreamTypes[track->streamType()].volume; 3098 ++fastTracks; 3099 } else { 3100 // was it previously active? 3101 if (state->mTrackMask & (1 << j)) { 3102 fastTrack->mBufferProvider = NULL; 3103 fastTrack->mGeneration++; 3104 state->mTrackMask &= ~(1 << j); 3105 didModify = true; 3106 // If any fast tracks were removed, we must wait for acknowledgement 3107 // because we're about to decrement the last sp<> on those tracks. 3108 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3109 } else { 3110 LOG_FATAL("fast track %d should have been active", j); 3111 } 3112 tracksToRemove->add(track); 3113 // Avoids a misleading display in dumpsys 3114 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 3115 } 3116 continue; 3117 } 3118 3119 { // local variable scope to avoid goto warning 3120 3121 audio_track_cblk_t* cblk = track->cblk(); 3122 3123 // The first time a track is added we wait 3124 // for all its buffers to be filled before processing it 3125 int name = track->name(); 3126 // make sure that we have enough frames to mix one full buffer. 3127 // enforce this condition only once to enable draining the buffer in case the client 3128 // app does not call stop() and relies on underrun to stop: 3129 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 3130 // during last round 3131 uint32_t minFrames = 1; 3132 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 3133 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 3134 if (t->sampleRate() == mSampleRate) { 3135 minFrames = mNormalFrameCount; 3136 } else { 3137 // +1 for rounding and +1 for additional sample needed for interpolation 3138 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1; 3139 // add frames already consumed but not yet released by the resampler 3140 // because cblk->framesReady() will include these frames 3141 minFrames += mAudioMixer->getUnreleasedFrames(track->name()); 3142 // the minimum track buffer size is normally twice the number of frames necessary 3143 // to fill one buffer and the resampler should not leave more than one buffer worth 3144 // of unreleased frames after each pass, but just in case... 3145 ALOG_ASSERT(minFrames <= cblk->frameCount); 3146 } 3147 } 3148 if ((track->framesReady() >= minFrames) && track->isReady() && 3149 !track->isPaused() && !track->isTerminated()) 3150 { 3151 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, 3152 this); 3153 3154 mixedTracks++; 3155 3156 // track->mainBuffer() != mMixBuffer means there is an effect chain 3157 // connected to the track 3158 chain.clear(); 3159 if (track->mainBuffer() != mMixBuffer) { 3160 chain = getEffectChain_l(track->sessionId()); 3161 // Delegate volume control to effect in track effect chain if needed 3162 if (chain != 0) { 3163 tracksWithEffect++; 3164 } else { 3165 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 3166 "session %d", 3167 name, track->sessionId()); 3168 } 3169 } 3170 3171 3172 int param = AudioMixer::VOLUME; 3173 if (track->mFillingUpStatus == Track::FS_FILLED) { 3174 // no ramp for the first volume setting 3175 track->mFillingUpStatus = Track::FS_ACTIVE; 3176 if (track->mState == TrackBase::RESUMING) { 3177 track->mState = TrackBase::ACTIVE; 3178 param = AudioMixer::RAMP_VOLUME; 3179 } 3180 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3181 } else if (cblk->server != 0) { 3182 // If the track is stopped before the first frame was mixed, 3183 // do not apply ramp 3184 param = AudioMixer::RAMP_VOLUME; 3185 } 3186 3187 // compute volume for this track 3188 uint32_t vl, vr, va; 3189 if (track->isMuted() || track->isPausing() || 3190 mStreamTypes[track->streamType()].mute) { 3191 vl = vr = va = 0; 3192 if (track->isPausing()) { 3193 track->setPaused(); 3194 } 3195 } else { 3196 3197 // read original volumes with volume control 3198 float typeVolume = mStreamTypes[track->streamType()].volume; 3199 float v = masterVolume * typeVolume; 3200 uint32_t vlr = cblk->getVolumeLR(); 3201 vl = vlr & 0xFFFF; 3202 vr = vlr >> 16; 3203 // track volumes come from shared memory, so can't be trusted and must be clamped 3204 if (vl > MAX_GAIN_INT) { 3205 ALOGV("Track left volume out of range: %04X", vl); 3206 vl = MAX_GAIN_INT; 3207 } 3208 if (vr > MAX_GAIN_INT) { 3209 ALOGV("Track right volume out of range: %04X", vr); 3210 vr = MAX_GAIN_INT; 3211 } 3212 // now apply the master volume and stream type volume 3213 vl = (uint32_t)(v * vl) << 12; 3214 vr = (uint32_t)(v * vr) << 12; 3215 // assuming master volume and stream type volume each go up to 1.0, 3216 // vl and vr are now in 8.24 format 3217 3218 uint16_t sendLevel = cblk->getSendLevel_U4_12(); 3219 // send level comes from shared memory and so may be corrupt 3220 if (sendLevel > MAX_GAIN_INT) { 3221 ALOGV("Track send level out of range: %04X", sendLevel); 3222 sendLevel = MAX_GAIN_INT; 3223 } 3224 va = (uint32_t)(v * sendLevel); 3225 } 3226 // Delegate volume control to effect in track effect chain if needed 3227 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3228 // Do not ramp volume if volume is controlled by effect 3229 param = AudioMixer::VOLUME; 3230 track->mHasVolumeController = true; 3231 } else { 3232 // force no volume ramp when volume controller was just disabled or removed 3233 // from effect chain to avoid volume spike 3234 if (track->mHasVolumeController) { 3235 param = AudioMixer::VOLUME; 3236 } 3237 track->mHasVolumeController = false; 3238 } 3239 3240 // Convert volumes from 8.24 to 4.12 format 3241 // This additional clamping is needed in case chain->setVolume_l() overshot 3242 vl = (vl + (1 << 11)) >> 12; 3243 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT; 3244 vr = (vr + (1 << 11)) >> 12; 3245 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT; 3246 3247 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3248 3249 // XXX: these things DON'T need to be done each time 3250 mAudioMixer->setBufferProvider(name, track); 3251 mAudioMixer->enable(name); 3252 3253 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3254 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3255 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3256 mAudioMixer->setParameter( 3257 name, 3258 AudioMixer::TRACK, 3259 AudioMixer::FORMAT, (void *)track->format()); 3260 mAudioMixer->setParameter( 3261 name, 3262 AudioMixer::TRACK, 3263 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3264 mAudioMixer->setParameter( 3265 name, 3266 AudioMixer::RESAMPLE, 3267 AudioMixer::SAMPLE_RATE, 3268 (void *)(cblk->sampleRate)); 3269 mAudioMixer->setParameter( 3270 name, 3271 AudioMixer::TRACK, 3272 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3273 mAudioMixer->setParameter( 3274 name, 3275 AudioMixer::TRACK, 3276 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3277 3278 // reset retry count 3279 track->mRetryCount = kMaxTrackRetries; 3280 3281 // If one track is ready, set the mixer ready if: 3282 // - the mixer was not ready during previous round OR 3283 // - no other track is not ready 3284 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3285 mixerStatus != MIXER_TRACKS_ENABLED) { 3286 mixerStatus = MIXER_TRACKS_READY; 3287 } 3288 } else { 3289 // clear effect chain input buffer if an active track underruns to avoid sending 3290 // previous audio buffer again to effects 3291 chain = getEffectChain_l(track->sessionId()); 3292 if (chain != 0) { 3293 chain->clearInputBuffer(); 3294 } 3295 3296 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, 3297 cblk->server, this); 3298 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3299 track->isStopped() || track->isPaused()) { 3300 // We have consumed all the buffers of this track. 3301 // Remove it from the list of active tracks. 3302 // TODO: use actual buffer filling status instead of latency when available from 3303 // audio HAL 3304 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3305 size_t framesWritten = mBytesWritten / mFrameSize; 3306 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3307 if (track->isStopped()) { 3308 track->reset(); 3309 } 3310 tracksToRemove->add(track); 3311 } 3312 } else { 3313 track->mUnderrunCount++; 3314 // No buffers for this track. Give it a few chances to 3315 // fill a buffer, then remove it from active list. 3316 if (--(track->mRetryCount) <= 0) { 3317 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3318 tracksToRemove->add(track); 3319 // indicate to client process that the track was disabled because of underrun; 3320 // it will then automatically call start() when data is available 3321 android_atomic_or(CBLK_DISABLED, &cblk->flags); 3322 // If one track is not ready, mark the mixer also not ready if: 3323 // - the mixer was ready during previous round OR 3324 // - no other track is ready 3325 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3326 mixerStatus != MIXER_TRACKS_READY) { 3327 mixerStatus = MIXER_TRACKS_ENABLED; 3328 } 3329 } 3330 mAudioMixer->disable(name); 3331 } 3332 3333 } // local variable scope to avoid goto warning 3334track_is_ready: ; 3335 3336 } 3337 3338 // Push the new FastMixer state if necessary 3339 bool pauseAudioWatchdog = false; 3340 if (didModify) { 3341 state->mFastTracksGen++; 3342 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3343 if (kUseFastMixer == FastMixer_Dynamic && 3344 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3345 state->mCommand = FastMixerState::COLD_IDLE; 3346 state->mColdFutexAddr = &mFastMixerFutex; 3347 state->mColdGen++; 3348 mFastMixerFutex = 0; 3349 if (kUseFastMixer == FastMixer_Dynamic) { 3350 mNormalSink = mOutputSink; 3351 } 3352 // If we go into cold idle, need to wait for acknowledgement 3353 // so that fast mixer stops doing I/O. 3354 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3355 pauseAudioWatchdog = true; 3356 } 3357 sq->end(); 3358 } 3359 if (sq != NULL) { 3360 sq->end(didModify); 3361 sq->push(block); 3362 } 3363#ifdef AUDIO_WATCHDOG 3364 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3365 mAudioWatchdog->pause(); 3366 } 3367#endif 3368 3369 // Now perform the deferred reset on fast tracks that have stopped 3370 while (resetMask != 0) { 3371 size_t i = __builtin_ctz(resetMask); 3372 ALOG_ASSERT(i < count); 3373 resetMask &= ~(1 << i); 3374 sp<Track> t = mActiveTracks[i].promote(); 3375 if (t == 0) continue; 3376 Track* track = t.get(); 3377 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3378 track->reset(); 3379 } 3380 3381 // remove all the tracks that need to be... 3382 count = tracksToRemove->size(); 3383 if (CC_UNLIKELY(count)) { 3384 for (size_t i=0 ; i<count ; i++) { 3385 const sp<Track>& track = tracksToRemove->itemAt(i); 3386 mActiveTracks.remove(track); 3387 if (track->mainBuffer() != mMixBuffer) { 3388 chain = getEffectChain_l(track->sessionId()); 3389 if (chain != 0) { 3390 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 3391 track->sessionId()); 3392 chain->decActiveTrackCnt(); 3393 } 3394 } 3395 if (track->isTerminated()) { 3396 removeTrack_l(track); 3397 } 3398 } 3399 } 3400 3401 // mix buffer must be cleared if all tracks are connected to an 3402 // effect chain as in this case the mixer will not write to 3403 // mix buffer and track effects will accumulate into it 3404 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3405 (mixedTracks == 0 && fastTracks > 0)) { 3406 // FIXME as a performance optimization, should remember previous zero status 3407 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3408 } 3409 3410 // if any fast tracks, then status is ready 3411 mMixerStatusIgnoringFastTracks = mixerStatus; 3412 if (fastTracks > 0) { 3413 mixerStatus = MIXER_TRACKS_READY; 3414 } 3415 return mixerStatus; 3416} 3417 3418/* 3419The derived values that are cached: 3420 - mixBufferSize from frame count * frame size 3421 - activeSleepTime from activeSleepTimeUs() 3422 - idleSleepTime from idleSleepTimeUs() 3423 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 3424 - maxPeriod from frame count and sample rate (MIXER only) 3425 3426The parameters that affect these derived values are: 3427 - frame count 3428 - frame size 3429 - sample rate 3430 - device type: A2DP or not 3431 - device latency 3432 - format: PCM or not 3433 - active sleep time 3434 - idle sleep time 3435*/ 3436 3437void AudioFlinger::PlaybackThread::cacheParameters_l() 3438{ 3439 mixBufferSize = mNormalFrameCount * mFrameSize; 3440 activeSleepTime = activeSleepTimeUs(); 3441 idleSleepTime = idleSleepTimeUs(); 3442} 3443 3444void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 3445{ 3446 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 3447 this, streamType, mTracks.size()); 3448 Mutex::Autolock _l(mLock); 3449 3450 size_t size = mTracks.size(); 3451 for (size_t i = 0; i < size; i++) { 3452 sp<Track> t = mTracks[i]; 3453 if (t->streamType() == streamType) { 3454 android_atomic_or(CBLK_INVALID, &t->mCblk->flags); 3455 t->mCblk->cv.signal(); 3456 } 3457 } 3458} 3459 3460// getTrackName_l() must be called with ThreadBase::mLock held 3461int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) 3462{ 3463 return mAudioMixer->getTrackName(channelMask, sessionId); 3464} 3465 3466// deleteTrackName_l() must be called with ThreadBase::mLock held 3467void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3468{ 3469 ALOGV("remove track (%d) and delete from mixer", name); 3470 mAudioMixer->deleteTrackName(name); 3471} 3472 3473// checkForNewParameters_l() must be called with ThreadBase::mLock held 3474bool AudioFlinger::MixerThread::checkForNewParameters_l() 3475{ 3476 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3477 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3478 bool reconfig = false; 3479 3480 while (!mNewParameters.isEmpty()) { 3481 3482 if (mFastMixer != NULL) { 3483 FastMixerStateQueue *sq = mFastMixer->sq(); 3484 FastMixerState *state = sq->begin(); 3485 if (!(state->mCommand & FastMixerState::IDLE)) { 3486 previousCommand = state->mCommand; 3487 state->mCommand = FastMixerState::HOT_IDLE; 3488 sq->end(); 3489 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3490 } else { 3491 sq->end(false /*didModify*/); 3492 } 3493 } 3494 3495 status_t status = NO_ERROR; 3496 String8 keyValuePair = mNewParameters[0]; 3497 AudioParameter param = AudioParameter(keyValuePair); 3498 int value; 3499 3500 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3501 reconfig = true; 3502 } 3503 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3504 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3505 status = BAD_VALUE; 3506 } else { 3507 reconfig = true; 3508 } 3509 } 3510 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3511 if (value != AUDIO_CHANNEL_OUT_STEREO) { 3512 status = BAD_VALUE; 3513 } else { 3514 reconfig = true; 3515 } 3516 } 3517 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3518 // do not accept frame count changes if tracks are open as the track buffer 3519 // size depends on frame count and correct behavior would not be guaranteed 3520 // if frame count is changed after track creation 3521 if (!mTracks.isEmpty()) { 3522 status = INVALID_OPERATION; 3523 } else { 3524 reconfig = true; 3525 } 3526 } 3527 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3528#ifdef ADD_BATTERY_DATA 3529 // when changing the audio output device, call addBatteryData to notify 3530 // the change 3531 if (mOutDevice != value) { 3532 uint32_t params = 0; 3533 // check whether speaker is on 3534 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3535 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3536 } 3537 3538 audio_devices_t deviceWithoutSpeaker 3539 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3540 // check if any other device (except speaker) is on 3541 if (value & deviceWithoutSpeaker ) { 3542 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3543 } 3544 3545 if (params != 0) { 3546 addBatteryData(params); 3547 } 3548 } 3549#endif 3550 3551 // forward device change to effects that have requested to be 3552 // aware of attached audio device. 3553 mOutDevice = value; 3554 for (size_t i = 0; i < mEffectChains.size(); i++) { 3555 mEffectChains[i]->setDevice_l(mOutDevice); 3556 } 3557 } 3558 3559 if (status == NO_ERROR) { 3560 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3561 keyValuePair.string()); 3562 if (!mStandby && status == INVALID_OPERATION) { 3563 mOutput->stream->common.standby(&mOutput->stream->common); 3564 mStandby = true; 3565 mBytesWritten = 0; 3566 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3567 keyValuePair.string()); 3568 } 3569 if (status == NO_ERROR && reconfig) { 3570 delete mAudioMixer; 3571 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't) 3572 mAudioMixer = NULL; 3573 readOutputParameters(); 3574 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3575 for (size_t i = 0; i < mTracks.size() ; i++) { 3576 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); 3577 if (name < 0) break; 3578 mTracks[i]->mName = name; 3579 // limit track sample rate to 2 x new output sample rate 3580 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) { 3581 mTracks[i]->mCblk->sampleRate = 2 * sampleRate(); 3582 } 3583 } 3584 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3585 } 3586 } 3587 3588 mNewParameters.removeAt(0); 3589 3590 mParamStatus = status; 3591 mParamCond.signal(); 3592 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3593 // already timed out waiting for the status and will never signal the condition. 3594 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3595 } 3596 3597 if (!(previousCommand & FastMixerState::IDLE)) { 3598 ALOG_ASSERT(mFastMixer != NULL); 3599 FastMixerStateQueue *sq = mFastMixer->sq(); 3600 FastMixerState *state = sq->begin(); 3601 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3602 state->mCommand = previousCommand; 3603 sq->end(); 3604 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3605 } 3606 3607 return reconfig; 3608} 3609 3610void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id) 3611{ 3612 NBAIO_Source *teeSource = source.get(); 3613 if (teeSource != NULL) { 3614 char teeTime[16]; 3615 struct timeval tv; 3616 gettimeofday(&tv, NULL); 3617 struct tm tm; 3618 localtime_r(&tv.tv_sec, &tm); 3619 strftime(teeTime, sizeof(teeTime), "%T", &tm); 3620 char teePath[64]; 3621 sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id); 3622 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); 3623 if (teeFd >= 0) { 3624 char wavHeader[44]; 3625 memcpy(wavHeader, 3626 "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", 3627 sizeof(wavHeader)); 3628 NBAIO_Format format = teeSource->format(); 3629 unsigned channelCount = Format_channelCount(format); 3630 ALOG_ASSERT(channelCount <= FCC_2); 3631 uint32_t sampleRate = Format_sampleRate(format); 3632 wavHeader[22] = channelCount; // number of channels 3633 wavHeader[24] = sampleRate; // sample rate 3634 wavHeader[25] = sampleRate >> 8; 3635 wavHeader[32] = channelCount * 2; // block alignment 3636 write(teeFd, wavHeader, sizeof(wavHeader)); 3637 size_t total = 0; 3638 bool firstRead = true; 3639 for (;;) { 3640#define TEE_SINK_READ 1024 3641 short buffer[TEE_SINK_READ * FCC_2]; 3642 size_t count = TEE_SINK_READ; 3643 ssize_t actual = teeSource->read(buffer, count, 3644 AudioBufferProvider::kInvalidPTS); 3645 bool wasFirstRead = firstRead; 3646 firstRead = false; 3647 if (actual <= 0) { 3648 if (actual == (ssize_t) OVERRUN && wasFirstRead) { 3649 continue; 3650 } 3651 break; 3652 } 3653 ALOG_ASSERT(actual <= (ssize_t)count); 3654 write(teeFd, buffer, actual * channelCount * sizeof(short)); 3655 total += actual; 3656 } 3657 lseek(teeFd, (off_t) 4, SEEK_SET); 3658 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8; 3659 write(teeFd, &temp, sizeof(temp)); 3660 lseek(teeFd, (off_t) 40, SEEK_SET); 3661 temp = total * channelCount * sizeof(short); 3662 write(teeFd, &temp, sizeof(temp)); 3663 close(teeFd); 3664 fdprintf(fd, "FastMixer tee copied to %s\n", teePath); 3665 } else { 3666 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno)); 3667 } 3668 } 3669} 3670 3671void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3672{ 3673 const size_t SIZE = 256; 3674 char buffer[SIZE]; 3675 String8 result; 3676 3677 PlaybackThread::dumpInternals(fd, args); 3678 3679 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 3680 result.append(buffer); 3681 write(fd, result.string(), result.size()); 3682 3683 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3684 FastMixerDumpState copy = mFastMixerDumpState; 3685 copy.dump(fd); 3686 3687#ifdef STATE_QUEUE_DUMP 3688 // Similar for state queue 3689 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3690 observerCopy.dump(fd); 3691 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3692 mutatorCopy.dump(fd); 3693#endif 3694 3695 // Write the tee output to a .wav file 3696 dumpTee(fd, mTeeSource, mId); 3697 3698#ifdef AUDIO_WATCHDOG 3699 if (mAudioWatchdog != 0) { 3700 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3701 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3702 wdCopy.dump(fd); 3703 } 3704#endif 3705} 3706 3707uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3708{ 3709 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3710} 3711 3712uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3713{ 3714 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3715} 3716 3717void AudioFlinger::MixerThread::cacheParameters_l() 3718{ 3719 PlaybackThread::cacheParameters_l(); 3720 3721 // FIXME: Relaxed timing because of a certain device that can't meet latency 3722 // Should be reduced to 2x after the vendor fixes the driver issue 3723 // increase threshold again due to low power audio mode. The way this warning 3724 // threshold is calculated and its usefulness should be reconsidered anyway. 3725 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3726} 3727 3728// ---------------------------------------------------------------------------- 3729AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3730 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3731 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3732 // mLeftVolFloat, mRightVolFloat 3733{ 3734} 3735 3736AudioFlinger::DirectOutputThread::~DirectOutputThread() 3737{ 3738} 3739 3740AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3741 Vector< sp<Track> > *tracksToRemove 3742) 3743{ 3744 sp<Track> trackToRemove; 3745 3746 mixer_state mixerStatus = MIXER_IDLE; 3747 3748 // find out which tracks need to be processed 3749 if (mActiveTracks.size() != 0) { 3750 sp<Track> t = mActiveTracks[0].promote(); 3751 // The track died recently 3752 if (t == 0) return MIXER_IDLE; 3753 3754 Track* const track = t.get(); 3755 audio_track_cblk_t* cblk = track->cblk(); 3756 3757 // The first time a track is added we wait 3758 // for all its buffers to be filled before processing it 3759 uint32_t minFrames; 3760 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3761 minFrames = mNormalFrameCount; 3762 } else { 3763 minFrames = 1; 3764 } 3765 if ((track->framesReady() >= minFrames) && track->isReady() && 3766 !track->isPaused() && !track->isTerminated()) 3767 { 3768 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server); 3769 3770 if (track->mFillingUpStatus == Track::FS_FILLED) { 3771 track->mFillingUpStatus = Track::FS_ACTIVE; 3772 mLeftVolFloat = mRightVolFloat = 0; 3773 if (track->mState == TrackBase::RESUMING) { 3774 track->mState = TrackBase::ACTIVE; 3775 } 3776 } 3777 3778 // compute volume for this track 3779 float left, right; 3780 if (track->isMuted() || mMasterMute || track->isPausing() || 3781 mStreamTypes[track->streamType()].mute) { 3782 left = right = 0; 3783 if (track->isPausing()) { 3784 track->setPaused(); 3785 } 3786 } else { 3787 float typeVolume = mStreamTypes[track->streamType()].volume; 3788 float v = mMasterVolume * typeVolume; 3789 uint32_t vlr = cblk->getVolumeLR(); 3790 float v_clamped = v * (vlr & 0xFFFF); 3791 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3792 left = v_clamped/MAX_GAIN; 3793 v_clamped = v * (vlr >> 16); 3794 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3795 right = v_clamped/MAX_GAIN; 3796 } 3797 3798 if (left != mLeftVolFloat || right != mRightVolFloat) { 3799 mLeftVolFloat = left; 3800 mRightVolFloat = right; 3801 3802 // Convert volumes from float to 8.24 3803 uint32_t vl = (uint32_t)(left * (1 << 24)); 3804 uint32_t vr = (uint32_t)(right * (1 << 24)); 3805 3806 // Delegate volume control to effect in track effect chain if needed 3807 // only one effect chain can be present on DirectOutputThread, so if 3808 // there is one, the track is connected to it 3809 if (!mEffectChains.isEmpty()) { 3810 // Do not ramp volume if volume is controlled by effect 3811 mEffectChains[0]->setVolume_l(&vl, &vr); 3812 left = (float)vl / (1 << 24); 3813 right = (float)vr / (1 << 24); 3814 } 3815 mOutput->stream->set_volume(mOutput->stream, left, right); 3816 } 3817 3818 // reset retry count 3819 track->mRetryCount = kMaxTrackRetriesDirect; 3820 mActiveTrack = t; 3821 mixerStatus = MIXER_TRACKS_READY; 3822 } else { 3823 // clear effect chain input buffer if an active track underruns to avoid sending 3824 // previous audio buffer again to effects 3825 if (!mEffectChains.isEmpty()) { 3826 mEffectChains[0]->clearInputBuffer(); 3827 } 3828 3829 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server); 3830 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3831 track->isStopped() || track->isPaused()) { 3832 // We have consumed all the buffers of this track. 3833 // Remove it from the list of active tracks. 3834 // TODO: implement behavior for compressed audio 3835 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3836 size_t framesWritten = mBytesWritten / mFrameSize; 3837 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3838 if (track->isStopped()) { 3839 track->reset(); 3840 } 3841 trackToRemove = track; 3842 } 3843 } else { 3844 // No buffers for this track. Give it a few chances to 3845 // fill a buffer, then remove it from active list. 3846 if (--(track->mRetryCount) <= 0) { 3847 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3848 trackToRemove = track; 3849 } else { 3850 mixerStatus = MIXER_TRACKS_ENABLED; 3851 } 3852 } 3853 } 3854 } 3855 3856 // FIXME merge this with similar code for removing multiple tracks 3857 // remove all the tracks that need to be... 3858 if (CC_UNLIKELY(trackToRemove != 0)) { 3859 tracksToRemove->add(trackToRemove); 3860 mActiveTracks.remove(trackToRemove); 3861 if (!mEffectChains.isEmpty()) { 3862 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(), 3863 trackToRemove->sessionId()); 3864 mEffectChains[0]->decActiveTrackCnt(); 3865 } 3866 if (trackToRemove->isTerminated()) { 3867 removeTrack_l(trackToRemove); 3868 } 3869 } 3870 3871 return mixerStatus; 3872} 3873 3874void AudioFlinger::DirectOutputThread::threadLoop_mix() 3875{ 3876 AudioBufferProvider::Buffer buffer; 3877 size_t frameCount = mFrameCount; 3878 int8_t *curBuf = (int8_t *)mMixBuffer; 3879 // output audio to hardware 3880 while (frameCount) { 3881 buffer.frameCount = frameCount; 3882 mActiveTrack->getNextBuffer(&buffer); 3883 if (CC_UNLIKELY(buffer.raw == NULL)) { 3884 memset(curBuf, 0, frameCount * mFrameSize); 3885 break; 3886 } 3887 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3888 frameCount -= buffer.frameCount; 3889 curBuf += buffer.frameCount * mFrameSize; 3890 mActiveTrack->releaseBuffer(&buffer); 3891 } 3892 sleepTime = 0; 3893 standbyTime = systemTime() + standbyDelay; 3894 mActiveTrack.clear(); 3895 3896} 3897 3898void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3899{ 3900 if (sleepTime == 0) { 3901 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3902 sleepTime = activeSleepTime; 3903 } else { 3904 sleepTime = idleSleepTime; 3905 } 3906 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3907 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3908 sleepTime = 0; 3909 } 3910} 3911 3912// getTrackName_l() must be called with ThreadBase::mLock held 3913int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask, 3914 int sessionId) 3915{ 3916 return 0; 3917} 3918 3919// deleteTrackName_l() must be called with ThreadBase::mLock held 3920void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 3921{ 3922} 3923 3924// checkForNewParameters_l() must be called with ThreadBase::mLock held 3925bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3926{ 3927 bool reconfig = false; 3928 3929 while (!mNewParameters.isEmpty()) { 3930 status_t status = NO_ERROR; 3931 String8 keyValuePair = mNewParameters[0]; 3932 AudioParameter param = AudioParameter(keyValuePair); 3933 int value; 3934 3935 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3936 // do not accept frame count changes if tracks are open as the track buffer 3937 // size depends on frame count and correct behavior would not be garantied 3938 // if frame count is changed after track creation 3939 if (!mTracks.isEmpty()) { 3940 status = INVALID_OPERATION; 3941 } else { 3942 reconfig = true; 3943 } 3944 } 3945 if (status == NO_ERROR) { 3946 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3947 keyValuePair.string()); 3948 if (!mStandby && status == INVALID_OPERATION) { 3949 mOutput->stream->common.standby(&mOutput->stream->common); 3950 mStandby = true; 3951 mBytesWritten = 0; 3952 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3953 keyValuePair.string()); 3954 } 3955 if (status == NO_ERROR && reconfig) { 3956 readOutputParameters(); 3957 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3958 } 3959 } 3960 3961 mNewParameters.removeAt(0); 3962 3963 mParamStatus = status; 3964 mParamCond.signal(); 3965 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3966 // already timed out waiting for the status and will never signal the condition. 3967 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3968 } 3969 return reconfig; 3970} 3971 3972uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3973{ 3974 uint32_t time; 3975 if (audio_is_linear_pcm(mFormat)) { 3976 time = PlaybackThread::activeSleepTimeUs(); 3977 } else { 3978 time = 10000; 3979 } 3980 return time; 3981} 3982 3983uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3984{ 3985 uint32_t time; 3986 if (audio_is_linear_pcm(mFormat)) { 3987 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3988 } else { 3989 time = 10000; 3990 } 3991 return time; 3992} 3993 3994uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3995{ 3996 uint32_t time; 3997 if (audio_is_linear_pcm(mFormat)) { 3998 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3999 } else { 4000 time = 10000; 4001 } 4002 return time; 4003} 4004 4005void AudioFlinger::DirectOutputThread::cacheParameters_l() 4006{ 4007 PlaybackThread::cacheParameters_l(); 4008 4009 // use shorter standby delay as on normal output to release 4010 // hardware resources as soon as possible 4011 standbyDelay = microseconds(activeSleepTime*2); 4012} 4013 4014// ---------------------------------------------------------------------------- 4015 4016AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4017 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4018 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4019 DUPLICATING), 4020 mWaitTimeMs(UINT_MAX) 4021{ 4022 addOutputTrack(mainThread); 4023} 4024 4025AudioFlinger::DuplicatingThread::~DuplicatingThread() 4026{ 4027 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4028 mOutputTracks[i]->destroy(); 4029 } 4030} 4031 4032void AudioFlinger::DuplicatingThread::threadLoop_mix() 4033{ 4034 // mix buffers... 4035 if (outputsReady(outputTracks)) { 4036 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4037 } else { 4038 memset(mMixBuffer, 0, mixBufferSize); 4039 } 4040 sleepTime = 0; 4041 writeFrames = mNormalFrameCount; 4042 standbyTime = systemTime() + standbyDelay; 4043} 4044 4045void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4046{ 4047 if (sleepTime == 0) { 4048 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4049 sleepTime = activeSleepTime; 4050 } else { 4051 sleepTime = idleSleepTime; 4052 } 4053 } else if (mBytesWritten != 0) { 4054 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4055 writeFrames = mNormalFrameCount; 4056 memset(mMixBuffer, 0, mixBufferSize); 4057 } else { 4058 // flush remaining overflow buffers in output tracks 4059 writeFrames = 0; 4060 } 4061 sleepTime = 0; 4062 } 4063} 4064 4065void AudioFlinger::DuplicatingThread::threadLoop_write() 4066{ 4067 for (size_t i = 0; i < outputTracks.size(); i++) { 4068 outputTracks[i]->write(mMixBuffer, writeFrames); 4069 } 4070 mBytesWritten += mixBufferSize; 4071} 4072 4073void AudioFlinger::DuplicatingThread::threadLoop_standby() 4074{ 4075 // DuplicatingThread implements standby by stopping all tracks 4076 for (size_t i = 0; i < outputTracks.size(); i++) { 4077 outputTracks[i]->stop(); 4078 } 4079} 4080 4081void AudioFlinger::DuplicatingThread::saveOutputTracks() 4082{ 4083 outputTracks = mOutputTracks; 4084} 4085 4086void AudioFlinger::DuplicatingThread::clearOutputTracks() 4087{ 4088 outputTracks.clear(); 4089} 4090 4091void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4092{ 4093 Mutex::Autolock _l(mLock); 4094 // FIXME explain this formula 4095 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4096 OutputTrack *outputTrack = new OutputTrack(thread, 4097 this, 4098 mSampleRate, 4099 mFormat, 4100 mChannelMask, 4101 frameCount); 4102 if (outputTrack->cblk() != NULL) { 4103 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4104 mOutputTracks.add(outputTrack); 4105 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4106 updateWaitTime_l(); 4107 } 4108} 4109 4110void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4111{ 4112 Mutex::Autolock _l(mLock); 4113 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4114 if (mOutputTracks[i]->thread() == thread) { 4115 mOutputTracks[i]->destroy(); 4116 mOutputTracks.removeAt(i); 4117 updateWaitTime_l(); 4118 return; 4119 } 4120 } 4121 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4122} 4123 4124// caller must hold mLock 4125void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4126{ 4127 mWaitTimeMs = UINT_MAX; 4128 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4129 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4130 if (strong != 0) { 4131 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4132 if (waitTimeMs < mWaitTimeMs) { 4133 mWaitTimeMs = waitTimeMs; 4134 } 4135 } 4136 } 4137} 4138 4139 4140bool AudioFlinger::DuplicatingThread::outputsReady( 4141 const SortedVector< sp<OutputTrack> > &outputTracks) 4142{ 4143 for (size_t i = 0; i < outputTracks.size(); i++) { 4144 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4145 if (thread == 0) { 4146 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4147 outputTracks[i].get()); 4148 return false; 4149 } 4150 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4151 // see note at standby() declaration 4152 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4153 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4154 thread.get()); 4155 return false; 4156 } 4157 } 4158 return true; 4159} 4160 4161uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4162{ 4163 return (mWaitTimeMs * 1000) / 2; 4164} 4165 4166void AudioFlinger::DuplicatingThread::cacheParameters_l() 4167{ 4168 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4169 updateWaitTime_l(); 4170 4171 MixerThread::cacheParameters_l(); 4172} 4173 4174// ---------------------------------------------------------------------------- 4175 4176// TrackBase constructor must be called with AudioFlinger::mLock held 4177AudioFlinger::ThreadBase::TrackBase::TrackBase( 4178 ThreadBase *thread, 4179 const sp<Client>& client, 4180 uint32_t sampleRate, 4181 audio_format_t format, 4182 audio_channel_mask_t channelMask, 4183 size_t frameCount, 4184 const sp<IMemory>& sharedBuffer, 4185 int sessionId) 4186 : RefBase(), 4187 mThread(thread), 4188 mClient(client), 4189 mCblk(NULL), 4190 // mBuffer 4191 // mBufferEnd 4192 mStepCount(0), 4193 mState(IDLE), 4194 mSampleRate(sampleRate), 4195 mFormat(format), 4196 mChannelMask(channelMask), 4197 mChannelCount(popcount(channelMask)), 4198 mFrameSize(audio_is_linear_pcm(format) ? 4199 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)), 4200 mStepServerFailed(false), 4201 mSessionId(sessionId) 4202{ 4203 // client == 0 implies sharedBuffer == 0 4204 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0)); 4205 4206 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), 4207 sharedBuffer->size()); 4208 4209 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize); 4210 size_t size = sizeof(audio_track_cblk_t); 4211 size_t bufferSize = frameCount * mFrameSize; 4212 if (sharedBuffer == 0) { 4213 size += bufferSize; 4214 } 4215 4216 if (client != 0) { 4217 mCblkMemory = client->heap()->allocate(size); 4218 if (mCblkMemory != 0) { 4219 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer()); 4220 // can't assume mCblk != NULL 4221 } else { 4222 ALOGE("not enough memory for AudioTrack size=%u", size); 4223 client->heap()->dump("AudioTrack"); 4224 return; 4225 } 4226 } else { 4227 mCblk = (audio_track_cblk_t *)(new uint8_t[size]); 4228 // assume mCblk != NULL 4229 } 4230 4231 // construct the shared structure in-place. 4232 if (mCblk != NULL) { 4233 new(mCblk) audio_track_cblk_t(); 4234 // clear all buffers 4235 mCblk->frameCount = frameCount; 4236 mCblk->sampleRate = sampleRate; 4237// uncomment the following lines to quickly test 32-bit wraparound 4238// mCblk->user = 0xffff0000; 4239// mCblk->server = 0xffff0000; 4240// mCblk->userBase = 0xffff0000; 4241// mCblk->serverBase = 0xffff0000; 4242 if (sharedBuffer == 0) { 4243 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 4244 memset(mBuffer, 0, bufferSize); 4245 // Force underrun condition to avoid false underrun callback until first data is 4246 // written to buffer (other flags are cleared) 4247 mCblk->flags = CBLK_UNDERRUN; 4248 } else { 4249 mBuffer = sharedBuffer->pointer(); 4250 } 4251 mBufferEnd = (uint8_t *)mBuffer + bufferSize; 4252 } 4253} 4254 4255AudioFlinger::ThreadBase::TrackBase::~TrackBase() 4256{ 4257 if (mCblk != NULL) { 4258 if (mClient == 0) { 4259 delete mCblk; 4260 } else { 4261 mCblk->~audio_track_cblk_t(); // destroy our shared-structure. 4262 } 4263 } 4264 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 4265 if (mClient != 0) { 4266 // Client destructor must run with AudioFlinger mutex locked 4267 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 4268 // If the client's reference count drops to zero, the associated destructor 4269 // must run with AudioFlinger lock held. Thus the explicit clear() rather than 4270 // relying on the automatic clear() at end of scope. 4271 mClient.clear(); 4272 } 4273} 4274 4275// AudioBufferProvider interface 4276// getNextBuffer() = 0; 4277// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack 4278void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4279{ 4280 buffer->raw = NULL; 4281 mStepCount = buffer->frameCount; 4282 // FIXME See note at getNextBuffer() 4283 (void) step(); // ignore return value of step() 4284 buffer->frameCount = 0; 4285} 4286 4287bool AudioFlinger::ThreadBase::TrackBase::step() { 4288 bool result; 4289 audio_track_cblk_t* cblk = this->cblk(); 4290 4291 result = cblk->stepServer(mStepCount, isOut()); 4292 if (!result) { 4293 ALOGV("stepServer failed acquiring cblk mutex"); 4294 mStepServerFailed = true; 4295 } 4296 return result; 4297} 4298 4299void AudioFlinger::ThreadBase::TrackBase::reset() { 4300 audio_track_cblk_t* cblk = this->cblk(); 4301 4302 cblk->user = 0; 4303 cblk->server = 0; 4304 cblk->userBase = 0; 4305 cblk->serverBase = 0; 4306 mStepServerFailed = false; 4307 ALOGV("TrackBase::reset"); 4308} 4309 4310uint32_t AudioFlinger::ThreadBase::TrackBase::sampleRate() const { 4311 return mCblk->sampleRate; 4312} 4313 4314void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const { 4315 audio_track_cblk_t* cblk = this->cblk(); 4316 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase) * mFrameSize; 4317 int8_t *bufferEnd = bufferStart + frames * mFrameSize; 4318 4319 // Check validity of returned pointer in case the track control block would have been corrupted. 4320 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd), 4321 "TrackBase::getBuffer buffer out of range:\n" 4322 " start: %p, end %p , mBuffer %p mBufferEnd %p\n" 4323 " server %u, serverBase %u, user %u, userBase %u, frameSize %u", 4324 bufferStart, bufferEnd, mBuffer, mBufferEnd, 4325 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, mFrameSize); 4326 4327 return bufferStart; 4328} 4329 4330status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event) 4331{ 4332 mSyncEvents.add(event); 4333 return NO_ERROR; 4334} 4335 4336// ---------------------------------------------------------------------------- 4337 4338// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 4339AudioFlinger::PlaybackThread::Track::Track( 4340 PlaybackThread *thread, 4341 const sp<Client>& client, 4342 audio_stream_type_t streamType, 4343 uint32_t sampleRate, 4344 audio_format_t format, 4345 audio_channel_mask_t channelMask, 4346 size_t frameCount, 4347 const sp<IMemory>& sharedBuffer, 4348 int sessionId, 4349 IAudioFlinger::track_flags_t flags) 4350 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, 4351 sessionId), 4352 mMute(false), 4353 mFillingUpStatus(FS_INVALID), 4354 // mRetryCount initialized later when needed 4355 mSharedBuffer(sharedBuffer), 4356 mStreamType(streamType), 4357 mName(-1), // see note below 4358 mMainBuffer(thread->mixBuffer()), 4359 mAuxBuffer(NULL), 4360 mAuxEffectId(0), mHasVolumeController(false), 4361 mPresentationCompleteFrames(0), 4362 mFlags(flags), 4363 mFastIndex(-1), 4364 mUnderrunCount(0), 4365 mCachedVolume(1.0) 4366{ 4367 if (mCblk != NULL) { 4368 // to avoid leaking a track name, do not allocate one unless there is an mCblk 4369 mName = thread->getTrackName_l(channelMask, sessionId); 4370 mCblk->mName = mName; 4371 if (mName < 0) { 4372 ALOGE("no more track names available"); 4373 return; 4374 } 4375 // only allocate a fast track index if we were able to allocate a normal track name 4376 if (flags & IAudioFlinger::TRACK_FAST) { 4377 ALOG_ASSERT(thread->mFastTrackAvailMask != 0); 4378 int i = __builtin_ctz(thread->mFastTrackAvailMask); 4379 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks); 4380 // FIXME This is too eager. We allocate a fast track index before the 4381 // fast track becomes active. Since fast tracks are a scarce resource, 4382 // this means we are potentially denying other more important fast tracks from 4383 // being created. It would be better to allocate the index dynamically. 4384 mFastIndex = i; 4385 mCblk->mName = i; 4386 // Read the initial underruns because this field is never cleared by the fast mixer 4387 mObservedUnderruns = thread->getFastTrackUnderruns(i); 4388 thread->mFastTrackAvailMask &= ~(1 << i); 4389 } 4390 } 4391 ALOGV("Track constructor name %d, calling pid %d", mName, 4392 IPCThreadState::self()->getCallingPid()); 4393} 4394 4395AudioFlinger::PlaybackThread::Track::~Track() 4396{ 4397 ALOGV("PlaybackThread::Track destructor"); 4398} 4399 4400void AudioFlinger::PlaybackThread::Track::destroy() 4401{ 4402 // NOTE: destroyTrack_l() can remove a strong reference to this Track 4403 // by removing it from mTracks vector, so there is a risk that this Tracks's 4404 // destructor is called. As the destructor needs to lock mLock, 4405 // we must acquire a strong reference on this Track before locking mLock 4406 // here so that the destructor is called only when exiting this function. 4407 // On the other hand, as long as Track::destroy() is only called by 4408 // TrackHandle destructor, the TrackHandle still holds a strong ref on 4409 // this Track with its member mTrack. 4410 sp<Track> keep(this); 4411 { // scope for mLock 4412 sp<ThreadBase> thread = mThread.promote(); 4413 if (thread != 0) { 4414 if (!isOutputTrack()) { 4415 if (mState == ACTIVE || mState == RESUMING) { 4416 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId); 4417 4418#ifdef ADD_BATTERY_DATA 4419 // to track the speaker usage 4420 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 4421#endif 4422 } 4423 AudioSystem::releaseOutput(thread->id()); 4424 } 4425 Mutex::Autolock _l(thread->mLock); 4426 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4427 playbackThread->destroyTrack_l(this); 4428 } 4429 } 4430} 4431 4432/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result) 4433{ 4434 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S M F SRate " 4435 "L dB R dB Server User Main buf Aux Buf Flags Underruns\n"); 4436} 4437 4438void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 4439{ 4440 uint32_t vlr = mCblk->getVolumeLR(); 4441 if (isFastTrack()) { 4442 sprintf(buffer, " F %2d", mFastIndex); 4443 } else { 4444 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0); 4445 } 4446 track_state state = mState; 4447 char stateChar; 4448 switch (state) { 4449 case IDLE: 4450 stateChar = 'I'; 4451 break; 4452 case TERMINATED: 4453 stateChar = 'T'; 4454 break; 4455 case STOPPING_1: 4456 stateChar = 's'; 4457 break; 4458 case STOPPING_2: 4459 stateChar = '5'; 4460 break; 4461 case STOPPED: 4462 stateChar = 'S'; 4463 break; 4464 case RESUMING: 4465 stateChar = 'R'; 4466 break; 4467 case ACTIVE: 4468 stateChar = 'A'; 4469 break; 4470 case PAUSING: 4471 stateChar = 'p'; 4472 break; 4473 case PAUSED: 4474 stateChar = 'P'; 4475 break; 4476 case FLUSHED: 4477 stateChar = 'F'; 4478 break; 4479 default: 4480 stateChar = '?'; 4481 break; 4482 } 4483 char nowInUnderrun; 4484 switch (mObservedUnderruns.mBitFields.mMostRecent) { 4485 case UNDERRUN_FULL: 4486 nowInUnderrun = ' '; 4487 break; 4488 case UNDERRUN_PARTIAL: 4489 nowInUnderrun = '<'; 4490 break; 4491 case UNDERRUN_EMPTY: 4492 nowInUnderrun = '*'; 4493 break; 4494 default: 4495 nowInUnderrun = '?'; 4496 break; 4497 } 4498 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g " 4499 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n", 4500 (mClient == 0) ? getpid_cached : mClient->pid(), 4501 mStreamType, 4502 mFormat, 4503 mChannelMask, 4504 mSessionId, 4505 mStepCount, 4506 mCblk->frameCount, 4507 stateChar, 4508 mMute, 4509 mFillingUpStatus, 4510 mCblk->sampleRate, 4511 20.0 * log10((vlr & 0xFFFF) / 4096.0), 4512 20.0 * log10((vlr >> 16) / 4096.0), 4513 mCblk->server, 4514 mCblk->user, 4515 (int)mMainBuffer, 4516 (int)mAuxBuffer, 4517 mCblk->flags, 4518 mUnderrunCount, 4519 nowInUnderrun); 4520} 4521 4522// AudioBufferProvider interface 4523status_t AudioFlinger::PlaybackThread::Track::getNextBuffer( 4524 AudioBufferProvider::Buffer* buffer, int64_t pts) 4525{ 4526 audio_track_cblk_t* cblk = this->cblk(); 4527 uint32_t framesReady; 4528 uint32_t framesReq = buffer->frameCount; 4529 4530 // Check if last stepServer failed, try to step now 4531 if (mStepServerFailed) { 4532 // FIXME When called by fast mixer, this takes a mutex with tryLock(). 4533 // Since the fast mixer is higher priority than client callback thread, 4534 // it does not result in priority inversion for client. 4535 // But a non-blocking solution would be preferable to avoid 4536 // fast mixer being unable to tryLock(), and 4537 // to avoid the extra context switches if the client wakes up, 4538 // discovers the mutex is locked, then has to wait for fast mixer to unlock. 4539 if (!step()) goto getNextBuffer_exit; 4540 ALOGV("stepServer recovered"); 4541 mStepServerFailed = false; 4542 } 4543 4544 // FIXME Same as above 4545 framesReady = cblk->framesReadyOut(); 4546 4547 if (CC_LIKELY(framesReady)) { 4548 uint32_t s = cblk->server; 4549 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 4550 4551 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd; 4552 if (framesReq > framesReady) { 4553 framesReq = framesReady; 4554 } 4555 if (framesReq > bufferEnd - s) { 4556 framesReq = bufferEnd - s; 4557 } 4558 4559 buffer->raw = getBuffer(s, framesReq); 4560 buffer->frameCount = framesReq; 4561 return NO_ERROR; 4562 } 4563 4564getNextBuffer_exit: 4565 buffer->raw = NULL; 4566 buffer->frameCount = 0; 4567 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get()); 4568 return NOT_ENOUGH_DATA; 4569} 4570 4571// Note that framesReady() takes a mutex on the control block using tryLock(). 4572// This could result in priority inversion if framesReady() is called by the normal mixer, 4573// as the normal mixer thread runs at lower 4574// priority than the client's callback thread: there is a short window within framesReady() 4575// during which the normal mixer could be preempted, and the client callback would block. 4576// Another problem can occur if framesReady() is called by the fast mixer: 4577// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer. 4578// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue. 4579size_t AudioFlinger::PlaybackThread::Track::framesReady() const { 4580 return mCblk->framesReadyOut(); 4581} 4582 4583// Don't call for fast tracks; the framesReady() could result in priority inversion 4584bool AudioFlinger::PlaybackThread::Track::isReady() const { 4585 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true; 4586 4587 if (framesReady() >= mCblk->frameCount || 4588 (mCblk->flags & CBLK_FORCEREADY)) { 4589 mFillingUpStatus = FS_FILLED; 4590 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags); 4591 return true; 4592 } 4593 return false; 4594} 4595 4596status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event, 4597 int triggerSession) 4598{ 4599 status_t status = NO_ERROR; 4600 ALOGV("start(%d), calling pid %d session %d", 4601 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 4602 4603 sp<ThreadBase> thread = mThread.promote(); 4604 if (thread != 0) { 4605 Mutex::Autolock _l(thread->mLock); 4606 track_state state = mState; 4607 // here the track could be either new, or restarted 4608 // in both cases "unstop" the track 4609 if (mState == PAUSED) { 4610 mState = TrackBase::RESUMING; 4611 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 4612 } else { 4613 mState = TrackBase::ACTIVE; 4614 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 4615 } 4616 4617 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) { 4618 thread->mLock.unlock(); 4619 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId); 4620 thread->mLock.lock(); 4621 4622#ifdef ADD_BATTERY_DATA 4623 // to track the speaker usage 4624 if (status == NO_ERROR) { 4625 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 4626 } 4627#endif 4628 } 4629 if (status == NO_ERROR) { 4630 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4631 playbackThread->addTrack_l(this); 4632 } else { 4633 mState = state; 4634 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 4635 } 4636 } else { 4637 status = BAD_VALUE; 4638 } 4639 return status; 4640} 4641 4642void AudioFlinger::PlaybackThread::Track::stop() 4643{ 4644 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 4645 sp<ThreadBase> thread = mThread.promote(); 4646 if (thread != 0) { 4647 Mutex::Autolock _l(thread->mLock); 4648 track_state state = mState; 4649 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) { 4650 // If the track is not active (PAUSED and buffers full), flush buffers 4651 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4652 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 4653 reset(); 4654 mState = STOPPED; 4655 } else if (!isFastTrack()) { 4656 mState = STOPPED; 4657 } else { 4658 // prepareTracks_l() will set state to STOPPING_2 after next underrun, 4659 // and then to STOPPED and reset() when presentation is complete 4660 mState = STOPPING_1; 4661 } 4662 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, 4663 playbackThread); 4664 } 4665 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) { 4666 thread->mLock.unlock(); 4667 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId); 4668 thread->mLock.lock(); 4669 4670#ifdef ADD_BATTERY_DATA 4671 // to track the speaker usage 4672 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 4673#endif 4674 } 4675 } 4676} 4677 4678void AudioFlinger::PlaybackThread::Track::pause() 4679{ 4680 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 4681 sp<ThreadBase> thread = mThread.promote(); 4682 if (thread != 0) { 4683 Mutex::Autolock _l(thread->mLock); 4684 if (mState == ACTIVE || mState == RESUMING) { 4685 mState = PAUSING; 4686 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 4687 if (!isOutputTrack()) { 4688 thread->mLock.unlock(); 4689 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId); 4690 thread->mLock.lock(); 4691 4692#ifdef ADD_BATTERY_DATA 4693 // to track the speaker usage 4694 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 4695#endif 4696 } 4697 } 4698 } 4699} 4700 4701void AudioFlinger::PlaybackThread::Track::flush() 4702{ 4703 ALOGV("flush(%d)", mName); 4704 sp<ThreadBase> thread = mThread.promote(); 4705 if (thread != 0) { 4706 Mutex::Autolock _l(thread->mLock); 4707 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED && 4708 mState != PAUSING && mState != IDLE && mState != FLUSHED) { 4709 return; 4710 } 4711 // No point remaining in PAUSED state after a flush => go to 4712 // FLUSHED state 4713 mState = FLUSHED; 4714 // do not reset the track if it is still in the process of being stopped or paused. 4715 // this will be done by prepareTracks_l() when the track is stopped. 4716 // prepareTracks_l() will see mState == FLUSHED, then 4717 // remove from active track list, reset(), and trigger presentation complete 4718 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4719 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 4720 reset(); 4721 } 4722 } 4723} 4724 4725void AudioFlinger::PlaybackThread::Track::reset() 4726{ 4727 // Do not reset twice to avoid discarding data written just after a flush and before 4728 // the audioflinger thread detects the track is stopped. 4729 if (!mResetDone) { 4730 TrackBase::reset(); 4731 // Force underrun condition to avoid false underrun callback until first data is 4732 // written to buffer 4733 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags); 4734 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags); 4735 mFillingUpStatus = FS_FILLING; 4736 mResetDone = true; 4737 if (mState == FLUSHED) { 4738 mState = IDLE; 4739 } 4740 } 4741} 4742 4743void AudioFlinger::PlaybackThread::Track::mute(bool muted) 4744{ 4745 mMute = muted; 4746} 4747 4748status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 4749{ 4750 status_t status = DEAD_OBJECT; 4751 sp<ThreadBase> thread = mThread.promote(); 4752 if (thread != 0) { 4753 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4754 sp<AudioFlinger> af = mClient->audioFlinger(); 4755 4756 Mutex::Autolock _l(af->mLock); 4757 4758 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 4759 4760 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) { 4761 Mutex::Autolock _dl(playbackThread->mLock); 4762 Mutex::Autolock _sl(srcThread->mLock); 4763 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 4764 if (chain == 0) { 4765 return INVALID_OPERATION; 4766 } 4767 4768 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId); 4769 if (effect == 0) { 4770 return INVALID_OPERATION; 4771 } 4772 srcThread->removeEffect_l(effect); 4773 playbackThread->addEffect_l(effect); 4774 // removeEffect_l() has stopped the effect if it was active so it must be restarted 4775 if (effect->state() == EffectModule::ACTIVE || 4776 effect->state() == EffectModule::STOPPING) { 4777 effect->start(); 4778 } 4779 4780 sp<EffectChain> dstChain = effect->chain().promote(); 4781 if (dstChain == 0) { 4782 srcThread->addEffect_l(effect); 4783 return INVALID_OPERATION; 4784 } 4785 AudioSystem::unregisterEffect(effect->id()); 4786 AudioSystem::registerEffect(&effect->desc(), 4787 srcThread->id(), 4788 dstChain->strategy(), 4789 AUDIO_SESSION_OUTPUT_MIX, 4790 effect->id()); 4791 } 4792 status = playbackThread->attachAuxEffect(this, EffectId); 4793 } 4794 return status; 4795} 4796 4797void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 4798{ 4799 mAuxEffectId = EffectId; 4800 mAuxBuffer = buffer; 4801} 4802 4803bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten, 4804 size_t audioHalFrames) 4805{ 4806 // a track is considered presented when the total number of frames written to audio HAL 4807 // corresponds to the number of frames written when presentationComplete() is called for the 4808 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time. 4809 if (mPresentationCompleteFrames == 0) { 4810 mPresentationCompleteFrames = framesWritten + audioHalFrames; 4811 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d", 4812 mPresentationCompleteFrames, audioHalFrames); 4813 } 4814 if (framesWritten >= mPresentationCompleteFrames) { 4815 ALOGV("presentationComplete() session %d complete: framesWritten %d", 4816 mSessionId, framesWritten); 4817 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 4818 return true; 4819 } 4820 return false; 4821} 4822 4823void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type) 4824{ 4825 for (int i = 0; i < (int)mSyncEvents.size(); i++) { 4826 if (mSyncEvents[i]->type() == type) { 4827 mSyncEvents[i]->trigger(); 4828 mSyncEvents.removeAt(i); 4829 i--; 4830 } 4831 } 4832} 4833 4834// implement VolumeBufferProvider interface 4835 4836uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR() 4837{ 4838 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs 4839 ALOG_ASSERT(isFastTrack() && (mCblk != NULL)); 4840 uint32_t vlr = mCblk->getVolumeLR(); 4841 uint32_t vl = vlr & 0xFFFF; 4842 uint32_t vr = vlr >> 16; 4843 // track volumes come from shared memory, so can't be trusted and must be clamped 4844 if (vl > MAX_GAIN_INT) { 4845 vl = MAX_GAIN_INT; 4846 } 4847 if (vr > MAX_GAIN_INT) { 4848 vr = MAX_GAIN_INT; 4849 } 4850 // now apply the cached master volume and stream type volume; 4851 // this is trusted but lacks any synchronization or barrier so may be stale 4852 float v = mCachedVolume; 4853 vl *= v; 4854 vr *= v; 4855 // re-combine into U4.16 4856 vlr = (vr << 16) | (vl & 0xFFFF); 4857 // FIXME look at mute, pause, and stop flags 4858 return vlr; 4859} 4860 4861status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event) 4862{ 4863 if (mState == TERMINATED || mState == PAUSED || 4864 ((framesReady() == 0) && ((mSharedBuffer != 0) || 4865 (mState == STOPPED)))) { 4866 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ", 4867 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady()); 4868 event->cancel(); 4869 return INVALID_OPERATION; 4870 } 4871 (void) TrackBase::setSyncEvent(event); 4872 return NO_ERROR; 4873} 4874 4875bool AudioFlinger::PlaybackThread::Track::isOut() const 4876{ 4877 return true; 4878} 4879 4880// timed audio tracks 4881 4882sp<AudioFlinger::PlaybackThread::TimedTrack> 4883AudioFlinger::PlaybackThread::TimedTrack::create( 4884 PlaybackThread *thread, 4885 const sp<Client>& client, 4886 audio_stream_type_t streamType, 4887 uint32_t sampleRate, 4888 audio_format_t format, 4889 audio_channel_mask_t channelMask, 4890 size_t frameCount, 4891 const sp<IMemory>& sharedBuffer, 4892 int sessionId) { 4893 if (!client->reserveTimedTrack()) 4894 return 0; 4895 4896 return new TimedTrack( 4897 thread, client, streamType, sampleRate, format, channelMask, frameCount, 4898 sharedBuffer, sessionId); 4899} 4900 4901AudioFlinger::PlaybackThread::TimedTrack::TimedTrack( 4902 PlaybackThread *thread, 4903 const sp<Client>& client, 4904 audio_stream_type_t streamType, 4905 uint32_t sampleRate, 4906 audio_format_t format, 4907 audio_channel_mask_t channelMask, 4908 size_t frameCount, 4909 const sp<IMemory>& sharedBuffer, 4910 int sessionId) 4911 : Track(thread, client, streamType, sampleRate, format, channelMask, 4912 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED), 4913 mQueueHeadInFlight(false), 4914 mTrimQueueHeadOnRelease(false), 4915 mFramesPendingInQueue(0), 4916 mTimedSilenceBuffer(NULL), 4917 mTimedSilenceBufferSize(0), 4918 mTimedAudioOutputOnTime(false), 4919 mMediaTimeTransformValid(false) 4920{ 4921 LocalClock lc; 4922 mLocalTimeFreq = lc.getLocalFreq(); 4923 4924 mLocalTimeToSampleTransform.a_zero = 0; 4925 mLocalTimeToSampleTransform.b_zero = 0; 4926 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate; 4927 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq; 4928 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer, 4929 &mLocalTimeToSampleTransform.a_to_b_denom); 4930 4931 mMediaTimeToSampleTransform.a_zero = 0; 4932 mMediaTimeToSampleTransform.b_zero = 0; 4933 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate; 4934 mMediaTimeToSampleTransform.a_to_b_denom = 1000000; 4935 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer, 4936 &mMediaTimeToSampleTransform.a_to_b_denom); 4937} 4938 4939AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() { 4940 mClient->releaseTimedTrack(); 4941 delete [] mTimedSilenceBuffer; 4942} 4943 4944status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer( 4945 size_t size, sp<IMemory>* buffer) { 4946 4947 Mutex::Autolock _l(mTimedBufferQueueLock); 4948 4949 trimTimedBufferQueue_l(); 4950 4951 // lazily initialize the shared memory heap for timed buffers 4952 if (mTimedMemoryDealer == NULL) { 4953 const int kTimedBufferHeapSize = 512 << 10; 4954 4955 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize, 4956 "AudioFlingerTimed"); 4957 if (mTimedMemoryDealer == NULL) 4958 return NO_MEMORY; 4959 } 4960 4961 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size); 4962 if (newBuffer == NULL) { 4963 newBuffer = mTimedMemoryDealer->allocate(size); 4964 if (newBuffer == NULL) 4965 return NO_MEMORY; 4966 } 4967 4968 *buffer = newBuffer; 4969 return NO_ERROR; 4970} 4971 4972// caller must hold mTimedBufferQueueLock 4973void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() { 4974 int64_t mediaTimeNow; 4975 { 4976 Mutex::Autolock mttLock(mMediaTimeTransformLock); 4977 if (!mMediaTimeTransformValid) 4978 return; 4979 4980 int64_t targetTimeNow; 4981 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) 4982 ? mCCHelper.getCommonTime(&targetTimeNow) 4983 : mCCHelper.getLocalTime(&targetTimeNow); 4984 4985 if (OK != res) 4986 return; 4987 4988 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow, 4989 &mediaTimeNow)) { 4990 return; 4991 } 4992 } 4993 4994 size_t trimEnd; 4995 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) { 4996 int64_t bufEnd; 4997 4998 if ((trimEnd + 1) < mTimedBufferQueue.size()) { 4999 // We have a next buffer. Just use its PTS as the PTS of the frame 5000 // following the last frame in this buffer. If the stream is sparse 5001 // (ie, there are deliberate gaps left in the stream which should be 5002 // filled with silence by the TimedAudioTrack), then this can result 5003 // in one extra buffer being left un-trimmed when it could have 5004 // been. In general, this is not typical, and we would rather 5005 // optimized away the TS calculation below for the more common case 5006 // where PTSes are contiguous. 5007 bufEnd = mTimedBufferQueue[trimEnd + 1].pts(); 5008 } else { 5009 // We have no next buffer. Compute the PTS of the frame following 5010 // the last frame in this buffer by computing the duration of of 5011 // this frame in media time units and adding it to the PTS of the 5012 // buffer. 5013 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size() 5014 / mFrameSize; 5015 5016 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount, 5017 &bufEnd)) { 5018 ALOGE("Failed to convert frame count of %lld to media time" 5019 " duration" " (scale factor %d/%u) in %s", 5020 frameCount, 5021 mMediaTimeToSampleTransform.a_to_b_numer, 5022 mMediaTimeToSampleTransform.a_to_b_denom, 5023 __PRETTY_FUNCTION__); 5024 break; 5025 } 5026 bufEnd += mTimedBufferQueue[trimEnd].pts(); 5027 } 5028 5029 if (bufEnd > mediaTimeNow) 5030 break; 5031 5032 // Is the buffer we want to use in the middle of a mix operation right 5033 // now? If so, don't actually trim it. Just wait for the releaseBuffer 5034 // from the mixer which should be coming back shortly. 5035 if (!trimEnd && mQueueHeadInFlight) { 5036 mTrimQueueHeadOnRelease = true; 5037 } 5038 } 5039 5040 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0; 5041 if (trimStart < trimEnd) { 5042 // Update the bookkeeping for framesReady() 5043 for (size_t i = trimStart; i < trimEnd; ++i) { 5044 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim"); 5045 } 5046 5047 // Now actually remove the buffers from the queue. 5048 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd); 5049 } 5050} 5051 5052void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l( 5053 const char* logTag) { 5054 ALOG_ASSERT(mTimedBufferQueue.size() > 0, 5055 "%s called (reason \"%s\"), but timed buffer queue has no" 5056 " elements to trim.", __FUNCTION__, logTag); 5057 5058 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag); 5059 mTimedBufferQueue.removeAt(0); 5060} 5061 5062void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l( 5063 const TimedBuffer& buf, 5064 const char* logTag) { 5065 uint32_t bufBytes = buf.buffer()->size(); 5066 uint32_t consumedAlready = buf.position(); 5067 5068 ALOG_ASSERT(consumedAlready <= bufBytes, 5069 "Bad bookkeeping while updating frames pending. Timed buffer is" 5070 " only %u bytes long, but claims to have consumed %u" 5071 " bytes. (update reason: \"%s\")", 5072 bufBytes, consumedAlready, logTag); 5073 5074 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize; 5075 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames, 5076 "Bad bookkeeping while updating frames pending. Should have at" 5077 " least %u queued frames, but we think we have only %u. (update" 5078 " reason: \"%s\")", 5079 bufFrames, mFramesPendingInQueue, logTag); 5080 5081 mFramesPendingInQueue -= bufFrames; 5082} 5083 5084status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer( 5085 const sp<IMemory>& buffer, int64_t pts) { 5086 5087 { 5088 Mutex::Autolock mttLock(mMediaTimeTransformLock); 5089 if (!mMediaTimeTransformValid) 5090 return INVALID_OPERATION; 5091 } 5092 5093 Mutex::Autolock _l(mTimedBufferQueueLock); 5094 5095 uint32_t bufFrames = buffer->size() / mFrameSize; 5096 mFramesPendingInQueue += bufFrames; 5097 mTimedBufferQueue.add(TimedBuffer(buffer, pts)); 5098 5099 return NO_ERROR; 5100} 5101 5102status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform( 5103 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) { 5104 5105 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d", 5106 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom, 5107 target); 5108 5109 if (!(target == TimedAudioTrack::LOCAL_TIME || 5110 target == TimedAudioTrack::COMMON_TIME)) { 5111 return BAD_VALUE; 5112 } 5113 5114 Mutex::Autolock lock(mMediaTimeTransformLock); 5115 mMediaTimeTransform = xform; 5116 mMediaTimeTransformTarget = target; 5117 mMediaTimeTransformValid = true; 5118 5119 return NO_ERROR; 5120} 5121 5122#define min(a, b) ((a) < (b) ? (a) : (b)) 5123 5124// implementation of getNextBuffer for tracks whose buffers have timestamps 5125status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer( 5126 AudioBufferProvider::Buffer* buffer, int64_t pts) 5127{ 5128 if (pts == AudioBufferProvider::kInvalidPTS) { 5129 buffer->raw = NULL; 5130 buffer->frameCount = 0; 5131 mTimedAudioOutputOnTime = false; 5132 return INVALID_OPERATION; 5133 } 5134 5135 Mutex::Autolock _l(mTimedBufferQueueLock); 5136 5137 ALOG_ASSERT(!mQueueHeadInFlight, 5138 "getNextBuffer called without releaseBuffer!"); 5139 5140 while (true) { 5141 5142 // if we have no timed buffers, then fail 5143 if (mTimedBufferQueue.isEmpty()) { 5144 buffer->raw = NULL; 5145 buffer->frameCount = 0; 5146 return NOT_ENOUGH_DATA; 5147 } 5148 5149 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 5150 5151 // calculate the PTS of the head of the timed buffer queue expressed in 5152 // local time 5153 int64_t headLocalPTS; 5154 { 5155 Mutex::Autolock mttLock(mMediaTimeTransformLock); 5156 5157 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid"); 5158 5159 if (mMediaTimeTransform.a_to_b_denom == 0) { 5160 // the transform represents a pause, so yield silence 5161 timedYieldSilence_l(buffer->frameCount, buffer); 5162 return NO_ERROR; 5163 } 5164 5165 int64_t transformedPTS; 5166 if (!mMediaTimeTransform.doForwardTransform(head.pts(), 5167 &transformedPTS)) { 5168 // the transform failed. this shouldn't happen, but if it does 5169 // then just drop this buffer 5170 ALOGW("timedGetNextBuffer transform failed"); 5171 buffer->raw = NULL; 5172 buffer->frameCount = 0; 5173 trimTimedBufferQueueHead_l("getNextBuffer; no transform"); 5174 return NO_ERROR; 5175 } 5176 5177 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) { 5178 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS, 5179 &headLocalPTS)) { 5180 buffer->raw = NULL; 5181 buffer->frameCount = 0; 5182 return INVALID_OPERATION; 5183 } 5184 } else { 5185 headLocalPTS = transformedPTS; 5186 } 5187 } 5188 5189 // adjust the head buffer's PTS to reflect the portion of the head buffer 5190 // that has already been consumed 5191 int64_t effectivePTS = headLocalPTS + 5192 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate()); 5193 5194 // Calculate the delta in samples between the head of the input buffer 5195 // queue and the start of the next output buffer that will be written. 5196 // If the transformation fails because of over or underflow, it means 5197 // that the sample's position in the output stream is so far out of 5198 // whack that it should just be dropped. 5199 int64_t sampleDelta; 5200 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) { 5201 ALOGV("*** head buffer is too far from PTS: dropped buffer"); 5202 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from" 5203 " mix"); 5204 continue; 5205 } 5206 if (!mLocalTimeToSampleTransform.doForwardTransform( 5207 (effectivePTS - pts) << 32, &sampleDelta)) { 5208 ALOGV("*** too late during sample rate transform: dropped buffer"); 5209 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample"); 5210 continue; 5211 } 5212 5213 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld" 5214 " sampleDelta=[%d.%08x]", 5215 head.pts(), head.position(), pts, 5216 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) 5217 + (sampleDelta >> 32)), 5218 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF)); 5219 5220 // if the delta between the ideal placement for the next input sample and 5221 // the current output position is within this threshold, then we will 5222 // concatenate the next input samples to the previous output 5223 const int64_t kSampleContinuityThreshold = 5224 (static_cast<int64_t>(sampleRate()) << 32) / 250; 5225 5226 // if this is the first buffer of audio that we're emitting from this track 5227 // then it should be almost exactly on time. 5228 const int64_t kSampleStartupThreshold = 1LL << 32; 5229 5230 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) || 5231 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) { 5232 // the next input is close enough to being on time, so concatenate it 5233 // with the last output 5234 timedYieldSamples_l(buffer); 5235 5236 ALOGVV("*** on time: head.pos=%d frameCount=%u", 5237 head.position(), buffer->frameCount); 5238 return NO_ERROR; 5239 } 5240 5241 // Looks like our output is not on time. Reset our on timed status. 5242 // Next time we mix samples from our input queue, then should be within 5243 // the StartupThreshold. 5244 mTimedAudioOutputOnTime = false; 5245 if (sampleDelta > 0) { 5246 // the gap between the current output position and the proper start of 5247 // the next input sample is too big, so fill it with silence 5248 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32; 5249 5250 timedYieldSilence_l(framesUntilNextInput, buffer); 5251 ALOGV("*** silence: frameCount=%u", buffer->frameCount); 5252 return NO_ERROR; 5253 } else { 5254 // the next input sample is late 5255 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32)); 5256 size_t onTimeSamplePosition = 5257 head.position() + lateFrames * mFrameSize; 5258 5259 if (onTimeSamplePosition > head.buffer()->size()) { 5260 // all the remaining samples in the head are too late, so 5261 // drop it and move on 5262 ALOGV("*** too late: dropped buffer"); 5263 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer"); 5264 continue; 5265 } else { 5266 // skip over the late samples 5267 head.setPosition(onTimeSamplePosition); 5268 5269 // yield the available samples 5270 timedYieldSamples_l(buffer); 5271 5272 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount); 5273 return NO_ERROR; 5274 } 5275 } 5276 } 5277} 5278 5279// Yield samples from the timed buffer queue head up to the given output 5280// buffer's capacity. 5281// 5282// Caller must hold mTimedBufferQueueLock 5283void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l( 5284 AudioBufferProvider::Buffer* buffer) { 5285 5286 const TimedBuffer& head = mTimedBufferQueue[0]; 5287 5288 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) + 5289 head.position()); 5290 5291 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) / 5292 mFrameSize); 5293 size_t framesRequested = buffer->frameCount; 5294 buffer->frameCount = min(framesLeftInHead, framesRequested); 5295 5296 mQueueHeadInFlight = true; 5297 mTimedAudioOutputOnTime = true; 5298} 5299 5300// Yield samples of silence up to the given output buffer's capacity 5301// 5302// Caller must hold mTimedBufferQueueLock 5303void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l( 5304 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) { 5305 5306 // lazily allocate a buffer filled with silence 5307 if (mTimedSilenceBufferSize < numFrames * mFrameSize) { 5308 delete [] mTimedSilenceBuffer; 5309 mTimedSilenceBufferSize = numFrames * mFrameSize; 5310 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize]; 5311 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize); 5312 } 5313 5314 buffer->raw = mTimedSilenceBuffer; 5315 size_t framesRequested = buffer->frameCount; 5316 buffer->frameCount = min(numFrames, framesRequested); 5317 5318 mTimedAudioOutputOnTime = false; 5319} 5320 5321// AudioBufferProvider interface 5322void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer( 5323 AudioBufferProvider::Buffer* buffer) { 5324 5325 Mutex::Autolock _l(mTimedBufferQueueLock); 5326 5327 // If the buffer which was just released is part of the buffer at the head 5328 // of the queue, be sure to update the amt of the buffer which has been 5329 // consumed. If the buffer being returned is not part of the head of the 5330 // queue, its either because the buffer is part of the silence buffer, or 5331 // because the head of the timed queue was trimmed after the mixer called 5332 // getNextBuffer but before the mixer called releaseBuffer. 5333 if (buffer->raw == mTimedSilenceBuffer) { 5334 ALOG_ASSERT(!mQueueHeadInFlight, 5335 "Queue head in flight during release of silence buffer!"); 5336 goto done; 5337 } 5338 5339 ALOG_ASSERT(mQueueHeadInFlight, 5340 "TimedTrack::releaseBuffer of non-silence buffer, but no queue" 5341 " head in flight."); 5342 5343 if (mTimedBufferQueue.size()) { 5344 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 5345 5346 void* start = head.buffer()->pointer(); 5347 void* end = reinterpret_cast<void*>( 5348 reinterpret_cast<uint8_t*>(head.buffer()->pointer()) 5349 + head.buffer()->size()); 5350 5351 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end), 5352 "released buffer not within the head of the timed buffer" 5353 " queue; qHead = [%p, %p], released buffer = %p", 5354 start, end, buffer->raw); 5355 5356 head.setPosition(head.position() + 5357 (buffer->frameCount * mFrameSize)); 5358 mQueueHeadInFlight = false; 5359 5360 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount, 5361 "Bad bookkeeping during releaseBuffer! Should have at" 5362 " least %u queued frames, but we think we have only %u", 5363 buffer->frameCount, mFramesPendingInQueue); 5364 5365 mFramesPendingInQueue -= buffer->frameCount; 5366 5367 if ((static_cast<size_t>(head.position()) >= head.buffer()->size()) 5368 || mTrimQueueHeadOnRelease) { 5369 trimTimedBufferQueueHead_l("releaseBuffer"); 5370 mTrimQueueHeadOnRelease = false; 5371 } 5372 } else { 5373 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no" 5374 " buffers in the timed buffer queue"); 5375 } 5376 5377done: 5378 buffer->raw = 0; 5379 buffer->frameCount = 0; 5380} 5381 5382size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const { 5383 Mutex::Autolock _l(mTimedBufferQueueLock); 5384 return mFramesPendingInQueue; 5385} 5386 5387AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer() 5388 : mPTS(0), mPosition(0) {} 5389 5390AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer( 5391 const sp<IMemory>& buffer, int64_t pts) 5392 : mBuffer(buffer), mPTS(pts), mPosition(0) {} 5393 5394// ---------------------------------------------------------------------------- 5395 5396// RecordTrack constructor must be called with AudioFlinger::mLock held 5397AudioFlinger::RecordThread::RecordTrack::RecordTrack( 5398 RecordThread *thread, 5399 const sp<Client>& client, 5400 uint32_t sampleRate, 5401 audio_format_t format, 5402 audio_channel_mask_t channelMask, 5403 size_t frameCount, 5404 int sessionId) 5405 : TrackBase(thread, client, sampleRate, format, 5406 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId), 5407 mOverflow(false) 5408{ 5409 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer); 5410} 5411 5412AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 5413{ 5414 ALOGV("%s", __func__); 5415} 5416 5417// AudioBufferProvider interface 5418status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, 5419 int64_t pts) 5420{ 5421 audio_track_cblk_t* cblk = this->cblk(); 5422 uint32_t framesAvail; 5423 uint32_t framesReq = buffer->frameCount; 5424 5425 // Check if last stepServer failed, try to step now 5426 if (mStepServerFailed) { 5427 if (!step()) goto getNextBuffer_exit; 5428 ALOGV("stepServer recovered"); 5429 mStepServerFailed = false; 5430 } 5431 5432 // FIXME lock is not actually held, so overrun is possible 5433 framesAvail = cblk->framesAvailableIn_l(); 5434 5435 if (CC_LIKELY(framesAvail)) { 5436 uint32_t s = cblk->server; 5437 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 5438 5439 if (framesReq > framesAvail) { 5440 framesReq = framesAvail; 5441 } 5442 if (framesReq > bufferEnd - s) { 5443 framesReq = bufferEnd - s; 5444 } 5445 5446 buffer->raw = getBuffer(s, framesReq); 5447 buffer->frameCount = framesReq; 5448 return NO_ERROR; 5449 } 5450 5451getNextBuffer_exit: 5452 buffer->raw = NULL; 5453 buffer->frameCount = 0; 5454 return NOT_ENOUGH_DATA; 5455} 5456 5457status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event, 5458 int triggerSession) 5459{ 5460 sp<ThreadBase> thread = mThread.promote(); 5461 if (thread != 0) { 5462 RecordThread *recordThread = (RecordThread *)thread.get(); 5463 return recordThread->start(this, event, triggerSession); 5464 } else { 5465 return BAD_VALUE; 5466 } 5467} 5468 5469void AudioFlinger::RecordThread::RecordTrack::stop() 5470{ 5471 sp<ThreadBase> thread = mThread.promote(); 5472 if (thread != 0) { 5473 RecordThread *recordThread = (RecordThread *)thread.get(); 5474 recordThread->mLock.lock(); 5475 bool doStop = recordThread->stop_l(this); 5476 if (doStop) { 5477 TrackBase::reset(); 5478 // Force overrun condition to avoid false overrun callback until first data is 5479 // read from buffer 5480 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags); 5481 } 5482 recordThread->mLock.unlock(); 5483 if (doStop) { 5484 AudioSystem::stopInput(recordThread->id()); 5485 } 5486 } 5487} 5488 5489/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result) 5490{ 5491 result.append(" Clien Fmt Chn mask Session Step S SRate Serv User FrameCount\n"); 5492} 5493 5494void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 5495{ 5496 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n", 5497 (mClient == 0) ? getpid_cached : mClient->pid(), 5498 mFormat, 5499 mChannelMask, 5500 mSessionId, 5501 mStepCount, 5502 mState, 5503 mCblk->sampleRate, 5504 mCblk->server, 5505 mCblk->user, 5506 mCblk->frameCount); 5507} 5508 5509bool AudioFlinger::RecordThread::RecordTrack::isOut() const 5510{ 5511 return false; 5512} 5513 5514// ---------------------------------------------------------------------------- 5515 5516AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 5517 PlaybackThread *playbackThread, 5518 DuplicatingThread *sourceThread, 5519 uint32_t sampleRate, 5520 audio_format_t format, 5521 audio_channel_mask_t channelMask, 5522 size_t frameCount) 5523 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, 5524 NULL, 0, IAudioFlinger::TRACK_DEFAULT), 5525 mActive(false), mSourceThread(sourceThread), mBuffers(NULL) 5526{ 5527 5528 if (mCblk != NULL) { 5529 mBuffers = (char*)mCblk + sizeof(audio_track_cblk_t); 5530 mOutBuffer.frameCount = 0; 5531 playbackThread->mTracks.add(this); 5532 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \ 5533 "mCblk->frameCount %d, mCblk->sampleRate %u, mChannelMask 0x%08x mBufferEnd %p", 5534 mCblk, mBuffer, mCblk->buffers, 5535 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd); 5536 } else { 5537 ALOGW("Error creating output track on thread %p", playbackThread); 5538 } 5539} 5540 5541AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 5542{ 5543 clearBufferQueue(); 5544} 5545 5546status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event, 5547 int triggerSession) 5548{ 5549 status_t status = Track::start(event, triggerSession); 5550 if (status != NO_ERROR) { 5551 return status; 5552 } 5553 5554 mActive = true; 5555 mRetryCount = 127; 5556 return status; 5557} 5558 5559void AudioFlinger::PlaybackThread::OutputTrack::stop() 5560{ 5561 Track::stop(); 5562 clearBufferQueue(); 5563 mOutBuffer.frameCount = 0; 5564 mActive = false; 5565} 5566 5567bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 5568{ 5569 Buffer *pInBuffer; 5570 Buffer inBuffer; 5571 uint32_t channelCount = mChannelCount; 5572 bool outputBufferFull = false; 5573 inBuffer.frameCount = frames; 5574 inBuffer.i16 = data; 5575 5576 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 5577 5578 if (!mActive && frames != 0) { 5579 start(); 5580 sp<ThreadBase> thread = mThread.promote(); 5581 if (thread != 0) { 5582 MixerThread *mixerThread = (MixerThread *)thread.get(); 5583 if (mCblk->frameCount > frames){ 5584 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 5585 uint32_t startFrames = (mCblk->frameCount - frames); 5586 pInBuffer = new Buffer; 5587 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 5588 pInBuffer->frameCount = startFrames; 5589 pInBuffer->i16 = pInBuffer->mBuffer; 5590 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 5591 mBufferQueue.add(pInBuffer); 5592 } else { 5593 ALOGW ("OutputTrack::write() %p no more buffers in queue", this); 5594 } 5595 } 5596 } 5597 } 5598 5599 while (waitTimeLeftMs) { 5600 // First write pending buffers, then new data 5601 if (mBufferQueue.size()) { 5602 pInBuffer = mBufferQueue.itemAt(0); 5603 } else { 5604 pInBuffer = &inBuffer; 5605 } 5606 5607 if (pInBuffer->frameCount == 0) { 5608 break; 5609 } 5610 5611 if (mOutBuffer.frameCount == 0) { 5612 mOutBuffer.frameCount = pInBuffer->frameCount; 5613 nsecs_t startTime = systemTime(); 5614 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) { 5615 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, 5616 mThread.unsafe_get()); 5617 outputBufferFull = true; 5618 break; 5619 } 5620 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 5621 if (waitTimeLeftMs >= waitTimeMs) { 5622 waitTimeLeftMs -= waitTimeMs; 5623 } else { 5624 waitTimeLeftMs = 0; 5625 } 5626 } 5627 5628 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : 5629 pInBuffer->frameCount; 5630 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 5631 mCblk->stepUserOut(outFrames); 5632 pInBuffer->frameCount -= outFrames; 5633 pInBuffer->i16 += outFrames * channelCount; 5634 mOutBuffer.frameCount -= outFrames; 5635 mOutBuffer.i16 += outFrames * channelCount; 5636 5637 if (pInBuffer->frameCount == 0) { 5638 if (mBufferQueue.size()) { 5639 mBufferQueue.removeAt(0); 5640 delete [] pInBuffer->mBuffer; 5641 delete pInBuffer; 5642 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, 5643 mThread.unsafe_get(), mBufferQueue.size()); 5644 } else { 5645 break; 5646 } 5647 } 5648 } 5649 5650 // If we could not write all frames, allocate a buffer and queue it for next time. 5651 if (inBuffer.frameCount) { 5652 sp<ThreadBase> thread = mThread.promote(); 5653 if (thread != 0 && !thread->standby()) { 5654 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 5655 pInBuffer = new Buffer; 5656 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 5657 pInBuffer->frameCount = inBuffer.frameCount; 5658 pInBuffer->i16 = pInBuffer->mBuffer; 5659 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * 5660 sizeof(int16_t)); 5661 mBufferQueue.add(pInBuffer); 5662 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, 5663 mThread.unsafe_get(), mBufferQueue.size()); 5664 } else { 5665 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", 5666 mThread.unsafe_get(), this); 5667 } 5668 } 5669 } 5670 5671 // Calling write() with a 0 length buffer, means that no more data will be written: 5672 // If no more buffers are pending, fill output track buffer to make sure it is started 5673 // by output mixer. 5674 if (frames == 0 && mBufferQueue.size() == 0) { 5675 if (mCblk->user < mCblk->frameCount) { 5676 frames = mCblk->frameCount - mCblk->user; 5677 pInBuffer = new Buffer; 5678 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 5679 pInBuffer->frameCount = frames; 5680 pInBuffer->i16 = pInBuffer->mBuffer; 5681 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 5682 mBufferQueue.add(pInBuffer); 5683 } else if (mActive) { 5684 stop(); 5685 } 5686 } 5687 5688 return outputBufferFull; 5689} 5690 5691status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer( 5692 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 5693{ 5694 int active; 5695 status_t result; 5696 audio_track_cblk_t* cblk = mCblk; 5697 uint32_t framesReq = buffer->frameCount; 5698 5699 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server); 5700 buffer->frameCount = 0; 5701 5702 uint32_t framesAvail = cblk->framesAvailableOut(); 5703 5704 5705 if (framesAvail == 0) { 5706 Mutex::Autolock _l(cblk->lock); 5707 goto start_loop_here; 5708 while (framesAvail == 0) { 5709 active = mActive; 5710 if (CC_UNLIKELY(!active)) { 5711 ALOGV("Not active and NO_MORE_BUFFERS"); 5712 return NO_MORE_BUFFERS; 5713 } 5714 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 5715 if (result != NO_ERROR) { 5716 return NO_MORE_BUFFERS; 5717 } 5718 // read the server count again 5719 start_loop_here: 5720 framesAvail = cblk->framesAvailableOut_l(); 5721 } 5722 } 5723 5724// if (framesAvail < framesReq) { 5725// return NO_MORE_BUFFERS; 5726// } 5727 5728 if (framesReq > framesAvail) { 5729 framesReq = framesAvail; 5730 } 5731 5732 uint32_t u = cblk->user; 5733 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 5734 5735 if (framesReq > bufferEnd - u) { 5736 framesReq = bufferEnd - u; 5737 } 5738 5739 buffer->frameCount = framesReq; 5740 buffer->raw = cblk->buffer(mBuffers, mFrameSize, u); 5741 return NO_ERROR; 5742} 5743 5744 5745void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 5746{ 5747 size_t size = mBufferQueue.size(); 5748 5749 for (size_t i = 0; i < size; i++) { 5750 Buffer *pBuffer = mBufferQueue.itemAt(i); 5751 delete [] pBuffer->mBuffer; 5752 delete pBuffer; 5753 } 5754 mBufferQueue.clear(); 5755} 5756 5757// ---------------------------------------------------------------------------- 5758 5759AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 5760 : RefBase(), 5761 mAudioFlinger(audioFlinger), 5762 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below 5763 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 5764 mPid(pid), 5765 mTimedTrackCount(0) 5766{ 5767 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 5768} 5769 5770// Client destructor must be called with AudioFlinger::mLock held 5771AudioFlinger::Client::~Client() 5772{ 5773 mAudioFlinger->removeClient_l(mPid); 5774} 5775 5776sp<MemoryDealer> AudioFlinger::Client::heap() const 5777{ 5778 return mMemoryDealer; 5779} 5780 5781// Reserve one of the limited slots for a timed audio track associated 5782// with this client 5783bool AudioFlinger::Client::reserveTimedTrack() 5784{ 5785 const int kMaxTimedTracksPerClient = 4; 5786 5787 Mutex::Autolock _l(mTimedTrackLock); 5788 5789 if (mTimedTrackCount >= kMaxTimedTracksPerClient) { 5790 ALOGW("can not create timed track - pid %d has exceeded the limit", 5791 mPid); 5792 return false; 5793 } 5794 5795 mTimedTrackCount++; 5796 return true; 5797} 5798 5799// Release a slot for a timed audio track 5800void AudioFlinger::Client::releaseTimedTrack() 5801{ 5802 Mutex::Autolock _l(mTimedTrackLock); 5803 mTimedTrackCount--; 5804} 5805 5806// ---------------------------------------------------------------------------- 5807 5808AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 5809 const sp<IAudioFlingerClient>& client, 5810 pid_t pid) 5811 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 5812{ 5813} 5814 5815AudioFlinger::NotificationClient::~NotificationClient() 5816{ 5817} 5818 5819void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 5820{ 5821 sp<NotificationClient> keep(this); 5822 mAudioFlinger->removeNotificationClient(mPid); 5823} 5824 5825// ---------------------------------------------------------------------------- 5826 5827AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 5828 : BnAudioTrack(), 5829 mTrack(track) 5830{ 5831} 5832 5833AudioFlinger::TrackHandle::~TrackHandle() { 5834 // just stop the track on deletion, associated resources 5835 // will be freed from the main thread once all pending buffers have 5836 // been played. Unless it's not in the active track list, in which 5837 // case we free everything now... 5838 mTrack->destroy(); 5839} 5840 5841sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 5842 return mTrack->getCblk(); 5843} 5844 5845status_t AudioFlinger::TrackHandle::start() { 5846 return mTrack->start(); 5847} 5848 5849void AudioFlinger::TrackHandle::stop() { 5850 mTrack->stop(); 5851} 5852 5853void AudioFlinger::TrackHandle::flush() { 5854 mTrack->flush(); 5855} 5856 5857void AudioFlinger::TrackHandle::mute(bool e) { 5858 mTrack->mute(e); 5859} 5860 5861void AudioFlinger::TrackHandle::pause() { 5862 mTrack->pause(); 5863} 5864 5865status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 5866{ 5867 return mTrack->attachAuxEffect(EffectId); 5868} 5869 5870status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size, 5871 sp<IMemory>* buffer) { 5872 if (!mTrack->isTimedTrack()) 5873 return INVALID_OPERATION; 5874 5875 PlaybackThread::TimedTrack* tt = 5876 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 5877 return tt->allocateTimedBuffer(size, buffer); 5878} 5879 5880status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer, 5881 int64_t pts) { 5882 if (!mTrack->isTimedTrack()) 5883 return INVALID_OPERATION; 5884 5885 PlaybackThread::TimedTrack* tt = 5886 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 5887 return tt->queueTimedBuffer(buffer, pts); 5888} 5889 5890status_t AudioFlinger::TrackHandle::setMediaTimeTransform( 5891 const LinearTransform& xform, int target) { 5892 5893 if (!mTrack->isTimedTrack()) 5894 return INVALID_OPERATION; 5895 5896 PlaybackThread::TimedTrack* tt = 5897 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 5898 return tt->setMediaTimeTransform( 5899 xform, static_cast<TimedAudioTrack::TargetTimeline>(target)); 5900} 5901 5902status_t AudioFlinger::TrackHandle::onTransact( 5903 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 5904{ 5905 return BnAudioTrack::onTransact(code, data, reply, flags); 5906} 5907 5908// ---------------------------------------------------------------------------- 5909 5910sp<IAudioRecord> AudioFlinger::openRecord( 5911 pid_t pid, 5912 audio_io_handle_t input, 5913 uint32_t sampleRate, 5914 audio_format_t format, 5915 audio_channel_mask_t channelMask, 5916 size_t frameCount, 5917 IAudioFlinger::track_flags_t flags, 5918 pid_t tid, 5919 int *sessionId, 5920 status_t *status) 5921{ 5922 sp<RecordThread::RecordTrack> recordTrack; 5923 sp<RecordHandle> recordHandle; 5924 sp<Client> client; 5925 status_t lStatus; 5926 RecordThread *thread; 5927 size_t inFrameCount; 5928 int lSessionId; 5929 5930 // check calling permissions 5931 if (!recordingAllowed()) { 5932 lStatus = PERMISSION_DENIED; 5933 goto Exit; 5934 } 5935 5936 // add client to list 5937 { // scope for mLock 5938 Mutex::Autolock _l(mLock); 5939 thread = checkRecordThread_l(input); 5940 if (thread == NULL) { 5941 lStatus = BAD_VALUE; 5942 goto Exit; 5943 } 5944 5945 client = registerPid_l(pid); 5946 5947 // If no audio session id is provided, create one here 5948 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 5949 lSessionId = *sessionId; 5950 } else { 5951 lSessionId = nextUniqueId(); 5952 if (sessionId != NULL) { 5953 *sessionId = lSessionId; 5954 } 5955 } 5956 // create new record track. 5957 // The record track uses one track in mHardwareMixerThread by convention. 5958 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask, 5959 frameCount, lSessionId, flags, tid, &lStatus); 5960 } 5961 if (lStatus != NO_ERROR) { 5962 // remove local strong reference to Client before deleting the RecordTrack so that the 5963 // Client destructor is called by the TrackBase destructor with mLock held 5964 client.clear(); 5965 recordTrack.clear(); 5966 goto Exit; 5967 } 5968 5969 // return to handle to client 5970 recordHandle = new RecordHandle(recordTrack); 5971 lStatus = NO_ERROR; 5972 5973Exit: 5974 if (status) { 5975 *status = lStatus; 5976 } 5977 return recordHandle; 5978} 5979 5980// ---------------------------------------------------------------------------- 5981 5982AudioFlinger::RecordHandle::RecordHandle( 5983 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 5984 : BnAudioRecord(), 5985 mRecordTrack(recordTrack) 5986{ 5987} 5988 5989AudioFlinger::RecordHandle::~RecordHandle() { 5990 stop_nonvirtual(); 5991 mRecordTrack->destroy(); 5992} 5993 5994sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 5995 return mRecordTrack->getCblk(); 5996} 5997 5998status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, 5999 int triggerSession) { 6000 ALOGV("RecordHandle::start()"); 6001 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession); 6002} 6003 6004void AudioFlinger::RecordHandle::stop() { 6005 stop_nonvirtual(); 6006} 6007 6008void AudioFlinger::RecordHandle::stop_nonvirtual() { 6009 ALOGV("RecordHandle::stop()"); 6010 mRecordTrack->stop(); 6011} 6012 6013status_t AudioFlinger::RecordHandle::onTransact( 6014 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 6015{ 6016 return BnAudioRecord::onTransact(code, data, reply, flags); 6017} 6018 6019// ---------------------------------------------------------------------------- 6020 6021AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 6022 AudioStreamIn *input, 6023 uint32_t sampleRate, 6024 audio_channel_mask_t channelMask, 6025 audio_io_handle_t id, 6026 audio_devices_t device, 6027 const sp<NBAIO_Sink>& teeSink) : 6028 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD), 6029 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 6030 // mRsmpInIndex and mInputBytes set by readInputParameters() 6031 mReqChannelCount(popcount(channelMask)), 6032 mReqSampleRate(sampleRate), 6033 // mBytesRead is only meaningful while active, and so is cleared in start() 6034 // (but might be better to also clear here for dump?) 6035 mTeeSink(teeSink) 6036{ 6037 snprintf(mName, kNameLength, "AudioIn_%X", id); 6038 6039 readInputParameters(); 6040 6041} 6042 6043 6044AudioFlinger::RecordThread::~RecordThread() 6045{ 6046 delete[] mRsmpInBuffer; 6047 delete mResampler; 6048 delete[] mRsmpOutBuffer; 6049} 6050 6051void AudioFlinger::RecordThread::onFirstRef() 6052{ 6053 run(mName, PRIORITY_URGENT_AUDIO); 6054} 6055 6056status_t AudioFlinger::RecordThread::readyToRun() 6057{ 6058 status_t status = initCheck(); 6059 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); 6060 return status; 6061} 6062 6063bool AudioFlinger::RecordThread::threadLoop() 6064{ 6065 AudioBufferProvider::Buffer buffer; 6066 sp<RecordTrack> activeTrack; 6067 Vector< sp<EffectChain> > effectChains; 6068 6069 nsecs_t lastWarning = 0; 6070 6071 inputStandBy(); 6072 acquireWakeLock(); 6073 6074 // used to verify we've read at least once before evaluating how many bytes were read 6075 bool readOnce = false; 6076 6077 // start recording 6078 while (!exitPending()) { 6079 6080 processConfigEvents(); 6081 6082 { // scope for mLock 6083 Mutex::Autolock _l(mLock); 6084 checkForNewParameters_l(); 6085 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 6086 standby(); 6087 6088 if (exitPending()) break; 6089 6090 releaseWakeLock_l(); 6091 ALOGV("RecordThread: loop stopping"); 6092 // go to sleep 6093 mWaitWorkCV.wait(mLock); 6094 ALOGV("RecordThread: loop starting"); 6095 acquireWakeLock_l(); 6096 continue; 6097 } 6098 if (mActiveTrack != 0) { 6099 if (mActiveTrack->mState == TrackBase::PAUSING) { 6100 standby(); 6101 mActiveTrack.clear(); 6102 mStartStopCond.broadcast(); 6103 } else if (mActiveTrack->mState == TrackBase::RESUMING) { 6104 if (mReqChannelCount != mActiveTrack->channelCount()) { 6105 mActiveTrack.clear(); 6106 mStartStopCond.broadcast(); 6107 } else if (readOnce) { 6108 // record start succeeds only if first read from audio input 6109 // succeeds 6110 if (mBytesRead >= 0) { 6111 mActiveTrack->mState = TrackBase::ACTIVE; 6112 } else { 6113 mActiveTrack.clear(); 6114 } 6115 mStartStopCond.broadcast(); 6116 } 6117 mStandby = false; 6118 } else if (mActiveTrack->mState == TrackBase::TERMINATED) { 6119 removeTrack_l(mActiveTrack); 6120 mActiveTrack.clear(); 6121 } 6122 } 6123 lockEffectChains_l(effectChains); 6124 } 6125 6126 if (mActiveTrack != 0) { 6127 if (mActiveTrack->mState != TrackBase::ACTIVE && 6128 mActiveTrack->mState != TrackBase::RESUMING) { 6129 unlockEffectChains(effectChains); 6130 usleep(kRecordThreadSleepUs); 6131 continue; 6132 } 6133 for (size_t i = 0; i < effectChains.size(); i ++) { 6134 effectChains[i]->process_l(); 6135 } 6136 6137 buffer.frameCount = mFrameCount; 6138 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) { 6139 readOnce = true; 6140 size_t framesOut = buffer.frameCount; 6141 if (mResampler == NULL) { 6142 // no resampling 6143 while (framesOut) { 6144 size_t framesIn = mFrameCount - mRsmpInIndex; 6145 if (framesIn) { 6146 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 6147 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * 6148 mActiveTrack->mFrameSize; 6149 if (framesIn > framesOut) 6150 framesIn = framesOut; 6151 mRsmpInIndex += framesIn; 6152 framesOut -= framesIn; 6153 if ((int)mChannelCount == mReqChannelCount || 6154 mFormat != AUDIO_FORMAT_PCM_16_BIT) { 6155 memcpy(dst, src, framesIn * mFrameSize); 6156 } else { 6157 if (mChannelCount == 1) { 6158 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, 6159 (int16_t *)src, framesIn); 6160 } else { 6161 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, 6162 (int16_t *)src, framesIn); 6163 } 6164 } 6165 } 6166 if (framesOut && mFrameCount == mRsmpInIndex) { 6167 void *readInto; 6168 if (framesOut == mFrameCount && 6169 ((int)mChannelCount == mReqChannelCount || 6170 mFormat != AUDIO_FORMAT_PCM_16_BIT)) { 6171 readInto = buffer.raw; 6172 framesOut = 0; 6173 } else { 6174 readInto = mRsmpInBuffer; 6175 mRsmpInIndex = 0; 6176 } 6177 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes); 6178 if (mBytesRead <= 0) { 6179 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) 6180 { 6181 ALOGE("Error reading audio input"); 6182 // Force input into standby so that it tries to 6183 // recover at next read attempt 6184 inputStandBy(); 6185 usleep(kRecordThreadSleepUs); 6186 } 6187 mRsmpInIndex = mFrameCount; 6188 framesOut = 0; 6189 buffer.frameCount = 0; 6190 } else if (mTeeSink != 0) { 6191 (void) mTeeSink->write(readInto, 6192 mBytesRead >> Format_frameBitShift(mTeeSink->format())); 6193 } 6194 } 6195 } 6196 } else { 6197 // resampling 6198 6199 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t)); 6200 // alter output frame count as if we were expecting stereo samples 6201 if (mChannelCount == 1 && mReqChannelCount == 1) { 6202 framesOut >>= 1; 6203 } 6204 mResampler->resample(mRsmpOutBuffer, framesOut, 6205 this /* AudioBufferProvider* */); 6206 // ditherAndClamp() works as long as all buffers returned by 6207 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true. 6208 if (mChannelCount == 2 && mReqChannelCount == 1) { 6209 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 6210 // the resampler always outputs stereo samples: 6211 // do post stereo to mono conversion 6212 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, 6213 framesOut); 6214 } else { 6215 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 6216 } 6217 6218 } 6219 if (mFramestoDrop == 0) { 6220 mActiveTrack->releaseBuffer(&buffer); 6221 } else { 6222 if (mFramestoDrop > 0) { 6223 mFramestoDrop -= buffer.frameCount; 6224 if (mFramestoDrop <= 0) { 6225 clearSyncStartEvent(); 6226 } 6227 } else { 6228 mFramestoDrop += buffer.frameCount; 6229 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 6230 mSyncStartEvent->isCancelled()) { 6231 ALOGW("Synced record %s, session %d, trigger session %d", 6232 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 6233 mActiveTrack->sessionId(), 6234 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 6235 clearSyncStartEvent(); 6236 } 6237 } 6238 } 6239 mActiveTrack->clearOverflow(); 6240 } 6241 // client isn't retrieving buffers fast enough 6242 else { 6243 if (!mActiveTrack->setOverflow()) { 6244 nsecs_t now = systemTime(); 6245 if ((now - lastWarning) > kWarningThrottleNs) { 6246 ALOGW("RecordThread: buffer overflow"); 6247 lastWarning = now; 6248 } 6249 } 6250 // Release the processor for a while before asking for a new buffer. 6251 // This will give the application more chance to read from the buffer and 6252 // clear the overflow. 6253 usleep(kRecordThreadSleepUs); 6254 } 6255 } 6256 // enable changes in effect chain 6257 unlockEffectChains(effectChains); 6258 effectChains.clear(); 6259 } 6260 6261 standby(); 6262 6263 { 6264 Mutex::Autolock _l(mLock); 6265 mActiveTrack.clear(); 6266 mStartStopCond.broadcast(); 6267 } 6268 6269 releaseWakeLock(); 6270 6271 ALOGV("RecordThread %p exiting", this); 6272 return false; 6273} 6274 6275void AudioFlinger::RecordThread::standby() 6276{ 6277 if (!mStandby) { 6278 inputStandBy(); 6279 mStandby = true; 6280 } 6281} 6282 6283void AudioFlinger::RecordThread::inputStandBy() 6284{ 6285 mInput->stream->common.standby(&mInput->stream->common); 6286} 6287 6288sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 6289 const sp<AudioFlinger::Client>& client, 6290 uint32_t sampleRate, 6291 audio_format_t format, 6292 audio_channel_mask_t channelMask, 6293 size_t frameCount, 6294 int sessionId, 6295 IAudioFlinger::track_flags_t flags, 6296 pid_t tid, 6297 status_t *status) 6298{ 6299 sp<RecordTrack> track; 6300 status_t lStatus; 6301 6302 lStatus = initCheck(); 6303 if (lStatus != NO_ERROR) { 6304 ALOGE("Audio driver not initialized."); 6305 goto Exit; 6306 } 6307 6308 // FIXME use flags and tid similar to createTrack_l() 6309 6310 { // scope for mLock 6311 Mutex::Autolock _l(mLock); 6312 6313 track = new RecordTrack(this, client, sampleRate, 6314 format, channelMask, frameCount, sessionId); 6315 6316 if (track->getCblk() == 0) { 6317 lStatus = NO_MEMORY; 6318 goto Exit; 6319 } 6320 mTracks.add(track); 6321 6322 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6323 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6324 mAudioFlinger->btNrecIsOff(); 6325 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 6326 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 6327 } 6328 lStatus = NO_ERROR; 6329 6330Exit: 6331 if (status) { 6332 *status = lStatus; 6333 } 6334 return track; 6335} 6336 6337status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 6338 AudioSystem::sync_event_t event, 6339 int triggerSession) 6340{ 6341 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 6342 sp<ThreadBase> strongMe = this; 6343 status_t status = NO_ERROR; 6344 6345 if (event == AudioSystem::SYNC_EVENT_NONE) { 6346 clearSyncStartEvent(); 6347 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 6348 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 6349 triggerSession, 6350 recordTrack->sessionId(), 6351 syncStartEventCallback, 6352 this); 6353 // Sync event can be cancelled by the trigger session if the track is not in a 6354 // compatible state in which case we start record immediately 6355 if (mSyncStartEvent->isCancelled()) { 6356 clearSyncStartEvent(); 6357 } else { 6358 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 6359 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 6360 } 6361 } 6362 6363 { 6364 AutoMutex lock(mLock); 6365 if (mActiveTrack != 0) { 6366 if (recordTrack != mActiveTrack.get()) { 6367 status = -EBUSY; 6368 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 6369 mActiveTrack->mState = TrackBase::ACTIVE; 6370 } 6371 return status; 6372 } 6373 6374 recordTrack->mState = TrackBase::IDLE; 6375 mActiveTrack = recordTrack; 6376 mLock.unlock(); 6377 status_t status = AudioSystem::startInput(mId); 6378 mLock.lock(); 6379 if (status != NO_ERROR) { 6380 mActiveTrack.clear(); 6381 clearSyncStartEvent(); 6382 return status; 6383 } 6384 mRsmpInIndex = mFrameCount; 6385 mBytesRead = 0; 6386 if (mResampler != NULL) { 6387 mResampler->reset(); 6388 } 6389 mActiveTrack->mState = TrackBase::RESUMING; 6390 // signal thread to start 6391 ALOGV("Signal record thread"); 6392 mWaitWorkCV.broadcast(); 6393 // do not wait for mStartStopCond if exiting 6394 if (exitPending()) { 6395 mActiveTrack.clear(); 6396 status = INVALID_OPERATION; 6397 goto startError; 6398 } 6399 mStartStopCond.wait(mLock); 6400 if (mActiveTrack == 0) { 6401 ALOGV("Record failed to start"); 6402 status = BAD_VALUE; 6403 goto startError; 6404 } 6405 ALOGV("Record started OK"); 6406 return status; 6407 } 6408startError: 6409 AudioSystem::stopInput(mId); 6410 clearSyncStartEvent(); 6411 return status; 6412} 6413 6414void AudioFlinger::RecordThread::clearSyncStartEvent() 6415{ 6416 if (mSyncStartEvent != 0) { 6417 mSyncStartEvent->cancel(); 6418 } 6419 mSyncStartEvent.clear(); 6420 mFramestoDrop = 0; 6421} 6422 6423void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 6424{ 6425 sp<SyncEvent> strongEvent = event.promote(); 6426 6427 if (strongEvent != 0) { 6428 RecordThread *me = (RecordThread *)strongEvent->cookie(); 6429 me->handleSyncStartEvent(strongEvent); 6430 } 6431} 6432 6433void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 6434{ 6435 if (event == mSyncStartEvent) { 6436 // TODO: use actual buffer filling status instead of 2 buffers when info is available 6437 // from audio HAL 6438 mFramestoDrop = mFrameCount * 2; 6439 } 6440} 6441 6442bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) { 6443 ALOGV("RecordThread::stop"); 6444 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) { 6445 return false; 6446 } 6447 recordTrack->mState = TrackBase::PAUSING; 6448 // do not wait for mStartStopCond if exiting 6449 if (exitPending()) { 6450 return true; 6451 } 6452 mStartStopCond.wait(mLock); 6453 // if we have been restarted, recordTrack == mActiveTrack.get() here 6454 if (exitPending() || recordTrack != mActiveTrack.get()) { 6455 ALOGV("Record stopped OK"); 6456 return true; 6457 } 6458 return false; 6459} 6460 6461bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const 6462{ 6463 return false; 6464} 6465 6466status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) 6467{ 6468#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 6469 if (!isValidSyncEvent(event)) { 6470 return BAD_VALUE; 6471 } 6472 6473 int eventSession = event->triggerSession(); 6474 status_t ret = NAME_NOT_FOUND; 6475 6476 Mutex::Autolock _l(mLock); 6477 6478 for (size_t i = 0; i < mTracks.size(); i++) { 6479 sp<RecordTrack> track = mTracks[i]; 6480 if (eventSession == track->sessionId()) { 6481 (void) track->setSyncEvent(event); 6482 ret = NO_ERROR; 6483 } 6484 } 6485 return ret; 6486#else 6487 return BAD_VALUE; 6488#endif 6489} 6490 6491void AudioFlinger::RecordThread::RecordTrack::destroy() 6492{ 6493 // see comments at AudioFlinger::PlaybackThread::Track::destroy() 6494 sp<RecordTrack> keep(this); 6495 { 6496 sp<ThreadBase> thread = mThread.promote(); 6497 if (thread != 0) { 6498 if (mState == ACTIVE || mState == RESUMING) { 6499 AudioSystem::stopInput(thread->id()); 6500 } 6501 AudioSystem::releaseInput(thread->id()); 6502 Mutex::Autolock _l(thread->mLock); 6503 RecordThread *recordThread = (RecordThread *) thread.get(); 6504 recordThread->destroyTrack_l(this); 6505 } 6506 } 6507} 6508 6509// destroyTrack_l() must be called with ThreadBase::mLock held 6510void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 6511{ 6512 track->mState = TrackBase::TERMINATED; 6513 // active tracks are removed by threadLoop() 6514 if (mActiveTrack != track) { 6515 removeTrack_l(track); 6516 } 6517} 6518 6519void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 6520{ 6521 mTracks.remove(track); 6522 // need anything related to effects here? 6523} 6524 6525void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 6526{ 6527 dumpInternals(fd, args); 6528 dumpTracks(fd, args); 6529 dumpEffectChains(fd, args); 6530} 6531 6532void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 6533{ 6534 const size_t SIZE = 256; 6535 char buffer[SIZE]; 6536 String8 result; 6537 6538 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 6539 result.append(buffer); 6540 6541 if (mActiveTrack != 0) { 6542 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 6543 result.append(buffer); 6544 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes); 6545 result.append(buffer); 6546 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 6547 result.append(buffer); 6548 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount); 6549 result.append(buffer); 6550 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate); 6551 result.append(buffer); 6552 } else { 6553 result.append("No active record client\n"); 6554 } 6555 6556 write(fd, result.string(), result.size()); 6557 6558 dumpBase(fd, args); 6559} 6560 6561void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args) 6562{ 6563 const size_t SIZE = 256; 6564 char buffer[SIZE]; 6565 String8 result; 6566 6567 snprintf(buffer, SIZE, "Input thread %p tracks\n", this); 6568 result.append(buffer); 6569 RecordTrack::appendDumpHeader(result); 6570 for (size_t i = 0; i < mTracks.size(); ++i) { 6571 sp<RecordTrack> track = mTracks[i]; 6572 if (track != 0) { 6573 track->dump(buffer, SIZE); 6574 result.append(buffer); 6575 } 6576 } 6577 6578 if (mActiveTrack != 0) { 6579 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this); 6580 result.append(buffer); 6581 RecordTrack::appendDumpHeader(result); 6582 mActiveTrack->dump(buffer, SIZE); 6583 result.append(buffer); 6584 6585 } 6586 write(fd, result.string(), result.size()); 6587} 6588 6589// AudioBufferProvider interface 6590status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 6591{ 6592 size_t framesReq = buffer->frameCount; 6593 size_t framesReady = mFrameCount - mRsmpInIndex; 6594 int channelCount; 6595 6596 if (framesReady == 0) { 6597 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 6598 if (mBytesRead <= 0) { 6599 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) { 6600 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 6601 // Force input into standby so that it tries to 6602 // recover at next read attempt 6603 inputStandBy(); 6604 usleep(kRecordThreadSleepUs); 6605 } 6606 buffer->raw = NULL; 6607 buffer->frameCount = 0; 6608 return NOT_ENOUGH_DATA; 6609 } 6610 mRsmpInIndex = 0; 6611 framesReady = mFrameCount; 6612 } 6613 6614 if (framesReq > framesReady) { 6615 framesReq = framesReady; 6616 } 6617 6618 if (mChannelCount == 1 && mReqChannelCount == 2) { 6619 channelCount = 1; 6620 } else { 6621 channelCount = 2; 6622 } 6623 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 6624 buffer->frameCount = framesReq; 6625 return NO_ERROR; 6626} 6627 6628// AudioBufferProvider interface 6629void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 6630{ 6631 mRsmpInIndex += buffer->frameCount; 6632 buffer->frameCount = 0; 6633} 6634 6635bool AudioFlinger::RecordThread::checkForNewParameters_l() 6636{ 6637 bool reconfig = false; 6638 6639 while (!mNewParameters.isEmpty()) { 6640 status_t status = NO_ERROR; 6641 String8 keyValuePair = mNewParameters[0]; 6642 AudioParameter param = AudioParameter(keyValuePair); 6643 int value; 6644 audio_format_t reqFormat = mFormat; 6645 uint32_t reqSamplingRate = mReqSampleRate; 6646 int reqChannelCount = mReqChannelCount; 6647 6648 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 6649 reqSamplingRate = value; 6650 reconfig = true; 6651 } 6652 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 6653 reqFormat = (audio_format_t) value; 6654 reconfig = true; 6655 } 6656 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 6657 reqChannelCount = popcount(value); 6658 reconfig = true; 6659 } 6660 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 6661 // do not accept frame count changes if tracks are open as the track buffer 6662 // size depends on frame count and correct behavior would not be guaranteed 6663 // if frame count is changed after track creation 6664 if (mActiveTrack != 0) { 6665 status = INVALID_OPERATION; 6666 } else { 6667 reconfig = true; 6668 } 6669 } 6670 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 6671 // forward device change to effects that have requested to be 6672 // aware of attached audio device. 6673 for (size_t i = 0; i < mEffectChains.size(); i++) { 6674 mEffectChains[i]->setDevice_l(value); 6675 } 6676 6677 // store input device and output device but do not forward output device to audio HAL. 6678 // Note that status is ignored by the caller for output device 6679 // (see AudioFlinger::setParameters() 6680 if (audio_is_output_devices(value)) { 6681 mOutDevice = value; 6682 status = BAD_VALUE; 6683 } else { 6684 mInDevice = value; 6685 // disable AEC and NS if the device is a BT SCO headset supporting those 6686 // pre processings 6687 if (mTracks.size() > 0) { 6688 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6689 mAudioFlinger->btNrecIsOff(); 6690 for (size_t i = 0; i < mTracks.size(); i++) { 6691 sp<RecordTrack> track = mTracks[i]; 6692 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6693 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6694 } 6695 } 6696 } 6697 } 6698 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 6699 mAudioSource != (audio_source_t)value) { 6700 // forward device change to effects that have requested to be 6701 // aware of attached audio device. 6702 for (size_t i = 0; i < mEffectChains.size(); i++) { 6703 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 6704 } 6705 mAudioSource = (audio_source_t)value; 6706 } 6707 if (status == NO_ERROR) { 6708 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6709 keyValuePair.string()); 6710 if (status == INVALID_OPERATION) { 6711 inputStandBy(); 6712 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6713 keyValuePair.string()); 6714 } 6715 if (reconfig) { 6716 if (status == BAD_VALUE && 6717 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 6718 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 6719 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) 6720 <= (2 * reqSamplingRate)) && 6721 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) 6722 <= FCC_2 && 6723 (reqChannelCount <= FCC_2)) { 6724 status = NO_ERROR; 6725 } 6726 if (status == NO_ERROR) { 6727 readInputParameters(); 6728 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 6729 } 6730 } 6731 } 6732 6733 mNewParameters.removeAt(0); 6734 6735 mParamStatus = status; 6736 mParamCond.signal(); 6737 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 6738 // already timed out waiting for the status and will never signal the condition. 6739 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 6740 } 6741 return reconfig; 6742} 6743 6744String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 6745{ 6746 char *s; 6747 String8 out_s8 = String8(); 6748 6749 Mutex::Autolock _l(mLock); 6750 if (initCheck() != NO_ERROR) { 6751 return out_s8; 6752 } 6753 6754 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 6755 out_s8 = String8(s); 6756 free(s); 6757 return out_s8; 6758} 6759 6760void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 6761 AudioSystem::OutputDescriptor desc; 6762 void *param2 = NULL; 6763 6764 switch (event) { 6765 case AudioSystem::INPUT_OPENED: 6766 case AudioSystem::INPUT_CONFIG_CHANGED: 6767 desc.channels = mChannelMask; 6768 desc.samplingRate = mSampleRate; 6769 desc.format = mFormat; 6770 desc.frameCount = mFrameCount; 6771 desc.latency = 0; 6772 param2 = &desc; 6773 break; 6774 6775 case AudioSystem::INPUT_CLOSED: 6776 default: 6777 break; 6778 } 6779 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 6780} 6781 6782void AudioFlinger::RecordThread::readInputParameters() 6783{ 6784 delete mRsmpInBuffer; 6785 // mRsmpInBuffer is always assigned a new[] below 6786 delete mRsmpOutBuffer; 6787 mRsmpOutBuffer = NULL; 6788 delete mResampler; 6789 mResampler = NULL; 6790 6791 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 6792 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 6793 mChannelCount = (uint16_t)popcount(mChannelMask); 6794 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 6795 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 6796 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common); 6797 mFrameCount = mInputBytes / mFrameSize; 6798 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects 6799 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 6800 6801 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) 6802 { 6803 int channelCount; 6804 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid 6805 // stereo to mono post process as the resampler always outputs stereo. 6806 if (mChannelCount == 1 && mReqChannelCount == 2) { 6807 channelCount = 1; 6808 } else { 6809 channelCount = 2; 6810 } 6811 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 6812 mResampler->setSampleRate(mSampleRate); 6813 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 6814 mRsmpOutBuffer = new int32_t[mFrameCount * 2]; 6815 6816 // optmization: if mono to mono, alter input frame count as if we were inputing 6817 // stereo samples 6818 if (mChannelCount == 1 && mReqChannelCount == 1) { 6819 mFrameCount >>= 1; 6820 } 6821 6822 } 6823 mRsmpInIndex = mFrameCount; 6824} 6825 6826unsigned int AudioFlinger::RecordThread::getInputFramesLost() 6827{ 6828 Mutex::Autolock _l(mLock); 6829 if (initCheck() != NO_ERROR) { 6830 return 0; 6831 } 6832 6833 return mInput->stream->get_input_frames_lost(mInput->stream); 6834} 6835 6836uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 6837{ 6838 Mutex::Autolock _l(mLock); 6839 uint32_t result = 0; 6840 if (getEffectChain_l(sessionId) != 0) { 6841 result = EFFECT_SESSION; 6842 } 6843 6844 for (size_t i = 0; i < mTracks.size(); ++i) { 6845 if (sessionId == mTracks[i]->sessionId()) { 6846 result |= TRACK_SESSION; 6847 break; 6848 } 6849 } 6850 6851 return result; 6852} 6853 6854KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 6855{ 6856 KeyedVector<int, bool> ids; 6857 Mutex::Autolock _l(mLock); 6858 for (size_t j = 0; j < mTracks.size(); ++j) { 6859 sp<RecordThread::RecordTrack> track = mTracks[j]; 6860 int sessionId = track->sessionId(); 6861 if (ids.indexOfKey(sessionId) < 0) { 6862 ids.add(sessionId, true); 6863 } 6864 } 6865 return ids; 6866} 6867 6868AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 6869{ 6870 Mutex::Autolock _l(mLock); 6871 AudioStreamIn *input = mInput; 6872 mInput = NULL; 6873 return input; 6874} 6875 6876// this method must always be called either with ThreadBase mLock held or inside the thread loop 6877audio_stream_t* AudioFlinger::RecordThread::stream() const 6878{ 6879 if (mInput == NULL) { 6880 return NULL; 6881 } 6882 return &mInput->stream->common; 6883} 6884 6885 6886// ---------------------------------------------------------------------------- 6887 6888audio_module_handle_t AudioFlinger::loadHwModule(const char *name) 6889{ 6890 if (!settingsAllowed()) { 6891 return 0; 6892 } 6893 Mutex::Autolock _l(mLock); 6894 return loadHwModule_l(name); 6895} 6896 6897// loadHwModule_l() must be called with AudioFlinger::mLock held 6898audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) 6899{ 6900 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 6901 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) { 6902 ALOGW("loadHwModule() module %s already loaded", name); 6903 return mAudioHwDevs.keyAt(i); 6904 } 6905 } 6906 6907 audio_hw_device_t *dev; 6908 6909 int rc = load_audio_interface(name, &dev); 6910 if (rc) { 6911 ALOGI("loadHwModule() error %d loading module %s ", rc, name); 6912 return 0; 6913 } 6914 6915 mHardwareStatus = AUDIO_HW_INIT; 6916 rc = dev->init_check(dev); 6917 mHardwareStatus = AUDIO_HW_IDLE; 6918 if (rc) { 6919 ALOGI("loadHwModule() init check error %d for module %s ", rc, name); 6920 return 0; 6921 } 6922 6923 // Check and cache this HAL's level of support for master mute and master 6924 // volume. If this is the first HAL opened, and it supports the get 6925 // methods, use the initial values provided by the HAL as the current 6926 // master mute and volume settings. 6927 6928 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0); 6929 { // scope for auto-lock pattern 6930 AutoMutex lock(mHardwareLock); 6931 6932 if (0 == mAudioHwDevs.size()) { 6933 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME; 6934 if (NULL != dev->get_master_volume) { 6935 float mv; 6936 if (OK == dev->get_master_volume(dev, &mv)) { 6937 mMasterVolume = mv; 6938 } 6939 } 6940 6941 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE; 6942 if (NULL != dev->get_master_mute) { 6943 bool mm; 6944 if (OK == dev->get_master_mute(dev, &mm)) { 6945 mMasterMute = mm; 6946 } 6947 } 6948 } 6949 6950 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 6951 if ((NULL != dev->set_master_volume) && 6952 (OK == dev->set_master_volume(dev, mMasterVolume))) { 6953 flags = static_cast<AudioHwDevice::Flags>(flags | 6954 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME); 6955 } 6956 6957 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE; 6958 if ((NULL != dev->set_master_mute) && 6959 (OK == dev->set_master_mute(dev, mMasterMute))) { 6960 flags = static_cast<AudioHwDevice::Flags>(flags | 6961 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE); 6962 } 6963 6964 mHardwareStatus = AUDIO_HW_IDLE; 6965 } 6966 6967 audio_module_handle_t handle = nextUniqueId(); 6968 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags)); 6969 6970 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d", 6971 name, dev->common.module->name, dev->common.module->id, handle); 6972 6973 return handle; 6974 6975} 6976 6977// ---------------------------------------------------------------------------- 6978 6979uint32_t AudioFlinger::getPrimaryOutputSamplingRate() 6980{ 6981 Mutex::Autolock _l(mLock); 6982 PlaybackThread *thread = primaryPlaybackThread_l(); 6983 return thread != NULL ? thread->sampleRate() : 0; 6984} 6985 6986size_t AudioFlinger::getPrimaryOutputFrameCount() 6987{ 6988 Mutex::Autolock _l(mLock); 6989 PlaybackThread *thread = primaryPlaybackThread_l(); 6990 return thread != NULL ? thread->frameCountHAL() : 0; 6991} 6992 6993// ---------------------------------------------------------------------------- 6994 6995audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module, 6996 audio_devices_t *pDevices, 6997 uint32_t *pSamplingRate, 6998 audio_format_t *pFormat, 6999 audio_channel_mask_t *pChannelMask, 7000 uint32_t *pLatencyMs, 7001 audio_output_flags_t flags) 7002{ 7003 status_t status; 7004 PlaybackThread *thread = NULL; 7005 struct audio_config config = { 7006 sample_rate: pSamplingRate ? *pSamplingRate : 0, 7007 channel_mask: pChannelMask ? *pChannelMask : 0, 7008 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT, 7009 }; 7010 audio_stream_out_t *outStream = NULL; 7011 AudioHwDevice *outHwDev; 7012 7013 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x", 7014 module, 7015 (pDevices != NULL) ? *pDevices : 0, 7016 config.sample_rate, 7017 config.format, 7018 config.channel_mask, 7019 flags); 7020 7021 if (pDevices == NULL || *pDevices == 0) { 7022 return 0; 7023 } 7024 7025 Mutex::Autolock _l(mLock); 7026 7027 outHwDev = findSuitableHwDev_l(module, *pDevices); 7028 if (outHwDev == NULL) 7029 return 0; 7030 7031 audio_hw_device_t *hwDevHal = outHwDev->hwDevice(); 7032 audio_io_handle_t id = nextUniqueId(); 7033 7034 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 7035 7036 status = hwDevHal->open_output_stream(hwDevHal, 7037 id, 7038 *pDevices, 7039 (audio_output_flags_t)flags, 7040 &config, 7041 &outStream); 7042 7043 mHardwareStatus = AUDIO_HW_IDLE; 7044 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, " 7045 "Channels %x, status %d", 7046 outStream, 7047 config.sample_rate, 7048 config.format, 7049 config.channel_mask, 7050 status); 7051 7052 if (status == NO_ERROR && outStream != NULL) { 7053 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream); 7054 7055 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) || 7056 (config.format != AUDIO_FORMAT_PCM_16_BIT) || 7057 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) { 7058 thread = new DirectOutputThread(this, output, id, *pDevices); 7059 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 7060 } else { 7061 thread = new MixerThread(this, output, id, *pDevices); 7062 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 7063 } 7064 mPlaybackThreads.add(id, thread); 7065 7066 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate; 7067 if (pFormat != NULL) *pFormat = config.format; 7068 if (pChannelMask != NULL) *pChannelMask = config.channel_mask; 7069 if (pLatencyMs != NULL) *pLatencyMs = thread->latency(); 7070 7071 // notify client processes of the new output creation 7072 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 7073 7074 // the first primary output opened designates the primary hw device 7075 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) { 7076 ALOGI("Using module %d has the primary audio interface", module); 7077 mPrimaryHardwareDev = outHwDev; 7078 7079 AutoMutex lock(mHardwareLock); 7080 mHardwareStatus = AUDIO_HW_SET_MODE; 7081 hwDevHal->set_mode(hwDevHal, mMode); 7082 mHardwareStatus = AUDIO_HW_IDLE; 7083 } 7084 return id; 7085 } 7086 7087 return 0; 7088} 7089 7090audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 7091 audio_io_handle_t output2) 7092{ 7093 Mutex::Autolock _l(mLock); 7094 MixerThread *thread1 = checkMixerThread_l(output1); 7095 MixerThread *thread2 = checkMixerThread_l(output2); 7096 7097 if (thread1 == NULL || thread2 == NULL) { 7098 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, 7099 output2); 7100 return 0; 7101 } 7102 7103 audio_io_handle_t id = nextUniqueId(); 7104 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 7105 thread->addOutputTrack(thread2); 7106 mPlaybackThreads.add(id, thread); 7107 // notify client processes of the new output creation 7108 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 7109 return id; 7110} 7111 7112status_t AudioFlinger::closeOutput(audio_io_handle_t output) 7113{ 7114 return closeOutput_nonvirtual(output); 7115} 7116 7117status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) 7118{ 7119 // keep strong reference on the playback thread so that 7120 // it is not destroyed while exit() is executed 7121 sp<PlaybackThread> thread; 7122 { 7123 Mutex::Autolock _l(mLock); 7124 thread = checkPlaybackThread_l(output); 7125 if (thread == NULL) { 7126 return BAD_VALUE; 7127 } 7128 7129 ALOGV("closeOutput() %d", output); 7130 7131 if (thread->type() == ThreadBase::MIXER) { 7132 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7133 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 7134 DuplicatingThread *dupThread = 7135 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 7136 dupThread->removeOutputTrack((MixerThread *)thread.get()); 7137 } 7138 } 7139 } 7140 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL); 7141 mPlaybackThreads.removeItem(output); 7142 } 7143 thread->exit(); 7144 // The thread entity (active unit of execution) is no longer running here, 7145 // but the ThreadBase container still exists. 7146 7147 if (thread->type() != ThreadBase::DUPLICATING) { 7148 AudioStreamOut *out = thread->clearOutput(); 7149 ALOG_ASSERT(out != NULL, "out shouldn't be NULL"); 7150 // from now on thread->mOutput is NULL 7151 out->hwDev()->close_output_stream(out->hwDev(), out->stream); 7152 delete out; 7153 } 7154 return NO_ERROR; 7155} 7156 7157status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 7158{ 7159 Mutex::Autolock _l(mLock); 7160 PlaybackThread *thread = checkPlaybackThread_l(output); 7161 7162 if (thread == NULL) { 7163 return BAD_VALUE; 7164 } 7165 7166 ALOGV("suspendOutput() %d", output); 7167 thread->suspend(); 7168 7169 return NO_ERROR; 7170} 7171 7172status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 7173{ 7174 Mutex::Autolock _l(mLock); 7175 PlaybackThread *thread = checkPlaybackThread_l(output); 7176 7177 if (thread == NULL) { 7178 return BAD_VALUE; 7179 } 7180 7181 ALOGV("restoreOutput() %d", output); 7182 7183 thread->restore(); 7184 7185 return NO_ERROR; 7186} 7187 7188audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module, 7189 audio_devices_t *pDevices, 7190 uint32_t *pSamplingRate, 7191 audio_format_t *pFormat, 7192 audio_channel_mask_t *pChannelMask) 7193{ 7194 status_t status; 7195 RecordThread *thread = NULL; 7196 struct audio_config config = { 7197 sample_rate: pSamplingRate ? *pSamplingRate : 0, 7198 channel_mask: pChannelMask ? *pChannelMask : 0, 7199 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT, 7200 }; 7201 uint32_t reqSamplingRate = config.sample_rate; 7202 audio_format_t reqFormat = config.format; 7203 audio_channel_mask_t reqChannels = config.channel_mask; 7204 audio_stream_in_t *inStream = NULL; 7205 AudioHwDevice *inHwDev; 7206 7207 if (pDevices == NULL || *pDevices == 0) { 7208 return 0; 7209 } 7210 7211 Mutex::Autolock _l(mLock); 7212 7213 inHwDev = findSuitableHwDev_l(module, *pDevices); 7214 if (inHwDev == NULL) 7215 return 0; 7216 7217 audio_hw_device_t *inHwHal = inHwDev->hwDevice(); 7218 audio_io_handle_t id = nextUniqueId(); 7219 7220 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, 7221 &inStream); 7222 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, " 7223 "status %d", 7224 inStream, 7225 config.sample_rate, 7226 config.format, 7227 config.channel_mask, 7228 status); 7229 7230 // If the input could not be opened with the requested parameters and we can handle the 7231 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can 7232 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs. 7233 if (status == BAD_VALUE && 7234 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && 7235 (config.sample_rate <= 2 * reqSamplingRate) && 7236 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) { 7237 ALOGV("openInput() reopening with proposed sampling rate and channel mask"); 7238 inStream = NULL; 7239 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream); 7240 } 7241 7242 if (status == NO_ERROR && inStream != NULL) { 7243 7244 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys, 7245 // or (re-)create if current Pipe is idle and does not match the new format 7246 sp<NBAIO_Sink> teeSink; 7247#ifdef TEE_SINK_INPUT_FRAMES 7248 enum { 7249 TEE_SINK_NO, // don't copy input 7250 TEE_SINK_NEW, // copy input using a new pipe 7251 TEE_SINK_OLD, // copy input using an existing pipe 7252 } kind; 7253 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common), 7254 popcount(inStream->common.get_channels(&inStream->common))); 7255 if (format == Format_Invalid) { 7256 kind = TEE_SINK_NO; 7257 } else if (mRecordTeeSink == 0) { 7258 kind = TEE_SINK_NEW; 7259 } else if (mRecordTeeSink->getStrongCount() != 1) { 7260 kind = TEE_SINK_NO; 7261 } else if (format == mRecordTeeSink->format()) { 7262 kind = TEE_SINK_OLD; 7263 } else { 7264 kind = TEE_SINK_NEW; 7265 } 7266 switch (kind) { 7267 case TEE_SINK_NEW: { 7268 Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format); 7269 size_t numCounterOffers = 0; 7270 const NBAIO_Format offers[1] = {format}; 7271 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 7272 ALOG_ASSERT(index == 0); 7273 PipeReader *pipeReader = new PipeReader(*pipe); 7274 numCounterOffers = 0; 7275 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 7276 ALOG_ASSERT(index == 0); 7277 mRecordTeeSink = pipe; 7278 mRecordTeeSource = pipeReader; 7279 teeSink = pipe; 7280 } 7281 break; 7282 case TEE_SINK_OLD: 7283 teeSink = mRecordTeeSink; 7284 break; 7285 case TEE_SINK_NO: 7286 default: 7287 break; 7288 } 7289#endif 7290 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 7291 7292 // Start record thread 7293 // RecorThread require both input and output device indication to forward to audio 7294 // pre processing modules 7295 audio_devices_t device = (*pDevices) | primaryOutputDevice_l(); 7296 7297 thread = new RecordThread(this, 7298 input, 7299 reqSamplingRate, 7300 reqChannels, 7301 id, 7302 device, teeSink); 7303 mRecordThreads.add(id, thread); 7304 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 7305 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate; 7306 if (pFormat != NULL) *pFormat = config.format; 7307 if (pChannelMask != NULL) *pChannelMask = reqChannels; 7308 7309 // notify client processes of the new input creation 7310 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 7311 return id; 7312 } 7313 7314 return 0; 7315} 7316 7317status_t AudioFlinger::closeInput(audio_io_handle_t input) 7318{ 7319 return closeInput_nonvirtual(input); 7320} 7321 7322status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) 7323{ 7324 // keep strong reference on the record thread so that 7325 // it is not destroyed while exit() is executed 7326 sp<RecordThread> thread; 7327 { 7328 Mutex::Autolock _l(mLock); 7329 thread = checkRecordThread_l(input); 7330 if (thread == 0) { 7331 return BAD_VALUE; 7332 } 7333 7334 ALOGV("closeInput() %d", input); 7335 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL); 7336 mRecordThreads.removeItem(input); 7337 } 7338 thread->exit(); 7339 // The thread entity (active unit of execution) is no longer running here, 7340 // but the ThreadBase container still exists. 7341 7342 AudioStreamIn *in = thread->clearInput(); 7343 ALOG_ASSERT(in != NULL, "in shouldn't be NULL"); 7344 // from now on thread->mInput is NULL 7345 in->hwDev()->close_input_stream(in->hwDev(), in->stream); 7346 delete in; 7347 7348 return NO_ERROR; 7349} 7350 7351status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 7352{ 7353 Mutex::Autolock _l(mLock); 7354 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 7355 7356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7357 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 7358 thread->invalidateTracks(stream); 7359 } 7360 7361 return NO_ERROR; 7362} 7363 7364 7365int AudioFlinger::newAudioSessionId() 7366{ 7367 return nextUniqueId(); 7368} 7369 7370void AudioFlinger::acquireAudioSessionId(int audioSession) 7371{ 7372 Mutex::Autolock _l(mLock); 7373 pid_t caller = IPCThreadState::self()->getCallingPid(); 7374 ALOGV("acquiring %d from %d", audioSession, caller); 7375 size_t num = mAudioSessionRefs.size(); 7376 for (size_t i = 0; i< num; i++) { 7377 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 7378 if (ref->mSessionid == audioSession && ref->mPid == caller) { 7379 ref->mCnt++; 7380 ALOGV(" incremented refcount to %d", ref->mCnt); 7381 return; 7382 } 7383 } 7384 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 7385 ALOGV(" added new entry for %d", audioSession); 7386} 7387 7388void AudioFlinger::releaseAudioSessionId(int audioSession) 7389{ 7390 Mutex::Autolock _l(mLock); 7391 pid_t caller = IPCThreadState::self()->getCallingPid(); 7392 ALOGV("releasing %d from %d", audioSession, caller); 7393 size_t num = mAudioSessionRefs.size(); 7394 for (size_t i = 0; i< num; i++) { 7395 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 7396 if (ref->mSessionid == audioSession && ref->mPid == caller) { 7397 ref->mCnt--; 7398 ALOGV(" decremented refcount to %d", ref->mCnt); 7399 if (ref->mCnt == 0) { 7400 mAudioSessionRefs.removeAt(i); 7401 delete ref; 7402 purgeStaleEffects_l(); 7403 } 7404 return; 7405 } 7406 } 7407 ALOGW("session id %d not found for pid %d", audioSession, caller); 7408} 7409 7410void AudioFlinger::purgeStaleEffects_l() { 7411 7412 ALOGV("purging stale effects"); 7413 7414 Vector< sp<EffectChain> > chains; 7415 7416 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7417 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 7418 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 7419 sp<EffectChain> ec = t->mEffectChains[j]; 7420 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 7421 chains.push(ec); 7422 } 7423 } 7424 } 7425 for (size_t i = 0; i < mRecordThreads.size(); i++) { 7426 sp<RecordThread> t = mRecordThreads.valueAt(i); 7427 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 7428 sp<EffectChain> ec = t->mEffectChains[j]; 7429 chains.push(ec); 7430 } 7431 } 7432 7433 for (size_t i = 0; i < chains.size(); i++) { 7434 sp<EffectChain> ec = chains[i]; 7435 int sessionid = ec->sessionId(); 7436 sp<ThreadBase> t = ec->mThread.promote(); 7437 if (t == 0) { 7438 continue; 7439 } 7440 size_t numsessionrefs = mAudioSessionRefs.size(); 7441 bool found = false; 7442 for (size_t k = 0; k < numsessionrefs; k++) { 7443 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 7444 if (ref->mSessionid == sessionid) { 7445 ALOGV(" session %d still exists for %d with %d refs", 7446 sessionid, ref->mPid, ref->mCnt); 7447 found = true; 7448 break; 7449 } 7450 } 7451 if (!found) { 7452 Mutex::Autolock _l (t->mLock); 7453 // remove all effects from the chain 7454 while (ec->mEffects.size()) { 7455 sp<EffectModule> effect = ec->mEffects[0]; 7456 effect->unPin(); 7457 t->removeEffect_l(effect); 7458 if (effect->purgeHandles()) { 7459 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 7460 } 7461 AudioSystem::unregisterEffect(effect->id()); 7462 } 7463 } 7464 } 7465 return; 7466} 7467 7468// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 7469AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 7470{ 7471 return mPlaybackThreads.valueFor(output).get(); 7472} 7473 7474// checkMixerThread_l() must be called with AudioFlinger::mLock held 7475AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 7476{ 7477 PlaybackThread *thread = checkPlaybackThread_l(output); 7478 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL; 7479} 7480 7481// checkRecordThread_l() must be called with AudioFlinger::mLock held 7482AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 7483{ 7484 return mRecordThreads.valueFor(input).get(); 7485} 7486 7487uint32_t AudioFlinger::nextUniqueId() 7488{ 7489 return android_atomic_inc(&mNextUniqueId); 7490} 7491 7492AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const 7493{ 7494 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7495 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 7496 AudioStreamOut *output = thread->getOutput(); 7497 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) { 7498 return thread; 7499 } 7500 } 7501 return NULL; 7502} 7503 7504audio_devices_t AudioFlinger::primaryOutputDevice_l() const 7505{ 7506 PlaybackThread *thread = primaryPlaybackThread_l(); 7507 7508 if (thread == NULL) { 7509 return 0; 7510 } 7511 7512 return thread->outDevice(); 7513} 7514 7515sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, 7516 int triggerSession, 7517 int listenerSession, 7518 sync_event_callback_t callBack, 7519 void *cookie) 7520{ 7521 Mutex::Autolock _l(mLock); 7522 7523 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie); 7524 status_t playStatus = NAME_NOT_FOUND; 7525 status_t recStatus = NAME_NOT_FOUND; 7526 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7527 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event); 7528 if (playStatus == NO_ERROR) { 7529 return event; 7530 } 7531 } 7532 for (size_t i = 0; i < mRecordThreads.size(); i++) { 7533 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event); 7534 if (recStatus == NO_ERROR) { 7535 return event; 7536 } 7537 } 7538 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) { 7539 mPendingSyncEvents.add(event); 7540 } else { 7541 ALOGV("createSyncEvent() invalid event %d", event->type()); 7542 event.clear(); 7543 } 7544 return event; 7545} 7546 7547// ---------------------------------------------------------------------------- 7548// Effect management 7549// ---------------------------------------------------------------------------- 7550 7551 7552status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 7553{ 7554 Mutex::Autolock _l(mLock); 7555 return EffectQueryNumberEffects(numEffects); 7556} 7557 7558status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 7559{ 7560 Mutex::Autolock _l(mLock); 7561 return EffectQueryEffect(index, descriptor); 7562} 7563 7564status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 7565 effect_descriptor_t *descriptor) const 7566{ 7567 Mutex::Autolock _l(mLock); 7568 return EffectGetDescriptor(pUuid, descriptor); 7569} 7570 7571 7572sp<IEffect> AudioFlinger::createEffect(pid_t pid, 7573 effect_descriptor_t *pDesc, 7574 const sp<IEffectClient>& effectClient, 7575 int32_t priority, 7576 audio_io_handle_t io, 7577 int sessionId, 7578 status_t *status, 7579 int *id, 7580 int *enabled) 7581{ 7582 status_t lStatus = NO_ERROR; 7583 sp<EffectHandle> handle; 7584 effect_descriptor_t desc; 7585 7586 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 7587 pid, effectClient.get(), priority, sessionId, io); 7588 7589 if (pDesc == NULL) { 7590 lStatus = BAD_VALUE; 7591 goto Exit; 7592 } 7593 7594 // check audio settings permission for global effects 7595 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 7596 lStatus = PERMISSION_DENIED; 7597 goto Exit; 7598 } 7599 7600 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 7601 // that can only be created by audio policy manager (running in same process) 7602 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) { 7603 lStatus = PERMISSION_DENIED; 7604 goto Exit; 7605 } 7606 7607 if (io == 0) { 7608 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 7609 // output must be specified by AudioPolicyManager when using session 7610 // AUDIO_SESSION_OUTPUT_STAGE 7611 lStatus = BAD_VALUE; 7612 goto Exit; 7613 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 7614 // if the output returned by getOutputForEffect() is removed before we lock the 7615 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 7616 // and we will exit safely 7617 io = AudioSystem::getOutputForEffect(&desc); 7618 } 7619 } 7620 7621 { 7622 Mutex::Autolock _l(mLock); 7623 7624 7625 if (!EffectIsNullUuid(&pDesc->uuid)) { 7626 // if uuid is specified, request effect descriptor 7627 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 7628 if (lStatus < 0) { 7629 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 7630 goto Exit; 7631 } 7632 } else { 7633 // if uuid is not specified, look for an available implementation 7634 // of the required type in effect factory 7635 if (EffectIsNullUuid(&pDesc->type)) { 7636 ALOGW("createEffect() no effect type"); 7637 lStatus = BAD_VALUE; 7638 goto Exit; 7639 } 7640 uint32_t numEffects = 0; 7641 effect_descriptor_t d; 7642 d.flags = 0; // prevent compiler warning 7643 bool found = false; 7644 7645 lStatus = EffectQueryNumberEffects(&numEffects); 7646 if (lStatus < 0) { 7647 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 7648 goto Exit; 7649 } 7650 for (uint32_t i = 0; i < numEffects; i++) { 7651 lStatus = EffectQueryEffect(i, &desc); 7652 if (lStatus < 0) { 7653 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 7654 continue; 7655 } 7656 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 7657 // If matching type found save effect descriptor. If the session is 7658 // 0 and the effect is not auxiliary, continue enumeration in case 7659 // an auxiliary version of this effect type is available 7660 found = true; 7661 d = desc; 7662 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 7663 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7664 break; 7665 } 7666 } 7667 } 7668 if (!found) { 7669 lStatus = BAD_VALUE; 7670 ALOGW("createEffect() effect not found"); 7671 goto Exit; 7672 } 7673 // For same effect type, chose auxiliary version over insert version if 7674 // connect to output mix (Compliance to OpenSL ES) 7675 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 7676 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 7677 desc = d; 7678 } 7679 } 7680 7681 // Do not allow auxiliary effects on a session different from 0 (output mix) 7682 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 7683 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7684 lStatus = INVALID_OPERATION; 7685 goto Exit; 7686 } 7687 7688 // check recording permission for visualizer 7689 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 7690 !recordingAllowed()) { 7691 lStatus = PERMISSION_DENIED; 7692 goto Exit; 7693 } 7694 7695 // return effect descriptor 7696 *pDesc = desc; 7697 7698 // If output is not specified try to find a matching audio session ID in one of the 7699 // output threads. 7700 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 7701 // because of code checking output when entering the function. 7702 // Note: io is never 0 when creating an effect on an input 7703 if (io == 0) { 7704 // look for the thread where the specified audio session is present 7705 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 7706 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 7707 io = mPlaybackThreads.keyAt(i); 7708 break; 7709 } 7710 } 7711 if (io == 0) { 7712 for (size_t i = 0; i < mRecordThreads.size(); i++) { 7713 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 7714 io = mRecordThreads.keyAt(i); 7715 break; 7716 } 7717 } 7718 } 7719 // If no output thread contains the requested session ID, default to 7720 // first output. The effect chain will be moved to the correct output 7721 // thread when a track with the same session ID is created 7722 if (io == 0 && mPlaybackThreads.size()) { 7723 io = mPlaybackThreads.keyAt(0); 7724 } 7725 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 7726 } 7727 ThreadBase *thread = checkRecordThread_l(io); 7728 if (thread == NULL) { 7729 thread = checkPlaybackThread_l(io); 7730 if (thread == NULL) { 7731 ALOGE("createEffect() unknown output thread"); 7732 lStatus = BAD_VALUE; 7733 goto Exit; 7734 } 7735 } 7736 7737 sp<Client> client = registerPid_l(pid); 7738 7739 // create effect on selected output thread 7740 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 7741 &desc, enabled, &lStatus); 7742 if (handle != 0 && id != NULL) { 7743 *id = handle->id(); 7744 } 7745 } 7746 7747Exit: 7748 if (status != NULL) { 7749 *status = lStatus; 7750 } 7751 return handle; 7752} 7753 7754status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 7755 audio_io_handle_t dstOutput) 7756{ 7757 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 7758 sessionId, srcOutput, dstOutput); 7759 Mutex::Autolock _l(mLock); 7760 if (srcOutput == dstOutput) { 7761 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 7762 return NO_ERROR; 7763 } 7764 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 7765 if (srcThread == NULL) { 7766 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 7767 return BAD_VALUE; 7768 } 7769 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 7770 if (dstThread == NULL) { 7771 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 7772 return BAD_VALUE; 7773 } 7774 7775 Mutex::Autolock _dl(dstThread->mLock); 7776 Mutex::Autolock _sl(srcThread->mLock); 7777 moveEffectChain_l(sessionId, srcThread, dstThread, false); 7778 7779 return NO_ERROR; 7780} 7781 7782// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 7783status_t AudioFlinger::moveEffectChain_l(int sessionId, 7784 AudioFlinger::PlaybackThread *srcThread, 7785 AudioFlinger::PlaybackThread *dstThread, 7786 bool reRegister) 7787{ 7788 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 7789 sessionId, srcThread, dstThread); 7790 7791 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 7792 if (chain == 0) { 7793 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 7794 sessionId, srcThread); 7795 return INVALID_OPERATION; 7796 } 7797 7798 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 7799 // so that a new chain is created with correct parameters when first effect is added. This is 7800 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 7801 // removed. 7802 srcThread->removeEffectChain_l(chain); 7803 7804 // transfer all effects one by one so that new effect chain is created on new thread with 7805 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 7806 audio_io_handle_t dstOutput = dstThread->id(); 7807 sp<EffectChain> dstChain; 7808 uint32_t strategy = 0; // prevent compiler warning 7809 sp<EffectModule> effect = chain->getEffectFromId_l(0); 7810 while (effect != 0) { 7811 srcThread->removeEffect_l(effect); 7812 dstThread->addEffect_l(effect); 7813 // removeEffect_l() has stopped the effect if it was active so it must be restarted 7814 if (effect->state() == EffectModule::ACTIVE || 7815 effect->state() == EffectModule::STOPPING) { 7816 effect->start(); 7817 } 7818 // if the move request is not received from audio policy manager, the effect must be 7819 // re-registered with the new strategy and output 7820 if (dstChain == 0) { 7821 dstChain = effect->chain().promote(); 7822 if (dstChain == 0) { 7823 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 7824 srcThread->addEffect_l(effect); 7825 return NO_INIT; 7826 } 7827 strategy = dstChain->strategy(); 7828 } 7829 if (reRegister) { 7830 AudioSystem::unregisterEffect(effect->id()); 7831 AudioSystem::registerEffect(&effect->desc(), 7832 dstOutput, 7833 strategy, 7834 sessionId, 7835 effect->id()); 7836 } 7837 effect = chain->getEffectFromId_l(0); 7838 } 7839 7840 return NO_ERROR; 7841} 7842 7843 7844// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held 7845sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 7846 const sp<AudioFlinger::Client>& client, 7847 const sp<IEffectClient>& effectClient, 7848 int32_t priority, 7849 int sessionId, 7850 effect_descriptor_t *desc, 7851 int *enabled, 7852 status_t *status 7853 ) 7854{ 7855 sp<EffectModule> effect; 7856 sp<EffectHandle> handle; 7857 status_t lStatus; 7858 sp<EffectChain> chain; 7859 bool chainCreated = false; 7860 bool effectCreated = false; 7861 bool effectRegistered = false; 7862 7863 lStatus = initCheck(); 7864 if (lStatus != NO_ERROR) { 7865 ALOGW("createEffect_l() Audio driver not initialized."); 7866 goto Exit; 7867 } 7868 7869 // Do not allow effects with session ID 0 on direct output or duplicating threads 7870 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format 7871 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { 7872 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", 7873 desc->name, sessionId); 7874 lStatus = BAD_VALUE; 7875 goto Exit; 7876 } 7877 // Only Pre processor effects are allowed on input threads and only on input threads 7878 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 7879 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 7880 desc->name, desc->flags, mType); 7881 lStatus = BAD_VALUE; 7882 goto Exit; 7883 } 7884 7885 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 7886 7887 { // scope for mLock 7888 Mutex::Autolock _l(mLock); 7889 7890 // check for existing effect chain with the requested audio session 7891 chain = getEffectChain_l(sessionId); 7892 if (chain == 0) { 7893 // create a new chain for this session 7894 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 7895 chain = new EffectChain(this, sessionId); 7896 addEffectChain_l(chain); 7897 chain->setStrategy(getStrategyForSession_l(sessionId)); 7898 chainCreated = true; 7899 } else { 7900 effect = chain->getEffectFromDesc_l(desc); 7901 } 7902 7903 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 7904 7905 if (effect == 0) { 7906 int id = mAudioFlinger->nextUniqueId(); 7907 // Check CPU and memory usage 7908 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 7909 if (lStatus != NO_ERROR) { 7910 goto Exit; 7911 } 7912 effectRegistered = true; 7913 // create a new effect module if none present in the chain 7914 effect = new EffectModule(this, chain, desc, id, sessionId); 7915 lStatus = effect->status(); 7916 if (lStatus != NO_ERROR) { 7917 goto Exit; 7918 } 7919 lStatus = chain->addEffect_l(effect); 7920 if (lStatus != NO_ERROR) { 7921 goto Exit; 7922 } 7923 effectCreated = true; 7924 7925 effect->setDevice(mOutDevice); 7926 effect->setDevice(mInDevice); 7927 effect->setMode(mAudioFlinger->getMode()); 7928 effect->setAudioSource(mAudioSource); 7929 } 7930 // create effect handle and connect it to effect module 7931 handle = new EffectHandle(effect, client, effectClient, priority); 7932 lStatus = effect->addHandle(handle.get()); 7933 if (enabled != NULL) { 7934 *enabled = (int)effect->isEnabled(); 7935 } 7936 } 7937 7938Exit: 7939 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 7940 Mutex::Autolock _l(mLock); 7941 if (effectCreated) { 7942 chain->removeEffect_l(effect); 7943 } 7944 if (effectRegistered) { 7945 AudioSystem::unregisterEffect(effect->id()); 7946 } 7947 if (chainCreated) { 7948 removeEffectChain_l(chain); 7949 } 7950 handle.clear(); 7951 } 7952 7953 if (status != NULL) { 7954 *status = lStatus; 7955 } 7956 return handle; 7957} 7958 7959sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId) 7960{ 7961 Mutex::Autolock _l(mLock); 7962 return getEffect_l(sessionId, effectId); 7963} 7964 7965sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 7966{ 7967 sp<EffectChain> chain = getEffectChain_l(sessionId); 7968 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 7969} 7970 7971// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 7972// PlaybackThread::mLock held 7973status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 7974{ 7975 // check for existing effect chain with the requested audio session 7976 int sessionId = effect->sessionId(); 7977 sp<EffectChain> chain = getEffectChain_l(sessionId); 7978 bool chainCreated = false; 7979 7980 if (chain == 0) { 7981 // create a new chain for this session 7982 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 7983 chain = new EffectChain(this, sessionId); 7984 addEffectChain_l(chain); 7985 chain->setStrategy(getStrategyForSession_l(sessionId)); 7986 chainCreated = true; 7987 } 7988 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 7989 7990 if (chain->getEffectFromId_l(effect->id()) != 0) { 7991 ALOGW("addEffect_l() %p effect %s already present in chain %p", 7992 this, effect->desc().name, chain.get()); 7993 return BAD_VALUE; 7994 } 7995 7996 status_t status = chain->addEffect_l(effect); 7997 if (status != NO_ERROR) { 7998 if (chainCreated) { 7999 removeEffectChain_l(chain); 8000 } 8001 return status; 8002 } 8003 8004 effect->setDevice(mOutDevice); 8005 effect->setDevice(mInDevice); 8006 effect->setMode(mAudioFlinger->getMode()); 8007 effect->setAudioSource(mAudioSource); 8008 return NO_ERROR; 8009} 8010 8011void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 8012 8013 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 8014 effect_descriptor_t desc = effect->desc(); 8015 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8016 detachAuxEffect_l(effect->id()); 8017 } 8018 8019 sp<EffectChain> chain = effect->chain().promote(); 8020 if (chain != 0) { 8021 // remove effect chain if removing last effect 8022 if (chain->removeEffect_l(effect) == 0) { 8023 removeEffectChain_l(chain); 8024 } 8025 } else { 8026 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 8027 } 8028} 8029 8030void AudioFlinger::ThreadBase::lockEffectChains_l( 8031 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 8032{ 8033 effectChains = mEffectChains; 8034 for (size_t i = 0; i < mEffectChains.size(); i++) { 8035 mEffectChains[i]->lock(); 8036 } 8037} 8038 8039void AudioFlinger::ThreadBase::unlockEffectChains( 8040 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 8041{ 8042 for (size_t i = 0; i < effectChains.size(); i++) { 8043 effectChains[i]->unlock(); 8044 } 8045} 8046 8047sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 8048{ 8049 Mutex::Autolock _l(mLock); 8050 return getEffectChain_l(sessionId); 8051} 8052 8053sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const 8054{ 8055 size_t size = mEffectChains.size(); 8056 for (size_t i = 0; i < size; i++) { 8057 if (mEffectChains[i]->sessionId() == sessionId) { 8058 return mEffectChains[i]; 8059 } 8060 } 8061 return 0; 8062} 8063 8064void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 8065{ 8066 Mutex::Autolock _l(mLock); 8067 size_t size = mEffectChains.size(); 8068 for (size_t i = 0; i < size; i++) { 8069 mEffectChains[i]->setMode_l(mode); 8070 } 8071} 8072 8073void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 8074 EffectHandle *handle, 8075 bool unpinIfLast) { 8076 8077 Mutex::Autolock _l(mLock); 8078 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 8079 // delete the effect module if removing last handle on it 8080 if (effect->removeHandle(handle) == 0) { 8081 if (!effect->isPinned() || unpinIfLast) { 8082 removeEffect_l(effect); 8083 AudioSystem::unregisterEffect(effect->id()); 8084 } 8085 } 8086} 8087 8088status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 8089{ 8090 int session = chain->sessionId(); 8091 int16_t *buffer = mMixBuffer; 8092 bool ownsBuffer = false; 8093 8094 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 8095 if (session > 0) { 8096 // Only one effect chain can be present in direct output thread and it uses 8097 // the mix buffer as input 8098 if (mType != DIRECT) { 8099 size_t numSamples = mNormalFrameCount * mChannelCount; 8100 buffer = new int16_t[numSamples]; 8101 memset(buffer, 0, numSamples * sizeof(int16_t)); 8102 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 8103 ownsBuffer = true; 8104 } 8105 8106 // Attach all tracks with same session ID to this chain. 8107 for (size_t i = 0; i < mTracks.size(); ++i) { 8108 sp<Track> track = mTracks[i]; 8109 if (session == track->sessionId()) { 8110 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 8111 buffer); 8112 track->setMainBuffer(buffer); 8113 chain->incTrackCnt(); 8114 } 8115 } 8116 8117 // indicate all active tracks in the chain 8118 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 8119 sp<Track> track = mActiveTracks[i].promote(); 8120 if (track == 0) continue; 8121 if (session == track->sessionId()) { 8122 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 8123 chain->incActiveTrackCnt(); 8124 } 8125 } 8126 } 8127 8128 chain->setInBuffer(buffer, ownsBuffer); 8129 chain->setOutBuffer(mMixBuffer); 8130 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 8131 // chains list in order to be processed last as it contains output stage effects 8132 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 8133 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 8134 // after track specific effects and before output stage 8135 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 8136 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 8137 // Effect chain for other sessions are inserted at beginning of effect 8138 // chains list to be processed before output mix effects. Relative order between other 8139 // sessions is not important 8140 size_t size = mEffectChains.size(); 8141 size_t i = 0; 8142 for (i = 0; i < size; i++) { 8143 if (mEffectChains[i]->sessionId() < session) break; 8144 } 8145 mEffectChains.insertAt(chain, i); 8146 checkSuspendOnAddEffectChain_l(chain); 8147 8148 return NO_ERROR; 8149} 8150 8151size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 8152{ 8153 int session = chain->sessionId(); 8154 8155 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 8156 8157 for (size_t i = 0; i < mEffectChains.size(); i++) { 8158 if (chain == mEffectChains[i]) { 8159 mEffectChains.removeAt(i); 8160 // detach all active tracks from the chain 8161 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 8162 sp<Track> track = mActiveTracks[i].promote(); 8163 if (track == 0) continue; 8164 if (session == track->sessionId()) { 8165 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 8166 chain.get(), session); 8167 chain->decActiveTrackCnt(); 8168 } 8169 } 8170 8171 // detach all tracks with same session ID from this chain 8172 for (size_t i = 0; i < mTracks.size(); ++i) { 8173 sp<Track> track = mTracks[i]; 8174 if (session == track->sessionId()) { 8175 track->setMainBuffer(mMixBuffer); 8176 chain->decTrackCnt(); 8177 } 8178 } 8179 break; 8180 } 8181 } 8182 return mEffectChains.size(); 8183} 8184 8185status_t AudioFlinger::PlaybackThread::attachAuxEffect( 8186 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 8187{ 8188 Mutex::Autolock _l(mLock); 8189 return attachAuxEffect_l(track, EffectId); 8190} 8191 8192status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 8193 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 8194{ 8195 status_t status = NO_ERROR; 8196 8197 if (EffectId == 0) { 8198 track->setAuxBuffer(0, NULL); 8199 } else { 8200 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 8201 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 8202 if (effect != 0) { 8203 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8204 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 8205 } else { 8206 status = INVALID_OPERATION; 8207 } 8208 } else { 8209 status = BAD_VALUE; 8210 } 8211 } 8212 return status; 8213} 8214 8215void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 8216{ 8217 for (size_t i = 0; i < mTracks.size(); ++i) { 8218 sp<Track> track = mTracks[i]; 8219 if (track->auxEffectId() == effectId) { 8220 attachAuxEffect_l(track, 0); 8221 } 8222 } 8223} 8224 8225status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 8226{ 8227 // only one chain per input thread 8228 if (mEffectChains.size() != 0) { 8229 return INVALID_OPERATION; 8230 } 8231 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 8232 8233 chain->setInBuffer(NULL); 8234 chain->setOutBuffer(NULL); 8235 8236 checkSuspendOnAddEffectChain_l(chain); 8237 8238 mEffectChains.add(chain); 8239 8240 return NO_ERROR; 8241} 8242 8243size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 8244{ 8245 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 8246 ALOGW_IF(mEffectChains.size() != 1, 8247 "removeEffectChain_l() %p invalid chain size %d on thread %p", 8248 chain.get(), mEffectChains.size(), this); 8249 if (mEffectChains.size() == 1) { 8250 mEffectChains.removeAt(0); 8251 } 8252 return 0; 8253} 8254 8255// ---------------------------------------------------------------------------- 8256// EffectModule implementation 8257// ---------------------------------------------------------------------------- 8258 8259#undef LOG_TAG 8260#define LOG_TAG "AudioFlinger::EffectModule" 8261 8262AudioFlinger::EffectModule::EffectModule(ThreadBase *thread, 8263 const wp<AudioFlinger::EffectChain>& chain, 8264 effect_descriptor_t *desc, 8265 int id, 8266 int sessionId) 8267 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX), 8268 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), 8269 mDescriptor(*desc), 8270 // mConfig is set by configure() and not used before then 8271 mEffectInterface(NULL), 8272 mStatus(NO_INIT), mState(IDLE), 8273 // mMaxDisableWaitCnt is set by configure() and not used before then 8274 // mDisableWaitCnt is set by process() and updateState() and not used before then 8275 mSuspended(false) 8276{ 8277 ALOGV("Constructor %p", this); 8278 int lStatus; 8279 8280 // create effect engine from effect factory 8281 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface); 8282 8283 if (mStatus != NO_ERROR) { 8284 return; 8285 } 8286 lStatus = init(); 8287 if (lStatus < 0) { 8288 mStatus = lStatus; 8289 goto Error; 8290 } 8291 8292 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface); 8293 return; 8294Error: 8295 EffectRelease(mEffectInterface); 8296 mEffectInterface = NULL; 8297 ALOGV("Constructor Error %d", mStatus); 8298} 8299 8300AudioFlinger::EffectModule::~EffectModule() 8301{ 8302 ALOGV("Destructor %p", this); 8303 if (mEffectInterface != NULL) { 8304 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 8305 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 8306 sp<ThreadBase> thread = mThread.promote(); 8307 if (thread != 0) { 8308 audio_stream_t *stream = thread->stream(); 8309 if (stream != NULL) { 8310 stream->remove_audio_effect(stream, mEffectInterface); 8311 } 8312 } 8313 } 8314 // release effect engine 8315 EffectRelease(mEffectInterface); 8316 } 8317} 8318 8319status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle) 8320{ 8321 status_t status; 8322 8323 Mutex::Autolock _l(mLock); 8324 int priority = handle->priority(); 8325 size_t size = mHandles.size(); 8326 EffectHandle *controlHandle = NULL; 8327 size_t i; 8328 for (i = 0; i < size; i++) { 8329 EffectHandle *h = mHandles[i]; 8330 if (h == NULL || h->destroyed_l()) continue; 8331 // first non destroyed handle is considered in control 8332 if (controlHandle == NULL) 8333 controlHandle = h; 8334 if (h->priority() <= priority) break; 8335 } 8336 // if inserted in first place, move effect control from previous owner to this handle 8337 if (i == 0) { 8338 bool enabled = false; 8339 if (controlHandle != NULL) { 8340 enabled = controlHandle->enabled(); 8341 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/); 8342 } 8343 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/); 8344 status = NO_ERROR; 8345 } else { 8346 status = ALREADY_EXISTS; 8347 } 8348 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i); 8349 mHandles.insertAt(handle, i); 8350 return status; 8351} 8352 8353size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle) 8354{ 8355 Mutex::Autolock _l(mLock); 8356 size_t size = mHandles.size(); 8357 size_t i; 8358 for (i = 0; i < size; i++) { 8359 if (mHandles[i] == handle) break; 8360 } 8361 if (i == size) { 8362 return size; 8363 } 8364 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i); 8365 8366 mHandles.removeAt(i); 8367 // if removed from first place, move effect control from this handle to next in line 8368 if (i == 0) { 8369 EffectHandle *h = controlHandle_l(); 8370 if (h != NULL) { 8371 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/); 8372 } 8373 } 8374 8375 // Prevent calls to process() and other functions on effect interface from now on. 8376 // The effect engine will be released by the destructor when the last strong reference on 8377 // this object is released which can happen after next process is called. 8378 if (mHandles.size() == 0 && !mPinned) { 8379 mState = DESTROYED; 8380 } 8381 8382 return mHandles.size(); 8383} 8384 8385// must be called with EffectModule::mLock held 8386AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l() 8387{ 8388 // the first valid handle in the list has control over the module 8389 for (size_t i = 0; i < mHandles.size(); i++) { 8390 EffectHandle *h = mHandles[i]; 8391 if (h != NULL && !h->destroyed_l()) { 8392 return h; 8393 } 8394 } 8395 8396 return NULL; 8397} 8398 8399size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast) 8400{ 8401 ALOGV("disconnect() %p handle %p", this, handle); 8402 // keep a strong reference on this EffectModule to avoid calling the 8403 // destructor before we exit 8404 sp<EffectModule> keep(this); 8405 { 8406 sp<ThreadBase> thread = mThread.promote(); 8407 if (thread != 0) { 8408 thread->disconnectEffect(keep, handle, unpinIfLast); 8409 } 8410 } 8411 return mHandles.size(); 8412} 8413 8414void AudioFlinger::EffectModule::updateState() { 8415 Mutex::Autolock _l(mLock); 8416 8417 switch (mState) { 8418 case RESTART: 8419 reset_l(); 8420 // FALL THROUGH 8421 8422 case STARTING: 8423 // clear auxiliary effect input buffer for next accumulation 8424 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8425 memset(mConfig.inputCfg.buffer.raw, 8426 0, 8427 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 8428 } 8429 start_l(); 8430 mState = ACTIVE; 8431 break; 8432 case STOPPING: 8433 stop_l(); 8434 mDisableWaitCnt = mMaxDisableWaitCnt; 8435 mState = STOPPED; 8436 break; 8437 case STOPPED: 8438 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the 8439 // turn off sequence. 8440 if (--mDisableWaitCnt == 0) { 8441 reset_l(); 8442 mState = IDLE; 8443 } 8444 break; 8445 default: //IDLE , ACTIVE, DESTROYED 8446 break; 8447 } 8448} 8449 8450void AudioFlinger::EffectModule::process() 8451{ 8452 Mutex::Autolock _l(mLock); 8453 8454 if (mState == DESTROYED || mEffectInterface == NULL || 8455 mConfig.inputCfg.buffer.raw == NULL || 8456 mConfig.outputCfg.buffer.raw == NULL) { 8457 return; 8458 } 8459 8460 if (isProcessEnabled()) { 8461 // do 32 bit to 16 bit conversion for auxiliary effect input buffer 8462 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8463 ditherAndClamp(mConfig.inputCfg.buffer.s32, 8464 mConfig.inputCfg.buffer.s32, 8465 mConfig.inputCfg.buffer.frameCount/2); 8466 } 8467 8468 // do the actual processing in the effect engine 8469 int ret = (*mEffectInterface)->process(mEffectInterface, 8470 &mConfig.inputCfg.buffer, 8471 &mConfig.outputCfg.buffer); 8472 8473 // force transition to IDLE state when engine is ready 8474 if (mState == STOPPED && ret == -ENODATA) { 8475 mDisableWaitCnt = 1; 8476 } 8477 8478 // clear auxiliary effect input buffer for next accumulation 8479 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8480 memset(mConfig.inputCfg.buffer.raw, 0, 8481 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 8482 } 8483 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT && 8484 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 8485 // If an insert effect is idle and input buffer is different from output buffer, 8486 // accumulate input onto output 8487 sp<EffectChain> chain = mChain.promote(); 8488 if (chain != 0 && chain->activeTrackCnt() != 0) { 8489 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here 8490 int16_t *in = mConfig.inputCfg.buffer.s16; 8491 int16_t *out = mConfig.outputCfg.buffer.s16; 8492 for (size_t i = 0; i < frameCnt; i++) { 8493 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]); 8494 } 8495 } 8496 } 8497} 8498 8499void AudioFlinger::EffectModule::reset_l() 8500{ 8501 if (mEffectInterface == NULL) { 8502 return; 8503 } 8504 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL); 8505} 8506 8507status_t AudioFlinger::EffectModule::configure() 8508{ 8509 if (mEffectInterface == NULL) { 8510 return NO_INIT; 8511 } 8512 8513 sp<ThreadBase> thread = mThread.promote(); 8514 if (thread == 0) { 8515 return DEAD_OBJECT; 8516 } 8517 8518 // TODO: handle configuration of effects replacing track process 8519 audio_channel_mask_t channelMask = thread->channelMask(); 8520 8521 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 8522 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; 8523 } else { 8524 mConfig.inputCfg.channels = channelMask; 8525 } 8526 mConfig.outputCfg.channels = channelMask; 8527 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 8528 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 8529 mConfig.inputCfg.samplingRate = thread->sampleRate(); 8530 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; 8531 mConfig.inputCfg.bufferProvider.cookie = NULL; 8532 mConfig.inputCfg.bufferProvider.getBuffer = NULL; 8533 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; 8534 mConfig.outputCfg.bufferProvider.cookie = NULL; 8535 mConfig.outputCfg.bufferProvider.getBuffer = NULL; 8536 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; 8537 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; 8538 // Insert effect: 8539 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE, 8540 // always overwrites output buffer: input buffer == output buffer 8541 // - in other sessions: 8542 // last effect in the chain accumulates in output buffer: input buffer != output buffer 8543 // other effect: overwrites output buffer: input buffer == output buffer 8544 // Auxiliary effect: 8545 // accumulates in output buffer: input buffer != output buffer 8546 // Therefore: accumulate <=> input buffer != output buffer 8547 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 8548 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; 8549 } else { 8550 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; 8551 } 8552 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; 8553 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; 8554 mConfig.inputCfg.buffer.frameCount = thread->frameCount(); 8555 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; 8556 8557 ALOGV("configure() %p thread %p buffer %p framecount %d", 8558 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); 8559 8560 status_t cmdStatus; 8561 uint32_t size = sizeof(int); 8562 status_t status = (*mEffectInterface)->command(mEffectInterface, 8563 EFFECT_CMD_SET_CONFIG, 8564 sizeof(effect_config_t), 8565 &mConfig, 8566 &size, 8567 &cmdStatus); 8568 if (status == 0) { 8569 status = cmdStatus; 8570 } 8571 8572 if (status == 0 && 8573 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) { 8574 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2]; 8575 effect_param_t *p = (effect_param_t *)buf32; 8576 8577 p->psize = sizeof(uint32_t); 8578 p->vsize = sizeof(uint32_t); 8579 size = sizeof(int); 8580 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY; 8581 8582 uint32_t latency = 0; 8583 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId); 8584 if (pbt != NULL) { 8585 latency = pbt->latency_l(); 8586 } 8587 8588 *((int32_t *)p->data + 1)= latency; 8589 (*mEffectInterface)->command(mEffectInterface, 8590 EFFECT_CMD_SET_PARAM, 8591 sizeof(effect_param_t) + 8, 8592 &buf32, 8593 &size, 8594 &cmdStatus); 8595 } 8596 8597 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / 8598 (1000 * mConfig.outputCfg.buffer.frameCount); 8599 8600 return status; 8601} 8602 8603status_t AudioFlinger::EffectModule::init() 8604{ 8605 Mutex::Autolock _l(mLock); 8606 if (mEffectInterface == NULL) { 8607 return NO_INIT; 8608 } 8609 status_t cmdStatus; 8610 uint32_t size = sizeof(status_t); 8611 status_t status = (*mEffectInterface)->command(mEffectInterface, 8612 EFFECT_CMD_INIT, 8613 0, 8614 NULL, 8615 &size, 8616 &cmdStatus); 8617 if (status == 0) { 8618 status = cmdStatus; 8619 } 8620 return status; 8621} 8622 8623status_t AudioFlinger::EffectModule::start() 8624{ 8625 Mutex::Autolock _l(mLock); 8626 return start_l(); 8627} 8628 8629status_t AudioFlinger::EffectModule::start_l() 8630{ 8631 if (mEffectInterface == NULL) { 8632 return NO_INIT; 8633 } 8634 status_t cmdStatus; 8635 uint32_t size = sizeof(status_t); 8636 status_t status = (*mEffectInterface)->command(mEffectInterface, 8637 EFFECT_CMD_ENABLE, 8638 0, 8639 NULL, 8640 &size, 8641 &cmdStatus); 8642 if (status == 0) { 8643 status = cmdStatus; 8644 } 8645 if (status == 0 && 8646 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 8647 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 8648 sp<ThreadBase> thread = mThread.promote(); 8649 if (thread != 0) { 8650 audio_stream_t *stream = thread->stream(); 8651 if (stream != NULL) { 8652 stream->add_audio_effect(stream, mEffectInterface); 8653 } 8654 } 8655 } 8656 return status; 8657} 8658 8659status_t AudioFlinger::EffectModule::stop() 8660{ 8661 Mutex::Autolock _l(mLock); 8662 return stop_l(); 8663} 8664 8665status_t AudioFlinger::EffectModule::stop_l() 8666{ 8667 if (mEffectInterface == NULL) { 8668 return NO_INIT; 8669 } 8670 status_t cmdStatus; 8671 uint32_t size = sizeof(status_t); 8672 status_t status = (*mEffectInterface)->command(mEffectInterface, 8673 EFFECT_CMD_DISABLE, 8674 0, 8675 NULL, 8676 &size, 8677 &cmdStatus); 8678 if (status == 0) { 8679 status = cmdStatus; 8680 } 8681 if (status == 0 && 8682 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 8683 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 8684 sp<ThreadBase> thread = mThread.promote(); 8685 if (thread != 0) { 8686 audio_stream_t *stream = thread->stream(); 8687 if (stream != NULL) { 8688 stream->remove_audio_effect(stream, mEffectInterface); 8689 } 8690 } 8691 } 8692 return status; 8693} 8694 8695status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, 8696 uint32_t cmdSize, 8697 void *pCmdData, 8698 uint32_t *replySize, 8699 void *pReplyData) 8700{ 8701 Mutex::Autolock _l(mLock); 8702 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); 8703 8704 if (mState == DESTROYED || mEffectInterface == NULL) { 8705 return NO_INIT; 8706 } 8707 status_t status = (*mEffectInterface)->command(mEffectInterface, 8708 cmdCode, 8709 cmdSize, 8710 pCmdData, 8711 replySize, 8712 pReplyData); 8713 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { 8714 uint32_t size = (replySize == NULL) ? 0 : *replySize; 8715 for (size_t i = 1; i < mHandles.size(); i++) { 8716 EffectHandle *h = mHandles[i]; 8717 if (h != NULL && !h->destroyed_l()) { 8718 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); 8719 } 8720 } 8721 } 8722 return status; 8723} 8724 8725status_t AudioFlinger::EffectModule::setEnabled(bool enabled) 8726{ 8727 Mutex::Autolock _l(mLock); 8728 return setEnabled_l(enabled); 8729} 8730 8731// must be called with EffectModule::mLock held 8732status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled) 8733{ 8734 8735 ALOGV("setEnabled %p enabled %d", this, enabled); 8736 8737 if (enabled != isEnabled()) { 8738 status_t status = AudioSystem::setEffectEnabled(mId, enabled); 8739 if (enabled && status != NO_ERROR) { 8740 return status; 8741 } 8742 8743 switch (mState) { 8744 // going from disabled to enabled 8745 case IDLE: 8746 mState = STARTING; 8747 break; 8748 case STOPPED: 8749 mState = RESTART; 8750 break; 8751 case STOPPING: 8752 mState = ACTIVE; 8753 break; 8754 8755 // going from enabled to disabled 8756 case RESTART: 8757 mState = STOPPED; 8758 break; 8759 case STARTING: 8760 mState = IDLE; 8761 break; 8762 case ACTIVE: 8763 mState = STOPPING; 8764 break; 8765 case DESTROYED: 8766 return NO_ERROR; // simply ignore as we are being destroyed 8767 } 8768 for (size_t i = 1; i < mHandles.size(); i++) { 8769 EffectHandle *h = mHandles[i]; 8770 if (h != NULL && !h->destroyed_l()) { 8771 h->setEnabled(enabled); 8772 } 8773 } 8774 } 8775 return NO_ERROR; 8776} 8777 8778bool AudioFlinger::EffectModule::isEnabled() const 8779{ 8780 switch (mState) { 8781 case RESTART: 8782 case STARTING: 8783 case ACTIVE: 8784 return true; 8785 case IDLE: 8786 case STOPPING: 8787 case STOPPED: 8788 case DESTROYED: 8789 default: 8790 return false; 8791 } 8792} 8793 8794bool AudioFlinger::EffectModule::isProcessEnabled() const 8795{ 8796 switch (mState) { 8797 case RESTART: 8798 case ACTIVE: 8799 case STOPPING: 8800 case STOPPED: 8801 return true; 8802 case IDLE: 8803 case STARTING: 8804 case DESTROYED: 8805 default: 8806 return false; 8807 } 8808} 8809 8810status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller) 8811{ 8812 Mutex::Autolock _l(mLock); 8813 status_t status = NO_ERROR; 8814 8815 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume 8816 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set) 8817 if (isProcessEnabled() && 8818 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL || 8819 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) { 8820 status_t cmdStatus; 8821 uint32_t volume[2]; 8822 uint32_t *pVolume = NULL; 8823 uint32_t size = sizeof(volume); 8824 volume[0] = *left; 8825 volume[1] = *right; 8826 if (controller) { 8827 pVolume = volume; 8828 } 8829 status = (*mEffectInterface)->command(mEffectInterface, 8830 EFFECT_CMD_SET_VOLUME, 8831 size, 8832 volume, 8833 &size, 8834 pVolume); 8835 if (controller && status == NO_ERROR && size == sizeof(volume)) { 8836 *left = volume[0]; 8837 *right = volume[1]; 8838 } 8839 } 8840 return status; 8841} 8842 8843status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device) 8844{ 8845 if (device == AUDIO_DEVICE_NONE) { 8846 return NO_ERROR; 8847 } 8848 8849 Mutex::Autolock _l(mLock); 8850 status_t status = NO_ERROR; 8851 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) { 8852 status_t cmdStatus; 8853 uint32_t size = sizeof(status_t); 8854 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE : 8855 EFFECT_CMD_SET_INPUT_DEVICE; 8856 status = (*mEffectInterface)->command(mEffectInterface, 8857 cmd, 8858 sizeof(uint32_t), 8859 &device, 8860 &size, 8861 &cmdStatus); 8862 } 8863 return status; 8864} 8865 8866status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode) 8867{ 8868 Mutex::Autolock _l(mLock); 8869 status_t status = NO_ERROR; 8870 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) { 8871 status_t cmdStatus; 8872 uint32_t size = sizeof(status_t); 8873 status = (*mEffectInterface)->command(mEffectInterface, 8874 EFFECT_CMD_SET_AUDIO_MODE, 8875 sizeof(audio_mode_t), 8876 &mode, 8877 &size, 8878 &cmdStatus); 8879 if (status == NO_ERROR) { 8880 status = cmdStatus; 8881 } 8882 } 8883 return status; 8884} 8885 8886status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source) 8887{ 8888 Mutex::Autolock _l(mLock); 8889 status_t status = NO_ERROR; 8890 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) { 8891 uint32_t size = 0; 8892 status = (*mEffectInterface)->command(mEffectInterface, 8893 EFFECT_CMD_SET_AUDIO_SOURCE, 8894 sizeof(audio_source_t), 8895 &source, 8896 &size, 8897 NULL); 8898 } 8899 return status; 8900} 8901 8902void AudioFlinger::EffectModule::setSuspended(bool suspended) 8903{ 8904 Mutex::Autolock _l(mLock); 8905 mSuspended = suspended; 8906} 8907 8908bool AudioFlinger::EffectModule::suspended() const 8909{ 8910 Mutex::Autolock _l(mLock); 8911 return mSuspended; 8912} 8913 8914bool AudioFlinger::EffectModule::purgeHandles() 8915{ 8916 bool enabled = false; 8917 Mutex::Autolock _l(mLock); 8918 for (size_t i = 0; i < mHandles.size(); i++) { 8919 EffectHandle *handle = mHandles[i]; 8920 if (handle != NULL && !handle->destroyed_l()) { 8921 handle->effect().clear(); 8922 if (handle->hasControl()) { 8923 enabled = handle->enabled(); 8924 } 8925 } 8926 } 8927 return enabled; 8928} 8929 8930void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args) 8931{ 8932 const size_t SIZE = 256; 8933 char buffer[SIZE]; 8934 String8 result; 8935 8936 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId); 8937 result.append(buffer); 8938 8939 bool locked = tryLock(mLock); 8940 // failed to lock - AudioFlinger is probably deadlocked 8941 if (!locked) { 8942 result.append("\t\tCould not lock Fx mutex:\n"); 8943 } 8944 8945 result.append("\t\tSession Status State Engine:\n"); 8946 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n", 8947 mSessionId, mStatus, mState, (uint32_t)mEffectInterface); 8948 result.append(buffer); 8949 8950 result.append("\t\tDescriptor:\n"); 8951 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 8952 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, 8953 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1], 8954 mDescriptor.uuid.node[2], 8955 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); 8956 result.append(buffer); 8957 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 8958 mDescriptor.type.timeLow, mDescriptor.type.timeMid, 8959 mDescriptor.type.timeHiAndVersion, 8960 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1], 8961 mDescriptor.type.node[2], 8962 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); 8963 result.append(buffer); 8964 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n", 8965 mDescriptor.apiVersion, 8966 mDescriptor.flags); 8967 result.append(buffer); 8968 snprintf(buffer, SIZE, "\t\t- name: %s\n", 8969 mDescriptor.name); 8970 result.append(buffer); 8971 snprintf(buffer, SIZE, "\t\t- implementor: %s\n", 8972 mDescriptor.implementor); 8973 result.append(buffer); 8974 8975 result.append("\t\t- Input configuration:\n"); 8976 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 8977 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 8978 (uint32_t)mConfig.inputCfg.buffer.raw, 8979 mConfig.inputCfg.buffer.frameCount, 8980 mConfig.inputCfg.samplingRate, 8981 mConfig.inputCfg.channels, 8982 mConfig.inputCfg.format); 8983 result.append(buffer); 8984 8985 result.append("\t\t- Output configuration:\n"); 8986 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 8987 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 8988 (uint32_t)mConfig.outputCfg.buffer.raw, 8989 mConfig.outputCfg.buffer.frameCount, 8990 mConfig.outputCfg.samplingRate, 8991 mConfig.outputCfg.channels, 8992 mConfig.outputCfg.format); 8993 result.append(buffer); 8994 8995 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size()); 8996 result.append(buffer); 8997 result.append("\t\t\tPid Priority Ctrl Locked client server\n"); 8998 for (size_t i = 0; i < mHandles.size(); ++i) { 8999 EffectHandle *handle = mHandles[i]; 9000 if (handle != NULL && !handle->destroyed_l()) { 9001 handle->dump(buffer, SIZE); 9002 result.append(buffer); 9003 } 9004 } 9005 9006 result.append("\n"); 9007 9008 write(fd, result.string(), result.length()); 9009 9010 if (locked) { 9011 mLock.unlock(); 9012 } 9013} 9014 9015// ---------------------------------------------------------------------------- 9016// EffectHandle implementation 9017// ---------------------------------------------------------------------------- 9018 9019#undef LOG_TAG 9020#define LOG_TAG "AudioFlinger::EffectHandle" 9021 9022AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect, 9023 const sp<AudioFlinger::Client>& client, 9024 const sp<IEffectClient>& effectClient, 9025 int32_t priority) 9026 : BnEffect(), 9027 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL), 9028 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false) 9029{ 9030 ALOGV("constructor %p", this); 9031 9032 if (client == 0) { 9033 return; 9034 } 9035 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int); 9036 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset); 9037 if (mCblkMemory != 0) { 9038 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer()); 9039 9040 if (mCblk != NULL) { 9041 new(mCblk) effect_param_cblk_t(); 9042 mBuffer = (uint8_t *)mCblk + bufOffset; 9043 } 9044 } else { 9045 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + 9046 sizeof(effect_param_cblk_t)); 9047 return; 9048 } 9049} 9050 9051AudioFlinger::EffectHandle::~EffectHandle() 9052{ 9053 ALOGV("Destructor %p", this); 9054 9055 if (mEffect == 0) { 9056 mDestroyed = true; 9057 return; 9058 } 9059 mEffect->lock(); 9060 mDestroyed = true; 9061 mEffect->unlock(); 9062 disconnect(false); 9063} 9064 9065status_t AudioFlinger::EffectHandle::enable() 9066{ 9067 ALOGV("enable %p", this); 9068 if (!mHasControl) return INVALID_OPERATION; 9069 if (mEffect == 0) return DEAD_OBJECT; 9070 9071 if (mEnabled) { 9072 return NO_ERROR; 9073 } 9074 9075 mEnabled = true; 9076 9077 sp<ThreadBase> thread = mEffect->thread().promote(); 9078 if (thread != 0) { 9079 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId()); 9080 } 9081 9082 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled 9083 if (mEffect->suspended()) { 9084 return NO_ERROR; 9085 } 9086 9087 status_t status = mEffect->setEnabled(true); 9088 if (status != NO_ERROR) { 9089 if (thread != 0) { 9090 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 9091 } 9092 mEnabled = false; 9093 } 9094 return status; 9095} 9096 9097status_t AudioFlinger::EffectHandle::disable() 9098{ 9099 ALOGV("disable %p", this); 9100 if (!mHasControl) return INVALID_OPERATION; 9101 if (mEffect == 0) return DEAD_OBJECT; 9102 9103 if (!mEnabled) { 9104 return NO_ERROR; 9105 } 9106 mEnabled = false; 9107 9108 if (mEffect->suspended()) { 9109 return NO_ERROR; 9110 } 9111 9112 status_t status = mEffect->setEnabled(false); 9113 9114 sp<ThreadBase> thread = mEffect->thread().promote(); 9115 if (thread != 0) { 9116 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 9117 } 9118 9119 return status; 9120} 9121 9122void AudioFlinger::EffectHandle::disconnect() 9123{ 9124 disconnect(true); 9125} 9126 9127void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast) 9128{ 9129 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false"); 9130 if (mEffect == 0) { 9131 return; 9132 } 9133 // restore suspended effects if the disconnected handle was enabled and the last one. 9134 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) { 9135 sp<ThreadBase> thread = mEffect->thread().promote(); 9136 if (thread != 0) { 9137 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 9138 } 9139 } 9140 9141 // release sp on module => module destructor can be called now 9142 mEffect.clear(); 9143 if (mClient != 0) { 9144 if (mCblk != NULL) { 9145 // unlike ~TrackBase(), mCblk is never a local new, so don't delete 9146 mCblk->~effect_param_cblk_t(); // destroy our shared-structure. 9147 } 9148 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 9149 // Client destructor must run with AudioFlinger mutex locked 9150 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 9151 mClient.clear(); 9152 } 9153} 9154 9155status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode, 9156 uint32_t cmdSize, 9157 void *pCmdData, 9158 uint32_t *replySize, 9159 void *pReplyData) 9160{ 9161 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", 9162 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get()); 9163 9164 // only get parameter command is permitted for applications not controlling the effect 9165 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) { 9166 return INVALID_OPERATION; 9167 } 9168 if (mEffect == 0) return DEAD_OBJECT; 9169 if (mClient == 0) return INVALID_OPERATION; 9170 9171 // handle commands that are not forwarded transparently to effect engine 9172 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) { 9173 // No need to trylock() here as this function is executed in the binder thread serving a 9174 // particular client process: no risk to block the whole media server process or mixer 9175 // threads if we are stuck here 9176 Mutex::Autolock _l(mCblk->lock); 9177 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE || 9178 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) { 9179 mCblk->serverIndex = 0; 9180 mCblk->clientIndex = 0; 9181 return BAD_VALUE; 9182 } 9183 status_t status = NO_ERROR; 9184 while (mCblk->serverIndex < mCblk->clientIndex) { 9185 int reply; 9186 uint32_t rsize = sizeof(int); 9187 int *p = (int *)(mBuffer + mCblk->serverIndex); 9188 int size = *p++; 9189 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) { 9190 ALOGW("command(): invalid parameter block size"); 9191 break; 9192 } 9193 effect_param_t *param = (effect_param_t *)p; 9194 if (param->psize == 0 || param->vsize == 0) { 9195 ALOGW("command(): null parameter or value size"); 9196 mCblk->serverIndex += size; 9197 continue; 9198 } 9199 uint32_t psize = sizeof(effect_param_t) + 9200 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + 9201 param->vsize; 9202 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, 9203 psize, 9204 p, 9205 &rsize, 9206 &reply); 9207 // stop at first error encountered 9208 if (ret != NO_ERROR) { 9209 status = ret; 9210 *(int *)pReplyData = reply; 9211 break; 9212 } else if (reply != NO_ERROR) { 9213 *(int *)pReplyData = reply; 9214 break; 9215 } 9216 mCblk->serverIndex += size; 9217 } 9218 mCblk->serverIndex = 0; 9219 mCblk->clientIndex = 0; 9220 return status; 9221 } else if (cmdCode == EFFECT_CMD_ENABLE) { 9222 *(int *)pReplyData = NO_ERROR; 9223 return enable(); 9224 } else if (cmdCode == EFFECT_CMD_DISABLE) { 9225 *(int *)pReplyData = NO_ERROR; 9226 return disable(); 9227 } 9228 9229 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 9230} 9231 9232void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled) 9233{ 9234 ALOGV("setControl %p control %d", this, hasControl); 9235 9236 mHasControl = hasControl; 9237 mEnabled = enabled; 9238 9239 if (signal && mEffectClient != 0) { 9240 mEffectClient->controlStatusChanged(hasControl); 9241 } 9242} 9243 9244void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode, 9245 uint32_t cmdSize, 9246 void *pCmdData, 9247 uint32_t replySize, 9248 void *pReplyData) 9249{ 9250 if (mEffectClient != 0) { 9251 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 9252 } 9253} 9254 9255 9256 9257void AudioFlinger::EffectHandle::setEnabled(bool enabled) 9258{ 9259 if (mEffectClient != 0) { 9260 mEffectClient->enableStatusChanged(enabled); 9261 } 9262} 9263 9264status_t AudioFlinger::EffectHandle::onTransact( 9265 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 9266{ 9267 return BnEffect::onTransact(code, data, reply, flags); 9268} 9269 9270 9271void AudioFlinger::EffectHandle::dump(char* buffer, size_t size) 9272{ 9273 bool locked = mCblk != NULL && tryLock(mCblk->lock); 9274 9275 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n", 9276 (mClient == 0) ? getpid_cached : mClient->pid(), 9277 mPriority, 9278 mHasControl, 9279 !locked, 9280 mCblk ? mCblk->clientIndex : 0, 9281 mCblk ? mCblk->serverIndex : 0 9282 ); 9283 9284 if (locked) { 9285 mCblk->lock.unlock(); 9286 } 9287} 9288 9289#undef LOG_TAG 9290#define LOG_TAG "AudioFlinger::EffectChain" 9291 9292AudioFlinger::EffectChain::EffectChain(ThreadBase *thread, 9293 int sessionId) 9294 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0), 9295 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX), 9296 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX) 9297{ 9298 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 9299 if (thread == NULL) { 9300 return; 9301 } 9302 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) / 9303 thread->frameCount(); 9304} 9305 9306AudioFlinger::EffectChain::~EffectChain() 9307{ 9308 if (mOwnInBuffer) { 9309 delete mInBuffer; 9310 } 9311 9312} 9313 9314// getEffectFromDesc_l() must be called with ThreadBase::mLock held 9315sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l( 9316 effect_descriptor_t *descriptor) 9317{ 9318 size_t size = mEffects.size(); 9319 9320 for (size_t i = 0; i < size; i++) { 9321 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) { 9322 return mEffects[i]; 9323 } 9324 } 9325 return 0; 9326} 9327 9328// getEffectFromId_l() must be called with ThreadBase::mLock held 9329sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id) 9330{ 9331 size_t size = mEffects.size(); 9332 9333 for (size_t i = 0; i < size; i++) { 9334 // by convention, return first effect if id provided is 0 (0 is never a valid id) 9335 if (id == 0 || mEffects[i]->id() == id) { 9336 return mEffects[i]; 9337 } 9338 } 9339 return 0; 9340} 9341 9342// getEffectFromType_l() must be called with ThreadBase::mLock held 9343sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l( 9344 const effect_uuid_t *type) 9345{ 9346 size_t size = mEffects.size(); 9347 9348 for (size_t i = 0; i < size; i++) { 9349 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) { 9350 return mEffects[i]; 9351 } 9352 } 9353 return 0; 9354} 9355 9356void AudioFlinger::EffectChain::clearInputBuffer() 9357{ 9358 Mutex::Autolock _l(mLock); 9359 sp<ThreadBase> thread = mThread.promote(); 9360 if (thread == 0) { 9361 ALOGW("clearInputBuffer(): cannot promote mixer thread"); 9362 return; 9363 } 9364 clearInputBuffer_l(thread); 9365} 9366 9367// Must be called with EffectChain::mLock locked 9368void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread) 9369{ 9370 size_t numSamples = thread->frameCount() * thread->channelCount(); 9371 memset(mInBuffer, 0, numSamples * sizeof(int16_t)); 9372 9373} 9374 9375// Must be called with EffectChain::mLock locked 9376void AudioFlinger::EffectChain::process_l() 9377{ 9378 sp<ThreadBase> thread = mThread.promote(); 9379 if (thread == 0) { 9380 ALOGW("process_l(): cannot promote mixer thread"); 9381 return; 9382 } 9383 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) || 9384 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE); 9385 // always process effects unless no more tracks are on the session and the effect tail 9386 // has been rendered 9387 bool doProcess = true; 9388 if (!isGlobalSession) { 9389 bool tracksOnSession = (trackCnt() != 0); 9390 9391 if (!tracksOnSession && mTailBufferCount == 0) { 9392 doProcess = false; 9393 } 9394 9395 if (activeTrackCnt() == 0) { 9396 // if no track is active and the effect tail has not been rendered, 9397 // the input buffer must be cleared here as the mixer process will not do it 9398 if (tracksOnSession || mTailBufferCount > 0) { 9399 clearInputBuffer_l(thread); 9400 if (mTailBufferCount > 0) { 9401 mTailBufferCount--; 9402 } 9403 } 9404 } 9405 } 9406 9407 size_t size = mEffects.size(); 9408 if (doProcess) { 9409 for (size_t i = 0; i < size; i++) { 9410 mEffects[i]->process(); 9411 } 9412 } 9413 for (size_t i = 0; i < size; i++) { 9414 mEffects[i]->updateState(); 9415 } 9416} 9417 9418// addEffect_l() must be called with PlaybackThread::mLock held 9419status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect) 9420{ 9421 effect_descriptor_t desc = effect->desc(); 9422 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK; 9423 9424 Mutex::Autolock _l(mLock); 9425 effect->setChain(this); 9426 sp<ThreadBase> thread = mThread.promote(); 9427 if (thread == 0) { 9428 return NO_INIT; 9429 } 9430 effect->setThread(thread); 9431 9432 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 9433 // Auxiliary effects are inserted at the beginning of mEffects vector as 9434 // they are processed first and accumulated in chain input buffer 9435 mEffects.insertAt(effect, 0); 9436 9437 // the input buffer for auxiliary effect contains mono samples in 9438 // 32 bit format. This is to avoid saturation in AudoMixer 9439 // accumulation stage. Saturation is done in EffectModule::process() before 9440 // calling the process in effect engine 9441 size_t numSamples = thread->frameCount(); 9442 int32_t *buffer = new int32_t[numSamples]; 9443 memset(buffer, 0, numSamples * sizeof(int32_t)); 9444 effect->setInBuffer((int16_t *)buffer); 9445 // auxiliary effects output samples to chain input buffer for further processing 9446 // by insert effects 9447 effect->setOutBuffer(mInBuffer); 9448 } else { 9449 // Insert effects are inserted at the end of mEffects vector as they are processed 9450 // after track and auxiliary effects. 9451 // Insert effect order as a function of indicated preference: 9452 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if 9453 // another effect is present 9454 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the 9455 // last effect claiming first position 9456 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the 9457 // first effect claiming last position 9458 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last 9459 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is 9460 // already present 9461 9462 size_t size = mEffects.size(); 9463 size_t idx_insert = size; 9464 ssize_t idx_insert_first = -1; 9465 ssize_t idx_insert_last = -1; 9466 9467 for (size_t i = 0; i < size; i++) { 9468 effect_descriptor_t d = mEffects[i]->desc(); 9469 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK; 9470 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK; 9471 if (iMode == EFFECT_FLAG_TYPE_INSERT) { 9472 // check invalid effect chaining combinations 9473 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE || 9474 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) { 9475 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", 9476 desc.name, d.name); 9477 return INVALID_OPERATION; 9478 } 9479 // remember position of first insert effect and by default 9480 // select this as insert position for new effect 9481 if (idx_insert == size) { 9482 idx_insert = i; 9483 } 9484 // remember position of last insert effect claiming 9485 // first position 9486 if (iPref == EFFECT_FLAG_INSERT_FIRST) { 9487 idx_insert_first = i; 9488 } 9489 // remember position of first insert effect claiming 9490 // last position 9491 if (iPref == EFFECT_FLAG_INSERT_LAST && 9492 idx_insert_last == -1) { 9493 idx_insert_last = i; 9494 } 9495 } 9496 } 9497 9498 // modify idx_insert from first position if needed 9499 if (insertPref == EFFECT_FLAG_INSERT_LAST) { 9500 if (idx_insert_last != -1) { 9501 idx_insert = idx_insert_last; 9502 } else { 9503 idx_insert = size; 9504 } 9505 } else { 9506 if (idx_insert_first != -1) { 9507 idx_insert = idx_insert_first + 1; 9508 } 9509 } 9510 9511 // always read samples from chain input buffer 9512 effect->setInBuffer(mInBuffer); 9513 9514 // if last effect in the chain, output samples to chain 9515 // output buffer, otherwise to chain input buffer 9516 if (idx_insert == size) { 9517 if (idx_insert != 0) { 9518 mEffects[idx_insert-1]->setOutBuffer(mInBuffer); 9519 mEffects[idx_insert-1]->configure(); 9520 } 9521 effect->setOutBuffer(mOutBuffer); 9522 } else { 9523 effect->setOutBuffer(mInBuffer); 9524 } 9525 mEffects.insertAt(effect, idx_insert); 9526 9527 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, 9528 idx_insert); 9529 } 9530 effect->configure(); 9531 return NO_ERROR; 9532} 9533 9534// removeEffect_l() must be called with PlaybackThread::mLock held 9535size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect) 9536{ 9537 Mutex::Autolock _l(mLock); 9538 size_t size = mEffects.size(); 9539 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK; 9540 9541 for (size_t i = 0; i < size; i++) { 9542 if (effect == mEffects[i]) { 9543 // calling stop here will remove pre-processing effect from the audio HAL. 9544 // This is safe as we hold the EffectChain mutex which guarantees that we are not in 9545 // the middle of a read from audio HAL 9546 if (mEffects[i]->state() == EffectModule::ACTIVE || 9547 mEffects[i]->state() == EffectModule::STOPPING) { 9548 mEffects[i]->stop(); 9549 } 9550 if (type == EFFECT_FLAG_TYPE_AUXILIARY) { 9551 delete[] effect->inBuffer(); 9552 } else { 9553 if (i == size - 1 && i != 0) { 9554 mEffects[i - 1]->setOutBuffer(mOutBuffer); 9555 mEffects[i - 1]->configure(); 9556 } 9557 } 9558 mEffects.removeAt(i); 9559 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), 9560 this, i); 9561 break; 9562 } 9563 } 9564 9565 return mEffects.size(); 9566} 9567 9568// setDevice_l() must be called with PlaybackThread::mLock held 9569void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device) 9570{ 9571 size_t size = mEffects.size(); 9572 for (size_t i = 0; i < size; i++) { 9573 mEffects[i]->setDevice(device); 9574 } 9575} 9576 9577// setMode_l() must be called with PlaybackThread::mLock held 9578void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode) 9579{ 9580 size_t size = mEffects.size(); 9581 for (size_t i = 0; i < size; i++) { 9582 mEffects[i]->setMode(mode); 9583 } 9584} 9585 9586// setAudioSource_l() must be called with PlaybackThread::mLock held 9587void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source) 9588{ 9589 size_t size = mEffects.size(); 9590 for (size_t i = 0; i < size; i++) { 9591 mEffects[i]->setAudioSource(source); 9592 } 9593} 9594 9595// setVolume_l() must be called with PlaybackThread::mLock held 9596bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right) 9597{ 9598 uint32_t newLeft = *left; 9599 uint32_t newRight = *right; 9600 bool hasControl = false; 9601 int ctrlIdx = -1; 9602 size_t size = mEffects.size(); 9603 9604 // first update volume controller 9605 for (size_t i = size; i > 0; i--) { 9606 if (mEffects[i - 1]->isProcessEnabled() && 9607 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) { 9608 ctrlIdx = i - 1; 9609 hasControl = true; 9610 break; 9611 } 9612 } 9613 9614 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) { 9615 if (hasControl) { 9616 *left = mNewLeftVolume; 9617 *right = mNewRightVolume; 9618 } 9619 return hasControl; 9620 } 9621 9622 mVolumeCtrlIdx = ctrlIdx; 9623 mLeftVolume = newLeft; 9624 mRightVolume = newRight; 9625 9626 // second get volume update from volume controller 9627 if (ctrlIdx >= 0) { 9628 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true); 9629 mNewLeftVolume = newLeft; 9630 mNewRightVolume = newRight; 9631 } 9632 // then indicate volume to all other effects in chain. 9633 // Pass altered volume to effects before volume controller 9634 // and requested volume to effects after controller 9635 uint32_t lVol = newLeft; 9636 uint32_t rVol = newRight; 9637 9638 for (size_t i = 0; i < size; i++) { 9639 if ((int)i == ctrlIdx) continue; 9640 // this also works for ctrlIdx == -1 when there is no volume controller 9641 if ((int)i > ctrlIdx) { 9642 lVol = *left; 9643 rVol = *right; 9644 } 9645 mEffects[i]->setVolume(&lVol, &rVol, false); 9646 } 9647 *left = newLeft; 9648 *right = newRight; 9649 9650 return hasControl; 9651} 9652 9653void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args) 9654{ 9655 const size_t SIZE = 256; 9656 char buffer[SIZE]; 9657 String8 result; 9658 9659 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId); 9660 result.append(buffer); 9661 9662 bool locked = tryLock(mLock); 9663 // failed to lock - AudioFlinger is probably deadlocked 9664 if (!locked) { 9665 result.append("\tCould not lock mutex:\n"); 9666 } 9667 9668 result.append("\tNum fx In buffer Out buffer Active tracks:\n"); 9669 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n", 9670 mEffects.size(), 9671 (uint32_t)mInBuffer, 9672 (uint32_t)mOutBuffer, 9673 mActiveTrackCnt); 9674 result.append(buffer); 9675 write(fd, result.string(), result.size()); 9676 9677 for (size_t i = 0; i < mEffects.size(); ++i) { 9678 sp<EffectModule> effect = mEffects[i]; 9679 if (effect != 0) { 9680 effect->dump(fd, args); 9681 } 9682 } 9683 9684 if (locked) { 9685 mLock.unlock(); 9686 } 9687} 9688 9689// must be called with ThreadBase::mLock held 9690void AudioFlinger::EffectChain::setEffectSuspended_l( 9691 const effect_uuid_t *type, bool suspend) 9692{ 9693 sp<SuspendedEffectDesc> desc; 9694 // use effect type UUID timelow as key as there is no real risk of identical 9695 // timeLow fields among effect type UUIDs. 9696 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow); 9697 if (suspend) { 9698 if (index >= 0) { 9699 desc = mSuspendedEffects.valueAt(index); 9700 } else { 9701 desc = new SuspendedEffectDesc(); 9702 desc->mType = *type; 9703 mSuspendedEffects.add(type->timeLow, desc); 9704 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow); 9705 } 9706 if (desc->mRefCount++ == 0) { 9707 sp<EffectModule> effect = getEffectIfEnabled(type); 9708 if (effect != 0) { 9709 desc->mEffect = effect; 9710 effect->setSuspended(true); 9711 effect->setEnabled(false); 9712 } 9713 } 9714 } else { 9715 if (index < 0) { 9716 return; 9717 } 9718 desc = mSuspendedEffects.valueAt(index); 9719 if (desc->mRefCount <= 0) { 9720 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount); 9721 desc->mRefCount = 1; 9722 } 9723 if (--desc->mRefCount == 0) { 9724 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 9725 if (desc->mEffect != 0) { 9726 sp<EffectModule> effect = desc->mEffect.promote(); 9727 if (effect != 0) { 9728 effect->setSuspended(false); 9729 effect->lock(); 9730 EffectHandle *handle = effect->controlHandle_l(); 9731 if (handle != NULL && !handle->destroyed_l()) { 9732 effect->setEnabled_l(handle->enabled()); 9733 } 9734 effect->unlock(); 9735 } 9736 desc->mEffect.clear(); 9737 } 9738 mSuspendedEffects.removeItemsAt(index); 9739 } 9740 } 9741} 9742 9743// must be called with ThreadBase::mLock held 9744void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend) 9745{ 9746 sp<SuspendedEffectDesc> desc; 9747 9748 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 9749 if (suspend) { 9750 if (index >= 0) { 9751 desc = mSuspendedEffects.valueAt(index); 9752 } else { 9753 desc = new SuspendedEffectDesc(); 9754 mSuspendedEffects.add((int)kKeyForSuspendAll, desc); 9755 ALOGV("setEffectSuspendedAll_l() add entry for 0"); 9756 } 9757 if (desc->mRefCount++ == 0) { 9758 Vector< sp<EffectModule> > effects; 9759 getSuspendEligibleEffects(effects); 9760 for (size_t i = 0; i < effects.size(); i++) { 9761 setEffectSuspended_l(&effects[i]->desc().type, true); 9762 } 9763 } 9764 } else { 9765 if (index < 0) { 9766 return; 9767 } 9768 desc = mSuspendedEffects.valueAt(index); 9769 if (desc->mRefCount <= 0) { 9770 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount); 9771 desc->mRefCount = 1; 9772 } 9773 if (--desc->mRefCount == 0) { 9774 Vector<const effect_uuid_t *> types; 9775 for (size_t i = 0; i < mSuspendedEffects.size(); i++) { 9776 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) { 9777 continue; 9778 } 9779 types.add(&mSuspendedEffects.valueAt(i)->mType); 9780 } 9781 for (size_t i = 0; i < types.size(); i++) { 9782 setEffectSuspended_l(types[i], false); 9783 } 9784 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", 9785 mSuspendedEffects.keyAt(index)); 9786 mSuspendedEffects.removeItem((int)kKeyForSuspendAll); 9787 } 9788 } 9789} 9790 9791 9792// The volume effect is used for automated tests only 9793#ifndef OPENSL_ES_H_ 9794static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6, 9795 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }; 9796const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_; 9797#endif //OPENSL_ES_H_ 9798 9799bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc) 9800{ 9801 // auxiliary effects and visualizer are never suspended on output mix 9802 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && 9803 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) || 9804 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) || 9805 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) { 9806 return false; 9807 } 9808 return true; 9809} 9810 9811void AudioFlinger::EffectChain::getSuspendEligibleEffects( 9812 Vector< sp<AudioFlinger::EffectModule> > &effects) 9813{ 9814 effects.clear(); 9815 for (size_t i = 0; i < mEffects.size(); i++) { 9816 if (isEffectEligibleForSuspend(mEffects[i]->desc())) { 9817 effects.add(mEffects[i]); 9818 } 9819 } 9820} 9821 9822sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled( 9823 const effect_uuid_t *type) 9824{ 9825 sp<EffectModule> effect = getEffectFromType_l(type); 9826 return effect != 0 && effect->isEnabled() ? effect : 0; 9827} 9828 9829void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 9830 bool enabled) 9831{ 9832 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 9833 if (enabled) { 9834 if (index < 0) { 9835 // if the effect is not suspend check if all effects are suspended 9836 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 9837 if (index < 0) { 9838 return; 9839 } 9840 if (!isEffectEligibleForSuspend(effect->desc())) { 9841 return; 9842 } 9843 setEffectSuspended_l(&effect->desc().type, enabled); 9844 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 9845 if (index < 0) { 9846 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!"); 9847 return; 9848 } 9849 } 9850 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x", 9851 effect->desc().type.timeLow); 9852 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 9853 // if effect is requested to suspended but was not yet enabled, supend it now. 9854 if (desc->mEffect == 0) { 9855 desc->mEffect = effect; 9856 effect->setEnabled(false); 9857 effect->setSuspended(true); 9858 } 9859 } else { 9860 if (index < 0) { 9861 return; 9862 } 9863 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x", 9864 effect->desc().type.timeLow); 9865 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 9866 desc->mEffect.clear(); 9867 effect->setSuspended(false); 9868 } 9869} 9870 9871#undef LOG_TAG 9872#define LOG_TAG "AudioFlinger" 9873 9874// ---------------------------------------------------------------------------- 9875 9876status_t AudioFlinger::onTransact( 9877 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 9878{ 9879 return BnAudioFlinger::onTransact(code, data, reply, flags); 9880} 9881 9882}; // namespace android 9883