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