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