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