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