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