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