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