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