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