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