Threads.cpp revision 2247f7b84bf0ce3cc9c909ef987eedb086e3b4e8
1/* 2** 3** Copyright 2012, 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#define ATRACE_TAG ATRACE_TAG_AUDIO 22 23#include "Configuration.h" 24#include <math.h> 25#include <fcntl.h> 26#include <linux/futex.h> 27#include <sys/stat.h> 28#include <sys/syscall.h> 29#include <cutils/properties.h> 30#include <media/AudioParameter.h> 31#include <media/AudioResamplerPublic.h> 32#include <media/TypeConverter.h> 33#include <utils/Log.h> 34#include <utils/Trace.h> 35 36#include <private/media/AudioTrackShared.h> 37#include <private/android_filesystem_config.h> 38#include <audio_utils/conversion.h> 39#include <audio_utils/primitives.h> 40#include <audio_utils/format.h> 41#include <audio_utils/minifloat.h> 42#include <system/audio_effects/effect_ns.h> 43#include <system/audio_effects/effect_aec.h> 44#include <system/audio.h> 45 46// NBAIO implementations 47#include <media/nbaio/AudioStreamInSource.h> 48#include <media/nbaio/AudioStreamOutSink.h> 49#include <media/nbaio/MonoPipe.h> 50#include <media/nbaio/MonoPipeReader.h> 51#include <media/nbaio/Pipe.h> 52#include <media/nbaio/PipeReader.h> 53#include <media/nbaio/SourceAudioBufferProvider.h> 54#include <mediautils/BatteryNotifier.h> 55 56#include <powermanager/PowerManager.h> 57 58#include "AudioFlinger.h" 59#include "FastMixer.h" 60#include "FastCapture.h" 61#include "ServiceUtilities.h" 62#include "mediautils/SchedulingPolicyService.h" 63 64#ifdef ADD_BATTERY_DATA 65#include <media/IMediaPlayerService.h> 66#include <media/IMediaDeathNotifier.h> 67#endif 68 69#ifdef DEBUG_CPU_USAGE 70#include <cpustats/CentralTendencyStatistics.h> 71#include <cpustats/ThreadCpuUsage.h> 72#endif 73 74#include "AutoPark.h" 75 76// ---------------------------------------------------------------------------- 77 78// Note: the following macro is used for extremely verbose logging message. In 79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 80// 0; but one side effect of this is to turn all LOGV's as well. Some messages 81// are so verbose that we want to suppress them even when we have ALOG_ASSERT 82// turned on. Do not uncomment the #def below unless you really know what you 83// are doing and want to see all of the extremely verbose messages. 84//#define VERY_VERY_VERBOSE_LOGGING 85#ifdef VERY_VERY_VERBOSE_LOGGING 86#define ALOGVV ALOGV 87#else 88#define ALOGVV(a...) do { } while(0) 89#endif 90 91// TODO: Move these macro/inlines to a header file. 92#define max(a, b) ((a) > (b) ? (a) : (b)) 93template <typename T> 94static inline T min(const T& a, const T& b) 95{ 96 return a < b ? a : b; 97} 98 99#ifndef ARRAY_SIZE 100#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 101#endif 102 103namespace android { 104 105// retry counts for buffer fill timeout 106// 50 * ~20msecs = 1 second 107static const int8_t kMaxTrackRetries = 50; 108static const int8_t kMaxTrackStartupRetries = 50; 109// allow less retry attempts on direct output thread. 110// direct outputs can be a scarce resource in audio hardware and should 111// be released as quickly as possible. 112static const int8_t kMaxTrackRetriesDirect = 2; 113 114 115 116// don't warn about blocked writes or record buffer overflows more often than this 117static const nsecs_t kWarningThrottleNs = seconds(5); 118 119// RecordThread loop sleep time upon application overrun or audio HAL read error 120static const int kRecordThreadSleepUs = 5000; 121 122// maximum time to wait in sendConfigEvent_l() for a status to be received 123static const nsecs_t kConfigEventTimeoutNs = seconds(2); 124 125// minimum sleep time for the mixer thread loop when tracks are active but in underrun 126static const uint32_t kMinThreadSleepTimeUs = 5000; 127// maximum divider applied to the active sleep time in the mixer thread loop 128static const uint32_t kMaxThreadSleepTimeShift = 2; 129 130// minimum normal sink buffer size, expressed in milliseconds rather than frames 131// FIXME This should be based on experimentally observed scheduling jitter 132static const uint32_t kMinNormalSinkBufferSizeMs = 20; 133// maximum normal sink buffer size 134static const uint32_t kMaxNormalSinkBufferSizeMs = 24; 135 136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread 137// FIXME This should be based on experimentally observed scheduling jitter 138static const uint32_t kMinNormalCaptureBufferSizeMs = 12; 139 140// Offloaded output thread standby delay: allows track transition without going to standby 141static const nsecs_t kOffloadStandbyDelayNs = seconds(1); 142 143// Direct output thread minimum sleep time in idle or active(underrun) state 144static const nsecs_t kDirectMinSleepTimeUs = 10000; 145 146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good 147// balance between power consumption and latency, and allows threads to be scheduled reliably 148// by the CFS scheduler. 149// FIXME Express other hardcoded references to 20ms with references to this constant and move 150// it appropriately. 151#define FMS_20 20 152 153// Whether to use fast mixer 154static const enum { 155 FastMixer_Never, // never initialize or use: for debugging only 156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 157 // normal mixer multiplier is 1 158 FastMixer_Static, // initialize if needed, then use all the time if initialized, 159 // multiplier is calculated based on min & max normal mixer buffer size 160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 161 // multiplier is calculated based on min & max normal mixer buffer size 162 // FIXME for FastMixer_Dynamic: 163 // Supporting this option will require fixing HALs that can't handle large writes. 164 // For example, one HAL implementation returns an error from a large write, 165 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 166 // We could either fix the HAL implementations, or provide a wrapper that breaks 167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 168} kUseFastMixer = FastMixer_Static; 169 170// Whether to use fast capture 171static const enum { 172 FastCapture_Never, // never initialize or use: for debugging only 173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only 174 FastCapture_Static, // initialize if needed, then use all the time if initialized 175} kUseFastCapture = FastCapture_Static; 176 177// Priorities for requestPriority 178static const int kPriorityAudioApp = 2; 179static const int kPriorityFastMixer = 3; 180static const int kPriorityFastCapture = 3; 181 182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the 183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks, 184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'. 185 186// This is the default value, if not specified by property. 187static const int kFastTrackMultiplier = 2; 188 189// The minimum and maximum allowed values 190static const int kFastTrackMultiplierMin = 1; 191static const int kFastTrackMultiplierMax = 2; 192 193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier. 194static int sFastTrackMultiplier = kFastTrackMultiplier; 195 196// See Thread::readOnlyHeap(). 197// Initially this heap is used to allocate client buffers for "fast" AudioRecord. 198// Eventually it will be the single buffer that FastCapture writes into via HAL read(), 199// and that all "fast" AudioRecord clients read from. In either case, the size can be small. 200static const size_t kRecordThreadReadOnlyHeapSize = 0x2000; 201 202// ---------------------------------------------------------------------------- 203 204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT; 205 206static void sFastTrackMultiplierInit() 207{ 208 char value[PROPERTY_VALUE_MAX]; 209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) { 210 char *endptr; 211 unsigned long ul = strtoul(value, &endptr, 0); 212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) { 213 sFastTrackMultiplier = (int) ul; 214 } 215 } 216} 217 218// ---------------------------------------------------------------------------- 219 220#ifdef ADD_BATTERY_DATA 221// To collect the amplifier usage 222static void addBatteryData(uint32_t params) { 223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 224 if (service == NULL) { 225 // it already logged 226 return; 227 } 228 229 service->addBatteryData(params); 230} 231#endif 232 233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset 234struct { 235 // call when you acquire a partial wakelock 236 void acquire(const sp<IBinder> &wakeLockToken) { 237 pthread_mutex_lock(&mLock); 238 if (wakeLockToken.get() == nullptr) { 239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME); 240 } else { 241 if (mCount == 0) { 242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME); 243 } 244 ++mCount; 245 } 246 pthread_mutex_unlock(&mLock); 247 } 248 249 // call when you release a partial wakelock. 250 void release(const sp<IBinder> &wakeLockToken) { 251 if (wakeLockToken.get() == nullptr) { 252 return; 253 } 254 pthread_mutex_lock(&mLock); 255 if (--mCount < 0) { 256 ALOGE("negative wakelock count"); 257 mCount = 0; 258 } 259 pthread_mutex_unlock(&mLock); 260 } 261 262 // retrieves the boottime timebase offset from monotonic. 263 int64_t getBoottimeOffset() { 264 pthread_mutex_lock(&mLock); 265 int64_t boottimeOffset = mBoottimeOffset; 266 pthread_mutex_unlock(&mLock); 267 return boottimeOffset; 268 } 269 270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC 271 // and the selected timebase. 272 // Currently only TIMEBASE_BOOTTIME is allowed. 273 // 274 // This only needs to be called upon acquiring the first partial wakelock 275 // after all other partial wakelocks are released. 276 // 277 // We do an empirical measurement of the offset rather than parsing 278 // /proc/timer_list since the latter is not a formal kernel ABI. 279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) { 280 int clockbase; 281 switch (timebase) { 282 case ExtendedTimestamp::TIMEBASE_BOOTTIME: 283 clockbase = SYSTEM_TIME_BOOTTIME; 284 break; 285 default: 286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase); 287 break; 288 } 289 // try three times to get the clock offset, choose the one 290 // with the minimum gap in measurements. 291 const int tries = 3; 292 nsecs_t bestGap, measured; 293 for (int i = 0; i < tries; ++i) { 294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC); 295 const nsecs_t tbase = systemTime(clockbase); 296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC); 297 const nsecs_t gap = tmono2 - tmono; 298 if (i == 0 || gap < bestGap) { 299 bestGap = gap; 300 measured = tbase - ((tmono + tmono2) >> 1); 301 } 302 } 303 304 // to avoid micro-adjusting, we don't change the timebase 305 // unless it is significantly different. 306 // 307 // Assumption: It probably takes more than toleranceNs to 308 // suspend and resume the device. 309 static int64_t toleranceNs = 10000; // 10 us 310 if (llabs(*offset - measured) > toleranceNs) { 311 ALOGV("Adjusting timebase offset old: %lld new: %lld", 312 (long long)*offset, (long long)measured); 313 *offset = measured; 314 } 315 } 316 317 pthread_mutex_t mLock; 318 int32_t mCount; 319 int64_t mBoottimeOffset; 320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization 321 322// ---------------------------------------------------------------------------- 323// CPU Stats 324// ---------------------------------------------------------------------------- 325 326class CpuStats { 327public: 328 CpuStats(); 329 void sample(const String8 &title); 330#ifdef DEBUG_CPU_USAGE 331private: 332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 334 335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 336 337 int mCpuNum; // thread's current CPU number 338 int mCpukHz; // frequency of thread's current CPU in kHz 339#endif 340}; 341 342CpuStats::CpuStats() 343#ifdef DEBUG_CPU_USAGE 344 : mCpuNum(-1), mCpukHz(-1) 345#endif 346{ 347} 348 349void CpuStats::sample(const String8 &title 350#ifndef DEBUG_CPU_USAGE 351 __unused 352#endif 353 ) { 354#ifdef DEBUG_CPU_USAGE 355 // get current thread's delta CPU time in wall clock ns 356 double wcNs; 357 bool valid = mCpuUsage.sampleAndEnable(wcNs); 358 359 // record sample for wall clock statistics 360 if (valid) { 361 mWcStats.sample(wcNs); 362 } 363 364 // get the current CPU number 365 int cpuNum = sched_getcpu(); 366 367 // get the current CPU frequency in kHz 368 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 369 370 // check if either CPU number or frequency changed 371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 372 mCpuNum = cpuNum; 373 mCpukHz = cpukHz; 374 // ignore sample for purposes of cycles 375 valid = false; 376 } 377 378 // if no change in CPU number or frequency, then record sample for cycle statistics 379 if (valid && mCpukHz > 0) { 380 double cycles = wcNs * cpukHz * 0.000001; 381 mHzStats.sample(cycles); 382 } 383 384 unsigned n = mWcStats.n(); 385 // mCpuUsage.elapsed() is expensive, so don't call it every loop 386 if ((n & 127) == 1) { 387 long long elapsed = mCpuUsage.elapsed(); 388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 389 double perLoop = elapsed / (double) n; 390 double perLoop100 = perLoop * 0.01; 391 double perLoop1k = perLoop * 0.001; 392 double mean = mWcStats.mean(); 393 double stddev = mWcStats.stddev(); 394 double minimum = mWcStats.minimum(); 395 double maximum = mWcStats.maximum(); 396 double meanCycles = mHzStats.mean(); 397 double stddevCycles = mHzStats.stddev(); 398 double minCycles = mHzStats.minimum(); 399 double maxCycles = mHzStats.maximum(); 400 mCpuUsage.resetElapsed(); 401 mWcStats.reset(); 402 mHzStats.reset(); 403 ALOGD("CPU usage for %s over past %.1f secs\n" 404 " (%u mixer loops at %.1f mean ms per loop):\n" 405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 408 title.string(), 409 elapsed * .000000001, n, perLoop * .000001, 410 mean * .001, 411 stddev * .001, 412 minimum * .001, 413 maximum * .001, 414 mean / perLoop100, 415 stddev / perLoop100, 416 minimum / perLoop100, 417 maximum / perLoop100, 418 meanCycles / perLoop1k, 419 stddevCycles / perLoop1k, 420 minCycles / perLoop1k, 421 maxCycles / perLoop1k); 422 423 } 424 } 425#endif 426}; 427 428// ---------------------------------------------------------------------------- 429// ThreadBase 430// ---------------------------------------------------------------------------- 431 432// static 433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type) 434{ 435 switch (type) { 436 case MIXER: 437 return "MIXER"; 438 case DIRECT: 439 return "DIRECT"; 440 case DUPLICATING: 441 return "DUPLICATING"; 442 case RECORD: 443 return "RECORD"; 444 case OFFLOAD: 445 return "OFFLOAD"; 446 default: 447 return "unknown"; 448 } 449} 450 451std::string devicesToString(audio_devices_t devices) 452{ 453 std::string result; 454 if (devices & AUDIO_DEVICE_BIT_IN) { 455 InputDeviceConverter::maskToString(devices, result); 456 } else { 457 OutputDeviceConverter::maskToString(devices, result); 458 } 459 return result; 460} 461 462std::string inputFlagsToString(audio_input_flags_t flags) 463{ 464 std::string result; 465 InputFlagConverter::maskToString(flags, result); 466 return result; 467} 468 469std::string outputFlagsToString(audio_output_flags_t flags) 470{ 471 std::string result; 472 OutputFlagConverter::maskToString(flags, result); 473 return result; 474} 475 476const char *sourceToString(audio_source_t source) 477{ 478 switch (source) { 479 case AUDIO_SOURCE_DEFAULT: return "default"; 480 case AUDIO_SOURCE_MIC: return "mic"; 481 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink"; 482 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink"; 483 case AUDIO_SOURCE_VOICE_CALL: return "voice call"; 484 case AUDIO_SOURCE_CAMCORDER: return "camcorder"; 485 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition"; 486 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication"; 487 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix"; 488 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed"; 489 case AUDIO_SOURCE_FM_TUNER: return "FM tuner"; 490 case AUDIO_SOURCE_HOTWORD: return "hotword"; 491 default: return "unknown"; 492 } 493} 494 495AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 496 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady) 497 : Thread(false /*canCallJava*/), 498 mType(type), 499 mAudioFlinger(audioFlinger), 500 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize 501 // are set by PlaybackThread::readOutputParameters_l() or 502 // RecordThread::readInputParameters_l() 503 //FIXME: mStandby should be true here. Is this some kind of hack? 504 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 505 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE), 506 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 507 // mName will be set by concrete (non-virtual) subclass 508 mDeathRecipient(new PMDeathRecipient(this)), 509 mSystemReady(systemReady) 510{ 511 memset(&mPatch, 0, sizeof(struct audio_patch)); 512} 513 514AudioFlinger::ThreadBase::~ThreadBase() 515{ 516 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns 517 mConfigEvents.clear(); 518 519 // do not lock the mutex in destructor 520 releaseWakeLock_l(); 521 if (mPowerManager != 0) { 522 sp<IBinder> binder = IInterface::asBinder(mPowerManager); 523 binder->unlinkToDeath(mDeathRecipient); 524 } 525} 526 527status_t AudioFlinger::ThreadBase::readyToRun() 528{ 529 status_t status = initCheck(); 530 if (status == NO_ERROR) { 531 ALOGI("AudioFlinger's thread %p ready to run", this); 532 } else { 533 ALOGE("No working audio driver found."); 534 } 535 return status; 536} 537 538void AudioFlinger::ThreadBase::exit() 539{ 540 ALOGV("ThreadBase::exit"); 541 // do any cleanup required for exit to succeed 542 preExit(); 543 { 544 // This lock prevents the following race in thread (uniprocessor for illustration): 545 // if (!exitPending()) { 546 // // context switch from here to exit() 547 // // exit() calls requestExit(), what exitPending() observes 548 // // exit() calls signal(), which is dropped since no waiters 549 // // context switch back from exit() to here 550 // mWaitWorkCV.wait(...); 551 // // now thread is hung 552 // } 553 AutoMutex lock(mLock); 554 requestExit(); 555 mWaitWorkCV.broadcast(); 556 } 557 // When Thread::requestExitAndWait is made virtual and this method is renamed to 558 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 559 requestExitAndWait(); 560} 561 562status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 563{ 564 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 565 Mutex::Autolock _l(mLock); 566 567 return sendSetParameterConfigEvent_l(keyValuePairs); 568} 569 570// sendConfigEvent_l() must be called with ThreadBase::mLock held 571// Can temporarily release the lock if waiting for a reply from processConfigEvents_l(). 572status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event) 573{ 574 status_t status = NO_ERROR; 575 576 if (event->mRequiresSystemReady && !mSystemReady) { 577 event->mWaitStatus = false; 578 mPendingConfigEvents.add(event); 579 return status; 580 } 581 mConfigEvents.add(event); 582 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType); 583 mWaitWorkCV.signal(); 584 mLock.unlock(); 585 { 586 Mutex::Autolock _l(event->mLock); 587 while (event->mWaitStatus) { 588 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) { 589 event->mStatus = TIMED_OUT; 590 event->mWaitStatus = false; 591 } 592 } 593 status = event->mStatus; 594 } 595 mLock.lock(); 596 return status; 597} 598 599void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid) 600{ 601 Mutex::Autolock _l(mLock); 602 sendIoConfigEvent_l(event, pid); 603} 604 605// sendIoConfigEvent_l() must be called with ThreadBase::mLock held 606void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid) 607{ 608 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid); 609 sendConfigEvent_l(configEvent); 610} 611 612void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) 613{ 614 Mutex::Autolock _l(mLock); 615 sendPrioConfigEvent_l(pid, tid, prio); 616} 617 618// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 619void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio) 620{ 621 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio); 622 sendConfigEvent_l(configEvent); 623} 624 625// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held 626status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair) 627{ 628 sp<ConfigEvent> configEvent; 629 AudioParameter param(keyValuePair); 630 int value; 631 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) { 632 setMasterMono_l(value != 0); 633 if (param.size() == 1) { 634 return NO_ERROR; // should be a solo parameter - we don't pass down 635 } 636 param.remove(String8(AudioParameter::keyMonoOutput)); 637 configEvent = new SetParameterConfigEvent(param.toString()); 638 } else { 639 configEvent = new SetParameterConfigEvent(keyValuePair); 640 } 641 return sendConfigEvent_l(configEvent); 642} 643 644status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent( 645 const struct audio_patch *patch, 646 audio_patch_handle_t *handle) 647{ 648 Mutex::Autolock _l(mLock); 649 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle); 650 status_t status = sendConfigEvent_l(configEvent); 651 if (status == NO_ERROR) { 652 CreateAudioPatchConfigEventData *data = 653 (CreateAudioPatchConfigEventData *)configEvent->mData.get(); 654 *handle = data->mHandle; 655 } 656 return status; 657} 658 659status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent( 660 const audio_patch_handle_t handle) 661{ 662 Mutex::Autolock _l(mLock); 663 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle); 664 return sendConfigEvent_l(configEvent); 665} 666 667 668// post condition: mConfigEvents.isEmpty() 669void AudioFlinger::ThreadBase::processConfigEvents_l() 670{ 671 bool configChanged = false; 672 673 while (!mConfigEvents.isEmpty()) { 674 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size()); 675 sp<ConfigEvent> event = mConfigEvents[0]; 676 mConfigEvents.removeAt(0); 677 switch (event->mType) { 678 case CFG_EVENT_PRIO: { 679 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get(); 680 // FIXME Need to understand why this has to be done asynchronously 681 int err = requestPriority(data->mPid, data->mTid, data->mPrio, 682 true /*asynchronous*/); 683 if (err != 0) { 684 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 685 data->mPrio, data->mPid, data->mTid, err); 686 } 687 } break; 688 case CFG_EVENT_IO: { 689 IoConfigEventData *data = (IoConfigEventData *)event->mData.get(); 690 ioConfigChanged(data->mEvent, data->mPid); 691 } break; 692 case CFG_EVENT_SET_PARAMETER: { 693 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get(); 694 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) { 695 configChanged = true; 696 } 697 } break; 698 case CFG_EVENT_CREATE_AUDIO_PATCH: { 699 CreateAudioPatchConfigEventData *data = 700 (CreateAudioPatchConfigEventData *)event->mData.get(); 701 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle); 702 } break; 703 case CFG_EVENT_RELEASE_AUDIO_PATCH: { 704 ReleaseAudioPatchConfigEventData *data = 705 (ReleaseAudioPatchConfigEventData *)event->mData.get(); 706 event->mStatus = releaseAudioPatch_l(data->mHandle); 707 } break; 708 default: 709 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType); 710 break; 711 } 712 { 713 Mutex::Autolock _l(event->mLock); 714 if (event->mWaitStatus) { 715 event->mWaitStatus = false; 716 event->mCond.signal(); 717 } 718 } 719 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this); 720 } 721 722 if (configChanged) { 723 cacheParameters_l(); 724 } 725} 726 727String8 channelMaskToString(audio_channel_mask_t mask, bool output) { 728 String8 s; 729 const audio_channel_representation_t representation = 730 audio_channel_mask_get_representation(mask); 731 732 switch (representation) { 733 case AUDIO_CHANNEL_REPRESENTATION_POSITION: { 734 if (output) { 735 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, "); 736 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, "); 737 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, "); 738 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, "); 739 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, "); 740 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, "); 741 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, "); 742 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, "); 743 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, "); 744 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, "); 745 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, "); 746 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,"); 747 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, "); 748 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, "); 749 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, "); 750 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, "); 751 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " ); 752 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " ); 753 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, "); 754 } else { 755 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, "); 756 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, "); 757 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, "); 758 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, "); 759 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, "); 760 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, "); 761 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, "); 762 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, "); 763 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, "); 764 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, "); 765 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, "); 766 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, "); 767 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, "); 768 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, "); 769 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, "); 770 } 771 const int len = s.length(); 772 if (len > 2) { 773 (void) s.lockBuffer(len); // needed? 774 s.unlockBuffer(len - 2); // remove trailing ", " 775 } 776 return s; 777 } 778 case AUDIO_CHANNEL_REPRESENTATION_INDEX: 779 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask)); 780 return s; 781 default: 782 s.appendFormat("unknown mask, representation:%d bits:%#x", 783 representation, audio_channel_mask_get_bits(mask)); 784 return s; 785 } 786} 787 788void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused) 789{ 790 const size_t SIZE = 256; 791 char buffer[SIZE]; 792 String8 result; 793 794 bool locked = AudioFlinger::dumpTryLock(mLock); 795 if (!locked) { 796 dprintf(fd, "thread %p may be deadlocked\n", this); 797 } 798 799 dprintf(fd, " Thread name: %s\n", mThreadName); 800 dprintf(fd, " I/O handle: %d\n", mId); 801 dprintf(fd, " TID: %d\n", getTid()); 802 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no"); 803 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate); 804 dprintf(fd, " HAL frame count: %zu\n", mFrameCount); 805 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str()); 806 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize); 807 dprintf(fd, " Channel count: %u\n", mChannelCount); 808 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask, 809 channelMaskToString(mChannelMask, mType != RECORD).string()); 810 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str()); 811 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize); 812 dprintf(fd, " Pending config events:"); 813 size_t numConfig = mConfigEvents.size(); 814 if (numConfig) { 815 for (size_t i = 0; i < numConfig; i++) { 816 mConfigEvents[i]->dump(buffer, SIZE); 817 dprintf(fd, "\n %s", buffer); 818 } 819 dprintf(fd, "\n"); 820 } else { 821 dprintf(fd, " none\n"); 822 } 823 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str()); 824 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str()); 825 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource)); 826 827 if (locked) { 828 mLock.unlock(); 829 } 830} 831 832void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 833{ 834 const size_t SIZE = 256; 835 char buffer[SIZE]; 836 String8 result; 837 838 size_t numEffectChains = mEffectChains.size(); 839 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains); 840 write(fd, buffer, strlen(buffer)); 841 842 for (size_t i = 0; i < numEffectChains; ++i) { 843 sp<EffectChain> chain = mEffectChains[i]; 844 if (chain != 0) { 845 chain->dump(fd, args); 846 } 847 } 848} 849 850void AudioFlinger::ThreadBase::acquireWakeLock() 851{ 852 Mutex::Autolock _l(mLock); 853 acquireWakeLock_l(); 854} 855 856String16 AudioFlinger::ThreadBase::getWakeLockTag() 857{ 858 switch (mType) { 859 case MIXER: 860 return String16("AudioMix"); 861 case DIRECT: 862 return String16("AudioDirectOut"); 863 case DUPLICATING: 864 return String16("AudioDup"); 865 case RECORD: 866 return String16("AudioIn"); 867 case OFFLOAD: 868 return String16("AudioOffload"); 869 default: 870 ALOG_ASSERT(false); 871 return String16("AudioUnknown"); 872 } 873} 874 875void AudioFlinger::ThreadBase::acquireWakeLock_l() 876{ 877 getPowerManager_l(); 878 if (mPowerManager != 0) { 879 sp<IBinder> binder = new BBinder(); 880 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids. 881 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 882 binder, 883 getWakeLockTag(), 884 String16("audioserver"), 885 true /* FIXME force oneway contrary to .aidl */); 886 if (status == NO_ERROR) { 887 mWakeLockToken = binder; 888 } 889 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status); 890 } 891 892 gBoottime.acquire(mWakeLockToken); 893 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] = 894 gBoottime.getBoottimeOffset(); 895} 896 897void AudioFlinger::ThreadBase::releaseWakeLock() 898{ 899 Mutex::Autolock _l(mLock); 900 releaseWakeLock_l(); 901} 902 903void AudioFlinger::ThreadBase::releaseWakeLock_l() 904{ 905 gBoottime.release(mWakeLockToken); 906 if (mWakeLockToken != 0) { 907 ALOGV("releaseWakeLock_l() %s", mThreadName); 908 if (mPowerManager != 0) { 909 mPowerManager->releaseWakeLock(mWakeLockToken, 0, 910 true /* FIXME force oneway contrary to .aidl */); 911 } 912 mWakeLockToken.clear(); 913 } 914} 915 916void AudioFlinger::ThreadBase::getPowerManager_l() { 917 if (mSystemReady && mPowerManager == 0) { 918 // use checkService() to avoid blocking if power service is not up yet 919 sp<IBinder> binder = 920 defaultServiceManager()->checkService(String16("power")); 921 if (binder == 0) { 922 ALOGW("Thread %s cannot connect to the power manager service", mThreadName); 923 } else { 924 mPowerManager = interface_cast<IPowerManager>(binder); 925 binder->linkToDeath(mDeathRecipient); 926 } 927 } 928} 929 930void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) { 931 getPowerManager_l(); 932 933#if !LOG_NDEBUG 934 std::stringstream s; 935 for (uid_t uid : uids) { 936 s << uid << " "; 937 } 938 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str()); 939#endif 940 941 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called. 942 if (mSystemReady) { 943 ALOGE("no wake lock to update, but system ready!"); 944 } else { 945 ALOGW("no wake lock to update, system not ready yet"); 946 } 947 return; 948 } 949 if (mPowerManager != 0) { 950 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints 951 status_t status = mPowerManager->updateWakeLockUids( 952 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(), 953 true /* FIXME force oneway contrary to .aidl */); 954 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status); 955 } 956} 957 958void AudioFlinger::ThreadBase::clearPowerManager() 959{ 960 Mutex::Autolock _l(mLock); 961 releaseWakeLock_l(); 962 mPowerManager.clear(); 963} 964 965void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused) 966{ 967 sp<ThreadBase> thread = mThread.promote(); 968 if (thread != 0) { 969 thread->clearPowerManager(); 970 } 971 ALOGW("power manager service died !!!"); 972} 973 974void AudioFlinger::ThreadBase::setEffectSuspended( 975 const effect_uuid_t *type, bool suspend, audio_session_t sessionId) 976{ 977 Mutex::Autolock _l(mLock); 978 setEffectSuspended_l(type, suspend, sessionId); 979} 980 981void AudioFlinger::ThreadBase::setEffectSuspended_l( 982 const effect_uuid_t *type, bool suspend, audio_session_t sessionId) 983{ 984 sp<EffectChain> chain = getEffectChain_l(sessionId); 985 if (chain != 0) { 986 if (type != NULL) { 987 chain->setEffectSuspended_l(type, suspend); 988 } else { 989 chain->setEffectSuspendedAll_l(suspend); 990 } 991 } 992 993 updateSuspendedSessions_l(type, suspend, sessionId); 994} 995 996void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 997{ 998 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 999 if (index < 0) { 1000 return; 1001 } 1002 1003 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 1004 mSuspendedSessions.valueAt(index); 1005 1006 for (size_t i = 0; i < sessionEffects.size(); i++) { 1007 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i); 1008 for (int j = 0; j < desc->mRefCount; j++) { 1009 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 1010 chain->setEffectSuspendedAll_l(true); 1011 } else { 1012 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 1013 desc->mType.timeLow); 1014 chain->setEffectSuspended_l(&desc->mType, true); 1015 } 1016 } 1017 } 1018} 1019 1020void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 1021 bool suspend, 1022 audio_session_t sessionId) 1023{ 1024 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 1025 1026 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 1027 1028 if (suspend) { 1029 if (index >= 0) { 1030 sessionEffects = mSuspendedSessions.valueAt(index); 1031 } else { 1032 mSuspendedSessions.add(sessionId, sessionEffects); 1033 } 1034 } else { 1035 if (index < 0) { 1036 return; 1037 } 1038 sessionEffects = mSuspendedSessions.valueAt(index); 1039 } 1040 1041 1042 int key = EffectChain::kKeyForSuspendAll; 1043 if (type != NULL) { 1044 key = type->timeLow; 1045 } 1046 index = sessionEffects.indexOfKey(key); 1047 1048 sp<SuspendedSessionDesc> desc; 1049 if (suspend) { 1050 if (index >= 0) { 1051 desc = sessionEffects.valueAt(index); 1052 } else { 1053 desc = new SuspendedSessionDesc(); 1054 if (type != NULL) { 1055 desc->mType = *type; 1056 } 1057 sessionEffects.add(key, desc); 1058 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 1059 } 1060 desc->mRefCount++; 1061 } else { 1062 if (index < 0) { 1063 return; 1064 } 1065 desc = sessionEffects.valueAt(index); 1066 if (--desc->mRefCount == 0) { 1067 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 1068 sessionEffects.removeItemsAt(index); 1069 if (sessionEffects.isEmpty()) { 1070 ALOGV("updateSuspendedSessions_l() restore removing session %d", 1071 sessionId); 1072 mSuspendedSessions.removeItem(sessionId); 1073 } 1074 } 1075 } 1076 if (!sessionEffects.isEmpty()) { 1077 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 1078 } 1079} 1080 1081void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1082 bool enabled, 1083 audio_session_t sessionId) 1084{ 1085 Mutex::Autolock _l(mLock); 1086 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 1087} 1088 1089void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 1090 bool enabled, 1091 audio_session_t sessionId) 1092{ 1093 if (mType != RECORD) { 1094 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 1095 // another session. This gives the priority to well behaved effect control panels 1096 // and applications not using global effects. 1097 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 1098 // global effects 1099 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 1100 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 1101 } 1102 } 1103 1104 sp<EffectChain> chain = getEffectChain_l(sessionId); 1105 if (chain != 0) { 1106 chain->checkSuspendOnEffectEnabled(effect, enabled); 1107 } 1108} 1109 1110// checkEffectCompatibility_l() must be called with ThreadBase::mLock held 1111status_t AudioFlinger::RecordThread::checkEffectCompatibility_l( 1112 const effect_descriptor_t *desc, audio_session_t sessionId) 1113{ 1114 // No global effect sessions on record threads 1115 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 1116 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s", 1117 desc->name, mThreadName); 1118 return BAD_VALUE; 1119 } 1120 // only pre processing effects on record thread 1121 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) { 1122 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s", 1123 desc->name, mThreadName); 1124 return BAD_VALUE; 1125 } 1126 1127 // always allow effects without processing load or latency 1128 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) { 1129 return NO_ERROR; 1130 } 1131 1132 audio_input_flags_t flags = mInput->flags; 1133 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) { 1134 if (flags & AUDIO_INPUT_FLAG_RAW) { 1135 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode", 1136 desc->name, mThreadName); 1137 return BAD_VALUE; 1138 } 1139 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1140 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode", 1141 desc->name, mThreadName); 1142 return BAD_VALUE; 1143 } 1144 } 1145 return NO_ERROR; 1146} 1147 1148// checkEffectCompatibility_l() must be called with ThreadBase::mLock held 1149status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l( 1150 const effect_descriptor_t *desc, audio_session_t sessionId) 1151{ 1152 // no preprocessing on playback threads 1153 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) { 1154 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback" 1155 " thread %s", desc->name, mThreadName); 1156 return BAD_VALUE; 1157 } 1158 1159 switch (mType) { 1160 case MIXER: { 1161 // Reject any effect on mixer multichannel sinks. 1162 // TODO: fix both format and multichannel issues with effects. 1163 if (mChannelCount != FCC_2) { 1164 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER" 1165 " thread %s", desc->name, mChannelCount, mThreadName); 1166 return BAD_VALUE; 1167 } 1168 audio_output_flags_t flags = mOutput->flags; 1169 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) { 1170 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1171 // global effects are applied only to non fast tracks if they are SW 1172 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1173 break; 1174 } 1175 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 1176 // only post processing on output stage session 1177 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) { 1178 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed" 1179 " on output stage session", desc->name); 1180 return BAD_VALUE; 1181 } 1182 } else { 1183 // no restriction on effects applied on non fast tracks 1184 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) { 1185 break; 1186 } 1187 } 1188 1189 // always allow effects without processing load or latency 1190 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) { 1191 break; 1192 } 1193 if (flags & AUDIO_OUTPUT_FLAG_RAW) { 1194 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode", 1195 desc->name); 1196 return BAD_VALUE; 1197 } 1198 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1199 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread" 1200 " in fast mode", desc->name); 1201 return BAD_VALUE; 1202 } 1203 } 1204 } break; 1205 case OFFLOAD: 1206 // nothing actionable on offload threads, if the effect: 1207 // - is offloadable: the effect can be created 1208 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable() 1209 // will take care of invalidating the tracks of the thread 1210 break; 1211 case DIRECT: 1212 // Reject any effect on Direct output threads for now, since the format of 1213 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo). 1214 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s", 1215 desc->name, mThreadName); 1216 return BAD_VALUE; 1217 case DUPLICATING: 1218 // Reject any effect on mixer multichannel sinks. 1219 // TODO: fix both format and multichannel issues with effects. 1220 if (mChannelCount != FCC_2) { 1221 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)" 1222 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName); 1223 return BAD_VALUE; 1224 } 1225 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) { 1226 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING" 1227 " thread %s", desc->name, mThreadName); 1228 return BAD_VALUE; 1229 } 1230 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 1231 ALOGW("checkEffectCompatibility_l(): post processing effect %s on" 1232 " DUPLICATING thread %s", desc->name, mThreadName); 1233 return BAD_VALUE; 1234 } 1235 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) { 1236 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on" 1237 " DUPLICATING thread %s", desc->name, mThreadName); 1238 return BAD_VALUE; 1239 } 1240 break; 1241 default: 1242 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType); 1243 } 1244 1245 return NO_ERROR; 1246} 1247 1248// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held 1249sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 1250 const sp<AudioFlinger::Client>& client, 1251 const sp<IEffectClient>& effectClient, 1252 int32_t priority, 1253 audio_session_t sessionId, 1254 effect_descriptor_t *desc, 1255 int *enabled, 1256 status_t *status, 1257 bool pinned) 1258{ 1259 sp<EffectModule> effect; 1260 sp<EffectHandle> handle; 1261 status_t lStatus; 1262 sp<EffectChain> chain; 1263 bool chainCreated = false; 1264 bool effectCreated = false; 1265 bool effectRegistered = false; 1266 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; 1267 1268 lStatus = initCheck(); 1269 if (lStatus != NO_ERROR) { 1270 ALOGW("createEffect_l() Audio driver not initialized."); 1271 goto Exit; 1272 } 1273 1274 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 1275 1276 { // scope for mLock 1277 Mutex::Autolock _l(mLock); 1278 1279 lStatus = checkEffectCompatibility_l(desc, sessionId); 1280 if (lStatus != NO_ERROR) { 1281 goto Exit; 1282 } 1283 1284 // check for existing effect chain with the requested audio session 1285 chain = getEffectChain_l(sessionId); 1286 if (chain == 0) { 1287 // create a new chain for this session 1288 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 1289 chain = new EffectChain(this, sessionId); 1290 addEffectChain_l(chain); 1291 chain->setStrategy(getStrategyForSession_l(sessionId)); 1292 chainCreated = true; 1293 } else { 1294 effect = chain->getEffectFromDesc_l(desc); 1295 } 1296 1297 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 1298 1299 if (effect == 0) { 1300 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT); 1301 // Check CPU and memory usage 1302 lStatus = AudioSystem::registerEffect( 1303 desc, mId, chain->strategy(), sessionId, effectId); 1304 if (lStatus != NO_ERROR) { 1305 goto Exit; 1306 } 1307 effectRegistered = true; 1308 // create a new effect module if none present in the chain 1309 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned); 1310 if (lStatus != NO_ERROR) { 1311 goto Exit; 1312 } 1313 effectCreated = true; 1314 1315 effect->setDevice(mOutDevice); 1316 effect->setDevice(mInDevice); 1317 effect->setMode(mAudioFlinger->getMode()); 1318 effect->setAudioSource(mAudioSource); 1319 } 1320 // create effect handle and connect it to effect module 1321 handle = new EffectHandle(effect, client, effectClient, priority); 1322 lStatus = handle->initCheck(); 1323 if (lStatus == OK) { 1324 lStatus = effect->addHandle(handle.get()); 1325 } 1326 if (enabled != NULL) { 1327 *enabled = (int)effect->isEnabled(); 1328 } 1329 } 1330 1331Exit: 1332 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 1333 Mutex::Autolock _l(mLock); 1334 if (effectCreated) { 1335 chain->removeEffect_l(effect); 1336 } 1337 if (effectRegistered) { 1338 AudioSystem::unregisterEffect(effectId); 1339 } 1340 if (chainCreated) { 1341 removeEffectChain_l(chain); 1342 } 1343 handle.clear(); 1344 } 1345 1346 *status = lStatus; 1347 return handle; 1348} 1349 1350void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle, 1351 bool unpinIfLast) 1352{ 1353 bool remove = false; 1354 sp<EffectModule> effect; 1355 { 1356 Mutex::Autolock _l(mLock); 1357 1358 effect = handle->effect().promote(); 1359 if (effect == 0) { 1360 return; 1361 } 1362 // restore suspended effects if the disconnected handle was enabled and the last one. 1363 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast); 1364 if (remove) { 1365 removeEffect_l(effect, true); 1366 } 1367 } 1368 if (remove) { 1369 mAudioFlinger->updateOrphanEffectChains(effect); 1370 AudioSystem::unregisterEffect(effect->id()); 1371 if (handle->enabled()) { 1372 checkSuspendOnEffectEnabled(effect, false, effect->sessionId()); 1373 } 1374 } 1375} 1376 1377sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId, 1378 int effectId) 1379{ 1380 Mutex::Autolock _l(mLock); 1381 return getEffect_l(sessionId, effectId); 1382} 1383 1384sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId, 1385 int effectId) 1386{ 1387 sp<EffectChain> chain = getEffectChain_l(sessionId); 1388 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 1389} 1390 1391// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 1392// PlaybackThread::mLock held 1393status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 1394{ 1395 // check for existing effect chain with the requested audio session 1396 audio_session_t sessionId = effect->sessionId(); 1397 sp<EffectChain> chain = getEffectChain_l(sessionId); 1398 bool chainCreated = false; 1399 1400 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(), 1401 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x", 1402 this, effect->desc().name, effect->desc().flags); 1403 1404 if (chain == 0) { 1405 // create a new chain for this session 1406 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 1407 chain = new EffectChain(this, sessionId); 1408 addEffectChain_l(chain); 1409 chain->setStrategy(getStrategyForSession_l(sessionId)); 1410 chainCreated = true; 1411 } 1412 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 1413 1414 if (chain->getEffectFromId_l(effect->id()) != 0) { 1415 ALOGW("addEffect_l() %p effect %s already present in chain %p", 1416 this, effect->desc().name, chain.get()); 1417 return BAD_VALUE; 1418 } 1419 1420 effect->setOffloaded(mType == OFFLOAD, mId); 1421 1422 status_t status = chain->addEffect_l(effect); 1423 if (status != NO_ERROR) { 1424 if (chainCreated) { 1425 removeEffectChain_l(chain); 1426 } 1427 return status; 1428 } 1429 1430 effect->setDevice(mOutDevice); 1431 effect->setDevice(mInDevice); 1432 effect->setMode(mAudioFlinger->getMode()); 1433 effect->setAudioSource(mAudioSource); 1434 return NO_ERROR; 1435} 1436 1437void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) { 1438 1439 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get()); 1440 effect_descriptor_t desc = effect->desc(); 1441 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 1442 detachAuxEffect_l(effect->id()); 1443 } 1444 1445 sp<EffectChain> chain = effect->chain().promote(); 1446 if (chain != 0) { 1447 // remove effect chain if removing last effect 1448 if (chain->removeEffect_l(effect, release) == 0) { 1449 removeEffectChain_l(chain); 1450 } 1451 } else { 1452 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 1453 } 1454} 1455 1456void AudioFlinger::ThreadBase::lockEffectChains_l( 1457 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 1458{ 1459 effectChains = mEffectChains; 1460 for (size_t i = 0; i < mEffectChains.size(); i++) { 1461 mEffectChains[i]->lock(); 1462 } 1463} 1464 1465void AudioFlinger::ThreadBase::unlockEffectChains( 1466 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 1467{ 1468 for (size_t i = 0; i < effectChains.size(); i++) { 1469 effectChains[i]->unlock(); 1470 } 1471} 1472 1473sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId) 1474{ 1475 Mutex::Autolock _l(mLock); 1476 return getEffectChain_l(sessionId); 1477} 1478 1479sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId) 1480 const 1481{ 1482 size_t size = mEffectChains.size(); 1483 for (size_t i = 0; i < size; i++) { 1484 if (mEffectChains[i]->sessionId() == sessionId) { 1485 return mEffectChains[i]; 1486 } 1487 } 1488 return 0; 1489} 1490 1491void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 1492{ 1493 Mutex::Autolock _l(mLock); 1494 size_t size = mEffectChains.size(); 1495 for (size_t i = 0; i < size; i++) { 1496 mEffectChains[i]->setMode_l(mode); 1497 } 1498} 1499 1500void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config) 1501{ 1502 config->type = AUDIO_PORT_TYPE_MIX; 1503 config->ext.mix.handle = mId; 1504 config->sample_rate = mSampleRate; 1505 config->format = mFormat; 1506 config->channel_mask = mChannelMask; 1507 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK| 1508 AUDIO_PORT_CONFIG_FORMAT; 1509} 1510 1511void AudioFlinger::ThreadBase::systemReady() 1512{ 1513 Mutex::Autolock _l(mLock); 1514 if (mSystemReady) { 1515 return; 1516 } 1517 mSystemReady = true; 1518 1519 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) { 1520 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i)); 1521 } 1522 mPendingConfigEvents.clear(); 1523} 1524 1525template <typename T> 1526ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) { 1527 ssize_t index = mActiveTracks.indexOf(track); 1528 if (index >= 0) { 1529 ALOGW("ActiveTracks<T>::add track %p already there", track.get()); 1530 return index; 1531 } 1532 mActiveTracksGeneration++; 1533 mLatestActiveTrack = track; 1534 ++mBatteryCounter[track->uid()].second; 1535 return mActiveTracks.add(track); 1536} 1537 1538template <typename T> 1539ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) { 1540 ssize_t index = mActiveTracks.remove(track); 1541 if (index < 0) { 1542 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get()); 1543 return index; 1544 } 1545 mActiveTracksGeneration++; 1546 --mBatteryCounter[track->uid()].second; 1547 // mLatestActiveTrack is not cleared even if is the same as track. 1548 return index; 1549} 1550 1551template <typename T> 1552void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() { 1553 for (const sp<T> &track : mActiveTracks) { 1554 BatteryNotifier::getInstance().noteStopAudio(track->uid()); 1555 } 1556 mLastActiveTracksGeneration = mActiveTracksGeneration; 1557 mActiveTracks.clear(); 1558 mLatestActiveTrack.clear(); 1559 mBatteryCounter.clear(); 1560} 1561 1562template <typename T> 1563void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState( 1564 sp<ThreadBase> thread, bool force) { 1565 // Updates ActiveTracks client uids to the thread wakelock. 1566 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) { 1567 thread->updateWakeLockUids_l(getWakeLockUids()); 1568 mLastActiveTracksGeneration = mActiveTracksGeneration; 1569 } 1570 1571 // Updates BatteryNotifier uids 1572 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) { 1573 const uid_t uid = it->first; 1574 ssize_t &previous = it->second.first; 1575 ssize_t ¤t = it->second.second; 1576 if (current > 0) { 1577 if (previous == 0) { 1578 BatteryNotifier::getInstance().noteStartAudio(uid); 1579 } 1580 previous = current; 1581 ++it; 1582 } else if (current == 0) { 1583 if (previous > 0) { 1584 BatteryNotifier::getInstance().noteStopAudio(uid); 1585 } 1586 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase. 1587 } else /* (current < 0) */ { 1588 LOG_ALWAYS_FATAL("negative battery count %zd", current); 1589 } 1590 } 1591} 1592 1593// ---------------------------------------------------------------------------- 1594// Playback 1595// ---------------------------------------------------------------------------- 1596 1597AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1598 AudioStreamOut* output, 1599 audio_io_handle_t id, 1600 audio_devices_t device, 1601 type_t type, 1602 bool systemReady) 1603 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady), 1604 mNormalFrameCount(0), mSinkBuffer(NULL), 1605 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision), 1606 mMixerBuffer(NULL), 1607 mMixerBufferSize(0), 1608 mMixerBufferFormat(AUDIO_FORMAT_INVALID), 1609 mMixerBufferValid(false), 1610 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision), 1611 mEffectBuffer(NULL), 1612 mEffectBufferSize(0), 1613 mEffectBufferFormat(AUDIO_FORMAT_INVALID), 1614 mEffectBufferValid(false), 1615 mSuspended(0), mBytesWritten(0), 1616 mFramesWritten(0), 1617 mSuspendedFrames(0), 1618 // mStreamTypes[] initialized in constructor body 1619 mOutput(output), 1620 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 1621 mMixerStatus(MIXER_IDLE), 1622 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 1623 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs), 1624 mBytesRemaining(0), 1625 mCurrentWriteLength(0), 1626 mUseAsyncWrite(false), 1627 mWriteAckSequence(0), 1628 mDrainSequence(0), 1629 mSignalPending(false), 1630 mScreenState(AudioFlinger::mScreenState), 1631 // index 0 is reserved for normal mixer's submix 1632 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1), 1633 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false) 1634{ 1635 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id); 1636 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 1637 1638 // Assumes constructor is called by AudioFlinger with it's mLock held, but 1639 // it would be safer to explicitly pass initial masterVolume/masterMute as 1640 // parameter. 1641 // 1642 // If the HAL we are using has support for master volume or master mute, 1643 // then do not attenuate or mute during mixing (just leave the volume at 1.0 1644 // and the mute set to false). 1645 mMasterVolume = audioFlinger->masterVolume_l(); 1646 mMasterMute = audioFlinger->masterMute_l(); 1647 if (mOutput && mOutput->audioHwDev) { 1648 if (mOutput->audioHwDev->canSetMasterVolume()) { 1649 mMasterVolume = 1.0; 1650 } 1651 1652 if (mOutput->audioHwDev->canSetMasterMute()) { 1653 mMasterMute = false; 1654 } 1655 } 1656 1657 readOutputParameters_l(); 1658 1659 // ++ operator does not compile 1660 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT; 1661 stream = (audio_stream_type_t) (stream + 1)) { 1662 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 1663 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1664 } 1665} 1666 1667AudioFlinger::PlaybackThread::~PlaybackThread() 1668{ 1669 mAudioFlinger->unregisterWriter(mNBLogWriter); 1670 free(mSinkBuffer); 1671 free(mMixerBuffer); 1672 free(mEffectBuffer); 1673} 1674 1675void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1676{ 1677 dumpInternals(fd, args); 1678 dumpTracks(fd, args); 1679 dumpEffectChains(fd, args); 1680 mLocalLog.dump(fd, args, " " /* prefix */); 1681} 1682 1683void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused) 1684{ 1685 const size_t SIZE = 256; 1686 char buffer[SIZE]; 1687 String8 result; 1688 1689 result.appendFormat(" Stream volumes in dB: "); 1690 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1691 const stream_type_t *st = &mStreamTypes[i]; 1692 if (i > 0) { 1693 result.appendFormat(", "); 1694 } 1695 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1696 if (st->mute) { 1697 result.append("M"); 1698 } 1699 } 1700 result.append("\n"); 1701 write(fd, result.string(), result.length()); 1702 result.clear(); 1703 1704 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1705 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1706 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n", 1707 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1708 1709 size_t numtracks = mTracks.size(); 1710 size_t numactive = mActiveTracks.size(); 1711 dprintf(fd, " %zu Tracks", numtracks); 1712 size_t numactiveseen = 0; 1713 if (numtracks) { 1714 dprintf(fd, " of which %zu are active\n", numactive); 1715 Track::appendDumpHeader(result); 1716 for (size_t i = 0; i < numtracks; ++i) { 1717 sp<Track> track = mTracks[i]; 1718 if (track != 0) { 1719 bool active = mActiveTracks.indexOf(track) >= 0; 1720 if (active) { 1721 numactiveseen++; 1722 } 1723 track->dump(buffer, SIZE, active); 1724 result.append(buffer); 1725 } 1726 } 1727 } else { 1728 result.append("\n"); 1729 } 1730 if (numactiveseen != numactive) { 1731 // some tracks in the active list were not in the tracks list 1732 snprintf(buffer, SIZE, " The following tracks are in the active list but" 1733 " not in the track list\n"); 1734 result.append(buffer); 1735 Track::appendDumpHeader(result); 1736 for (size_t i = 0; i < numactive; ++i) { 1737 sp<Track> track = mActiveTracks[i]; 1738 if (mTracks.indexOf(track) < 0) { 1739 track->dump(buffer, SIZE, true); 1740 result.append(buffer); 1741 } 1742 } 1743 } 1744 1745 write(fd, result.string(), result.size()); 1746} 1747 1748void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1749{ 1750 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type())); 1751 1752 dumpBase(fd, args); 1753 1754 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount); 1755 dprintf(fd, " Last write occurred (msecs): %llu\n", 1756 (unsigned long long) ns2ms(systemTime() - mLastWriteTime)); 1757 dprintf(fd, " Total writes: %d\n", mNumWrites); 1758 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites); 1759 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no"); 1760 dprintf(fd, " Suspend count: %d\n", mSuspended); 1761 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer); 1762 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer); 1763 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer); 1764 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask); 1765 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs); 1766 AudioStreamOut *output = mOutput; 1767 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE; 1768 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", 1769 output, flags, outputFlagsToString(flags).c_str()); 1770 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten); 1771 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames); 1772 if (mPipeSink.get() != nullptr) { 1773 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten()); 1774 } 1775 if (output != nullptr) { 1776 dprintf(fd, " Hal stream dump:\n"); 1777 (void)output->stream->dump(fd); 1778 } 1779} 1780 1781// Thread virtuals 1782 1783void AudioFlinger::PlaybackThread::onFirstRef() 1784{ 1785 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO); 1786} 1787 1788// ThreadBase virtuals 1789void AudioFlinger::PlaybackThread::preExit() 1790{ 1791 ALOGV(" preExit()"); 1792 // FIXME this is using hard-coded strings but in the future, this functionality will be 1793 // converted to use audio HAL extensions required to support tunneling 1794 status_t result = mOutput->stream->setParameters(String8("exiting=1")); 1795 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result); 1796} 1797 1798// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1799sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1800 const sp<AudioFlinger::Client>& client, 1801 audio_stream_type_t streamType, 1802 uint32_t sampleRate, 1803 audio_format_t format, 1804 audio_channel_mask_t channelMask, 1805 size_t *pFrameCount, 1806 const sp<IMemory>& sharedBuffer, 1807 audio_session_t sessionId, 1808 audio_output_flags_t *flags, 1809 pid_t tid, 1810 uid_t uid, 1811 status_t *status, 1812 audio_port_handle_t portId) 1813{ 1814 size_t frameCount = *pFrameCount; 1815 sp<Track> track; 1816 status_t lStatus; 1817 audio_output_flags_t outputFlags = mOutput->flags; 1818 1819 // special case for FAST flag considered OK if fast mixer is present 1820 if (hasFastMixer()) { 1821 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST); 1822 } 1823 1824 // Check if requested flags are compatible with output stream flags 1825 if ((*flags & outputFlags) != *flags) { 1826 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)", 1827 *flags, outputFlags); 1828 *flags = (audio_output_flags_t)(*flags & outputFlags); 1829 } 1830 1831 // client expresses a preference for FAST, but we get the final say 1832 if (*flags & AUDIO_OUTPUT_FLAG_FAST) { 1833 if ( 1834 // PCM data 1835 audio_is_linear_pcm(format) && 1836 // TODO: extract as a data library function that checks that a computationally 1837 // expensive downmixer is not required: isFastOutputChannelConversion() 1838 (channelMask == mChannelMask || 1839 mChannelMask != AUDIO_CHANNEL_OUT_STEREO || 1840 (channelMask == AUDIO_CHANNEL_OUT_MONO 1841 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) && 1842 // hardware sample rate 1843 (sampleRate == mSampleRate) && 1844 // normal mixer has an associated fast mixer 1845 hasFastMixer() && 1846 // there are sufficient fast track slots available 1847 (mFastTrackAvailMask != 0) 1848 // FIXME test that MixerThread for this fast track has a capable output HAL 1849 // FIXME add a permission test also? 1850 ) { 1851 // static tracks can have any nonzero framecount, streaming tracks check against minimum. 1852 if (sharedBuffer == 0) { 1853 // read the fast track multiplier property the first time it is needed 1854 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit); 1855 if (ok != 0) { 1856 ALOGE("%s pthread_once failed: %d", __func__, ok); 1857 } 1858 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0 1859 } 1860 1861 // check compatibility with audio effects. 1862 { // scope for mLock 1863 Mutex::Autolock _l(mLock); 1864 for (audio_session_t session : { 1865 AUDIO_SESSION_OUTPUT_STAGE, 1866 AUDIO_SESSION_OUTPUT_MIX, 1867 sessionId, 1868 }) { 1869 sp<EffectChain> chain = getEffectChain_l(session); 1870 if (chain.get() != nullptr) { 1871 audio_output_flags_t old = *flags; 1872 chain->checkOutputFlagCompatibility(flags); 1873 if (old != *flags) { 1874 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x", 1875 (int)session, (int)old, (int)*flags); 1876 } 1877 } 1878 } 1879 } 1880 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0, 1881 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu", 1882 frameCount, mFrameCount); 1883 } else { 1884 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu " 1885 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x " 1886 "sampleRate=%u mSampleRate=%u " 1887 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1888 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat, 1889 audio_is_linear_pcm(format), 1890 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1891 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST); 1892 } 1893 } 1894 // For normal PCM streaming tracks, update minimum frame count. 1895 // For compatibility with AudioTrack calculation, buffer depth is forced 1896 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1897 // This is probably too conservative, but legacy application code may depend on it. 1898 // If you change this calculation, also review the start threshold which is related. 1899 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST) 1900 && audio_has_proportional_frames(format) && sharedBuffer == 0) { 1901 // this must match AudioTrack.cpp calculateMinFrameCount(). 1902 // TODO: Move to a common library 1903 uint32_t latencyMs = 0; 1904 lStatus = mOutput->stream->getLatency(&latencyMs); 1905 if (lStatus != OK) { 1906 ALOGE("Error when retrieving output stream latency: %d", lStatus); 1907 goto Exit; 1908 } 1909 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1910 if (minBufCount < 2) { 1911 minBufCount = 2; 1912 } 1913 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack 1914 // or the client should compute and pass in a larger buffer request. 1915 size_t minFrameCount = 1916 minBufCount * sourceFramesNeededWithTimestretch( 1917 sampleRate, mNormalFrameCount, 1918 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/); 1919 if (frameCount < minFrameCount) { // including frameCount == 0 1920 frameCount = minFrameCount; 1921 } 1922 } 1923 *pFrameCount = frameCount; 1924 1925 switch (mType) { 1926 1927 case DIRECT: 1928 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()? 1929 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1930 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x " 1931 "for output %p with format %#x", 1932 sampleRate, format, channelMask, mOutput, mFormat); 1933 lStatus = BAD_VALUE; 1934 goto Exit; 1935 } 1936 } 1937 break; 1938 1939 case OFFLOAD: 1940 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1941 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \"" 1942 "for output %p with format %#x", 1943 sampleRate, format, channelMask, mOutput, mFormat); 1944 lStatus = BAD_VALUE; 1945 goto Exit; 1946 } 1947 break; 1948 1949 default: 1950 if (!audio_is_linear_pcm(format)) { 1951 ALOGE("createTrack_l() Bad parameter: format %#x \"" 1952 "for output %p with format %#x", 1953 format, mOutput, mFormat); 1954 lStatus = BAD_VALUE; 1955 goto Exit; 1956 } 1957 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) { 1958 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1959 lStatus = BAD_VALUE; 1960 goto Exit; 1961 } 1962 break; 1963 1964 } 1965 1966 lStatus = initCheck(); 1967 if (lStatus != NO_ERROR) { 1968 ALOGE("createTrack_l() audio driver not initialized"); 1969 goto Exit; 1970 } 1971 1972 { // scope for mLock 1973 Mutex::Autolock _l(mLock); 1974 1975 // all tracks in same audio session must share the same routing strategy otherwise 1976 // conflicts will happen when tracks are moved from one output to another by audio policy 1977 // manager 1978 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1979 for (size_t i = 0; i < mTracks.size(); ++i) { 1980 sp<Track> t = mTracks[i]; 1981 if (t != 0 && t->isExternalTrack()) { 1982 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1983 if (sessionId == t->sessionId() && strategy != actual) { 1984 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1985 strategy, actual); 1986 lStatus = BAD_VALUE; 1987 goto Exit; 1988 } 1989 } 1990 } 1991 1992 track = new Track(this, client, streamType, sampleRate, format, 1993 channelMask, frameCount, NULL, sharedBuffer, 1994 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId); 1995 1996 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; 1997 if (lStatus != NO_ERROR) { 1998 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus); 1999 // track must be cleared from the caller as the caller has the AF lock 2000 goto Exit; 2001 } 2002 mTracks.add(track); 2003 2004 sp<EffectChain> chain = getEffectChain_l(sessionId); 2005 if (chain != 0) { 2006 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 2007 track->setMainBuffer(chain->inBuffer()); 2008 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 2009 chain->incTrackCnt(); 2010 } 2011 2012 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) { 2013 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 2014 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 2015 // so ask activity manager to do this on our behalf 2016 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 2017 } 2018 } 2019 2020 lStatus = NO_ERROR; 2021 2022Exit: 2023 *status = lStatus; 2024 return track; 2025} 2026 2027uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 2028{ 2029 return latency; 2030} 2031 2032uint32_t AudioFlinger::PlaybackThread::latency() const 2033{ 2034 Mutex::Autolock _l(mLock); 2035 return latency_l(); 2036} 2037uint32_t AudioFlinger::PlaybackThread::latency_l() const 2038{ 2039 uint32_t latency; 2040 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) { 2041 return correctLatency_l(latency); 2042 } 2043 return 0; 2044} 2045 2046void AudioFlinger::PlaybackThread::setMasterVolume(float value) 2047{ 2048 Mutex::Autolock _l(mLock); 2049 // Don't apply master volume in SW if our HAL can do it for us. 2050 if (mOutput && mOutput->audioHwDev && 2051 mOutput->audioHwDev->canSetMasterVolume()) { 2052 mMasterVolume = 1.0; 2053 } else { 2054 mMasterVolume = value; 2055 } 2056} 2057 2058void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 2059{ 2060 Mutex::Autolock _l(mLock); 2061 // Don't apply master mute in SW if our HAL can do it for us. 2062 if (mOutput && mOutput->audioHwDev && 2063 mOutput->audioHwDev->canSetMasterMute()) { 2064 mMasterMute = false; 2065 } else { 2066 mMasterMute = muted; 2067 } 2068} 2069 2070void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 2071{ 2072 Mutex::Autolock _l(mLock); 2073 mStreamTypes[stream].volume = value; 2074 broadcast_l(); 2075} 2076 2077void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 2078{ 2079 Mutex::Autolock _l(mLock); 2080 mStreamTypes[stream].mute = muted; 2081 broadcast_l(); 2082} 2083 2084float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 2085{ 2086 Mutex::Autolock _l(mLock); 2087 return mStreamTypes[stream].volume; 2088} 2089 2090// addTrack_l() must be called with ThreadBase::mLock held 2091status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 2092{ 2093 status_t status = ALREADY_EXISTS; 2094 2095 if (mActiveTracks.indexOf(track) < 0) { 2096 // the track is newly added, make sure it fills up all its 2097 // buffers before playing. This is to ensure the client will 2098 // effectively get the latency it requested. 2099 if (track->isExternalTrack()) { 2100 TrackBase::track_state state = track->mState; 2101 mLock.unlock(); 2102 status = AudioSystem::startOutput(mId, track->streamType(), 2103 track->sessionId()); 2104 mLock.lock(); 2105 // abort track was stopped/paused while we released the lock 2106 if (state != track->mState) { 2107 if (status == NO_ERROR) { 2108 mLock.unlock(); 2109 AudioSystem::stopOutput(mId, track->streamType(), 2110 track->sessionId()); 2111 mLock.lock(); 2112 } 2113 return INVALID_OPERATION; 2114 } 2115 // abort if start is rejected by audio policy manager 2116 if (status != NO_ERROR) { 2117 return PERMISSION_DENIED; 2118 } 2119#ifdef ADD_BATTERY_DATA 2120 // to track the speaker usage 2121 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 2122#endif 2123 } 2124 2125 // set retry count for buffer fill 2126 if (track->isOffloaded()) { 2127 if (track->isStopping_1()) { 2128 track->mRetryCount = kMaxTrackStopRetriesOffload; 2129 } else { 2130 track->mRetryCount = kMaxTrackStartupRetriesOffload; 2131 } 2132 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED; 2133 } else { 2134 track->mRetryCount = kMaxTrackStartupRetries; 2135 track->mFillingUpStatus = 2136 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; 2137 } 2138 2139 track->mResetDone = false; 2140 track->mPresentationCompleteFrames = 0; 2141 mActiveTracks.add(track); 2142 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2143 if (chain != 0) { 2144 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 2145 track->sessionId()); 2146 chain->incActiveTrackCnt(); 2147 } 2148 2149 char buffer[256]; 2150 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */); 2151 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis 2152 2153 status = NO_ERROR; 2154 } 2155 2156 onAddNewTrack_l(); 2157 return status; 2158} 2159 2160bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 2161{ 2162 track->terminate(); 2163 // active tracks are removed by threadLoop() 2164 bool trackActive = (mActiveTracks.indexOf(track) >= 0); 2165 track->mState = TrackBase::STOPPED; 2166 if (!trackActive) { 2167 removeTrack_l(track); 2168 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) { 2169 track->mState = TrackBase::STOPPING_1; 2170 } 2171 2172 return trackActive; 2173} 2174 2175void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 2176{ 2177 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 2178 2179 char buffer[256]; 2180 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */); 2181 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis 2182 2183 mTracks.remove(track); 2184 deleteTrackName_l(track->name()); 2185 // redundant as track is about to be destroyed, for dumpsys only 2186 track->mName = -1; 2187 if (track->isFastTrack()) { 2188 int index = track->mFastIndex; 2189 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks); 2190 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 2191 mFastTrackAvailMask |= 1 << index; 2192 // redundant as track is about to be destroyed, for dumpsys only 2193 track->mFastIndex = -1; 2194 } 2195 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2196 if (chain != 0) { 2197 chain->decTrackCnt(); 2198 } 2199} 2200 2201void AudioFlinger::PlaybackThread::broadcast_l() 2202{ 2203 // Thread could be blocked waiting for async 2204 // so signal it to handle state changes immediately 2205 // If threadLoop is currently unlocked a signal of mWaitWorkCV will 2206 // be lost so we also flag to prevent it blocking on mWaitWorkCV 2207 mSignalPending = true; 2208 mWaitWorkCV.broadcast(); 2209} 2210 2211String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 2212{ 2213 Mutex::Autolock _l(mLock); 2214 String8 out_s8; 2215 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) { 2216 return out_s8; 2217 } 2218 return String8(); 2219} 2220 2221void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 2222 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 2223 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event); 2224 2225 desc->mIoHandle = mId; 2226 2227 switch (event) { 2228 case AUDIO_OUTPUT_OPENED: 2229 case AUDIO_OUTPUT_CONFIG_CHANGED: 2230 desc->mPatch = mPatch; 2231 desc->mChannelMask = mChannelMask; 2232 desc->mSamplingRate = mSampleRate; 2233 desc->mFormat = mFormat; 2234 desc->mFrameCount = mNormalFrameCount; // FIXME see 2235 // AudioFlinger::frameCount(audio_io_handle_t) 2236 desc->mFrameCountHAL = mFrameCount; 2237 desc->mLatency = latency_l(); 2238 break; 2239 2240 case AUDIO_OUTPUT_CLOSED: 2241 default: 2242 break; 2243 } 2244 mAudioFlinger->ioConfigChanged(event, desc, pid); 2245} 2246 2247void AudioFlinger::PlaybackThread::onWriteReady() 2248{ 2249 mCallbackThread->resetWriteBlocked(); 2250} 2251 2252void AudioFlinger::PlaybackThread::onDrainReady() 2253{ 2254 mCallbackThread->resetDraining(); 2255} 2256 2257void AudioFlinger::PlaybackThread::onError() 2258{ 2259 mCallbackThread->setAsyncError(); 2260} 2261 2262void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence) 2263{ 2264 Mutex::Autolock _l(mLock); 2265 // reject out of sequence requests 2266 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) { 2267 mWriteAckSequence &= ~1; 2268 mWaitWorkCV.signal(); 2269 } 2270} 2271 2272void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence) 2273{ 2274 Mutex::Autolock _l(mLock); 2275 // reject out of sequence requests 2276 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) { 2277 mDrainSequence &= ~1; 2278 mWaitWorkCV.signal(); 2279 } 2280} 2281 2282void AudioFlinger::PlaybackThread::readOutputParameters_l() 2283{ 2284 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL 2285 mSampleRate = mOutput->getSampleRate(); 2286 mChannelMask = mOutput->getChannelMask(); 2287 if (!audio_is_output_channel(mChannelMask)) { 2288 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask); 2289 } 2290 if ((mType == MIXER || mType == DUPLICATING) 2291 && !isValidPcmSinkChannelMask(mChannelMask)) { 2292 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output", 2293 mChannelMask); 2294 } 2295 mChannelCount = audio_channel_count_from_out_mask(mChannelMask); 2296 2297 // Get actual HAL format. 2298 status_t result = mOutput->stream->getFormat(&mHALFormat); 2299 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result); 2300 // Get format from the shim, which will be different than the HAL format 2301 // if playing compressed audio over HDMI passthrough. 2302 mFormat = mOutput->getFormat(); 2303 if (!audio_is_valid_format(mFormat)) { 2304 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat); 2305 } 2306 if ((mType == MIXER || mType == DUPLICATING) 2307 && !isValidPcmSinkFormat(mFormat)) { 2308 LOG_FATAL("HAL format %#x not supported for mixed output", 2309 mFormat); 2310 } 2311 mFrameSize = mOutput->getFrameSize(); 2312 result = mOutput->stream->getBufferSize(&mBufferSize); 2313 LOG_ALWAYS_FATAL_IF(result != OK, 2314 "Error when retrieving output stream buffer size: %d", result); 2315 mFrameCount = mBufferSize / mFrameSize; 2316 if (mFrameCount & 15) { 2317 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames", 2318 mFrameCount); 2319 } 2320 2321 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) { 2322 if (mOutput->stream->setCallback(this) == OK) { 2323 mUseAsyncWrite = true; 2324 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 2325 } 2326 } 2327 2328 mHwSupportsPause = false; 2329 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) { 2330 bool supportsPause = false, supportsResume = false; 2331 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) { 2332 if (supportsPause && supportsResume) { 2333 mHwSupportsPause = true; 2334 } else if (supportsPause) { 2335 ALOGW("direct output implements pause but not resume"); 2336 } else if (supportsResume) { 2337 ALOGW("direct output implements resume but not pause"); 2338 } 2339 } 2340 } 2341 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) { 2342 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume"); 2343 } 2344 2345 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) { 2346 // For best precision, we use float instead of the associated output 2347 // device format (typically PCM 16 bit). 2348 2349 mFormat = AUDIO_FORMAT_PCM_FLOAT; 2350 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 2351 mBufferSize = mFrameSize * mFrameCount; 2352 2353 // TODO: We currently use the associated output device channel mask and sample rate. 2354 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads 2355 // (if a valid mask) to avoid premature downmix. 2356 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads 2357 // instead of the output device sample rate to avoid loss of high frequency information. 2358 // This may need to be updated as MixerThread/OutputTracks are added and not here. 2359 } 2360 2361 // Calculate size of normal sink buffer relative to the HAL output buffer size 2362 double multiplier = 1.0; 2363 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 2364 kUseFastMixer == FastMixer_Dynamic)) { 2365 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000; 2366 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000; 2367 2368 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 2369 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 2370 maxNormalFrameCount = maxNormalFrameCount & ~15; 2371 if (maxNormalFrameCount < minNormalFrameCount) { 2372 maxNormalFrameCount = minNormalFrameCount; 2373 } 2374 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 2375 if (multiplier <= 1.0) { 2376 multiplier = 1.0; 2377 } else if (multiplier <= 2.0) { 2378 if (2 * mFrameCount <= maxNormalFrameCount) { 2379 multiplier = 2.0; 2380 } else { 2381 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 2382 } 2383 } else { 2384 multiplier = floor(multiplier); 2385 } 2386 } 2387 mNormalFrameCount = multiplier * mFrameCount; 2388 // round up to nearest 16 frames to satisfy AudioMixer 2389 if (mType == MIXER || mType == DUPLICATING) { 2390 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 2391 } 2392 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount, 2393 mNormalFrameCount); 2394 2395 // Check if we want to throttle the processing to no more than 2x normal rate 2396 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */); 2397 mThreadThrottleTimeMs = 0; 2398 mThreadThrottleEndMs = 0; 2399 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate); 2400 2401 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames. 2402 // Originally this was int16_t[] array, need to remove legacy implications. 2403 free(mSinkBuffer); 2404 mSinkBuffer = NULL; 2405 // For sink buffer size, we use the frame size from the downstream sink to avoid problems 2406 // with non PCM formats for compressed music, e.g. AAC, and Offload threads. 2407 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 2408 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 2409 2410 // We resize the mMixerBuffer according to the requirements of the sink buffer which 2411 // drives the output. 2412 free(mMixerBuffer); 2413 mMixerBuffer = NULL; 2414 if (mMixerBufferEnabled) { 2415 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT. 2416 mMixerBufferSize = mNormalFrameCount * mChannelCount 2417 * audio_bytes_per_sample(mMixerBufferFormat); 2418 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize); 2419 } 2420 free(mEffectBuffer); 2421 mEffectBuffer = NULL; 2422 if (mEffectBufferEnabled) { 2423 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only 2424 mEffectBufferSize = mNormalFrameCount * mChannelCount 2425 * audio_bytes_per_sample(mEffectBufferFormat); 2426 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize); 2427 } 2428 2429 // force reconfiguration of effect chains and engines to take new buffer size and audio 2430 // parameters into account 2431 // Note that mLock is not held when readOutputParameters_l() is called from the constructor 2432 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 2433 // matter. 2434 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 2435 Vector< sp<EffectChain> > effectChains = mEffectChains; 2436 for (size_t i = 0; i < effectChains.size(); i ++) { 2437 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 2438 } 2439} 2440 2441 2442status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 2443{ 2444 if (halFrames == NULL || dspFrames == NULL) { 2445 return BAD_VALUE; 2446 } 2447 Mutex::Autolock _l(mLock); 2448 if (initCheck() != NO_ERROR) { 2449 return INVALID_OPERATION; 2450 } 2451 int64_t framesWritten = mBytesWritten / mFrameSize; 2452 *halFrames = framesWritten; 2453 2454 if (isSuspended()) { 2455 // return an estimation of rendered frames when the output is suspended 2456 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 2457 *dspFrames = (uint32_t) 2458 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0); 2459 return NO_ERROR; 2460 } else { 2461 status_t status; 2462 uint32_t frames; 2463 status = mOutput->getRenderPosition(&frames); 2464 *dspFrames = (size_t)frames; 2465 return status; 2466 } 2467} 2468 2469// hasAudioSession_l() must be called with ThreadBase::mLock held 2470uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const 2471{ 2472 uint32_t result = 0; 2473 if (getEffectChain_l(sessionId) != 0) { 2474 result = EFFECT_SESSION; 2475 } 2476 2477 for (size_t i = 0; i < mTracks.size(); ++i) { 2478 sp<Track> track = mTracks[i]; 2479 if (sessionId == track->sessionId() && !track->isInvalid()) { 2480 result |= TRACK_SESSION; 2481 if (track->isFastTrack()) { 2482 result |= FAST_SESSION; 2483 } 2484 break; 2485 } 2486 } 2487 2488 return result; 2489} 2490 2491uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) 2492{ 2493 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2494 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2495 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2496 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2497 } 2498 for (size_t i = 0; i < mTracks.size(); i++) { 2499 sp<Track> track = mTracks[i]; 2500 if (sessionId == track->sessionId() && !track->isInvalid()) { 2501 return AudioSystem::getStrategyForStream(track->streamType()); 2502 } 2503 } 2504 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2505} 2506 2507 2508AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2509{ 2510 Mutex::Autolock _l(mLock); 2511 return mOutput; 2512} 2513 2514AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2515{ 2516 Mutex::Autolock _l(mLock); 2517 AudioStreamOut *output = mOutput; 2518 mOutput = NULL; 2519 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2520 // must push a NULL and wait for ack 2521 mOutputSink.clear(); 2522 mPipeSink.clear(); 2523 mNormalSink.clear(); 2524 return output; 2525} 2526 2527// this method must always be called either with ThreadBase mLock held or inside the thread loop 2528sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const 2529{ 2530 if (mOutput == NULL) { 2531 return NULL; 2532 } 2533 return mOutput->stream; 2534} 2535 2536uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2537{ 2538 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2539} 2540 2541status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2542{ 2543 if (!isValidSyncEvent(event)) { 2544 return BAD_VALUE; 2545 } 2546 2547 Mutex::Autolock _l(mLock); 2548 2549 for (size_t i = 0; i < mTracks.size(); ++i) { 2550 sp<Track> track = mTracks[i]; 2551 if (event->triggerSession() == track->sessionId()) { 2552 (void) track->setSyncEvent(event); 2553 return NO_ERROR; 2554 } 2555 } 2556 2557 return NAME_NOT_FOUND; 2558} 2559 2560bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 2561{ 2562 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 2563} 2564 2565void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 2566 const Vector< sp<Track> >& tracksToRemove) 2567{ 2568 size_t count = tracksToRemove.size(); 2569 if (count > 0) { 2570 for (size_t i = 0 ; i < count ; i++) { 2571 const sp<Track>& track = tracksToRemove.itemAt(i); 2572 if (track->isExternalTrack()) { 2573 AudioSystem::stopOutput(mId, track->streamType(), 2574 track->sessionId()); 2575#ifdef ADD_BATTERY_DATA 2576 // to track the speaker usage 2577 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 2578#endif 2579 if (track->isTerminated()) { 2580 AudioSystem::releaseOutput(mId, track->streamType(), 2581 track->sessionId()); 2582 } 2583 } 2584 } 2585 } 2586} 2587 2588void AudioFlinger::PlaybackThread::checkSilentMode_l() 2589{ 2590 if (!mMasterMute) { 2591 char value[PROPERTY_VALUE_MAX]; 2592 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) { 2593 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX"); 2594 return; 2595 } 2596 if (property_get("ro.audio.silent", value, "0") > 0) { 2597 char *endptr; 2598 unsigned long ul = strtoul(value, &endptr, 0); 2599 if (*endptr == '\0' && ul != 0) { 2600 ALOGD("Silence is golden"); 2601 // The setprop command will not allow a property to be changed after 2602 // the first time it is set, so we don't have to worry about un-muting. 2603 setMasterMute_l(true); 2604 } 2605 } 2606 } 2607} 2608 2609// shared by MIXER and DIRECT, overridden by DUPLICATING 2610ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 2611{ 2612 mInWrite = true; 2613 ssize_t bytesWritten; 2614 const size_t offset = mCurrentWriteLength - mBytesRemaining; 2615 2616 // If an NBAIO sink is present, use it to write the normal mixer's submix 2617 if (mNormalSink != 0) { 2618 2619 const size_t count = mBytesRemaining / mFrameSize; 2620 2621 ATRACE_BEGIN("write"); 2622 // update the setpoint when AudioFlinger::mScreenState changes 2623 uint32_t screenState = AudioFlinger::mScreenState; 2624 if (screenState != mScreenState) { 2625 mScreenState = screenState; 2626 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2627 if (pipe != NULL) { 2628 pipe->setAvgFrames((mScreenState & 1) ? 2629 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2630 } 2631 } 2632 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count); 2633 ATRACE_END(); 2634 if (framesWritten > 0) { 2635 bytesWritten = framesWritten * mFrameSize; 2636 } else { 2637 bytesWritten = framesWritten; 2638 } 2639 // otherwise use the HAL / AudioStreamOut directly 2640 } else { 2641 // Direct output and offload threads 2642 2643 if (mUseAsyncWrite) { 2644 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 2645 mWriteAckSequence += 2; 2646 mWriteAckSequence |= 1; 2647 ALOG_ASSERT(mCallbackThread != 0); 2648 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2649 } 2650 // FIXME We should have an implementation of timestamps for direct output threads. 2651 // They are used e.g for multichannel PCM playback over HDMI. 2652 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining); 2653 2654 if (mUseAsyncWrite && 2655 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 2656 // do not wait for async callback in case of error of full write 2657 mWriteAckSequence &= ~1; 2658 ALOG_ASSERT(mCallbackThread != 0); 2659 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2660 } 2661 } 2662 2663 mNumWrites++; 2664 mInWrite = false; 2665 mStandby = false; 2666 return bytesWritten; 2667} 2668 2669void AudioFlinger::PlaybackThread::threadLoop_drain() 2670{ 2671 bool supportsDrain = false; 2672 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) { 2673 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 2674 if (mUseAsyncWrite) { 2675 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 2676 mDrainSequence |= 1; 2677 ALOG_ASSERT(mCallbackThread != 0); 2678 mCallbackThread->setDraining(mDrainSequence); 2679 } 2680 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK); 2681 ALOGE_IF(result != OK, "Error when draining stream: %d", result); 2682 } 2683} 2684 2685void AudioFlinger::PlaybackThread::threadLoop_exit() 2686{ 2687 { 2688 Mutex::Autolock _l(mLock); 2689 for (size_t i = 0; i < mTracks.size(); i++) { 2690 sp<Track> track = mTracks[i]; 2691 track->invalidate(); 2692 } 2693 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain. 2694 // After we exit there are no more track changes sent to BatteryNotifier 2695 // because that requires an active threadLoop. 2696 // TODO: should we decActiveTrackCnt() of the cleared track effect chain? 2697 mActiveTracks.clear(); 2698 } 2699} 2700 2701/* 2702The derived values that are cached: 2703 - mSinkBufferSize from frame count * frame size 2704 - mActiveSleepTimeUs from activeSleepTimeUs() 2705 - mIdleSleepTimeUs from idleSleepTimeUs() 2706 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least 2707 kDefaultStandbyTimeInNsecs when connected to an A2DP device. 2708 - maxPeriod from frame count and sample rate (MIXER only) 2709 2710The parameters that affect these derived values are: 2711 - frame count 2712 - frame size 2713 - sample rate 2714 - device type: A2DP or not 2715 - device latency 2716 - format: PCM or not 2717 - active sleep time 2718 - idle sleep time 2719*/ 2720 2721void AudioFlinger::PlaybackThread::cacheParameters_l() 2722{ 2723 mSinkBufferSize = mNormalFrameCount * mFrameSize; 2724 mActiveSleepTimeUs = activeSleepTimeUs(); 2725 mIdleSleepTimeUs = idleSleepTimeUs(); 2726 2727 // make sure standby delay is not too short when connected to an A2DP sink to avoid 2728 // truncating audio when going to standby. 2729 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs; 2730 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) { 2731 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) { 2732 mStandbyDelayNs = kDefaultStandbyTimeInNsecs; 2733 } 2734 } 2735} 2736 2737bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType) 2738{ 2739 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu", 2740 this, streamType, mTracks.size()); 2741 bool trackMatch = false; 2742 size_t size = mTracks.size(); 2743 for (size_t i = 0; i < size; i++) { 2744 sp<Track> t = mTracks[i]; 2745 if (t->streamType() == streamType && t->isExternalTrack()) { 2746 t->invalidate(); 2747 trackMatch = true; 2748 } 2749 } 2750 return trackMatch; 2751} 2752 2753void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 2754{ 2755 Mutex::Autolock _l(mLock); 2756 invalidateTracks_l(streamType); 2757} 2758 2759status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 2760{ 2761 audio_session_t session = chain->sessionId(); 2762 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer; 2763 status_t result = EffectBufferHalInterface::mirror( 2764 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer, 2765 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize, 2766 &halInBuffer); 2767 if (result != OK) return result; 2768 halOutBuffer = halInBuffer; 2769 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData()); 2770 2771 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 2772 if (session > AUDIO_SESSION_OUTPUT_MIX) { 2773 // Only one effect chain can be present in direct output thread and it uses 2774 // the sink buffer as input 2775 if (mType != DIRECT) { 2776 size_t numSamples = mNormalFrameCount * mChannelCount; 2777 status_t result = EffectBufferHalInterface::allocate( 2778 numSamples * sizeof(int16_t), 2779 &halInBuffer); 2780 if (result != OK) return result; 2781 buffer = halInBuffer->audioBuffer()->s16; 2782 ALOGV("addEffectChain_l() creating new input buffer %p session %d", 2783 buffer, session); 2784 } 2785 2786 // Attach all tracks with same session ID to this chain. 2787 for (size_t i = 0; i < mTracks.size(); ++i) { 2788 sp<Track> track = mTracks[i]; 2789 if (session == track->sessionId()) { 2790 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 2791 buffer); 2792 track->setMainBuffer(buffer); 2793 chain->incTrackCnt(); 2794 } 2795 } 2796 2797 // indicate all active tracks in the chain 2798 for (const sp<Track> &track : mActiveTracks) { 2799 if (session == track->sessionId()) { 2800 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 2801 chain->incActiveTrackCnt(); 2802 } 2803 } 2804 } 2805 chain->setThread(this); 2806 chain->setInBuffer(halInBuffer); 2807 chain->setOutBuffer(halOutBuffer); 2808 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 2809 // chains list in order to be processed last as it contains output stage effects. 2810 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 2811 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 2812 // after track specific effects and before output stage. 2813 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 2814 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX. 2815 // Effect chain for other sessions are inserted at beginning of effect 2816 // chains list to be processed before output mix effects. Relative order between other 2817 // sessions is not important. 2818 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 && 2819 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX, 2820 "audio_session_t constants misdefined"); 2821 size_t size = mEffectChains.size(); 2822 size_t i = 0; 2823 for (i = 0; i < size; i++) { 2824 if (mEffectChains[i]->sessionId() < session) { 2825 break; 2826 } 2827 } 2828 mEffectChains.insertAt(chain, i); 2829 checkSuspendOnAddEffectChain_l(chain); 2830 2831 return NO_ERROR; 2832} 2833 2834size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2835{ 2836 audio_session_t session = chain->sessionId(); 2837 2838 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2839 2840 for (size_t i = 0; i < mEffectChains.size(); i++) { 2841 if (chain == mEffectChains[i]) { 2842 mEffectChains.removeAt(i); 2843 // detach all active tracks from the chain 2844 for (const sp<Track> &track : mActiveTracks) { 2845 if (session == track->sessionId()) { 2846 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2847 chain.get(), session); 2848 chain->decActiveTrackCnt(); 2849 } 2850 } 2851 2852 // detach all tracks with same session ID from this chain 2853 for (size_t i = 0; i < mTracks.size(); ++i) { 2854 sp<Track> track = mTracks[i]; 2855 if (session == track->sessionId()) { 2856 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer)); 2857 chain->decTrackCnt(); 2858 } 2859 } 2860 break; 2861 } 2862 } 2863 return mEffectChains.size(); 2864} 2865 2866status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2867 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId) 2868{ 2869 Mutex::Autolock _l(mLock); 2870 return attachAuxEffect_l(track, EffectId); 2871} 2872 2873status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2874 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId) 2875{ 2876 status_t status = NO_ERROR; 2877 2878 if (EffectId == 0) { 2879 track->setAuxBuffer(0, NULL); 2880 } else { 2881 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2882 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2883 if (effect != 0) { 2884 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2885 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2886 } else { 2887 status = INVALID_OPERATION; 2888 } 2889 } else { 2890 status = BAD_VALUE; 2891 } 2892 } 2893 return status; 2894} 2895 2896void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2897{ 2898 for (size_t i = 0; i < mTracks.size(); ++i) { 2899 sp<Track> track = mTracks[i]; 2900 if (track->auxEffectId() == effectId) { 2901 attachAuxEffect_l(track, 0); 2902 } 2903 } 2904} 2905 2906bool AudioFlinger::PlaybackThread::threadLoop() 2907{ 2908 Vector< sp<Track> > tracksToRemove; 2909 2910 mStandbyTimeNs = systemTime(); 2911 nsecs_t lastWriteFinished = -1; // time last server write completed 2912 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written 2913 2914 // MIXER 2915 nsecs_t lastWarning = 0; 2916 2917 // DUPLICATING 2918 // FIXME could this be made local to while loop? 2919 writeFrames = 0; 2920 2921 cacheParameters_l(); 2922 mSleepTimeUs = mIdleSleepTimeUs; 2923 2924 if (mType == MIXER) { 2925 sleepTimeShift = 0; 2926 } 2927 2928 CpuStats cpuStats; 2929 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2930 2931 acquireWakeLock(); 2932 2933 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2934 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2935 // and then that string will be logged at the next convenient opportunity. 2936 const char *logString = NULL; 2937 2938 checkSilentMode_l(); 2939 2940 while (!exitPending()) 2941 { 2942 cpuStats.sample(myName); 2943 2944 Vector< sp<EffectChain> > effectChains; 2945 2946 { // scope for mLock 2947 2948 Mutex::Autolock _l(mLock); 2949 2950 processConfigEvents_l(); 2951 2952 if (logString != NULL) { 2953 mNBLogWriter->logTimestamp(); 2954 mNBLogWriter->log(logString); 2955 logString = NULL; 2956 } 2957 2958 // Gather the framesReleased counters for all active tracks, 2959 // and associate with the sink frames written out. We need 2960 // this to convert the sink timestamp to the track timestamp. 2961 bool kernelLocationUpdate = false; 2962 if (mNormalSink != 0) { 2963 // Note: The DuplicatingThread may not have a mNormalSink. 2964 // We always fetch the timestamp here because often the downstream 2965 // sink will block while writing. 2966 ExtendedTimestamp timestamp; // use private copy to fetch 2967 (void) mNormalSink->getTimestamp(timestamp); 2968 2969 // We keep track of the last valid kernel position in case we are in underrun 2970 // and the normal mixer period is the same as the fast mixer period, or there 2971 // is some error from the HAL. 2972 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) { 2973 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] = 2974 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]; 2975 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] = 2976 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]; 2977 2978 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] = 2979 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER]; 2980 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] = 2981 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER]; 2982 } 2983 2984 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) { 2985 kernelLocationUpdate = true; 2986 } else { 2987 ALOGVV("getTimestamp error - no valid kernel position"); 2988 } 2989 2990 // copy over kernel info 2991 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 2992 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] 2993 + mSuspendedFrames; // add frames discarded when suspended 2994 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = 2995 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]; 2996 } 2997 // mFramesWritten for non-offloaded tracks are contiguous 2998 // even after standby() is called. This is useful for the track frame 2999 // to sink frame mapping. 3000 bool serverLocationUpdate = false; 3001 if (mFramesWritten != lastFramesWritten) { 3002 serverLocationUpdate = true; 3003 lastFramesWritten = mFramesWritten; 3004 } 3005 // Only update timestamps if there is a meaningful change. 3006 // Either the kernel timestamp must be valid or we have written something. 3007 if (kernelLocationUpdate || serverLocationUpdate) { 3008 if (serverLocationUpdate) { 3009 // use the time before we called the HAL write - it is a bit more accurate 3010 // to when the server last read data than the current time here. 3011 // 3012 // If we haven't written anything, mLastWriteTime will be -1 3013 // and we use systemTime(). 3014 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten; 3015 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1 3016 ? systemTime() : mLastWriteTime; 3017 } 3018 3019 for (const sp<Track> &t : mActiveTracks) { 3020 if (!t->isFastTrack()) { 3021 t->updateTrackFrameInfo( 3022 t->mAudioTrackServerProxy->framesReleased(), 3023 mFramesWritten, 3024 mTimestamp); 3025 } 3026 } 3027 } 3028 3029 saveOutputTracks(); 3030 if (mSignalPending) { 3031 // A signal was raised while we were unlocked 3032 mSignalPending = false; 3033 } else if (waitingAsyncCallback_l()) { 3034 if (exitPending()) { 3035 break; 3036 } 3037 bool released = false; 3038 if (!keepWakeLock()) { 3039 releaseWakeLock_l(); 3040 released = true; 3041 } 3042 ALOGV("wait async completion"); 3043 mWaitWorkCV.wait(mLock); 3044 ALOGV("async completion/wake"); 3045 if (released) { 3046 acquireWakeLock_l(); 3047 } 3048 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3049 mSleepTimeUs = 0; 3050 3051 continue; 3052 } 3053 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) || 3054 isSuspended()) { 3055 // put audio hardware into standby after short delay 3056 if (shouldStandby_l()) { 3057 3058 threadLoop_standby(); 3059 3060 mStandby = true; 3061 } 3062 3063 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 3064 // we're about to wait, flush the binder command buffer 3065 IPCThreadState::self()->flushCommands(); 3066 3067 clearOutputTracks(); 3068 3069 if (exitPending()) { 3070 break; 3071 } 3072 3073 releaseWakeLock_l(); 3074 // wait until we have something to do... 3075 ALOGV("%s going to sleep", myName.string()); 3076 mWaitWorkCV.wait(mLock); 3077 ALOGV("%s waking up", myName.string()); 3078 acquireWakeLock_l(); 3079 3080 mMixerStatus = MIXER_IDLE; 3081 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 3082 mBytesWritten = 0; 3083 mBytesRemaining = 0; 3084 checkSilentMode_l(); 3085 3086 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3087 mSleepTimeUs = mIdleSleepTimeUs; 3088 if (mType == MIXER) { 3089 sleepTimeShift = 0; 3090 } 3091 3092 continue; 3093 } 3094 } 3095 // mMixerStatusIgnoringFastTracks is also updated internally 3096 mMixerStatus = prepareTracks_l(&tracksToRemove); 3097 3098 mActiveTracks.updatePowerState(this); 3099 3100 // prevent any changes in effect chain list and in each effect chain 3101 // during mixing and effect process as the audio buffers could be deleted 3102 // or modified if an effect is created or deleted 3103 lockEffectChains_l(effectChains); 3104 } // mLock scope ends 3105 3106 if (mBytesRemaining == 0) { 3107 mCurrentWriteLength = 0; 3108 if (mMixerStatus == MIXER_TRACKS_READY) { 3109 // threadLoop_mix() sets mCurrentWriteLength 3110 threadLoop_mix(); 3111 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 3112 && (mMixerStatus != MIXER_DRAIN_ALL)) { 3113 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data 3114 // must be written to HAL 3115 threadLoop_sleepTime(); 3116 if (mSleepTimeUs == 0) { 3117 mCurrentWriteLength = mSinkBufferSize; 3118 } 3119 } 3120 // Either threadLoop_mix() or threadLoop_sleepTime() should have set 3121 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0. 3122 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid) 3123 // or mSinkBuffer (if there are no effects). 3124 // 3125 // This is done pre-effects computation; if effects change to 3126 // support higher precision, this needs to move. 3127 // 3128 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l(). 3129 // TODO use mSleepTimeUs == 0 as an additional condition. 3130 if (mMixerBufferValid) { 3131 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer; 3132 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat; 3133 3134 // mono blend occurs for mixer threads only (not direct or offloaded) 3135 // and is handled here if we're going directly to the sink. 3136 if (requireMonoBlend() && !mEffectBufferValid) { 3137 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount, 3138 true /*limit*/); 3139 } 3140 3141 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat, 3142 mNormalFrameCount * mChannelCount); 3143 } 3144 3145 mBytesRemaining = mCurrentWriteLength; 3146 if (isSuspended()) { 3147 // Simulate write to HAL when suspended (e.g. BT SCO phone call). 3148 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer. 3149 const size_t framesRemaining = mBytesRemaining / mFrameSize; 3150 mBytesWritten += mBytesRemaining; 3151 mFramesWritten += framesRemaining; 3152 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position 3153 mBytesRemaining = 0; 3154 } 3155 3156 // only process effects if we're going to write 3157 if (mSleepTimeUs == 0 && mType != OFFLOAD) { 3158 for (size_t i = 0; i < effectChains.size(); i ++) { 3159 effectChains[i]->process_l(); 3160 } 3161 } 3162 } 3163 // Process effect chains for offloaded thread even if no audio 3164 // was read from audio track: process only updates effect state 3165 // and thus does have to be synchronized with audio writes but may have 3166 // to be called while waiting for async write callback 3167 if (mType == OFFLOAD) { 3168 for (size_t i = 0; i < effectChains.size(); i ++) { 3169 effectChains[i]->process_l(); 3170 } 3171 } 3172 3173 // Only if the Effects buffer is enabled and there is data in the 3174 // Effects buffer (buffer valid), we need to 3175 // copy into the sink buffer. 3176 // TODO use mSleepTimeUs == 0 as an additional condition. 3177 if (mEffectBufferValid) { 3178 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat); 3179 3180 if (requireMonoBlend()) { 3181 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount, 3182 true /*limit*/); 3183 } 3184 3185 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat, 3186 mNormalFrameCount * mChannelCount); 3187 } 3188 3189 // enable changes in effect chain 3190 unlockEffectChains(effectChains); 3191 3192 if (!waitingAsyncCallback()) { 3193 // mSleepTimeUs == 0 means we must write to audio hardware 3194 if (mSleepTimeUs == 0) { 3195 ssize_t ret = 0; 3196 // We save lastWriteFinished here, as previousLastWriteFinished, 3197 // for throttling. On thread start, previousLastWriteFinished will be 3198 // set to -1, which properly results in no throttling after the first write. 3199 nsecs_t previousLastWriteFinished = lastWriteFinished; 3200 nsecs_t delta = 0; 3201 if (mBytesRemaining) { 3202 // FIXME rewrite to reduce number of system calls 3203 mLastWriteTime = systemTime(); // also used for dumpsys 3204 ret = threadLoop_write(); 3205 lastWriteFinished = systemTime(); 3206 delta = lastWriteFinished - mLastWriteTime; 3207 if (ret < 0) { 3208 mBytesRemaining = 0; 3209 } else { 3210 mBytesWritten += ret; 3211 mBytesRemaining -= ret; 3212 mFramesWritten += ret / mFrameSize; 3213 } 3214 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 3215 (mMixerStatus == MIXER_DRAIN_ALL)) { 3216 threadLoop_drain(); 3217 } 3218 if (mType == MIXER && !mStandby) { 3219 // write blocked detection 3220 if (delta > maxPeriod) { 3221 mNumDelayedWrites++; 3222 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) { 3223 ATRACE_NAME("underrun"); 3224 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 3225 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this); 3226 lastWarning = lastWriteFinished; 3227 } 3228 } 3229 3230 if (mThreadThrottle 3231 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks) 3232 && ret > 0) { // we wrote something 3233 // Limit MixerThread data processing to no more than twice the 3234 // expected processing rate. 3235 // 3236 // This helps prevent underruns with NuPlayer and other applications 3237 // which may set up buffers that are close to the minimum size, or use 3238 // deep buffers, and rely on a double-buffering sleep strategy to fill. 3239 // 3240 // The throttle smooths out sudden large data drains from the device, 3241 // e.g. when it comes out of standby, which often causes problems with 3242 // (1) mixer threads without a fast mixer (which has its own warm-up) 3243 // (2) minimum buffer sized tracks (even if the track is full, 3244 // the app won't fill fast enough to handle the sudden draw). 3245 // 3246 // Total time spent in last processing cycle equals time spent in 3247 // 1. threadLoop_write, as well as time spent in 3248 // 2. threadLoop_mix (significant for heavy mixing, especially 3249 // on low tier processors) 3250 3251 // it's OK if deltaMs is an overestimate. 3252 const int32_t deltaMs = 3253 (lastWriteFinished - previousLastWriteFinished) / 1000000; 3254 const int32_t throttleMs = mHalfBufferMs - deltaMs; 3255 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) { 3256 usleep(throttleMs * 1000); 3257 // notify of throttle start on verbose log 3258 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs, 3259 "mixer(%p) throttle begin:" 3260 " ret(%zd) deltaMs(%d) requires sleep %d ms", 3261 this, ret, deltaMs, throttleMs); 3262 mThreadThrottleTimeMs += throttleMs; 3263 // Throttle must be attributed to the previous mixer loop's write time 3264 // to allow back-to-back throttling. 3265 lastWriteFinished += throttleMs * 1000000; 3266 } else { 3267 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs; 3268 if (diff > 0) { 3269 // notify of throttle end on debug log 3270 // but prevent spamming for bluetooth 3271 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()), 3272 "mixer(%p) throttle end: throttle time(%u)", this, diff); 3273 mThreadThrottleEndMs = mThreadThrottleTimeMs; 3274 } 3275 } 3276 } 3277 } 3278 3279 } else { 3280 ATRACE_BEGIN("sleep"); 3281 Mutex::Autolock _l(mLock); 3282 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) { 3283 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs)); 3284 } 3285 ATRACE_END(); 3286 } 3287 } 3288 3289 // Finally let go of removed track(s), without the lock held 3290 // since we can't guarantee the destructors won't acquire that 3291 // same lock. This will also mutate and push a new fast mixer state. 3292 threadLoop_removeTracks(tracksToRemove); 3293 tracksToRemove.clear(); 3294 3295 // FIXME I don't understand the need for this here; 3296 // it was in the original code but maybe the 3297 // assignment in saveOutputTracks() makes this unnecessary? 3298 clearOutputTracks(); 3299 3300 // Effect chains will be actually deleted here if they were removed from 3301 // mEffectChains list during mixing or effects processing 3302 effectChains.clear(); 3303 3304 // FIXME Note that the above .clear() is no longer necessary since effectChains 3305 // is now local to this block, but will keep it for now (at least until merge done). 3306 } 3307 3308 threadLoop_exit(); 3309 3310 if (!mStandby) { 3311 threadLoop_standby(); 3312 mStandby = true; 3313 } 3314 3315 releaseWakeLock(); 3316 3317 ALOGV("Thread %p type %d exiting", this, mType); 3318 return false; 3319} 3320 3321// removeTracks_l() must be called with ThreadBase::mLock held 3322void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 3323{ 3324 size_t count = tracksToRemove.size(); 3325 if (count > 0) { 3326 for (size_t i=0 ; i<count ; i++) { 3327 const sp<Track>& track = tracksToRemove.itemAt(i); 3328 mActiveTracks.remove(track); 3329 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 3330 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 3331 if (chain != 0) { 3332 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 3333 track->sessionId()); 3334 chain->decActiveTrackCnt(); 3335 } 3336 if (track->isTerminated()) { 3337 removeTrack_l(track); 3338 } else { // inactive but not terminated 3339 char buffer[256]; 3340 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */); 3341 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4); 3342 } 3343 } 3344 } 3345 3346} 3347 3348status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 3349{ 3350 if (mNormalSink != 0) { 3351 ExtendedTimestamp ets; 3352 status_t status = mNormalSink->getTimestamp(ets); 3353 if (status == NO_ERROR) { 3354 status = ets.getBestTimestamp(×tamp); 3355 } 3356 return status; 3357 } 3358 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) { 3359 uint64_t position64; 3360 if (mOutput->getPresentationPosition(&position64, ×tamp.mTime) == OK) { 3361 timestamp.mPosition = (uint32_t)position64; 3362 return NO_ERROR; 3363 } 3364 } 3365 return INVALID_OPERATION; 3366} 3367 3368status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch, 3369 audio_patch_handle_t *handle) 3370{ 3371 status_t status; 3372 if (property_get_bool("af.patch_park", false /* default_value */)) { 3373 // Park FastMixer to avoid potential DOS issues with writing to the HAL 3374 // or if HAL does not properly lock against access. 3375 AutoPark<FastMixer> park(mFastMixer); 3376 status = PlaybackThread::createAudioPatch_l(patch, handle); 3377 } else { 3378 status = PlaybackThread::createAudioPatch_l(patch, handle); 3379 } 3380 return status; 3381} 3382 3383status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch, 3384 audio_patch_handle_t *handle) 3385{ 3386 status_t status = NO_ERROR; 3387 3388 // store new device and send to effects 3389 audio_devices_t type = AUDIO_DEVICE_NONE; 3390 for (unsigned int i = 0; i < patch->num_sinks; i++) { 3391 type |= patch->sinks[i].ext.device.type; 3392 } 3393 3394#ifdef ADD_BATTERY_DATA 3395 // when changing the audio output device, call addBatteryData to notify 3396 // the change 3397 if (mOutDevice != type) { 3398 uint32_t params = 0; 3399 // check whether speaker is on 3400 if (type & AUDIO_DEVICE_OUT_SPEAKER) { 3401 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3402 } 3403 3404 audio_devices_t deviceWithoutSpeaker 3405 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3406 // check if any other device (except speaker) is on 3407 if (type & deviceWithoutSpeaker) { 3408 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3409 } 3410 3411 if (params != 0) { 3412 addBatteryData(params); 3413 } 3414 } 3415#endif 3416 3417 for (size_t i = 0; i < mEffectChains.size(); i++) { 3418 mEffectChains[i]->setDevice_l(type); 3419 } 3420 3421 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when 3422 // the thread is created so that the first patch creation triggers an ioConfigChanged callback 3423 bool configChanged = mPrevOutDevice != type; 3424 mOutDevice = type; 3425 mPatch = *patch; 3426 3427 if (mOutput->audioHwDev->supportsAudioPatches()) { 3428 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice(); 3429 status = hwDevice->createAudioPatch(patch->num_sources, 3430 patch->sources, 3431 patch->num_sinks, 3432 patch->sinks, 3433 handle); 3434 } else { 3435 char *address; 3436 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) { 3437 //FIXME: we only support address on first sink with HAL version < 3.0 3438 address = audio_device_address_to_parameter( 3439 patch->sinks[0].ext.device.type, 3440 patch->sinks[0].ext.device.address); 3441 } else { 3442 address = (char *)calloc(1, 1); 3443 } 3444 AudioParameter param = AudioParameter(String8(address)); 3445 free(address); 3446 param.addInt(String8(AudioParameter::keyRouting), (int)type); 3447 status = mOutput->stream->setParameters(param.toString()); 3448 *handle = AUDIO_PATCH_HANDLE_NONE; 3449 } 3450 if (configChanged) { 3451 mPrevOutDevice = type; 3452 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 3453 } 3454 return status; 3455} 3456 3457status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 3458{ 3459 status_t status; 3460 if (property_get_bool("af.patch_park", false /* default_value */)) { 3461 // Park FastMixer to avoid potential DOS issues with writing to the HAL 3462 // or if HAL does not properly lock against access. 3463 AutoPark<FastMixer> park(mFastMixer); 3464 status = PlaybackThread::releaseAudioPatch_l(handle); 3465 } else { 3466 status = PlaybackThread::releaseAudioPatch_l(handle); 3467 } 3468 return status; 3469} 3470 3471status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 3472{ 3473 status_t status = NO_ERROR; 3474 3475 mOutDevice = AUDIO_DEVICE_NONE; 3476 3477 if (mOutput->audioHwDev->supportsAudioPatches()) { 3478 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice(); 3479 status = hwDevice->releaseAudioPatch(handle); 3480 } else { 3481 AudioParameter param; 3482 param.addInt(String8(AudioParameter::keyRouting), 0); 3483 status = mOutput->stream->setParameters(param.toString()); 3484 } 3485 return status; 3486} 3487 3488void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track) 3489{ 3490 Mutex::Autolock _l(mLock); 3491 mTracks.add(track); 3492} 3493 3494void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track) 3495{ 3496 Mutex::Autolock _l(mLock); 3497 destroyTrack_l(track); 3498} 3499 3500void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config) 3501{ 3502 ThreadBase::getAudioPortConfig(config); 3503 config->role = AUDIO_PORT_ROLE_SOURCE; 3504 config->ext.mix.hw_module = mOutput->audioHwDev->handle(); 3505 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT; 3506} 3507 3508// ---------------------------------------------------------------------------- 3509 3510AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 3511 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type) 3512 : PlaybackThread(audioFlinger, output, id, device, type, systemReady), 3513 // mAudioMixer below 3514 // mFastMixer below 3515 mFastMixerFutex(0), 3516 mMasterMono(false) 3517 // mOutputSink below 3518 // mPipeSink below 3519 // mNormalSink below 3520{ 3521 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 3522 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, " 3523 "mFrameCount=%zu, mNormalFrameCount=%zu", 3524 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 3525 mNormalFrameCount); 3526 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3527 3528 if (type == DUPLICATING) { 3529 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks 3530 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write(). 3531 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink. 3532 return; 3533 } 3534 // create an NBAIO sink for the HAL output stream, and negotiate 3535 mOutputSink = new AudioStreamOutSink(output->stream); 3536 size_t numCounterOffers = 0; 3537 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 3538#if !LOG_NDEBUG 3539 ssize_t index = 3540#else 3541 (void) 3542#endif 3543 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 3544 ALOG_ASSERT(index == 0); 3545 3546 // initialize fast mixer depending on configuration 3547 bool initFastMixer; 3548 switch (kUseFastMixer) { 3549 case FastMixer_Never: 3550 initFastMixer = false; 3551 break; 3552 case FastMixer_Always: 3553 initFastMixer = true; 3554 break; 3555 case FastMixer_Static: 3556 case FastMixer_Dynamic: 3557 initFastMixer = mFrameCount < mNormalFrameCount; 3558 break; 3559 } 3560 if (initFastMixer) { 3561 audio_format_t fastMixerFormat; 3562 if (mMixerBufferEnabled && mEffectBufferEnabled) { 3563 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT; 3564 } else { 3565 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT; 3566 } 3567 if (mFormat != fastMixerFormat) { 3568 // change our Sink format to accept our intermediate precision 3569 mFormat = fastMixerFormat; 3570 free(mSinkBuffer); 3571 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 3572 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 3573 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 3574 } 3575 3576 // create a MonoPipe to connect our submix to FastMixer 3577 NBAIO_Format format = mOutputSink->format(); 3578#ifdef TEE_SINK 3579 NBAIO_Format origformat = format; 3580#endif 3581 // adjust format to match that of the Fast Mixer 3582 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat); 3583 format.mFormat = fastMixerFormat; 3584 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount; 3585 3586 // This pipe depth compensates for scheduling latency of the normal mixer thread. 3587 // When it wakes up after a maximum latency, it runs a few cycles quickly before 3588 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 3589 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 3590 const NBAIO_Format offers[1] = {format}; 3591 size_t numCounterOffers = 0; 3592#if !LOG_NDEBUG || defined(TEE_SINK) 3593 ssize_t index = 3594#else 3595 (void) 3596#endif 3597 monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 3598 ALOG_ASSERT(index == 0); 3599 monoPipe->setAvgFrames((mScreenState & 1) ? 3600 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 3601 mPipeSink = monoPipe; 3602 3603#ifdef TEE_SINK 3604 if (mTeeSinkOutputEnabled) { 3605 // create a Pipe to archive a copy of FastMixer's output for dumpsys 3606 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat); 3607 const NBAIO_Format offers2[1] = {origformat}; 3608 numCounterOffers = 0; 3609 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers); 3610 ALOG_ASSERT(index == 0); 3611 mTeeSink = teeSink; 3612 PipeReader *teeSource = new PipeReader(*teeSink); 3613 numCounterOffers = 0; 3614 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers); 3615 ALOG_ASSERT(index == 0); 3616 mTeeSource = teeSource; 3617 } 3618#endif 3619 3620 // create fast mixer and configure it initially with just one fast track for our submix 3621 mFastMixer = new FastMixer(); 3622 FastMixerStateQueue *sq = mFastMixer->sq(); 3623#ifdef STATE_QUEUE_DUMP 3624 sq->setObserverDump(&mStateQueueObserverDump); 3625 sq->setMutatorDump(&mStateQueueMutatorDump); 3626#endif 3627 FastMixerState *state = sq->begin(); 3628 FastTrack *fastTrack = &state->mFastTracks[0]; 3629 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 3630 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 3631 fastTrack->mVolumeProvider = NULL; 3632 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer 3633 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer 3634 fastTrack->mGeneration++; 3635 state->mFastTracksGen++; 3636 state->mTrackMask = 1; 3637 // fast mixer will use the HAL output sink 3638 state->mOutputSink = mOutputSink.get(); 3639 state->mOutputSinkGen++; 3640 state->mFrameCount = mFrameCount; 3641 state->mCommand = FastMixerState::COLD_IDLE; 3642 // already done in constructor initialization list 3643 //mFastMixerFutex = 0; 3644 state->mColdFutexAddr = &mFastMixerFutex; 3645 state->mColdGen++; 3646 state->mDumpState = &mFastMixerDumpState; 3647#ifdef TEE_SINK 3648 state->mTeeSink = mTeeSink.get(); 3649#endif 3650 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 3651 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 3652 sq->end(); 3653 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3654 3655 // start the fast mixer 3656 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 3657 pid_t tid = mFastMixer->getTid(); 3658 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 3659 stream()->setHalThreadPriority(kPriorityFastMixer); 3660 3661#ifdef AUDIO_WATCHDOG 3662 // create and start the watchdog 3663 mAudioWatchdog = new AudioWatchdog(); 3664 mAudioWatchdog->setDump(&mAudioWatchdogDump); 3665 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 3666 tid = mAudioWatchdog->getTid(); 3667 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 3668#endif 3669 3670 } 3671 3672 switch (kUseFastMixer) { 3673 case FastMixer_Never: 3674 case FastMixer_Dynamic: 3675 mNormalSink = mOutputSink; 3676 break; 3677 case FastMixer_Always: 3678 mNormalSink = mPipeSink; 3679 break; 3680 case FastMixer_Static: 3681 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 3682 break; 3683 } 3684} 3685 3686AudioFlinger::MixerThread::~MixerThread() 3687{ 3688 if (mFastMixer != 0) { 3689 FastMixerStateQueue *sq = mFastMixer->sq(); 3690 FastMixerState *state = sq->begin(); 3691 if (state->mCommand == FastMixerState::COLD_IDLE) { 3692 int32_t old = android_atomic_inc(&mFastMixerFutex); 3693 if (old == -1) { 3694 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3695 } 3696 } 3697 state->mCommand = FastMixerState::EXIT; 3698 sq->end(); 3699 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3700 mFastMixer->join(); 3701 // Though the fast mixer thread has exited, it's state queue is still valid. 3702 // We'll use that extract the final state which contains one remaining fast track 3703 // corresponding to our sub-mix. 3704 state = sq->begin(); 3705 ALOG_ASSERT(state->mTrackMask == 1); 3706 FastTrack *fastTrack = &state->mFastTracks[0]; 3707 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 3708 delete fastTrack->mBufferProvider; 3709 sq->end(false /*didModify*/); 3710 mFastMixer.clear(); 3711#ifdef AUDIO_WATCHDOG 3712 if (mAudioWatchdog != 0) { 3713 mAudioWatchdog->requestExit(); 3714 mAudioWatchdog->requestExitAndWait(); 3715 mAudioWatchdog.clear(); 3716 } 3717#endif 3718 } 3719 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 3720 delete mAudioMixer; 3721} 3722 3723 3724uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 3725{ 3726 if (mFastMixer != 0) { 3727 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 3728 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 3729 } 3730 return latency; 3731} 3732 3733 3734void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 3735{ 3736 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 3737} 3738 3739ssize_t AudioFlinger::MixerThread::threadLoop_write() 3740{ 3741 // FIXME we should only do one push per cycle; confirm this is true 3742 // Start the fast mixer if it's not already running 3743 if (mFastMixer != 0) { 3744 FastMixerStateQueue *sq = mFastMixer->sq(); 3745 FastMixerState *state = sq->begin(); 3746 if (state->mCommand != FastMixerState::MIX_WRITE && 3747 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 3748 if (state->mCommand == FastMixerState::COLD_IDLE) { 3749 3750 // FIXME workaround for first HAL write being CPU bound on some devices 3751 ATRACE_BEGIN("write"); 3752 mOutput->write((char *)mSinkBuffer, 0); 3753 ATRACE_END(); 3754 3755 int32_t old = android_atomic_inc(&mFastMixerFutex); 3756 if (old == -1) { 3757 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3758 } 3759#ifdef AUDIO_WATCHDOG 3760 if (mAudioWatchdog != 0) { 3761 mAudioWatchdog->resume(); 3762 } 3763#endif 3764 } 3765 state->mCommand = FastMixerState::MIX_WRITE; 3766#ifdef FAST_THREAD_STATISTICS 3767 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 3768 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN); 3769#endif 3770 sq->end(); 3771 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3772 if (kUseFastMixer == FastMixer_Dynamic) { 3773 mNormalSink = mPipeSink; 3774 } 3775 } else { 3776 sq->end(false /*didModify*/); 3777 } 3778 } 3779 return PlaybackThread::threadLoop_write(); 3780} 3781 3782void AudioFlinger::MixerThread::threadLoop_standby() 3783{ 3784 // Idle the fast mixer if it's currently running 3785 if (mFastMixer != 0) { 3786 FastMixerStateQueue *sq = mFastMixer->sq(); 3787 FastMixerState *state = sq->begin(); 3788 if (!(state->mCommand & FastMixerState::IDLE)) { 3789 // Report any frames trapped in the Monopipe 3790 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get(); 3791 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite(); 3792 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld " 3793 "monoPipeWritten:%lld monoPipeLeft:%lld", 3794 (long long)mFramesWritten, (long long)mSuspendedFrames, 3795 (long long)mPipeSink->framesWritten(), pipeFrames); 3796 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str()); 3797 3798 state->mCommand = FastMixerState::COLD_IDLE; 3799 state->mColdFutexAddr = &mFastMixerFutex; 3800 state->mColdGen++; 3801 mFastMixerFutex = 0; 3802 sq->end(); 3803 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 3804 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3805 if (kUseFastMixer == FastMixer_Dynamic) { 3806 mNormalSink = mOutputSink; 3807 } 3808#ifdef AUDIO_WATCHDOG 3809 if (mAudioWatchdog != 0) { 3810 mAudioWatchdog->pause(); 3811 } 3812#endif 3813 } else { 3814 sq->end(false /*didModify*/); 3815 } 3816 } 3817 PlaybackThread::threadLoop_standby(); 3818} 3819 3820bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 3821{ 3822 return false; 3823} 3824 3825bool AudioFlinger::PlaybackThread::shouldStandby_l() 3826{ 3827 return !mStandby; 3828} 3829 3830bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 3831{ 3832 Mutex::Autolock _l(mLock); 3833 return waitingAsyncCallback_l(); 3834} 3835 3836// shared by MIXER and DIRECT, overridden by DUPLICATING 3837void AudioFlinger::PlaybackThread::threadLoop_standby() 3838{ 3839 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 3840 mOutput->standby(); 3841 if (mUseAsyncWrite != 0) { 3842 // discard any pending drain or write ack by incrementing sequence 3843 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 3844 mDrainSequence = (mDrainSequence + 2) & ~1; 3845 ALOG_ASSERT(mCallbackThread != 0); 3846 mCallbackThread->setWriteBlocked(mWriteAckSequence); 3847 mCallbackThread->setDraining(mDrainSequence); 3848 } 3849 mHwPaused = false; 3850} 3851 3852void AudioFlinger::PlaybackThread::onAddNewTrack_l() 3853{ 3854 ALOGV("signal playback thread"); 3855 broadcast_l(); 3856} 3857 3858void AudioFlinger::PlaybackThread::onAsyncError() 3859{ 3860 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) { 3861 invalidateTracks((audio_stream_type_t)i); 3862 } 3863} 3864 3865void AudioFlinger::MixerThread::threadLoop_mix() 3866{ 3867 // mix buffers... 3868 mAudioMixer->process(); 3869 mCurrentWriteLength = mSinkBufferSize; 3870 // increase sleep time progressively when application underrun condition clears. 3871 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 3872 // that a steady state of alternating ready/not ready conditions keeps the sleep time 3873 // such that we would underrun the audio HAL. 3874 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) { 3875 sleepTimeShift--; 3876 } 3877 mSleepTimeUs = 0; 3878 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3879 //TODO: delay standby when effects have a tail 3880 3881} 3882 3883void AudioFlinger::MixerThread::threadLoop_sleepTime() 3884{ 3885 // If no tracks are ready, sleep once for the duration of an output 3886 // buffer size, then write 0s to the output 3887 if (mSleepTimeUs == 0) { 3888 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3889 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift; 3890 if (mSleepTimeUs < kMinThreadSleepTimeUs) { 3891 mSleepTimeUs = kMinThreadSleepTimeUs; 3892 } 3893 // reduce sleep time in case of consecutive application underruns to avoid 3894 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 3895 // duration we would end up writing less data than needed by the audio HAL if 3896 // the condition persists. 3897 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 3898 sleepTimeShift++; 3899 } 3900 } else { 3901 mSleepTimeUs = mIdleSleepTimeUs; 3902 } 3903 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 3904 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared 3905 // before effects processing or output. 3906 if (mMixerBufferValid) { 3907 memset(mMixerBuffer, 0, mMixerBufferSize); 3908 } else { 3909 memset(mSinkBuffer, 0, mSinkBufferSize); 3910 } 3911 mSleepTimeUs = 0; 3912 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 3913 "anticipated start"); 3914 } 3915 // TODO add standby time extension fct of effect tail 3916} 3917 3918// prepareTracks_l() must be called with ThreadBase::mLock held 3919AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 3920 Vector< sp<Track> > *tracksToRemove) 3921{ 3922 3923 mixer_state mixerStatus = MIXER_IDLE; 3924 // find out which tracks need to be processed 3925 size_t count = mActiveTracks.size(); 3926 size_t mixedTracks = 0; 3927 size_t tracksWithEffect = 0; 3928 // counts only _active_ fast tracks 3929 size_t fastTracks = 0; 3930 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 3931 3932 float masterVolume = mMasterVolume; 3933 bool masterMute = mMasterMute; 3934 3935 if (masterMute) { 3936 masterVolume = 0; 3937 } 3938 // Delegate master volume control to effect in output mix effect chain if needed 3939 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 3940 if (chain != 0) { 3941 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 3942 chain->setVolume_l(&v, &v); 3943 masterVolume = (float)((v + (1 << 23)) >> 24); 3944 chain.clear(); 3945 } 3946 3947 // prepare a new state to push 3948 FastMixerStateQueue *sq = NULL; 3949 FastMixerState *state = NULL; 3950 bool didModify = false; 3951 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 3952 if (mFastMixer != 0) { 3953 sq = mFastMixer->sq(); 3954 state = sq->begin(); 3955 } 3956 3957 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found. 3958 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found. 3959 3960 for (size_t i=0 ; i<count ; i++) { 3961 const sp<Track> t = mActiveTracks[i]; 3962 3963 // this const just means the local variable doesn't change 3964 Track* const track = t.get(); 3965 3966 // process fast tracks 3967 if (track->isFastTrack()) { 3968 3969 // It's theoretically possible (though unlikely) for a fast track to be created 3970 // and then removed within the same normal mix cycle. This is not a problem, as 3971 // the track never becomes active so it's fast mixer slot is never touched. 3972 // The converse, of removing an (active) track and then creating a new track 3973 // at the identical fast mixer slot within the same normal mix cycle, 3974 // is impossible because the slot isn't marked available until the end of each cycle. 3975 int j = track->mFastIndex; 3976 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks); 3977 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 3978 FastTrack *fastTrack = &state->mFastTracks[j]; 3979 3980 // Determine whether the track is currently in underrun condition, 3981 // and whether it had a recent underrun. 3982 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 3983 FastTrackUnderruns underruns = ftDump->mUnderruns; 3984 uint32_t recentFull = (underruns.mBitFields.mFull - 3985 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 3986 uint32_t recentPartial = (underruns.mBitFields.mPartial - 3987 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 3988 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 3989 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 3990 uint32_t recentUnderruns = recentPartial + recentEmpty; 3991 track->mObservedUnderruns = underruns; 3992 // don't count underruns that occur while stopping or pausing 3993 // or stopped which can occur when flush() is called while active 3994 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 3995 recentUnderruns > 0) { 3996 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 3997 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 3998 } else { 3999 track->mAudioTrackServerProxy->tallyUnderrunFrames(0); 4000 } 4001 4002 // This is similar to the state machine for normal tracks, 4003 // with a few modifications for fast tracks. 4004 bool isActive = true; 4005 switch (track->mState) { 4006 case TrackBase::STOPPING_1: 4007 // track stays active in STOPPING_1 state until first underrun 4008 if (recentUnderruns > 0 || track->isTerminated()) { 4009 track->mState = TrackBase::STOPPING_2; 4010 } 4011 break; 4012 case TrackBase::PAUSING: 4013 // ramp down is not yet implemented 4014 track->setPaused(); 4015 break; 4016 case TrackBase::RESUMING: 4017 // ramp up is not yet implemented 4018 track->mState = TrackBase::ACTIVE; 4019 break; 4020 case TrackBase::ACTIVE: 4021 if (recentFull > 0 || recentPartial > 0) { 4022 // track has provided at least some frames recently: reset retry count 4023 track->mRetryCount = kMaxTrackRetries; 4024 } 4025 if (recentUnderruns == 0) { 4026 // no recent underruns: stay active 4027 break; 4028 } 4029 // there has recently been an underrun of some kind 4030 if (track->sharedBuffer() == 0) { 4031 // were any of the recent underruns "empty" (no frames available)? 4032 if (recentEmpty == 0) { 4033 // no, then ignore the partial underruns as they are allowed indefinitely 4034 break; 4035 } 4036 // there has recently been an "empty" underrun: decrement the retry counter 4037 if (--(track->mRetryCount) > 0) { 4038 break; 4039 } 4040 // indicate to client process that the track was disabled because of underrun; 4041 // it will then automatically call start() when data is available 4042 track->disable(); 4043 // remove from active list, but state remains ACTIVE [confusing but true] 4044 isActive = false; 4045 break; 4046 } 4047 // fall through 4048 case TrackBase::STOPPING_2: 4049 case TrackBase::PAUSED: 4050 case TrackBase::STOPPED: 4051 case TrackBase::FLUSHED: // flush() while active 4052 // Check for presentation complete if track is inactive 4053 // We have consumed all the buffers of this track. 4054 // This would be incomplete if we auto-paused on underrun 4055 { 4056 uint32_t latency = 0; 4057 status_t result = mOutput->stream->getLatency(&latency); 4058 ALOGE_IF(result != OK, 4059 "Error when retrieving output stream latency: %d", result); 4060 size_t audioHALFrames = (latency * mSampleRate) / 1000; 4061 int64_t framesWritten = mBytesWritten / mFrameSize; 4062 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 4063 // track stays in active list until presentation is complete 4064 break; 4065 } 4066 } 4067 if (track->isStopping_2()) { 4068 track->mState = TrackBase::STOPPED; 4069 } 4070 if (track->isStopped()) { 4071 // Can't reset directly, as fast mixer is still polling this track 4072 // track->reset(); 4073 // So instead mark this track as needing to be reset after push with ack 4074 resetMask |= 1 << i; 4075 } 4076 isActive = false; 4077 break; 4078 case TrackBase::IDLE: 4079 default: 4080 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState); 4081 } 4082 4083 if (isActive) { 4084 // was it previously inactive? 4085 if (!(state->mTrackMask & (1 << j))) { 4086 ExtendedAudioBufferProvider *eabp = track; 4087 VolumeProvider *vp = track; 4088 fastTrack->mBufferProvider = eabp; 4089 fastTrack->mVolumeProvider = vp; 4090 fastTrack->mChannelMask = track->mChannelMask; 4091 fastTrack->mFormat = track->mFormat; 4092 fastTrack->mGeneration++; 4093 state->mTrackMask |= 1 << j; 4094 didModify = true; 4095 // no acknowledgement required for newly active tracks 4096 } 4097 // cache the combined master volume and stream type volume for fast mixer; this 4098 // lacks any synchronization or barrier so VolumeProvider may read a stale value 4099 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 4100 ++fastTracks; 4101 } else { 4102 // was it previously active? 4103 if (state->mTrackMask & (1 << j)) { 4104 fastTrack->mBufferProvider = NULL; 4105 fastTrack->mGeneration++; 4106 state->mTrackMask &= ~(1 << j); 4107 didModify = true; 4108 // If any fast tracks were removed, we must wait for acknowledgement 4109 // because we're about to decrement the last sp<> on those tracks. 4110 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 4111 } else { 4112 LOG_ALWAYS_FATAL("fast track %d should have been active; " 4113 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d", 4114 j, track->mState, state->mTrackMask, recentUnderruns, 4115 track->sharedBuffer() != 0); 4116 } 4117 tracksToRemove->add(track); 4118 // Avoids a misleading display in dumpsys 4119 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 4120 } 4121 continue; 4122 } 4123 4124 { // local variable scope to avoid goto warning 4125 4126 audio_track_cblk_t* cblk = track->cblk(); 4127 4128 // The first time a track is added we wait 4129 // for all its buffers to be filled before processing it 4130 int name = track->name(); 4131 // make sure that we have enough frames to mix one full buffer. 4132 // enforce this condition only once to enable draining the buffer in case the client 4133 // app does not call stop() and relies on underrun to stop: 4134 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 4135 // during last round 4136 size_t desiredFrames; 4137 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate(); 4138 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate(); 4139 4140 desiredFrames = sourceFramesNeededWithTimestretch( 4141 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed); 4142 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed. 4143 // add frames already consumed but not yet released by the resampler 4144 // because mAudioTrackServerProxy->framesReady() will include these frames 4145 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 4146 4147 uint32_t minFrames = 1; 4148 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 4149 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 4150 minFrames = desiredFrames; 4151 } 4152 4153 size_t framesReady = track->framesReady(); 4154 if (ATRACE_ENABLED()) { 4155 // I wish we had formatted trace names 4156 char traceName[16]; 4157 strcpy(traceName, "nRdy"); 4158 int name = track->name(); 4159 if (AudioMixer::TRACK0 <= name && 4160 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) { 4161 name -= AudioMixer::TRACK0; 4162 traceName[4] = (name / 10) + '0'; 4163 traceName[5] = (name % 10) + '0'; 4164 } else { 4165 traceName[4] = '?'; 4166 traceName[5] = '?'; 4167 } 4168 traceName[6] = '\0'; 4169 ATRACE_INT(traceName, framesReady); 4170 } 4171 if ((framesReady >= minFrames) && track->isReady() && 4172 !track->isPaused() && !track->isTerminated()) 4173 { 4174 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 4175 4176 mixedTracks++; 4177 4178 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means 4179 // there is an effect chain connected to the track 4180 chain.clear(); 4181 if (track->mainBuffer() != mSinkBuffer && 4182 track->mainBuffer() != mMixerBuffer) { 4183 if (mEffectBufferEnabled) { 4184 mEffectBufferValid = true; // Later can set directly. 4185 } 4186 chain = getEffectChain_l(track->sessionId()); 4187 // Delegate volume control to effect in track effect chain if needed 4188 if (chain != 0) { 4189 tracksWithEffect++; 4190 } else { 4191 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 4192 "session %d", 4193 name, track->sessionId()); 4194 } 4195 } 4196 4197 4198 int param = AudioMixer::VOLUME; 4199 if (track->mFillingUpStatus == Track::FS_FILLED) { 4200 // no ramp for the first volume setting 4201 track->mFillingUpStatus = Track::FS_ACTIVE; 4202 if (track->mState == TrackBase::RESUMING) { 4203 track->mState = TrackBase::ACTIVE; 4204 param = AudioMixer::RAMP_VOLUME; 4205 } 4206 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 4207 // FIXME should not make a decision based on mServer 4208 } else if (cblk->mServer != 0) { 4209 // If the track is stopped before the first frame was mixed, 4210 // do not apply ramp 4211 param = AudioMixer::RAMP_VOLUME; 4212 } 4213 4214 // compute volume for this track 4215 uint32_t vl, vr; // in U8.24 integer format 4216 float vlf, vrf, vaf; // in [0.0, 1.0] float format 4217 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 4218 vl = vr = 0; 4219 vlf = vrf = vaf = 0.; 4220 if (track->isPausing()) { 4221 track->setPaused(); 4222 } 4223 } else { 4224 4225 // read original volumes with volume control 4226 float typeVolume = mStreamTypes[track->streamType()].volume; 4227 float v = masterVolume * typeVolume; 4228 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy; 4229 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 4230 vlf = float_from_gain(gain_minifloat_unpack_left(vlr)); 4231 vrf = float_from_gain(gain_minifloat_unpack_right(vlr)); 4232 // track volumes come from shared memory, so can't be trusted and must be clamped 4233 if (vlf > GAIN_FLOAT_UNITY) { 4234 ALOGV("Track left volume out of range: %.3g", vlf); 4235 vlf = GAIN_FLOAT_UNITY; 4236 } 4237 if (vrf > GAIN_FLOAT_UNITY) { 4238 ALOGV("Track right volume out of range: %.3g", vrf); 4239 vrf = GAIN_FLOAT_UNITY; 4240 } 4241 // now apply the master volume and stream type volume 4242 vlf *= v; 4243 vrf *= v; 4244 // assuming master volume and stream type volume each go up to 1.0, 4245 // then derive vl and vr as U8.24 versions for the effect chain 4246 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT; 4247 vl = (uint32_t) (scaleto8_24 * vlf); 4248 vr = (uint32_t) (scaleto8_24 * vrf); 4249 // vl and vr are now in U8.24 format 4250 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 4251 // send level comes from shared memory and so may be corrupt 4252 if (sendLevel > MAX_GAIN_INT) { 4253 ALOGV("Track send level out of range: %04X", sendLevel); 4254 sendLevel = MAX_GAIN_INT; 4255 } 4256 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel 4257 vaf = v * sendLevel * (1. / MAX_GAIN_INT); 4258 } 4259 4260 // Delegate volume control to effect in track effect chain if needed 4261 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 4262 // Do not ramp volume if volume is controlled by effect 4263 param = AudioMixer::VOLUME; 4264 // Update remaining floating point volume levels 4265 vlf = (float)vl / (1 << 24); 4266 vrf = (float)vr / (1 << 24); 4267 track->mHasVolumeController = true; 4268 } else { 4269 // force no volume ramp when volume controller was just disabled or removed 4270 // from effect chain to avoid volume spike 4271 if (track->mHasVolumeController) { 4272 param = AudioMixer::VOLUME; 4273 } 4274 track->mHasVolumeController = false; 4275 } 4276 4277 // XXX: these things DON'T need to be done each time 4278 mAudioMixer->setBufferProvider(name, track); 4279 mAudioMixer->enable(name); 4280 4281 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf); 4282 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf); 4283 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf); 4284 mAudioMixer->setParameter( 4285 name, 4286 AudioMixer::TRACK, 4287 AudioMixer::FORMAT, (void *)track->format()); 4288 mAudioMixer->setParameter( 4289 name, 4290 AudioMixer::TRACK, 4291 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask()); 4292 mAudioMixer->setParameter( 4293 name, 4294 AudioMixer::TRACK, 4295 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask); 4296 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 4297 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX; 4298 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 4299 if (reqSampleRate == 0) { 4300 reqSampleRate = mSampleRate; 4301 } else if (reqSampleRate > maxSampleRate) { 4302 reqSampleRate = maxSampleRate; 4303 } 4304 mAudioMixer->setParameter( 4305 name, 4306 AudioMixer::RESAMPLE, 4307 AudioMixer::SAMPLE_RATE, 4308 (void *)(uintptr_t)reqSampleRate); 4309 4310 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate(); 4311 mAudioMixer->setParameter( 4312 name, 4313 AudioMixer::TIMESTRETCH, 4314 AudioMixer::PLAYBACK_RATE, 4315 &playbackRate); 4316 4317 /* 4318 * Select the appropriate output buffer for the track. 4319 * 4320 * Tracks with effects go into their own effects chain buffer 4321 * and from there into either mEffectBuffer or mSinkBuffer. 4322 * 4323 * Other tracks can use mMixerBuffer for higher precision 4324 * channel accumulation. If this buffer is enabled 4325 * (mMixerBufferEnabled true), then selected tracks will accumulate 4326 * into it. 4327 * 4328 */ 4329 if (mMixerBufferEnabled 4330 && (track->mainBuffer() == mSinkBuffer 4331 || track->mainBuffer() == mMixerBuffer)) { 4332 mAudioMixer->setParameter( 4333 name, 4334 AudioMixer::TRACK, 4335 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat); 4336 mAudioMixer->setParameter( 4337 name, 4338 AudioMixer::TRACK, 4339 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer); 4340 // TODO: override track->mainBuffer()? 4341 mMixerBufferValid = true; 4342 } else { 4343 mAudioMixer->setParameter( 4344 name, 4345 AudioMixer::TRACK, 4346 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT); 4347 mAudioMixer->setParameter( 4348 name, 4349 AudioMixer::TRACK, 4350 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 4351 } 4352 mAudioMixer->setParameter( 4353 name, 4354 AudioMixer::TRACK, 4355 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 4356 4357 // reset retry count 4358 track->mRetryCount = kMaxTrackRetries; 4359 4360 // If one track is ready, set the mixer ready if: 4361 // - the mixer was not ready during previous round OR 4362 // - no other track is not ready 4363 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 4364 mixerStatus != MIXER_TRACKS_ENABLED) { 4365 mixerStatus = MIXER_TRACKS_READY; 4366 } 4367 } else { 4368 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 4369 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)", 4370 track, framesReady, desiredFrames); 4371 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 4372 } else { 4373 track->mAudioTrackServerProxy->tallyUnderrunFrames(0); 4374 } 4375 4376 // clear effect chain input buffer if an active track underruns to avoid sending 4377 // previous audio buffer again to effects 4378 chain = getEffectChain_l(track->sessionId()); 4379 if (chain != 0) { 4380 chain->clearInputBuffer(); 4381 } 4382 4383 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 4384 if ((track->sharedBuffer() != 0) || track->isTerminated() || 4385 track->isStopped() || track->isPaused()) { 4386 // We have consumed all the buffers of this track. 4387 // Remove it from the list of active tracks. 4388 // TODO: use actual buffer filling status instead of latency when available from 4389 // audio HAL 4390 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 4391 int64_t framesWritten = mBytesWritten / mFrameSize; 4392 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 4393 if (track->isStopped()) { 4394 track->reset(); 4395 } 4396 tracksToRemove->add(track); 4397 } 4398 } else { 4399 // No buffers for this track. Give it a few chances to 4400 // fill a buffer, then remove it from active list. 4401 if (--(track->mRetryCount) <= 0) { 4402 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 4403 tracksToRemove->add(track); 4404 // indicate to client process that the track was disabled because of underrun; 4405 // it will then automatically call start() when data is available 4406 track->disable(); 4407 // If one track is not ready, mark the mixer also not ready if: 4408 // - the mixer was ready during previous round OR 4409 // - no other track is ready 4410 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 4411 mixerStatus != MIXER_TRACKS_READY) { 4412 mixerStatus = MIXER_TRACKS_ENABLED; 4413 } 4414 } 4415 mAudioMixer->disable(name); 4416 } 4417 4418 } // local variable scope to avoid goto warning 4419 4420 } 4421 4422 // Push the new FastMixer state if necessary 4423 bool pauseAudioWatchdog = false; 4424 if (didModify) { 4425 state->mFastTracksGen++; 4426 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 4427 if (kUseFastMixer == FastMixer_Dynamic && 4428 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 4429 state->mCommand = FastMixerState::COLD_IDLE; 4430 state->mColdFutexAddr = &mFastMixerFutex; 4431 state->mColdGen++; 4432 mFastMixerFutex = 0; 4433 if (kUseFastMixer == FastMixer_Dynamic) { 4434 mNormalSink = mOutputSink; 4435 } 4436 // If we go into cold idle, need to wait for acknowledgement 4437 // so that fast mixer stops doing I/O. 4438 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 4439 pauseAudioWatchdog = true; 4440 } 4441 } 4442 if (sq != NULL) { 4443 sq->end(didModify); 4444 sq->push(block); 4445 } 4446#ifdef AUDIO_WATCHDOG 4447 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 4448 mAudioWatchdog->pause(); 4449 } 4450#endif 4451 4452 // Now perform the deferred reset on fast tracks that have stopped 4453 while (resetMask != 0) { 4454 size_t i = __builtin_ctz(resetMask); 4455 ALOG_ASSERT(i < count); 4456 resetMask &= ~(1 << i); 4457 sp<Track> track = mActiveTracks[i]; 4458 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 4459 track->reset(); 4460 } 4461 4462 // remove all the tracks that need to be... 4463 removeTracks_l(*tracksToRemove); 4464 4465 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) { 4466 mEffectBufferValid = true; 4467 } 4468 4469 if (mEffectBufferValid) { 4470 // as long as there are effects we should clear the effects buffer, to avoid 4471 // passing a non-clean buffer to the effect chain 4472 memset(mEffectBuffer, 0, mEffectBufferSize); 4473 } 4474 // sink or mix buffer must be cleared if all tracks are connected to an 4475 // effect chain as in this case the mixer will not write to the sink or mix buffer 4476 // and track effects will accumulate into it 4477 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 4478 (mixedTracks == 0 && fastTracks > 0))) { 4479 // FIXME as a performance optimization, should remember previous zero status 4480 if (mMixerBufferValid) { 4481 memset(mMixerBuffer, 0, mMixerBufferSize); 4482 // TODO: In testing, mSinkBuffer below need not be cleared because 4483 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer 4484 // after mixing. 4485 // 4486 // To enforce this guarantee: 4487 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 4488 // (mixedTracks == 0 && fastTracks > 0)) 4489 // must imply MIXER_TRACKS_READY. 4490 // Later, we may clear buffers regardless, and skip much of this logic. 4491 } 4492 // FIXME as a performance optimization, should remember previous zero status 4493 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize); 4494 } 4495 4496 // if any fast tracks, then status is ready 4497 mMixerStatusIgnoringFastTracks = mixerStatus; 4498 if (fastTracks > 0) { 4499 mixerStatus = MIXER_TRACKS_READY; 4500 } 4501 return mixerStatus; 4502} 4503 4504// trackCountForUid_l() must be called with ThreadBase::mLock held 4505uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) 4506{ 4507 uint32_t trackCount = 0; 4508 for (size_t i = 0; i < mTracks.size() ; i++) { 4509 if (mTracks[i]->uid() == uid) { 4510 trackCount++; 4511 } 4512 } 4513 return trackCount; 4514} 4515 4516// getTrackName_l() must be called with ThreadBase::mLock held 4517int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, 4518 audio_format_t format, audio_session_t sessionId, uid_t uid) 4519{ 4520 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) { 4521 return -1; 4522 } 4523 return mAudioMixer->getTrackName(channelMask, format, sessionId); 4524} 4525 4526// deleteTrackName_l() must be called with ThreadBase::mLock held 4527void AudioFlinger::MixerThread::deleteTrackName_l(int name) 4528{ 4529 ALOGV("remove track (%d) and delete from mixer", name); 4530 mAudioMixer->deleteTrackName(name); 4531} 4532 4533// checkForNewParameter_l() must be called with ThreadBase::mLock held 4534bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair, 4535 status_t& status) 4536{ 4537 bool reconfig = false; 4538 bool a2dpDeviceChanged = false; 4539 4540 status = NO_ERROR; 4541 4542 AutoPark<FastMixer> park(mFastMixer); 4543 4544 AudioParameter param = AudioParameter(keyValuePair); 4545 int value; 4546 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4547 reconfig = true; 4548 } 4549 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4550 if (!isValidPcmSinkFormat((audio_format_t) value)) { 4551 status = BAD_VALUE; 4552 } else { 4553 // no need to save value, since it's constant 4554 reconfig = true; 4555 } 4556 } 4557 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4558 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) { 4559 status = BAD_VALUE; 4560 } else { 4561 // no need to save value, since it's constant 4562 reconfig = true; 4563 } 4564 } 4565 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4566 // do not accept frame count changes if tracks are open as the track buffer 4567 // size depends on frame count and correct behavior would not be guaranteed 4568 // if frame count is changed after track creation 4569 if (!mTracks.isEmpty()) { 4570 status = INVALID_OPERATION; 4571 } else { 4572 reconfig = true; 4573 } 4574 } 4575 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4576#ifdef ADD_BATTERY_DATA 4577 // when changing the audio output device, call addBatteryData to notify 4578 // the change 4579 if (mOutDevice != value) { 4580 uint32_t params = 0; 4581 // check whether speaker is on 4582 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 4583 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 4584 } 4585 4586 audio_devices_t deviceWithoutSpeaker 4587 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 4588 // check if any other device (except speaker) is on 4589 if (value & deviceWithoutSpeaker) { 4590 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 4591 } 4592 4593 if (params != 0) { 4594 addBatteryData(params); 4595 } 4596 } 4597#endif 4598 4599 // forward device change to effects that have requested to be 4600 // aware of attached audio device. 4601 if (value != AUDIO_DEVICE_NONE) { 4602 a2dpDeviceChanged = 4603 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP); 4604 mOutDevice = value; 4605 for (size_t i = 0; i < mEffectChains.size(); i++) { 4606 mEffectChains[i]->setDevice_l(mOutDevice); 4607 } 4608 } 4609 } 4610 4611 if (status == NO_ERROR) { 4612 status = mOutput->stream->setParameters(keyValuePair); 4613 if (!mStandby && status == INVALID_OPERATION) { 4614 mOutput->standby(); 4615 mStandby = true; 4616 mBytesWritten = 0; 4617 status = mOutput->stream->setParameters(keyValuePair); 4618 } 4619 if (status == NO_ERROR && reconfig) { 4620 readOutputParameters_l(); 4621 delete mAudioMixer; 4622 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 4623 for (size_t i = 0; i < mTracks.size() ; i++) { 4624 int name = getTrackName_l(mTracks[i]->mChannelMask, 4625 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid()); 4626 if (name < 0) { 4627 break; 4628 } 4629 mTracks[i]->mName = name; 4630 } 4631 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 4632 } 4633 } 4634 4635 return reconfig || a2dpDeviceChanged; 4636} 4637 4638 4639void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 4640{ 4641 PlaybackThread::dumpInternals(fd, args); 4642 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs); 4643 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames()); 4644 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off"); 4645 4646 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 4647 // while we are dumping it. It may be inconsistent, but it won't mutate! 4648 // This is a large object so we place it on the heap. 4649 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages. 4650 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState); 4651 copy->dump(fd); 4652 delete copy; 4653 4654#ifdef STATE_QUEUE_DUMP 4655 // Similar for state queue 4656 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 4657 observerCopy.dump(fd); 4658 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 4659 mutatorCopy.dump(fd); 4660#endif 4661 4662#ifdef TEE_SINK 4663 // Write the tee output to a .wav file 4664 dumpTee(fd, mTeeSource, mId); 4665#endif 4666 4667#ifdef AUDIO_WATCHDOG 4668 if (mAudioWatchdog != 0) { 4669 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 4670 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 4671 wdCopy.dump(fd); 4672 } 4673#endif 4674} 4675 4676uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 4677{ 4678 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 4679} 4680 4681uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 4682{ 4683 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 4684} 4685 4686void AudioFlinger::MixerThread::cacheParameters_l() 4687{ 4688 PlaybackThread::cacheParameters_l(); 4689 4690 // FIXME: Relaxed timing because of a certain device that can't meet latency 4691 // Should be reduced to 2x after the vendor fixes the driver issue 4692 // increase threshold again due to low power audio mode. The way this warning 4693 // threshold is calculated and its usefulness should be reconsidered anyway. 4694 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 4695} 4696 4697// ---------------------------------------------------------------------------- 4698 4699AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4700 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady) 4701 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady) 4702 // mLeftVolFloat, mRightVolFloat 4703{ 4704} 4705 4706AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4707 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 4708 ThreadBase::type_t type, bool systemReady) 4709 : PlaybackThread(audioFlinger, output, id, device, type, systemReady) 4710 // mLeftVolFloat, mRightVolFloat 4711{ 4712} 4713 4714AudioFlinger::DirectOutputThread::~DirectOutputThread() 4715{ 4716} 4717 4718void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 4719{ 4720 float left, right; 4721 4722 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 4723 left = right = 0; 4724 } else { 4725 float typeVolume = mStreamTypes[track->streamType()].volume; 4726 float v = mMasterVolume * typeVolume; 4727 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy; 4728 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 4729 left = float_from_gain(gain_minifloat_unpack_left(vlr)); 4730 if (left > GAIN_FLOAT_UNITY) { 4731 left = GAIN_FLOAT_UNITY; 4732 } 4733 left *= v; 4734 right = float_from_gain(gain_minifloat_unpack_right(vlr)); 4735 if (right > GAIN_FLOAT_UNITY) { 4736 right = GAIN_FLOAT_UNITY; 4737 } 4738 right *= v; 4739 } 4740 4741 if (lastTrack) { 4742 if (left != mLeftVolFloat || right != mRightVolFloat) { 4743 mLeftVolFloat = left; 4744 mRightVolFloat = right; 4745 4746 // Convert volumes from float to 8.24 4747 uint32_t vl = (uint32_t)(left * (1 << 24)); 4748 uint32_t vr = (uint32_t)(right * (1 << 24)); 4749 4750 // Delegate volume control to effect in track effect chain if needed 4751 // only one effect chain can be present on DirectOutputThread, so if 4752 // there is one, the track is connected to it 4753 if (!mEffectChains.isEmpty()) { 4754 mEffectChains[0]->setVolume_l(&vl, &vr); 4755 left = (float)vl / (1 << 24); 4756 right = (float)vr / (1 << 24); 4757 } 4758 status_t result = mOutput->stream->setVolume(left, right); 4759 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result); 4760 } 4761 } 4762} 4763 4764void AudioFlinger::DirectOutputThread::onAddNewTrack_l() 4765{ 4766 sp<Track> previousTrack = mPreviousTrack.promote(); 4767 sp<Track> latestTrack = mActiveTracks.getLatest(); 4768 4769 if (previousTrack != 0 && latestTrack != 0) { 4770 if (mType == DIRECT) { 4771 if (previousTrack.get() != latestTrack.get()) { 4772 mFlushPending = true; 4773 } 4774 } else /* mType == OFFLOAD */ { 4775 if (previousTrack->sessionId() != latestTrack->sessionId()) { 4776 mFlushPending = true; 4777 } 4778 } 4779 } 4780 PlaybackThread::onAddNewTrack_l(); 4781} 4782 4783AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 4784 Vector< sp<Track> > *tracksToRemove 4785) 4786{ 4787 size_t count = mActiveTracks.size(); 4788 mixer_state mixerStatus = MIXER_IDLE; 4789 bool doHwPause = false; 4790 bool doHwResume = false; 4791 4792 // find out which tracks need to be processed 4793 for (const sp<Track> &t : mActiveTracks) { 4794 if (t->isInvalid()) { 4795 ALOGW("An invalidated track shouldn't be in active list"); 4796 tracksToRemove->add(t); 4797 continue; 4798 } 4799 4800 Track* const track = t.get(); 4801#ifdef VERY_VERY_VERBOSE_LOGGING 4802 audio_track_cblk_t* cblk = track->cblk(); 4803#endif 4804 // Only consider last track started for volume and mixer state control. 4805 // In theory an older track could underrun and restart after the new one starts 4806 // but as we only care about the transition phase between two tracks on a 4807 // direct output, it is not a problem to ignore the underrun case. 4808 sp<Track> l = mActiveTracks.getLatest(); 4809 bool last = l.get() == track; 4810 4811 if (track->isPausing()) { 4812 track->setPaused(); 4813 if (mHwSupportsPause && last && !mHwPaused) { 4814 doHwPause = true; 4815 mHwPaused = true; 4816 } 4817 tracksToRemove->add(track); 4818 } else if (track->isFlushPending()) { 4819 track->flushAck(); 4820 if (last) { 4821 mFlushPending = true; 4822 } 4823 } else if (track->isResumePending()) { 4824 track->resumeAck(); 4825 if (last) { 4826 mLeftVolFloat = mRightVolFloat = -1.0; 4827 if (mHwPaused) { 4828 doHwResume = true; 4829 mHwPaused = false; 4830 } 4831 } 4832 } 4833 4834 // The first time a track is added we wait 4835 // for all its buffers to be filled before processing it. 4836 // Allow draining the buffer in case the client 4837 // app does not call stop() and relies on underrun to stop: 4838 // hence the test on (track->mRetryCount > 1). 4839 // If retryCount<=1 then track is about to underrun and be removed. 4840 // Do not use a high threshold for compressed audio. 4841 uint32_t minFrames; 4842 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing() 4843 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) { 4844 minFrames = mNormalFrameCount; 4845 } else { 4846 minFrames = 1; 4847 } 4848 4849 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() && 4850 !track->isStopping_2() && !track->isStopped()) 4851 { 4852 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 4853 4854 if (track->mFillingUpStatus == Track::FS_FILLED) { 4855 track->mFillingUpStatus = Track::FS_ACTIVE; 4856 if (last) { 4857 // make sure processVolume_l() will apply new volume even if 0 4858 mLeftVolFloat = mRightVolFloat = -1.0; 4859 } 4860 if (!mHwSupportsPause) { 4861 track->resumeAck(); 4862 } 4863 } 4864 4865 // compute volume for this track 4866 processVolume_l(track, last); 4867 if (last) { 4868 sp<Track> previousTrack = mPreviousTrack.promote(); 4869 if (previousTrack != 0) { 4870 if (track != previousTrack.get()) { 4871 // Flush any data still being written from last track 4872 mBytesRemaining = 0; 4873 // Invalidate previous track to force a seek when resuming. 4874 previousTrack->invalidate(); 4875 } 4876 } 4877 mPreviousTrack = track; 4878 4879 // reset retry count 4880 track->mRetryCount = kMaxTrackRetriesDirect; 4881 mActiveTrack = t; 4882 mixerStatus = MIXER_TRACKS_READY; 4883 if (mHwPaused) { 4884 doHwResume = true; 4885 mHwPaused = false; 4886 } 4887 } 4888 } else { 4889 // clear effect chain input buffer if the last active track started underruns 4890 // to avoid sending previous audio buffer again to effects 4891 if (!mEffectChains.isEmpty() && last) { 4892 mEffectChains[0]->clearInputBuffer(); 4893 } 4894 if (track->isStopping_1()) { 4895 track->mState = TrackBase::STOPPING_2; 4896 if (last && mHwPaused) { 4897 doHwResume = true; 4898 mHwPaused = false; 4899 } 4900 } 4901 if ((track->sharedBuffer() != 0) || track->isStopped() || 4902 track->isStopping_2() || track->isPaused()) { 4903 // We have consumed all the buffers of this track. 4904 // Remove it from the list of active tracks. 4905 size_t audioHALFrames; 4906 if (audio_has_proportional_frames(mFormat)) { 4907 audioHALFrames = (latency_l() * mSampleRate) / 1000; 4908 } else { 4909 audioHALFrames = 0; 4910 } 4911 4912 int64_t framesWritten = mBytesWritten / mFrameSize; 4913 if (mStandby || !last || 4914 track->presentationComplete(framesWritten, audioHALFrames)) { 4915 if (track->isStopping_2()) { 4916 track->mState = TrackBase::STOPPED; 4917 } 4918 if (track->isStopped()) { 4919 track->reset(); 4920 } 4921 tracksToRemove->add(track); 4922 } 4923 } else { 4924 // No buffers for this track. Give it a few chances to 4925 // fill a buffer, then remove it from active list. 4926 // Only consider last track started for mixer state control 4927 if (--(track->mRetryCount) <= 0) { 4928 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 4929 tracksToRemove->add(track); 4930 // indicate to client process that the track was disabled because of underrun; 4931 // it will then automatically call start() when data is available 4932 track->disable(); 4933 } else if (last) { 4934 ALOGW("pause because of UNDERRUN, framesReady = %zu," 4935 "minFrames = %u, mFormat = %#x", 4936 track->framesReady(), minFrames, mFormat); 4937 mixerStatus = MIXER_TRACKS_ENABLED; 4938 if (mHwSupportsPause && !mHwPaused && !mStandby) { 4939 doHwPause = true; 4940 mHwPaused = true; 4941 } 4942 } 4943 } 4944 } 4945 } 4946 4947 // if an active track did not command a flush, check for pending flush on stopped tracks 4948 if (!mFlushPending) { 4949 for (size_t i = 0; i < mTracks.size(); i++) { 4950 if (mTracks[i]->isFlushPending()) { 4951 mTracks[i]->flushAck(); 4952 mFlushPending = true; 4953 } 4954 } 4955 } 4956 4957 // make sure the pause/flush/resume sequence is executed in the right order. 4958 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 4959 // before flush and then resume HW. This can happen in case of pause/flush/resume 4960 // if resume is received before pause is executed. 4961 if (mHwSupportsPause && !mStandby && 4962 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 4963 status_t result = mOutput->stream->pause(); 4964 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result); 4965 } 4966 if (mFlushPending) { 4967 flushHw_l(); 4968 } 4969 if (mHwSupportsPause && !mStandby && doHwResume) { 4970 status_t result = mOutput->stream->resume(); 4971 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result); 4972 } 4973 // remove all the tracks that need to be... 4974 removeTracks_l(*tracksToRemove); 4975 4976 return mixerStatus; 4977} 4978 4979void AudioFlinger::DirectOutputThread::threadLoop_mix() 4980{ 4981 size_t frameCount = mFrameCount; 4982 int8_t *curBuf = (int8_t *)mSinkBuffer; 4983 // output audio to hardware 4984 while (frameCount) { 4985 AudioBufferProvider::Buffer buffer; 4986 buffer.frameCount = frameCount; 4987 status_t status = mActiveTrack->getNextBuffer(&buffer); 4988 if (status != NO_ERROR || buffer.raw == NULL) { 4989 // no need to pad with 0 for compressed audio 4990 if (audio_has_proportional_frames(mFormat)) { 4991 memset(curBuf, 0, frameCount * mFrameSize); 4992 } 4993 break; 4994 } 4995 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 4996 frameCount -= buffer.frameCount; 4997 curBuf += buffer.frameCount * mFrameSize; 4998 mActiveTrack->releaseBuffer(&buffer); 4999 } 5000 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer; 5001 mSleepTimeUs = 0; 5002 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5003 mActiveTrack.clear(); 5004} 5005 5006void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 5007{ 5008 // do not write to HAL when paused 5009 if (mHwPaused || (usesHwAvSync() && mStandby)) { 5010 mSleepTimeUs = mIdleSleepTimeUs; 5011 return; 5012 } 5013 if (mSleepTimeUs == 0) { 5014 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5015 mSleepTimeUs = mActiveSleepTimeUs; 5016 } else { 5017 mSleepTimeUs = mIdleSleepTimeUs; 5018 } 5019 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) { 5020 memset(mSinkBuffer, 0, mFrameCount * mFrameSize); 5021 mSleepTimeUs = 0; 5022 } 5023} 5024 5025void AudioFlinger::DirectOutputThread::threadLoop_exit() 5026{ 5027 { 5028 Mutex::Autolock _l(mLock); 5029 for (size_t i = 0; i < mTracks.size(); i++) { 5030 if (mTracks[i]->isFlushPending()) { 5031 mTracks[i]->flushAck(); 5032 mFlushPending = true; 5033 } 5034 } 5035 if (mFlushPending) { 5036 flushHw_l(); 5037 } 5038 } 5039 PlaybackThread::threadLoop_exit(); 5040} 5041 5042// must be called with thread mutex locked 5043bool AudioFlinger::DirectOutputThread::shouldStandby_l() 5044{ 5045 bool trackPaused = false; 5046 bool trackStopped = false; 5047 5048 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) { 5049 return !mStandby; 5050 } 5051 5052 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 5053 // after a timeout and we will enter standby then. 5054 if (mTracks.size() > 0) { 5055 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 5056 trackStopped = mTracks[mTracks.size() - 1]->isStopped() || 5057 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE; 5058 } 5059 5060 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped)); 5061} 5062 5063// getTrackName_l() must be called with ThreadBase::mLock held 5064int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 5065 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid) 5066{ 5067 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) { 5068 return -1; 5069 } 5070 return 0; 5071} 5072 5073// deleteTrackName_l() must be called with ThreadBase::mLock held 5074void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 5075{ 5076} 5077 5078// checkForNewParameter_l() must be called with ThreadBase::mLock held 5079bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair, 5080 status_t& status) 5081{ 5082 bool reconfig = false; 5083 bool a2dpDeviceChanged = false; 5084 5085 status = NO_ERROR; 5086 5087 AudioParameter param = AudioParameter(keyValuePair); 5088 int value; 5089 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 5090 // forward device change to effects that have requested to be 5091 // aware of attached audio device. 5092 if (value != AUDIO_DEVICE_NONE) { 5093 a2dpDeviceChanged = 5094 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP); 5095 mOutDevice = value; 5096 for (size_t i = 0; i < mEffectChains.size(); i++) { 5097 mEffectChains[i]->setDevice_l(mOutDevice); 5098 } 5099 } 5100 } 5101 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 5102 // do not accept frame count changes if tracks are open as the track buffer 5103 // size depends on frame count and correct behavior would not be garantied 5104 // if frame count is changed after track creation 5105 if (!mTracks.isEmpty()) { 5106 status = INVALID_OPERATION; 5107 } else { 5108 reconfig = true; 5109 } 5110 } 5111 if (status == NO_ERROR) { 5112 status = mOutput->stream->setParameters(keyValuePair); 5113 if (!mStandby && status == INVALID_OPERATION) { 5114 mOutput->standby(); 5115 mStandby = true; 5116 mBytesWritten = 0; 5117 status = mOutput->stream->setParameters(keyValuePair); 5118 } 5119 if (status == NO_ERROR && reconfig) { 5120 readOutputParameters_l(); 5121 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 5122 } 5123 } 5124 5125 return reconfig || a2dpDeviceChanged; 5126} 5127 5128uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 5129{ 5130 uint32_t time; 5131 if (audio_has_proportional_frames(mFormat)) { 5132 time = PlaybackThread::activeSleepTimeUs(); 5133 } else { 5134 time = kDirectMinSleepTimeUs; 5135 } 5136 return time; 5137} 5138 5139uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 5140{ 5141 uint32_t time; 5142 if (audio_has_proportional_frames(mFormat)) { 5143 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 5144 } else { 5145 time = kDirectMinSleepTimeUs; 5146 } 5147 return time; 5148} 5149 5150uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 5151{ 5152 uint32_t time; 5153 if (audio_has_proportional_frames(mFormat)) { 5154 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 5155 } else { 5156 time = kDirectMinSleepTimeUs; 5157 } 5158 return time; 5159} 5160 5161void AudioFlinger::DirectOutputThread::cacheParameters_l() 5162{ 5163 PlaybackThread::cacheParameters_l(); 5164 5165 // use shorter standby delay as on normal output to release 5166 // hardware resources as soon as possible 5167 // no delay on outputs with HW A/V sync 5168 if (usesHwAvSync()) { 5169 mStandbyDelayNs = 0; 5170 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) { 5171 mStandbyDelayNs = kOffloadStandbyDelayNs; 5172 } else { 5173 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2); 5174 } 5175} 5176 5177void AudioFlinger::DirectOutputThread::flushHw_l() 5178{ 5179 mOutput->flush(); 5180 mHwPaused = false; 5181 mFlushPending = false; 5182} 5183 5184// ---------------------------------------------------------------------------- 5185 5186AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 5187 const wp<AudioFlinger::PlaybackThread>& playbackThread) 5188 : Thread(false /*canCallJava*/), 5189 mPlaybackThread(playbackThread), 5190 mWriteAckSequence(0), 5191 mDrainSequence(0), 5192 mAsyncError(false) 5193{ 5194} 5195 5196AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 5197{ 5198} 5199 5200void AudioFlinger::AsyncCallbackThread::onFirstRef() 5201{ 5202 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 5203} 5204 5205bool AudioFlinger::AsyncCallbackThread::threadLoop() 5206{ 5207 while (!exitPending()) { 5208 uint32_t writeAckSequence; 5209 uint32_t drainSequence; 5210 bool asyncError; 5211 5212 { 5213 Mutex::Autolock _l(mLock); 5214 while (!((mWriteAckSequence & 1) || 5215 (mDrainSequence & 1) || 5216 mAsyncError || 5217 exitPending())) { 5218 mWaitWorkCV.wait(mLock); 5219 } 5220 5221 if (exitPending()) { 5222 break; 5223 } 5224 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 5225 mWriteAckSequence, mDrainSequence); 5226 writeAckSequence = mWriteAckSequence; 5227 mWriteAckSequence &= ~1; 5228 drainSequence = mDrainSequence; 5229 mDrainSequence &= ~1; 5230 asyncError = mAsyncError; 5231 mAsyncError = false; 5232 } 5233 { 5234 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 5235 if (playbackThread != 0) { 5236 if (writeAckSequence & 1) { 5237 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 5238 } 5239 if (drainSequence & 1) { 5240 playbackThread->resetDraining(drainSequence >> 1); 5241 } 5242 if (asyncError) { 5243 playbackThread->onAsyncError(); 5244 } 5245 } 5246 } 5247 } 5248 return false; 5249} 5250 5251void AudioFlinger::AsyncCallbackThread::exit() 5252{ 5253 ALOGV("AsyncCallbackThread::exit"); 5254 Mutex::Autolock _l(mLock); 5255 requestExit(); 5256 mWaitWorkCV.broadcast(); 5257} 5258 5259void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 5260{ 5261 Mutex::Autolock _l(mLock); 5262 // bit 0 is cleared 5263 mWriteAckSequence = sequence << 1; 5264} 5265 5266void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 5267{ 5268 Mutex::Autolock _l(mLock); 5269 // ignore unexpected callbacks 5270 if (mWriteAckSequence & 2) { 5271 mWriteAckSequence |= 1; 5272 mWaitWorkCV.signal(); 5273 } 5274} 5275 5276void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 5277{ 5278 Mutex::Autolock _l(mLock); 5279 // bit 0 is cleared 5280 mDrainSequence = sequence << 1; 5281} 5282 5283void AudioFlinger::AsyncCallbackThread::resetDraining() 5284{ 5285 Mutex::Autolock _l(mLock); 5286 // ignore unexpected callbacks 5287 if (mDrainSequence & 2) { 5288 mDrainSequence |= 1; 5289 mWaitWorkCV.signal(); 5290 } 5291} 5292 5293void AudioFlinger::AsyncCallbackThread::setAsyncError() 5294{ 5295 Mutex::Autolock _l(mLock); 5296 mAsyncError = true; 5297 mWaitWorkCV.signal(); 5298} 5299 5300 5301// ---------------------------------------------------------------------------- 5302AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 5303 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady) 5304 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady), 5305 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true), 5306 mOffloadUnderrunPosition(~0LL) 5307{ 5308 //FIXME: mStandby should be set to true by ThreadBase constructor 5309 mStandby = true; 5310 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */); 5311} 5312 5313void AudioFlinger::OffloadThread::threadLoop_exit() 5314{ 5315 if (mFlushPending || mHwPaused) { 5316 // If a flush is pending or track was paused, just discard buffered data 5317 flushHw_l(); 5318 } else { 5319 mMixerStatus = MIXER_DRAIN_ALL; 5320 threadLoop_drain(); 5321 } 5322 if (mUseAsyncWrite) { 5323 ALOG_ASSERT(mCallbackThread != 0); 5324 mCallbackThread->exit(); 5325 } 5326 PlaybackThread::threadLoop_exit(); 5327} 5328 5329AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 5330 Vector< sp<Track> > *tracksToRemove 5331) 5332{ 5333 size_t count = mActiveTracks.size(); 5334 5335 mixer_state mixerStatus = MIXER_IDLE; 5336 bool doHwPause = false; 5337 bool doHwResume = false; 5338 5339 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count); 5340 5341 // find out which tracks need to be processed 5342 for (const sp<Track> &t : mActiveTracks) { 5343 Track* const track = t.get(); 5344#ifdef VERY_VERY_VERBOSE_LOGGING 5345 audio_track_cblk_t* cblk = track->cblk(); 5346#endif 5347 // Only consider last track started for volume and mixer state control. 5348 // In theory an older track could underrun and restart after the new one starts 5349 // but as we only care about the transition phase between two tracks on a 5350 // direct output, it is not a problem to ignore the underrun case. 5351 sp<Track> l = mActiveTracks.getLatest(); 5352 bool last = l.get() == track; 5353 5354 if (track->isInvalid()) { 5355 ALOGW("An invalidated track shouldn't be in active list"); 5356 tracksToRemove->add(track); 5357 continue; 5358 } 5359 5360 if (track->mState == TrackBase::IDLE) { 5361 ALOGW("An idle track shouldn't be in active list"); 5362 continue; 5363 } 5364 5365 if (track->isPausing()) { 5366 track->setPaused(); 5367 if (last) { 5368 if (mHwSupportsPause && !mHwPaused) { 5369 doHwPause = true; 5370 mHwPaused = true; 5371 } 5372 // If we were part way through writing the mixbuffer to 5373 // the HAL we must save this until we resume 5374 // BUG - this will be wrong if a different track is made active, 5375 // in that case we want to discard the pending data in the 5376 // mixbuffer and tell the client to present it again when the 5377 // track is resumed 5378 mPausedWriteLength = mCurrentWriteLength; 5379 mPausedBytesRemaining = mBytesRemaining; 5380 mBytesRemaining = 0; // stop writing 5381 } 5382 tracksToRemove->add(track); 5383 } else if (track->isFlushPending()) { 5384 if (track->isStopping_1()) { 5385 track->mRetryCount = kMaxTrackStopRetriesOffload; 5386 } else { 5387 track->mRetryCount = kMaxTrackRetriesOffload; 5388 } 5389 track->flushAck(); 5390 if (last) { 5391 mFlushPending = true; 5392 } 5393 } else if (track->isResumePending()){ 5394 track->resumeAck(); 5395 if (last) { 5396 if (mPausedBytesRemaining) { 5397 // Need to continue write that was interrupted 5398 mCurrentWriteLength = mPausedWriteLength; 5399 mBytesRemaining = mPausedBytesRemaining; 5400 mPausedBytesRemaining = 0; 5401 } 5402 if (mHwPaused) { 5403 doHwResume = true; 5404 mHwPaused = false; 5405 // threadLoop_mix() will handle the case that we need to 5406 // resume an interrupted write 5407 } 5408 // enable write to audio HAL 5409 mSleepTimeUs = 0; 5410 5411 mLeftVolFloat = mRightVolFloat = -1.0; 5412 5413 // Do not handle new data in this iteration even if track->framesReady() 5414 mixerStatus = MIXER_TRACKS_ENABLED; 5415 } 5416 } else if (track->framesReady() && track->isReady() && 5417 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 5418 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 5419 if (track->mFillingUpStatus == Track::FS_FILLED) { 5420 track->mFillingUpStatus = Track::FS_ACTIVE; 5421 if (last) { 5422 // make sure processVolume_l() will apply new volume even if 0 5423 mLeftVolFloat = mRightVolFloat = -1.0; 5424 } 5425 } 5426 5427 if (last) { 5428 sp<Track> previousTrack = mPreviousTrack.promote(); 5429 if (previousTrack != 0) { 5430 if (track != previousTrack.get()) { 5431 // Flush any data still being written from last track 5432 mBytesRemaining = 0; 5433 if (mPausedBytesRemaining) { 5434 // Last track was paused so we also need to flush saved 5435 // mixbuffer state and invalidate track so that it will 5436 // re-submit that unwritten data when it is next resumed 5437 mPausedBytesRemaining = 0; 5438 // Invalidate is a bit drastic - would be more efficient 5439 // to have a flag to tell client that some of the 5440 // previously written data was lost 5441 previousTrack->invalidate(); 5442 } 5443 // flush data already sent to the DSP if changing audio session as audio 5444 // comes from a different source. Also invalidate previous track to force a 5445 // seek when resuming. 5446 if (previousTrack->sessionId() != track->sessionId()) { 5447 previousTrack->invalidate(); 5448 } 5449 } 5450 } 5451 mPreviousTrack = track; 5452 // reset retry count 5453 if (track->isStopping_1()) { 5454 track->mRetryCount = kMaxTrackStopRetriesOffload; 5455 } else { 5456 track->mRetryCount = kMaxTrackRetriesOffload; 5457 } 5458 mActiveTrack = t; 5459 mixerStatus = MIXER_TRACKS_READY; 5460 } 5461 } else { 5462 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 5463 if (track->isStopping_1()) { 5464 if (--(track->mRetryCount) <= 0) { 5465 // Hardware buffer can hold a large amount of audio so we must 5466 // wait for all current track's data to drain before we say 5467 // that the track is stopped. 5468 if (mBytesRemaining == 0) { 5469 // Only start draining when all data in mixbuffer 5470 // has been written 5471 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 5472 track->mState = TrackBase::STOPPING_2; // so presentation completes after 5473 // drain do not drain if no data was ever sent to HAL (mStandby == true) 5474 if (last && !mStandby) { 5475 // do not modify drain sequence if we are already draining. This happens 5476 // when resuming from pause after drain. 5477 if ((mDrainSequence & 1) == 0) { 5478 mSleepTimeUs = 0; 5479 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5480 mixerStatus = MIXER_DRAIN_TRACK; 5481 mDrainSequence += 2; 5482 } 5483 if (mHwPaused) { 5484 // It is possible to move from PAUSED to STOPPING_1 without 5485 // a resume so we must ensure hardware is running 5486 doHwResume = true; 5487 mHwPaused = false; 5488 } 5489 } 5490 } 5491 } else if (last) { 5492 ALOGV("stopping1 underrun retries left %d", track->mRetryCount); 5493 mixerStatus = MIXER_TRACKS_ENABLED; 5494 } 5495 } else if (track->isStopping_2()) { 5496 // Drain has completed or we are in standby, signal presentation complete 5497 if (!(mDrainSequence & 1) || !last || mStandby) { 5498 track->mState = TrackBase::STOPPED; 5499 uint32_t latency = 0; 5500 status_t result = mOutput->stream->getLatency(&latency); 5501 ALOGE_IF(result != OK, 5502 "Error when retrieving output stream latency: %d", result); 5503 size_t audioHALFrames = (latency * mSampleRate) / 1000; 5504 int64_t framesWritten = 5505 mBytesWritten / mOutput->getFrameSize(); 5506 track->presentationComplete(framesWritten, audioHALFrames); 5507 track->reset(); 5508 tracksToRemove->add(track); 5509 } 5510 } else { 5511 // No buffers for this track. Give it a few chances to 5512 // fill a buffer, then remove it from active list. 5513 if (--(track->mRetryCount) <= 0) { 5514 bool running = false; 5515 uint64_t position = 0; 5516 struct timespec unused; 5517 // The running check restarts the retry counter at least once. 5518 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused); 5519 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) { 5520 running = true; 5521 mOffloadUnderrunPosition = position; 5522 } 5523 if (ret == NO_ERROR) { 5524 ALOGVV("underrun counter, running(%d): %lld vs %lld", running, 5525 (long long)position, (long long)mOffloadUnderrunPosition); 5526 } 5527 if (running) { // still running, give us more time. 5528 track->mRetryCount = kMaxTrackRetriesOffload; 5529 } else { 5530 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 5531 track->name()); 5532 tracksToRemove->add(track); 5533 // indicate to client process that the track was disabled because of underrun; 5534 // it will then automatically call start() when data is available 5535 track->disable(); 5536 } 5537 } else if (last){ 5538 mixerStatus = MIXER_TRACKS_ENABLED; 5539 } 5540 } 5541 } 5542 // compute volume for this track 5543 processVolume_l(track, last); 5544 } 5545 5546 // make sure the pause/flush/resume sequence is executed in the right order. 5547 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 5548 // before flush and then resume HW. This can happen in case of pause/flush/resume 5549 // if resume is received before pause is executed. 5550 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 5551 status_t result = mOutput->stream->pause(); 5552 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result); 5553 } 5554 if (mFlushPending) { 5555 flushHw_l(); 5556 } 5557 if (!mStandby && doHwResume) { 5558 status_t result = mOutput->stream->resume(); 5559 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result); 5560 } 5561 5562 // remove all the tracks that need to be... 5563 removeTracks_l(*tracksToRemove); 5564 5565 return mixerStatus; 5566} 5567 5568// must be called with thread mutex locked 5569bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 5570{ 5571 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 5572 mWriteAckSequence, mDrainSequence); 5573 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 5574 return true; 5575 } 5576 return false; 5577} 5578 5579bool AudioFlinger::OffloadThread::waitingAsyncCallback() 5580{ 5581 Mutex::Autolock _l(mLock); 5582 return waitingAsyncCallback_l(); 5583} 5584 5585void AudioFlinger::OffloadThread::flushHw_l() 5586{ 5587 DirectOutputThread::flushHw_l(); 5588 // Flush anything still waiting in the mixbuffer 5589 mCurrentWriteLength = 0; 5590 mBytesRemaining = 0; 5591 mPausedWriteLength = 0; 5592 mPausedBytesRemaining = 0; 5593 // reset bytes written count to reflect that DSP buffers are empty after flush. 5594 mBytesWritten = 0; 5595 mOffloadUnderrunPosition = ~0LL; 5596 5597 if (mUseAsyncWrite) { 5598 // discard any pending drain or write ack by incrementing sequence 5599 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 5600 mDrainSequence = (mDrainSequence + 2) & ~1; 5601 ALOG_ASSERT(mCallbackThread != 0); 5602 mCallbackThread->setWriteBlocked(mWriteAckSequence); 5603 mCallbackThread->setDraining(mDrainSequence); 5604 } 5605} 5606 5607void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType) 5608{ 5609 Mutex::Autolock _l(mLock); 5610 if (PlaybackThread::invalidateTracks_l(streamType)) { 5611 mFlushPending = true; 5612 } 5613} 5614 5615// ---------------------------------------------------------------------------- 5616 5617AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 5618 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady) 5619 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 5620 systemReady, DUPLICATING), 5621 mWaitTimeMs(UINT_MAX) 5622{ 5623 addOutputTrack(mainThread); 5624} 5625 5626AudioFlinger::DuplicatingThread::~DuplicatingThread() 5627{ 5628 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5629 mOutputTracks[i]->destroy(); 5630 } 5631} 5632 5633void AudioFlinger::DuplicatingThread::threadLoop_mix() 5634{ 5635 // mix buffers... 5636 if (outputsReady(outputTracks)) { 5637 mAudioMixer->process(); 5638 } else { 5639 if (mMixerBufferValid) { 5640 memset(mMixerBuffer, 0, mMixerBufferSize); 5641 } else { 5642 memset(mSinkBuffer, 0, mSinkBufferSize); 5643 } 5644 } 5645 mSleepTimeUs = 0; 5646 writeFrames = mNormalFrameCount; 5647 mCurrentWriteLength = mSinkBufferSize; 5648 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5649} 5650 5651void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 5652{ 5653 if (mSleepTimeUs == 0) { 5654 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5655 mSleepTimeUs = mActiveSleepTimeUs; 5656 } else { 5657 mSleepTimeUs = mIdleSleepTimeUs; 5658 } 5659 } else if (mBytesWritten != 0) { 5660 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5661 writeFrames = mNormalFrameCount; 5662 memset(mSinkBuffer, 0, mSinkBufferSize); 5663 } else { 5664 // flush remaining overflow buffers in output tracks 5665 writeFrames = 0; 5666 } 5667 mSleepTimeUs = 0; 5668 } 5669} 5670 5671ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 5672{ 5673 for (size_t i = 0; i < outputTracks.size(); i++) { 5674 outputTracks[i]->write(mSinkBuffer, writeFrames); 5675 } 5676 mStandby = false; 5677 return (ssize_t)mSinkBufferSize; 5678} 5679 5680void AudioFlinger::DuplicatingThread::threadLoop_standby() 5681{ 5682 // DuplicatingThread implements standby by stopping all tracks 5683 for (size_t i = 0; i < outputTracks.size(); i++) { 5684 outputTracks[i]->stop(); 5685 } 5686} 5687 5688void AudioFlinger::DuplicatingThread::saveOutputTracks() 5689{ 5690 outputTracks = mOutputTracks; 5691} 5692 5693void AudioFlinger::DuplicatingThread::clearOutputTracks() 5694{ 5695 outputTracks.clear(); 5696} 5697 5698void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 5699{ 5700 Mutex::Autolock _l(mLock); 5701 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass. 5702 // Adjust for thread->sampleRate() to determine minimum buffer frame count. 5703 // Then triple buffer because Threads do not run synchronously and may not be clock locked. 5704 const size_t frameCount = 5705 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate()); 5706 // TODO: Consider asynchronous sample rate conversion to handle clock disparity 5707 // from different OutputTracks and their associated MixerThreads (e.g. one may 5708 // nearly empty and the other may be dropping data). 5709 5710 sp<OutputTrack> outputTrack = new OutputTrack(thread, 5711 this, 5712 mSampleRate, 5713 mFormat, 5714 mChannelMask, 5715 frameCount, 5716 IPCThreadState::self()->getCallingUid()); 5717 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY; 5718 if (status != NO_ERROR) { 5719 ALOGE("addOutputTrack() initCheck failed %d", status); 5720 return; 5721 } 5722 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f); 5723 mOutputTracks.add(outputTrack); 5724 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread); 5725 updateWaitTime_l(); 5726} 5727 5728void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 5729{ 5730 Mutex::Autolock _l(mLock); 5731 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5732 if (mOutputTracks[i]->thread() == thread) { 5733 mOutputTracks[i]->destroy(); 5734 mOutputTracks.removeAt(i); 5735 updateWaitTime_l(); 5736 if (thread->getOutput() == mOutput) { 5737 mOutput = NULL; 5738 } 5739 return; 5740 } 5741 } 5742 ALOGV("removeOutputTrack(): unknown thread: %p", thread); 5743} 5744 5745// caller must hold mLock 5746void AudioFlinger::DuplicatingThread::updateWaitTime_l() 5747{ 5748 mWaitTimeMs = UINT_MAX; 5749 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5750 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 5751 if (strong != 0) { 5752 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 5753 if (waitTimeMs < mWaitTimeMs) { 5754 mWaitTimeMs = waitTimeMs; 5755 } 5756 } 5757 } 5758} 5759 5760 5761bool AudioFlinger::DuplicatingThread::outputsReady( 5762 const SortedVector< sp<OutputTrack> > &outputTracks) 5763{ 5764 for (size_t i = 0; i < outputTracks.size(); i++) { 5765 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 5766 if (thread == 0) { 5767 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 5768 outputTracks[i].get()); 5769 return false; 5770 } 5771 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 5772 // see note at standby() declaration 5773 if (playbackThread->standby() && !playbackThread->isSuspended()) { 5774 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 5775 thread.get()); 5776 return false; 5777 } 5778 } 5779 return true; 5780} 5781 5782uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 5783{ 5784 return (mWaitTimeMs * 1000) / 2; 5785} 5786 5787void AudioFlinger::DuplicatingThread::cacheParameters_l() 5788{ 5789 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 5790 updateWaitTime_l(); 5791 5792 MixerThread::cacheParameters_l(); 5793} 5794 5795// ---------------------------------------------------------------------------- 5796// Record 5797// ---------------------------------------------------------------------------- 5798 5799AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 5800 AudioStreamIn *input, 5801 audio_io_handle_t id, 5802 audio_devices_t outDevice, 5803 audio_devices_t inDevice, 5804 bool systemReady 5805#ifdef TEE_SINK 5806 , const sp<NBAIO_Sink>& teeSink 5807#endif 5808 ) : 5809 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady), 5810 mInput(input), mRsmpInBuffer(NULL), 5811 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l() 5812 mRsmpInRear(0) 5813#ifdef TEE_SINK 5814 , mTeeSink(teeSink) 5815#endif 5816 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize, 5817 "RecordThreadRO", MemoryHeapBase::READ_ONLY)) 5818 // mFastCapture below 5819 , mFastCaptureFutex(0) 5820 // mInputSource 5821 // mPipeSink 5822 // mPipeSource 5823 , mPipeFramesP2(0) 5824 // mPipeMemory 5825 // mFastCaptureNBLogWriter 5826 , mFastTrackAvail(false) 5827{ 5828 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id); 5829 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 5830 5831 readInputParameters_l(); 5832 5833 // create an NBAIO source for the HAL input stream, and negotiate 5834 mInputSource = new AudioStreamInSource(input->stream); 5835 size_t numCounterOffers = 0; 5836 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 5837#if !LOG_NDEBUG 5838 ssize_t index = 5839#else 5840 (void) 5841#endif 5842 mInputSource->negotiate(offers, 1, NULL, numCounterOffers); 5843 ALOG_ASSERT(index == 0); 5844 5845 // initialize fast capture depending on configuration 5846 bool initFastCapture; 5847 switch (kUseFastCapture) { 5848 case FastCapture_Never: 5849 initFastCapture = false; 5850 break; 5851 case FastCapture_Always: 5852 initFastCapture = true; 5853 break; 5854 case FastCapture_Static: 5855 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs; 5856 break; 5857 // case FastCapture_Dynamic: 5858 } 5859 5860 if (initFastCapture) { 5861 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from 5862 NBAIO_Format format = mInputSource->format(); 5863 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread 5864 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000); 5865 size_t pipeSize = pipeFramesP2 * Format_frameSize(format); 5866 void *pipeBuffer; 5867 const sp<MemoryDealer> roHeap(readOnlyHeap()); 5868 sp<IMemory> pipeMemory; 5869 if ((roHeap == 0) || 5870 (pipeMemory = roHeap->allocate(pipeSize)) == 0 || 5871 (pipeBuffer = pipeMemory->pointer()) == NULL) { 5872 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize); 5873 goto failed; 5874 } 5875 // pipe will be shared directly with fast clients, so clear to avoid leaking old information 5876 memset(pipeBuffer, 0, pipeSize); 5877 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer); 5878 const NBAIO_Format offers[1] = {format}; 5879 size_t numCounterOffers = 0; 5880 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 5881 ALOG_ASSERT(index == 0); 5882 mPipeSink = pipe; 5883 PipeReader *pipeReader = new PipeReader(*pipe); 5884 numCounterOffers = 0; 5885 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 5886 ALOG_ASSERT(index == 0); 5887 mPipeSource = pipeReader; 5888 mPipeFramesP2 = pipeFramesP2; 5889 mPipeMemory = pipeMemory; 5890 5891 // create fast capture 5892 mFastCapture = new FastCapture(); 5893 FastCaptureStateQueue *sq = mFastCapture->sq(); 5894#ifdef STATE_QUEUE_DUMP 5895 // FIXME 5896#endif 5897 FastCaptureState *state = sq->begin(); 5898 state->mCblk = NULL; 5899 state->mInputSource = mInputSource.get(); 5900 state->mInputSourceGen++; 5901 state->mPipeSink = pipe; 5902 state->mPipeSinkGen++; 5903 state->mFrameCount = mFrameCount; 5904 state->mCommand = FastCaptureState::COLD_IDLE; 5905 // already done in constructor initialization list 5906 //mFastCaptureFutex = 0; 5907 state->mColdFutexAddr = &mFastCaptureFutex; 5908 state->mColdGen++; 5909 state->mDumpState = &mFastCaptureDumpState; 5910#ifdef TEE_SINK 5911 // FIXME 5912#endif 5913 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture"); 5914 state->mNBLogWriter = mFastCaptureNBLogWriter.get(); 5915 sq->end(); 5916 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5917 5918 // start the fast capture 5919 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO); 5920 pid_t tid = mFastCapture->getTid(); 5921 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture); 5922 stream()->setHalThreadPriority(kPriorityFastCapture); 5923#ifdef AUDIO_WATCHDOG 5924 // FIXME 5925#endif 5926 5927 mFastTrackAvail = true; 5928 } 5929failed: ; 5930 5931 // FIXME mNormalSource 5932} 5933 5934AudioFlinger::RecordThread::~RecordThread() 5935{ 5936 if (mFastCapture != 0) { 5937 FastCaptureStateQueue *sq = mFastCapture->sq(); 5938 FastCaptureState *state = sq->begin(); 5939 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5940 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5941 if (old == -1) { 5942 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5943 } 5944 } 5945 state->mCommand = FastCaptureState::EXIT; 5946 sq->end(); 5947 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5948 mFastCapture->join(); 5949 mFastCapture.clear(); 5950 } 5951 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter); 5952 mAudioFlinger->unregisterWriter(mNBLogWriter); 5953 free(mRsmpInBuffer); 5954} 5955 5956void AudioFlinger::RecordThread::onFirstRef() 5957{ 5958 run(mThreadName, PRIORITY_URGENT_AUDIO); 5959} 5960 5961bool AudioFlinger::RecordThread::threadLoop() 5962{ 5963 nsecs_t lastWarning = 0; 5964 5965 inputStandBy(); 5966 5967reacquire_wakelock: 5968 sp<RecordTrack> activeTrack; 5969 { 5970 Mutex::Autolock _l(mLock); 5971 acquireWakeLock_l(); 5972 } 5973 5974 // used to request a deferred sleep, to be executed later while mutex is unlocked 5975 uint32_t sleepUs = 0; 5976 5977 // loop while there is work to do 5978 for (;;) { 5979 Vector< sp<EffectChain> > effectChains; 5980 5981 // activeTracks accumulates a copy of a subset of mActiveTracks 5982 Vector< sp<RecordTrack> > activeTracks; 5983 5984 // reference to the (first and only) active fast track 5985 sp<RecordTrack> fastTrack; 5986 5987 // reference to a fast track which is about to be removed 5988 sp<RecordTrack> fastTrackToRemove; 5989 5990 { // scope for mLock 5991 Mutex::Autolock _l(mLock); 5992 5993 processConfigEvents_l(); 5994 5995 // check exitPending here because checkForNewParameters_l() and 5996 // checkForNewParameters_l() can temporarily release mLock 5997 if (exitPending()) { 5998 break; 5999 } 6000 6001 // sleep with mutex unlocked 6002 if (sleepUs > 0) { 6003 ATRACE_BEGIN("sleepC"); 6004 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs)); 6005 ATRACE_END(); 6006 sleepUs = 0; 6007 continue; 6008 } 6009 6010 // if no active track(s), then standby and release wakelock 6011 size_t size = mActiveTracks.size(); 6012 if (size == 0) { 6013 standbyIfNotAlreadyInStandby(); 6014 // exitPending() can't become true here 6015 releaseWakeLock_l(); 6016 ALOGV("RecordThread: loop stopping"); 6017 // go to sleep 6018 mWaitWorkCV.wait(mLock); 6019 ALOGV("RecordThread: loop starting"); 6020 goto reacquire_wakelock; 6021 } 6022 6023 bool doBroadcast = false; 6024 bool allStopped = true; 6025 for (size_t i = 0; i < size; ) { 6026 6027 activeTrack = mActiveTracks[i]; 6028 if (activeTrack->isTerminated()) { 6029 if (activeTrack->isFastTrack()) { 6030 ALOG_ASSERT(fastTrackToRemove == 0); 6031 fastTrackToRemove = activeTrack; 6032 } 6033 removeTrack_l(activeTrack); 6034 mActiveTracks.remove(activeTrack); 6035 size--; 6036 continue; 6037 } 6038 6039 TrackBase::track_state activeTrackState = activeTrack->mState; 6040 switch (activeTrackState) { 6041 6042 case TrackBase::PAUSING: 6043 mActiveTracks.remove(activeTrack); 6044 doBroadcast = true; 6045 size--; 6046 continue; 6047 6048 case TrackBase::STARTING_1: 6049 sleepUs = 10000; 6050 i++; 6051 allStopped = false; 6052 continue; 6053 6054 case TrackBase::STARTING_2: 6055 doBroadcast = true; 6056 mStandby = false; 6057 activeTrack->mState = TrackBase::ACTIVE; 6058 allStopped = false; 6059 break; 6060 6061 case TrackBase::ACTIVE: 6062 allStopped = false; 6063 break; 6064 6065 case TrackBase::IDLE: 6066 i++; 6067 continue; 6068 6069 default: 6070 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState); 6071 } 6072 6073 activeTracks.add(activeTrack); 6074 i++; 6075 6076 if (activeTrack->isFastTrack()) { 6077 ALOG_ASSERT(!mFastTrackAvail); 6078 ALOG_ASSERT(fastTrack == 0); 6079 fastTrack = activeTrack; 6080 } 6081 } 6082 6083 mActiveTracks.updatePowerState(this); 6084 6085 if (allStopped) { 6086 standbyIfNotAlreadyInStandby(); 6087 } 6088 if (doBroadcast) { 6089 mStartStopCond.broadcast(); 6090 } 6091 6092 // sleep if there are no active tracks to process 6093 if (activeTracks.size() == 0) { 6094 if (sleepUs == 0) { 6095 sleepUs = kRecordThreadSleepUs; 6096 } 6097 continue; 6098 } 6099 sleepUs = 0; 6100 6101 lockEffectChains_l(effectChains); 6102 } 6103 6104 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0 6105 6106 size_t size = effectChains.size(); 6107 for (size_t i = 0; i < size; i++) { 6108 // thread mutex is not locked, but effect chain is locked 6109 effectChains[i]->process_l(); 6110 } 6111 6112 // Push a new fast capture state if fast capture is not already running, or cblk change 6113 if (mFastCapture != 0) { 6114 FastCaptureStateQueue *sq = mFastCapture->sq(); 6115 FastCaptureState *state = sq->begin(); 6116 bool didModify = false; 6117 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED; 6118 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME && 6119 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) { 6120 if (state->mCommand == FastCaptureState::COLD_IDLE) { 6121 int32_t old = android_atomic_inc(&mFastCaptureFutex); 6122 if (old == -1) { 6123 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 6124 } 6125 } 6126 state->mCommand = FastCaptureState::READ_WRITE; 6127#if 0 // FIXME 6128 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 6129 FastThreadDumpState::kSamplingNforLowRamDevice : 6130 FastThreadDumpState::kSamplingN); 6131#endif 6132 didModify = true; 6133 } 6134 audio_track_cblk_t *cblkOld = state->mCblk; 6135 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL; 6136 if (cblkNew != cblkOld) { 6137 state->mCblk = cblkNew; 6138 // block until acked if removing a fast track 6139 if (cblkOld != NULL) { 6140 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED; 6141 } 6142 didModify = true; 6143 } 6144 sq->end(didModify); 6145 if (didModify) { 6146 sq->push(block); 6147#if 0 6148 if (kUseFastCapture == FastCapture_Dynamic) { 6149 mNormalSource = mPipeSource; 6150 } 6151#endif 6152 } 6153 } 6154 6155 // now run the fast track destructor with thread mutex unlocked 6156 fastTrackToRemove.clear(); 6157 6158 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one. 6159 // Only the client(s) that are too slow will overrun. But if even the fastest client is too 6160 // slow, then this RecordThread will overrun by not calling HAL read often enough. 6161 // If destination is non-contiguous, first read past the nominal end of buffer, then 6162 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 6163 6164 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1); 6165 ssize_t framesRead; 6166 6167 // If an NBAIO source is present, use it to read the normal capture's data 6168 if (mPipeSource != 0) { 6169 size_t framesToRead = mBufferSize / mFrameSize; 6170 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2); 6171 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize, 6172 framesToRead); 6173 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of 6174 // buffer size or at least for 20ms. 6175 size_t sleepFrames = max( 6176 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000); 6177 if (framesRead <= (ssize_t) sleepFrames) { 6178 sleepUs = (sleepFrames * 1000000LL) / mSampleRate; 6179 } 6180 if (framesRead < 0) { 6181 status_t status = (status_t) framesRead; 6182 switch (status) { 6183 case OVERRUN: 6184 ALOGW("overrun on read from pipe"); 6185 framesRead = 0; 6186 break; 6187 case NEGOTIATE: 6188 ALOGE("re-negotiation is needed"); 6189 framesRead = -1; // Will cause an attempt to recover. 6190 break; 6191 default: 6192 ALOGE("unknown error %d on read from pipe", status); 6193 break; 6194 } 6195 } 6196 // otherwise use the HAL / AudioStreamIn directly 6197 } else { 6198 ATRACE_BEGIN("read"); 6199 size_t bytesRead; 6200 status_t result = mInput->stream->read( 6201 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead); 6202 ATRACE_END(); 6203 if (result < 0) { 6204 framesRead = result; 6205 } else { 6206 framesRead = bytesRead / mFrameSize; 6207 } 6208 } 6209 6210 // Update server timestamp with server stats 6211 // systemTime() is optional if the hardware supports timestamps. 6212 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead; 6213 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime(); 6214 6215 // Update server timestamp with kernel stats 6216 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) { 6217 int64_t position, time; 6218 int ret = mInput->stream->getCapturePosition(&position, &time); 6219 if (ret == NO_ERROR) { 6220 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position; 6221 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time; 6222 // Note: In general record buffers should tend to be empty in 6223 // a properly running pipeline. 6224 // 6225 // Also, it is not advantageous to call get_presentation_position during the read 6226 // as the read obtains a lock, preventing the timestamp call from executing. 6227 } 6228 } 6229 // Use this to track timestamp information 6230 // ALOGD("%s", mTimestamp.toString().c_str()); 6231 6232 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) { 6233 ALOGE("read failed: framesRead=%zd", framesRead); 6234 // Force input into standby so that it tries to recover at next read attempt 6235 inputStandBy(); 6236 sleepUs = kRecordThreadSleepUs; 6237 } 6238 if (framesRead <= 0) { 6239 goto unlock; 6240 } 6241 ALOG_ASSERT(framesRead > 0); 6242 6243 if (mTeeSink != 0) { 6244 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead); 6245 } 6246 // If destination is non-contiguous, we now correct for reading past end of buffer. 6247 { 6248 size_t part1 = mRsmpInFramesP2 - rear; 6249 if ((size_t) framesRead > part1) { 6250 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize, 6251 (framesRead - part1) * mFrameSize); 6252 } 6253 } 6254 rear = mRsmpInRear += framesRead; 6255 6256 size = activeTracks.size(); 6257 // loop over each active track 6258 for (size_t i = 0; i < size; i++) { 6259 activeTrack = activeTracks[i]; 6260 6261 // skip fast tracks, as those are handled directly by FastCapture 6262 if (activeTrack->isFastTrack()) { 6263 continue; 6264 } 6265 6266 // TODO: This code probably should be moved to RecordTrack. 6267 // TODO: Update the activeTrack buffer converter in case of reconfigure. 6268 6269 enum { 6270 OVERRUN_UNKNOWN, 6271 OVERRUN_TRUE, 6272 OVERRUN_FALSE 6273 } overrun = OVERRUN_UNKNOWN; 6274 6275 // loop over getNextBuffer to handle circular sink 6276 for (;;) { 6277 6278 activeTrack->mSink.frameCount = ~0; 6279 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink); 6280 size_t framesOut = activeTrack->mSink.frameCount; 6281 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0)); 6282 6283 // check available frames and handle overrun conditions 6284 // if the record track isn't draining fast enough. 6285 bool hasOverrun; 6286 size_t framesIn; 6287 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun); 6288 if (hasOverrun) { 6289 overrun = OVERRUN_TRUE; 6290 } 6291 if (framesOut == 0 || framesIn == 0) { 6292 break; 6293 } 6294 6295 // Don't allow framesOut to be larger than what is possible with resampling 6296 // from framesIn. 6297 // This isn't strictly necessary but helps limit buffer resizing in 6298 // RecordBufferConverter. TODO: remove when no longer needed. 6299 framesOut = min(framesOut, 6300 destinationFramesPossible( 6301 framesIn, mSampleRate, activeTrack->mSampleRate)); 6302 // process frames from the RecordThread buffer provider to the RecordTrack buffer 6303 framesOut = activeTrack->mRecordBufferConverter->convert( 6304 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut); 6305 6306 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) { 6307 overrun = OVERRUN_FALSE; 6308 } 6309 6310 if (activeTrack->mFramesToDrop == 0) { 6311 if (framesOut > 0) { 6312 activeTrack->mSink.frameCount = framesOut; 6313 activeTrack->releaseBuffer(&activeTrack->mSink); 6314 } 6315 } else { 6316 // FIXME could do a partial drop of framesOut 6317 if (activeTrack->mFramesToDrop > 0) { 6318 activeTrack->mFramesToDrop -= framesOut; 6319 if (activeTrack->mFramesToDrop <= 0) { 6320 activeTrack->clearSyncStartEvent(); 6321 } 6322 } else { 6323 activeTrack->mFramesToDrop += framesOut; 6324 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 || 6325 activeTrack->mSyncStartEvent->isCancelled()) { 6326 ALOGW("Synced record %s, session %d, trigger session %d", 6327 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled", 6328 activeTrack->sessionId(), 6329 (activeTrack->mSyncStartEvent != 0) ? 6330 activeTrack->mSyncStartEvent->triggerSession() : 6331 AUDIO_SESSION_NONE); 6332 activeTrack->clearSyncStartEvent(); 6333 } 6334 } 6335 } 6336 6337 if (framesOut == 0) { 6338 break; 6339 } 6340 } 6341 6342 switch (overrun) { 6343 case OVERRUN_TRUE: 6344 // client isn't retrieving buffers fast enough 6345 if (!activeTrack->setOverflow()) { 6346 nsecs_t now = systemTime(); 6347 // FIXME should lastWarning per track? 6348 if ((now - lastWarning) > kWarningThrottleNs) { 6349 ALOGW("RecordThread: buffer overflow"); 6350 lastWarning = now; 6351 } 6352 } 6353 break; 6354 case OVERRUN_FALSE: 6355 activeTrack->clearOverflow(); 6356 break; 6357 case OVERRUN_UNKNOWN: 6358 break; 6359 } 6360 6361 // update frame information and push timestamp out 6362 activeTrack->updateTrackFrameInfo( 6363 activeTrack->mServerProxy->framesReleased(), 6364 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER], 6365 mSampleRate, mTimestamp); 6366 } 6367 6368unlock: 6369 // enable changes in effect chain 6370 unlockEffectChains(effectChains); 6371 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 6372 } 6373 6374 standbyIfNotAlreadyInStandby(); 6375 6376 { 6377 Mutex::Autolock _l(mLock); 6378 for (size_t i = 0; i < mTracks.size(); i++) { 6379 sp<RecordTrack> track = mTracks[i]; 6380 track->invalidate(); 6381 } 6382 mActiveTracks.clear(); 6383 mStartStopCond.broadcast(); 6384 } 6385 6386 releaseWakeLock(); 6387 6388 ALOGV("RecordThread %p exiting", this); 6389 return false; 6390} 6391 6392void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 6393{ 6394 if (!mStandby) { 6395 inputStandBy(); 6396 mStandby = true; 6397 } 6398} 6399 6400void AudioFlinger::RecordThread::inputStandBy() 6401{ 6402 // Idle the fast capture if it's currently running 6403 if (mFastCapture != 0) { 6404 FastCaptureStateQueue *sq = mFastCapture->sq(); 6405 FastCaptureState *state = sq->begin(); 6406 if (!(state->mCommand & FastCaptureState::IDLE)) { 6407 state->mCommand = FastCaptureState::COLD_IDLE; 6408 state->mColdFutexAddr = &mFastCaptureFutex; 6409 state->mColdGen++; 6410 mFastCaptureFutex = 0; 6411 sq->end(); 6412 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 6413 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED); 6414#if 0 6415 if (kUseFastCapture == FastCapture_Dynamic) { 6416 // FIXME 6417 } 6418#endif 6419#ifdef AUDIO_WATCHDOG 6420 // FIXME 6421#endif 6422 } else { 6423 sq->end(false /*didModify*/); 6424 } 6425 } 6426 status_t result = mInput->stream->standby(); 6427 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result); 6428 6429 // If going into standby, flush the pipe source. 6430 if (mPipeSource.get() != nullptr) { 6431 const ssize_t flushed = mPipeSource->flush(); 6432 if (flushed > 0) { 6433 ALOGV("Input standby flushed PipeSource %zd frames", flushed); 6434 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed; 6435 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime(); 6436 } 6437 } 6438} 6439 6440// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held 6441sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 6442 const sp<AudioFlinger::Client>& client, 6443 uint32_t sampleRate, 6444 audio_format_t format, 6445 audio_channel_mask_t channelMask, 6446 size_t *pFrameCount, 6447 audio_session_t sessionId, 6448 size_t *notificationFrames, 6449 uid_t uid, 6450 audio_input_flags_t *flags, 6451 pid_t tid, 6452 status_t *status, 6453 audio_port_handle_t portId) 6454{ 6455 size_t frameCount = *pFrameCount; 6456 sp<RecordTrack> track; 6457 status_t lStatus; 6458 audio_input_flags_t inputFlags = mInput->flags; 6459 6460 // special case for FAST flag considered OK if fast capture is present 6461 if (hasFastCapture()) { 6462 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST); 6463 } 6464 6465 // Check if requested flags are compatible with output stream flags 6466 if ((*flags & inputFlags) != *flags) { 6467 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and" 6468 " input flags (%08x)", 6469 *flags, inputFlags); 6470 *flags = (audio_input_flags_t)(*flags & inputFlags); 6471 } 6472 6473 // client expresses a preference for FAST, but we get the final say 6474 if (*flags & AUDIO_INPUT_FLAG_FAST) { 6475 if ( 6476 // we formerly checked for a callback handler (non-0 tid), 6477 // but that is no longer required for TRANSFER_OBTAIN mode 6478 // 6479 // frame count is not specified, or is exactly the pipe depth 6480 ((frameCount == 0) || (frameCount == mPipeFramesP2)) && 6481 // PCM data 6482 audio_is_linear_pcm(format) && 6483 // hardware format 6484 (format == mFormat) && 6485 // hardware channel mask 6486 (channelMask == mChannelMask) && 6487 // hardware sample rate 6488 (sampleRate == mSampleRate) && 6489 // record thread has an associated fast capture 6490 hasFastCapture() && 6491 // there are sufficient fast track slots available 6492 mFastTrackAvail 6493 ) { 6494 // check compatibility with audio effects. 6495 Mutex::Autolock _l(mLock); 6496 // Do not accept FAST flag if the session has software effects 6497 sp<EffectChain> chain = getEffectChain_l(sessionId); 6498 if (chain != 0) { 6499 audio_input_flags_t old = *flags; 6500 chain->checkInputFlagCompatibility(flags); 6501 if (old != *flags) { 6502 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x", 6503 (int)old, (int)*flags); 6504 } 6505 } 6506 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0, 6507 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu", 6508 frameCount, mFrameCount); 6509 } else { 6510 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu " 6511 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 6512 "hasFastCapture=%d tid=%d mFastTrackAvail=%d", 6513 frameCount, mFrameCount, mPipeFramesP2, 6514 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate, 6515 hasFastCapture(), tid, mFastTrackAvail); 6516 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST); 6517 } 6518 } 6519 6520 // compute track buffer size in frames, and suggest the notification frame count 6521 if (*flags & AUDIO_INPUT_FLAG_FAST) { 6522 // fast track: frame count is exactly the pipe depth 6523 frameCount = mPipeFramesP2; 6524 // ignore requested notificationFrames, and always notify exactly once every HAL buffer 6525 *notificationFrames = mFrameCount; 6526 } else { 6527 // not fast track: max notification period is resampled equivalent of one HAL buffer time 6528 // or 20 ms if there is a fast capture 6529 // TODO This could be a roundupRatio inline, and const 6530 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount) 6531 * sampleRate + mSampleRate - 1) / mSampleRate; 6532 // minimum number of notification periods is at least kMinNotifications, 6533 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs) 6534 static const size_t kMinNotifications = 3; 6535 static const uint32_t kMinMs = 30; 6536 // TODO This could be a roundupRatio inline 6537 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000; 6538 // TODO This could be a roundupRatio inline 6539 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) / 6540 maxNotificationFrames; 6541 const size_t minFrameCount = maxNotificationFrames * 6542 max(kMinNotifications, minNotificationsByMs); 6543 frameCount = max(frameCount, minFrameCount); 6544 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) { 6545 *notificationFrames = maxNotificationFrames; 6546 } 6547 } 6548 *pFrameCount = frameCount; 6549 6550 lStatus = initCheck(); 6551 if (lStatus != NO_ERROR) { 6552 ALOGE("createRecordTrack_l() audio driver not initialized"); 6553 goto Exit; 6554 } 6555 6556 { // scope for mLock 6557 Mutex::Autolock _l(mLock); 6558 6559 track = new RecordTrack(this, client, sampleRate, 6560 format, channelMask, frameCount, NULL, sessionId, uid, 6561 *flags, TrackBase::TYPE_DEFAULT, portId); 6562 6563 lStatus = track->initCheck(); 6564 if (lStatus != NO_ERROR) { 6565 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 6566 // track must be cleared from the caller as the caller has the AF lock 6567 goto Exit; 6568 } 6569 mTracks.add(track); 6570 6571 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6572 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6573 mAudioFlinger->btNrecIsOff(); 6574 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 6575 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 6576 6577 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) { 6578 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 6579 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 6580 // so ask activity manager to do this on our behalf 6581 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 6582 } 6583 } 6584 6585 lStatus = NO_ERROR; 6586 6587Exit: 6588 *status = lStatus; 6589 return track; 6590} 6591 6592status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 6593 AudioSystem::sync_event_t event, 6594 audio_session_t triggerSession) 6595{ 6596 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 6597 sp<ThreadBase> strongMe = this; 6598 status_t status = NO_ERROR; 6599 6600 if (event == AudioSystem::SYNC_EVENT_NONE) { 6601 recordTrack->clearSyncStartEvent(); 6602 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 6603 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 6604 triggerSession, 6605 recordTrack->sessionId(), 6606 syncStartEventCallback, 6607 recordTrack); 6608 // Sync event can be cancelled by the trigger session if the track is not in a 6609 // compatible state in which case we start record immediately 6610 if (recordTrack->mSyncStartEvent->isCancelled()) { 6611 recordTrack->clearSyncStartEvent(); 6612 } else { 6613 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 6614 recordTrack->mFramesToDrop = - 6615 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000); 6616 } 6617 } 6618 6619 { 6620 // This section is a rendezvous between binder thread executing start() and RecordThread 6621 AutoMutex lock(mLock); 6622 if (mActiveTracks.indexOf(recordTrack) >= 0) { 6623 if (recordTrack->mState == TrackBase::PAUSING) { 6624 ALOGV("active record track PAUSING -> ACTIVE"); 6625 recordTrack->mState = TrackBase::ACTIVE; 6626 } else { 6627 ALOGV("active record track state %d", recordTrack->mState); 6628 } 6629 return status; 6630 } 6631 6632 // TODO consider other ways of handling this, such as changing the state to :STARTING and 6633 // adding the track to mActiveTracks after returning from AudioSystem::startInput(), 6634 // or using a separate command thread 6635 recordTrack->mState = TrackBase::STARTING_1; 6636 mActiveTracks.add(recordTrack); 6637 status_t status = NO_ERROR; 6638 if (recordTrack->isExternalTrack()) { 6639 mLock.unlock(); 6640 status = AudioSystem::startInput(mId, recordTrack->sessionId()); 6641 mLock.lock(); 6642 // FIXME should verify that recordTrack is still in mActiveTracks 6643 if (status != NO_ERROR) { 6644 mActiveTracks.remove(recordTrack); 6645 recordTrack->clearSyncStartEvent(); 6646 ALOGV("RecordThread::start error %d", status); 6647 return status; 6648 } 6649 } 6650 // Catch up with current buffer indices if thread is already running. 6651 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront 6652 // was initialized to some value closer to the thread's mRsmpInFront, then the track could 6653 // see previously buffered data before it called start(), but with greater risk of overrun. 6654 6655 recordTrack->mResamplerBufferProvider->reset(); 6656 // clear any converter state as new data will be discontinuous 6657 recordTrack->mRecordBufferConverter->reset(); 6658 recordTrack->mState = TrackBase::STARTING_2; 6659 // signal thread to start 6660 mWaitWorkCV.broadcast(); 6661 if (mActiveTracks.indexOf(recordTrack) < 0) { 6662 ALOGV("Record failed to start"); 6663 status = BAD_VALUE; 6664 goto startError; 6665 } 6666 return status; 6667 } 6668 6669startError: 6670 if (recordTrack->isExternalTrack()) { 6671 AudioSystem::stopInput(mId, recordTrack->sessionId()); 6672 } 6673 recordTrack->clearSyncStartEvent(); 6674 // FIXME I wonder why we do not reset the state here? 6675 return status; 6676} 6677 6678void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 6679{ 6680 sp<SyncEvent> strongEvent = event.promote(); 6681 6682 if (strongEvent != 0) { 6683 sp<RefBase> ptr = strongEvent->cookie().promote(); 6684 if (ptr != 0) { 6685 RecordTrack *recordTrack = (RecordTrack *)ptr.get(); 6686 recordTrack->handleSyncStartEvent(strongEvent); 6687 } 6688 } 6689} 6690 6691bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 6692 ALOGV("RecordThread::stop"); 6693 AutoMutex _l(mLock); 6694 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 6695 return false; 6696 } 6697 // note that threadLoop may still be processing the track at this point [without lock] 6698 recordTrack->mState = TrackBase::PAUSING; 6699 // signal thread to stop 6700 mWaitWorkCV.broadcast(); 6701 // do not wait for mStartStopCond if exiting 6702 if (exitPending()) { 6703 return true; 6704 } 6705 // FIXME incorrect usage of wait: no explicit predicate or loop 6706 mStartStopCond.wait(mLock); 6707 // if we have been restarted, recordTrack is in mActiveTracks here 6708 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 6709 ALOGV("Record stopped OK"); 6710 return true; 6711 } 6712 return false; 6713} 6714 6715bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 6716{ 6717 return false; 6718} 6719 6720status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 6721{ 6722#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 6723 if (!isValidSyncEvent(event)) { 6724 return BAD_VALUE; 6725 } 6726 6727 audio_session_t eventSession = event->triggerSession(); 6728 status_t ret = NAME_NOT_FOUND; 6729 6730 Mutex::Autolock _l(mLock); 6731 6732 for (size_t i = 0; i < mTracks.size(); i++) { 6733 sp<RecordTrack> track = mTracks[i]; 6734 if (eventSession == track->sessionId()) { 6735 (void) track->setSyncEvent(event); 6736 ret = NO_ERROR; 6737 } 6738 } 6739 return ret; 6740#else 6741 return BAD_VALUE; 6742#endif 6743} 6744 6745// destroyTrack_l() must be called with ThreadBase::mLock held 6746void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 6747{ 6748 track->terminate(); 6749 track->mState = TrackBase::STOPPED; 6750 // active tracks are removed by threadLoop() 6751 if (mActiveTracks.indexOf(track) < 0) { 6752 removeTrack_l(track); 6753 } 6754} 6755 6756void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 6757{ 6758 mTracks.remove(track); 6759 // need anything related to effects here? 6760 if (track->isFastTrack()) { 6761 ALOG_ASSERT(!mFastTrackAvail); 6762 mFastTrackAvail = true; 6763 } 6764} 6765 6766void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 6767{ 6768 dumpInternals(fd, args); 6769 dumpTracks(fd, args); 6770 dumpEffectChains(fd, args); 6771} 6772 6773void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 6774{ 6775 dprintf(fd, "\nInput thread %p:\n", this); 6776 6777 dumpBase(fd, args); 6778 6779 AudioStreamIn *input = mInput; 6780 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE; 6781 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n", 6782 input, flags, inputFlagsToString(flags).c_str()); 6783 if (mActiveTracks.size() == 0) { 6784 dprintf(fd, " No active record clients\n"); 6785 } 6786 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no"); 6787 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no"); 6788 6789 // Make a non-atomic copy of fast capture dump state so it won't change underneath us 6790 // while we are dumping it. It may be inconsistent, but it won't mutate! 6791 // This is a large object so we place it on the heap. 6792 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages. 6793 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState); 6794 copy->dump(fd); 6795 delete copy; 6796} 6797 6798void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 6799{ 6800 const size_t SIZE = 256; 6801 char buffer[SIZE]; 6802 String8 result; 6803 6804 size_t numtracks = mTracks.size(); 6805 size_t numactive = mActiveTracks.size(); 6806 size_t numactiveseen = 0; 6807 dprintf(fd, " %zu Tracks", numtracks); 6808 if (numtracks) { 6809 dprintf(fd, " of which %zu are active\n", numactive); 6810 RecordTrack::appendDumpHeader(result); 6811 for (size_t i = 0; i < numtracks ; ++i) { 6812 sp<RecordTrack> track = mTracks[i]; 6813 if (track != 0) { 6814 bool active = mActiveTracks.indexOf(track) >= 0; 6815 if (active) { 6816 numactiveseen++; 6817 } 6818 track->dump(buffer, SIZE, active); 6819 result.append(buffer); 6820 } 6821 } 6822 } else { 6823 dprintf(fd, "\n"); 6824 } 6825 6826 if (numactiveseen != numactive) { 6827 snprintf(buffer, SIZE, " The following tracks are in the active list but" 6828 " not in the track list\n"); 6829 result.append(buffer); 6830 RecordTrack::appendDumpHeader(result); 6831 for (size_t i = 0; i < numactive; ++i) { 6832 sp<RecordTrack> track = mActiveTracks[i]; 6833 if (mTracks.indexOf(track) < 0) { 6834 track->dump(buffer, SIZE, true); 6835 result.append(buffer); 6836 } 6837 } 6838 6839 } 6840 write(fd, result.string(), result.size()); 6841} 6842 6843 6844void AudioFlinger::RecordThread::ResamplerBufferProvider::reset() 6845{ 6846 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6847 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6848 mRsmpInFront = recordThread->mRsmpInRear; 6849 mRsmpInUnrel = 0; 6850} 6851 6852void AudioFlinger::RecordThread::ResamplerBufferProvider::sync( 6853 size_t *framesAvailable, bool *hasOverrun) 6854{ 6855 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6856 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6857 const int32_t rear = recordThread->mRsmpInRear; 6858 const int32_t front = mRsmpInFront; 6859 const ssize_t filled = rear - front; 6860 6861 size_t framesIn; 6862 bool overrun = false; 6863 if (filled < 0) { 6864 // should not happen, but treat like a massive overrun and re-sync 6865 framesIn = 0; 6866 mRsmpInFront = rear; 6867 overrun = true; 6868 } else if ((size_t) filled <= recordThread->mRsmpInFrames) { 6869 framesIn = (size_t) filled; 6870 } else { 6871 // client is not keeping up with server, but give it latest data 6872 framesIn = recordThread->mRsmpInFrames; 6873 mRsmpInFront = /* front = */ rear - framesIn; 6874 overrun = true; 6875 } 6876 if (framesAvailable != NULL) { 6877 *framesAvailable = framesIn; 6878 } 6879 if (hasOverrun != NULL) { 6880 *hasOverrun = overrun; 6881 } 6882} 6883 6884// AudioBufferProvider interface 6885status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer( 6886 AudioBufferProvider::Buffer* buffer) 6887{ 6888 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6889 if (threadBase == 0) { 6890 buffer->frameCount = 0; 6891 buffer->raw = NULL; 6892 return NOT_ENOUGH_DATA; 6893 } 6894 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6895 int32_t rear = recordThread->mRsmpInRear; 6896 int32_t front = mRsmpInFront; 6897 ssize_t filled = rear - front; 6898 // FIXME should not be P2 (don't want to increase latency) 6899 // FIXME if client not keeping up, discard 6900 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames)); 6901 // 'filled' may be non-contiguous, so return only the first contiguous chunk 6902 front &= recordThread->mRsmpInFramesP2 - 1; 6903 size_t part1 = recordThread->mRsmpInFramesP2 - front; 6904 if (part1 > (size_t) filled) { 6905 part1 = filled; 6906 } 6907 size_t ask = buffer->frameCount; 6908 ALOG_ASSERT(ask > 0); 6909 if (part1 > ask) { 6910 part1 = ask; 6911 } 6912 if (part1 == 0) { 6913 // out of data is fine since the resampler will return a short-count. 6914 buffer->raw = NULL; 6915 buffer->frameCount = 0; 6916 mRsmpInUnrel = 0; 6917 return NOT_ENOUGH_DATA; 6918 } 6919 6920 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize; 6921 buffer->frameCount = part1; 6922 mRsmpInUnrel = part1; 6923 return NO_ERROR; 6924} 6925 6926// AudioBufferProvider interface 6927void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer( 6928 AudioBufferProvider::Buffer* buffer) 6929{ 6930 size_t stepCount = buffer->frameCount; 6931 if (stepCount == 0) { 6932 return; 6933 } 6934 ALOG_ASSERT(stepCount <= mRsmpInUnrel); 6935 mRsmpInUnrel -= stepCount; 6936 mRsmpInFront += stepCount; 6937 buffer->raw = NULL; 6938 buffer->frameCount = 0; 6939} 6940 6941AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter( 6942 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat, 6943 uint32_t srcSampleRate, 6944 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat, 6945 uint32_t dstSampleRate) : 6946 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars 6947 // mSrcFormat 6948 // mSrcSampleRate 6949 // mDstChannelMask 6950 // mDstFormat 6951 // mDstSampleRate 6952 // mSrcChannelCount 6953 // mDstChannelCount 6954 // mDstFrameSize 6955 mBuf(NULL), mBufFrames(0), mBufFrameSize(0), 6956 mResampler(NULL), 6957 mIsLegacyDownmix(false), 6958 mIsLegacyUpmix(false), 6959 mRequiresFloat(false), 6960 mInputConverterProvider(NULL) 6961{ 6962 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate, 6963 dstChannelMask, dstFormat, dstSampleRate); 6964} 6965 6966AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() { 6967 free(mBuf); 6968 delete mResampler; 6969 delete mInputConverterProvider; 6970} 6971 6972size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst, 6973 AudioBufferProvider *provider, size_t frames) 6974{ 6975 if (mInputConverterProvider != NULL) { 6976 mInputConverterProvider->setBufferProvider(provider); 6977 provider = mInputConverterProvider; 6978 } 6979 6980 if (mResampler == NULL) { 6981 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x", 6982 mSrcSampleRate, mSrcFormat, mDstFormat); 6983 6984 AudioBufferProvider::Buffer buffer; 6985 for (size_t i = frames; i > 0; ) { 6986 buffer.frameCount = i; 6987 status_t status = provider->getNextBuffer(&buffer); 6988 if (status != OK || buffer.frameCount == 0) { 6989 frames -= i; // cannot fill request. 6990 break; 6991 } 6992 // format convert to destination buffer 6993 convertNoResampler(dst, buffer.raw, buffer.frameCount); 6994 6995 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize; 6996 i -= buffer.frameCount; 6997 provider->releaseBuffer(&buffer); 6998 } 6999 } else { 7000 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x", 7001 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat); 7002 7003 // reallocate buffer if needed 7004 if (mBufFrameSize != 0 && mBufFrames < frames) { 7005 free(mBuf); 7006 mBufFrames = frames; 7007 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize); 7008 } 7009 // resampler accumulates, but we only have one source track 7010 memset(mBuf, 0, frames * mBufFrameSize); 7011 frames = mResampler->resample((int32_t*)mBuf, frames, provider); 7012 // format convert to destination buffer 7013 convertResampler(dst, mBuf, frames); 7014 } 7015 return frames; 7016} 7017 7018status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters( 7019 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat, 7020 uint32_t srcSampleRate, 7021 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat, 7022 uint32_t dstSampleRate) 7023{ 7024 // quick evaluation if there is any change. 7025 if (mSrcFormat == srcFormat 7026 && mSrcChannelMask == srcChannelMask 7027 && mSrcSampleRate == srcSampleRate 7028 && mDstFormat == dstFormat 7029 && mDstChannelMask == dstChannelMask 7030 && mDstSampleRate == dstSampleRate) { 7031 return NO_ERROR; 7032 } 7033 7034 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x" 7035 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u", 7036 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate); 7037 const bool valid = 7038 audio_is_input_channel(srcChannelMask) 7039 && audio_is_input_channel(dstChannelMask) 7040 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat) 7041 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat) 7042 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) 7043 ; // no upsampling checks for now 7044 if (!valid) { 7045 return BAD_VALUE; 7046 } 7047 7048 mSrcFormat = srcFormat; 7049 mSrcChannelMask = srcChannelMask; 7050 mSrcSampleRate = srcSampleRate; 7051 mDstFormat = dstFormat; 7052 mDstChannelMask = dstChannelMask; 7053 mDstSampleRate = dstSampleRate; 7054 7055 // compute derived parameters 7056 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask); 7057 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask); 7058 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat); 7059 7060 // do we need to resample? 7061 delete mResampler; 7062 mResampler = NULL; 7063 if (mSrcSampleRate != mDstSampleRate) { 7064 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT, 7065 mSrcChannelCount, mDstSampleRate); 7066 mResampler->setSampleRate(mSrcSampleRate); 7067 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT); 7068 } 7069 7070 // are we running legacy channel conversion modes? 7071 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO 7072 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK) 7073 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO; 7074 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO 7075 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO 7076 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK); 7077 7078 // do we need to process in float? 7079 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix; 7080 7081 // do we need a staging buffer to convert for destination (we can still optimize this)? 7082 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity 7083 if (mResampler != NULL) { 7084 mBufFrameSize = max(mSrcChannelCount, FCC_2) 7085 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT); 7086 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float 7087 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT); 7088 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) { 7089 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat); 7090 } else { 7091 mBufFrameSize = 0; 7092 } 7093 mBufFrames = 0; // force the buffer to be resized. 7094 7095 // do we need an input converter buffer provider to give us float? 7096 delete mInputConverterProvider; 7097 mInputConverterProvider = NULL; 7098 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) { 7099 mInputConverterProvider = new ReformatBufferProvider( 7100 audio_channel_count_from_in_mask(mSrcChannelMask), 7101 mSrcFormat, 7102 AUDIO_FORMAT_PCM_FLOAT, 7103 256 /* provider buffer frame count */); 7104 } 7105 7106 // do we need a remixer to do channel mask conversion 7107 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) { 7108 (void) memcpy_by_index_array_initialization_from_channel_mask( 7109 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask); 7110 } 7111 return NO_ERROR; 7112} 7113 7114void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler( 7115 void *dst, const void *src, size_t frames) 7116{ 7117 // src is native type unless there is legacy upmix or downmix, whereupon it is float. 7118 if (mBufFrameSize != 0 && mBufFrames < frames) { 7119 free(mBuf); 7120 mBufFrames = frames; 7121 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize); 7122 } 7123 // do we need to do legacy upmix and downmix? 7124 if (mIsLegacyUpmix || mIsLegacyDownmix) { 7125 void *dstBuf = mBuf != NULL ? mBuf : dst; 7126 if (mIsLegacyUpmix) { 7127 upmix_to_stereo_float_from_mono_float((float *)dstBuf, 7128 (const float *)src, frames); 7129 } else /*mIsLegacyDownmix */ { 7130 downmix_to_mono_float_from_stereo_float((float *)dstBuf, 7131 (const float *)src, frames); 7132 } 7133 if (mBuf != NULL) { 7134 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT, 7135 frames * mDstChannelCount); 7136 } 7137 return; 7138 } 7139 // do we need to do channel mask conversion? 7140 if (mSrcChannelMask != mDstChannelMask) { 7141 void *dstBuf = mBuf != NULL ? mBuf : dst; 7142 memcpy_by_index_array(dstBuf, mDstChannelCount, 7143 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames); 7144 if (dstBuf == dst) { 7145 return; // format is the same 7146 } 7147 } 7148 // convert to destination buffer 7149 const void *convertBuf = mBuf != NULL ? mBuf : src; 7150 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat, 7151 frames * mDstChannelCount); 7152} 7153 7154void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler( 7155 void *dst, /*not-a-const*/ void *src, size_t frames) 7156{ 7157 // src buffer format is ALWAYS float when entering this routine 7158 if (mIsLegacyUpmix) { 7159 ; // mono to stereo already handled by resampler 7160 } else if (mIsLegacyDownmix 7161 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) { 7162 // the resampler outputs stereo for mono input channel (a feature?) 7163 // must convert to mono 7164 downmix_to_mono_float_from_stereo_float((float *)src, 7165 (const float *)src, frames); 7166 } else if (mSrcChannelMask != mDstChannelMask) { 7167 // convert to mono channel again for channel mask conversion (could be skipped 7168 // with further optimization). 7169 if (mSrcChannelCount == 1) { 7170 downmix_to_mono_float_from_stereo_float((float *)src, 7171 (const float *)src, frames); 7172 } 7173 // convert to destination format (in place, OK as float is larger than other types) 7174 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) { 7175 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT, 7176 frames * mSrcChannelCount); 7177 } 7178 // channel convert and save to dst 7179 memcpy_by_index_array(dst, mDstChannelCount, 7180 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames); 7181 return; 7182 } 7183 // convert to destination format and save to dst 7184 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT, 7185 frames * mDstChannelCount); 7186} 7187 7188bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair, 7189 status_t& status) 7190{ 7191 bool reconfig = false; 7192 7193 status = NO_ERROR; 7194 7195 audio_format_t reqFormat = mFormat; 7196 uint32_t samplingRate = mSampleRate; 7197 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs). 7198 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount); 7199 7200 AudioParameter param = AudioParameter(keyValuePair); 7201 int value; 7202 7203 // scope for AutoPark extends to end of method 7204 AutoPark<FastCapture> park(mFastCapture); 7205 7206 // TODO Investigate when this code runs. Check with audio policy when a sample rate and 7207 // channel count change can be requested. Do we mandate the first client defines the 7208 // HAL sampling rate and channel count or do we allow changes on the fly? 7209 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 7210 samplingRate = value; 7211 reconfig = true; 7212 } 7213 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 7214 if (!audio_is_linear_pcm((audio_format_t) value)) { 7215 status = BAD_VALUE; 7216 } else { 7217 reqFormat = (audio_format_t) value; 7218 reconfig = true; 7219 } 7220 } 7221 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 7222 audio_channel_mask_t mask = (audio_channel_mask_t) value; 7223 if (!audio_is_input_channel(mask) || 7224 audio_channel_count_from_in_mask(mask) > FCC_8) { 7225 status = BAD_VALUE; 7226 } else { 7227 channelMask = mask; 7228 reconfig = true; 7229 } 7230 } 7231 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 7232 // do not accept frame count changes if tracks are open as the track buffer 7233 // size depends on frame count and correct behavior would not be guaranteed 7234 // if frame count is changed after track creation 7235 if (mActiveTracks.size() > 0) { 7236 status = INVALID_OPERATION; 7237 } else { 7238 reconfig = true; 7239 } 7240 } 7241 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 7242 // forward device change to effects that have requested to be 7243 // aware of attached audio device. 7244 for (size_t i = 0; i < mEffectChains.size(); i++) { 7245 mEffectChains[i]->setDevice_l(value); 7246 } 7247 7248 // store input device and output device but do not forward output device to audio HAL. 7249 // Note that status is ignored by the caller for output device 7250 // (see AudioFlinger::setParameters() 7251 if (audio_is_output_devices(value)) { 7252 mOutDevice = value; 7253 status = BAD_VALUE; 7254 } else { 7255 mInDevice = value; 7256 if (value != AUDIO_DEVICE_NONE) { 7257 mPrevInDevice = value; 7258 } 7259 // disable AEC and NS if the device is a BT SCO headset supporting those 7260 // pre processings 7261 if (mTracks.size() > 0) { 7262 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 7263 mAudioFlinger->btNrecIsOff(); 7264 for (size_t i = 0; i < mTracks.size(); i++) { 7265 sp<RecordTrack> track = mTracks[i]; 7266 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 7267 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 7268 } 7269 } 7270 } 7271 } 7272 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 7273 mAudioSource != (audio_source_t)value) { 7274 // forward device change to effects that have requested to be 7275 // aware of attached audio device. 7276 for (size_t i = 0; i < mEffectChains.size(); i++) { 7277 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 7278 } 7279 mAudioSource = (audio_source_t)value; 7280 } 7281 7282 if (status == NO_ERROR) { 7283 status = mInput->stream->setParameters(keyValuePair); 7284 if (status == INVALID_OPERATION) { 7285 inputStandBy(); 7286 status = mInput->stream->setParameters(keyValuePair); 7287 } 7288 if (reconfig) { 7289 if (status == BAD_VALUE) { 7290 uint32_t sRate; 7291 audio_channel_mask_t channelMask; 7292 audio_format_t format; 7293 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK && 7294 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) && 7295 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) && 7296 audio_channel_count_from_in_mask(channelMask) <= FCC_8) { 7297 status = NO_ERROR; 7298 } 7299 } 7300 if (status == NO_ERROR) { 7301 readInputParameters_l(); 7302 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7303 } 7304 } 7305 } 7306 7307 return reconfig; 7308} 7309 7310String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 7311{ 7312 Mutex::Autolock _l(mLock); 7313 if (initCheck() == NO_ERROR) { 7314 String8 out_s8; 7315 if (mInput->stream->getParameters(keys, &out_s8) == OK) { 7316 return out_s8; 7317 } 7318 } 7319 return String8(); 7320} 7321 7322void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 7323 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 7324 7325 desc->mIoHandle = mId; 7326 7327 switch (event) { 7328 case AUDIO_INPUT_OPENED: 7329 case AUDIO_INPUT_CONFIG_CHANGED: 7330 desc->mPatch = mPatch; 7331 desc->mChannelMask = mChannelMask; 7332 desc->mSamplingRate = mSampleRate; 7333 desc->mFormat = mFormat; 7334 desc->mFrameCount = mFrameCount; 7335 desc->mFrameCountHAL = mFrameCount; 7336 desc->mLatency = 0; 7337 break; 7338 7339 case AUDIO_INPUT_CLOSED: 7340 default: 7341 break; 7342 } 7343 mAudioFlinger->ioConfigChanged(event, desc, pid); 7344} 7345 7346void AudioFlinger::RecordThread::readInputParameters_l() 7347{ 7348 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat); 7349 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result); 7350 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 7351 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8); 7352 mFormat = mHALFormat; 7353 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat); 7354 result = mInput->stream->getFrameSize(&mFrameSize); 7355 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result); 7356 result = mInput->stream->getBufferSize(&mBufferSize); 7357 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result); 7358 mFrameCount = mBufferSize / mFrameSize; 7359 // This is the formula for calculating the temporary buffer size. 7360 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to 7361 // 1 full output buffer, regardless of the alignment of the available input. 7362 // The value is somewhat arbitrary, and could probably be even larger. 7363 // A larger value should allow more old data to be read after a track calls start(), 7364 // without increasing latency. 7365 // 7366 // Note this is independent of the maximum downsampling ratio permitted for capture. 7367 mRsmpInFrames = mFrameCount * 7; 7368 mRsmpInFramesP2 = roundup(mRsmpInFrames); 7369 free(mRsmpInBuffer); 7370 mRsmpInBuffer = NULL; 7371 7372 // TODO optimize audio capture buffer sizes ... 7373 // Here we calculate the size of the sliding buffer used as a source 7374 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7). 7375 // For current HAL frame counts, this is usually 2048 = 40 ms. It would 7376 // be better to have it derived from the pipe depth in the long term. 7377 // The current value is higher than necessary. However it should not add to latency. 7378 7379 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 7380 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1; 7381 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize); 7382 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here. 7383 7384 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints. 7385 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks? 7386} 7387 7388uint32_t AudioFlinger::RecordThread::getInputFramesLost() 7389{ 7390 Mutex::Autolock _l(mLock); 7391 uint32_t result; 7392 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) { 7393 return result; 7394 } 7395 return 0; 7396} 7397 7398// hasAudioSession_l() must be called with ThreadBase::mLock held 7399uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const 7400{ 7401 uint32_t result = 0; 7402 if (getEffectChain_l(sessionId) != 0) { 7403 result = EFFECT_SESSION; 7404 } 7405 7406 for (size_t i = 0; i < mTracks.size(); ++i) { 7407 if (sessionId == mTracks[i]->sessionId()) { 7408 result |= TRACK_SESSION; 7409 if (mTracks[i]->isFastTrack()) { 7410 result |= FAST_SESSION; 7411 } 7412 break; 7413 } 7414 } 7415 7416 return result; 7417} 7418 7419KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const 7420{ 7421 KeyedVector<audio_session_t, bool> ids; 7422 Mutex::Autolock _l(mLock); 7423 for (size_t j = 0; j < mTracks.size(); ++j) { 7424 sp<RecordThread::RecordTrack> track = mTracks[j]; 7425 audio_session_t sessionId = track->sessionId(); 7426 if (ids.indexOfKey(sessionId) < 0) { 7427 ids.add(sessionId, true); 7428 } 7429 } 7430 return ids; 7431} 7432 7433AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 7434{ 7435 Mutex::Autolock _l(mLock); 7436 AudioStreamIn *input = mInput; 7437 mInput = NULL; 7438 return input; 7439} 7440 7441// this method must always be called either with ThreadBase mLock held or inside the thread loop 7442sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const 7443{ 7444 if (mInput == NULL) { 7445 return NULL; 7446 } 7447 return mInput->stream; 7448} 7449 7450status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 7451{ 7452 // only one chain per input thread 7453 if (mEffectChains.size() != 0) { 7454 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this); 7455 return INVALID_OPERATION; 7456 } 7457 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 7458 chain->setThread(this); 7459 chain->setInBuffer(NULL); 7460 chain->setOutBuffer(NULL); 7461 7462 checkSuspendOnAddEffectChain_l(chain); 7463 7464 // make sure enabled pre processing effects state is communicated to the HAL as we 7465 // just moved them to a new input stream. 7466 chain->syncHalEffectsState(); 7467 7468 mEffectChains.add(chain); 7469 7470 return NO_ERROR; 7471} 7472 7473size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 7474{ 7475 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 7476 ALOGW_IF(mEffectChains.size() != 1, 7477 "removeEffectChain_l() %p invalid chain size %zu on thread %p", 7478 chain.get(), mEffectChains.size(), this); 7479 if (mEffectChains.size() == 1) { 7480 mEffectChains.removeAt(0); 7481 } 7482 return 0; 7483} 7484 7485status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch, 7486 audio_patch_handle_t *handle) 7487{ 7488 status_t status = NO_ERROR; 7489 7490 // store new device and send to effects 7491 mInDevice = patch->sources[0].ext.device.type; 7492 mPatch = *patch; 7493 for (size_t i = 0; i < mEffectChains.size(); i++) { 7494 mEffectChains[i]->setDevice_l(mInDevice); 7495 } 7496 7497 // disable AEC and NS if the device is a BT SCO headset supporting those 7498 // pre processings 7499 if (mTracks.size() > 0) { 7500 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 7501 mAudioFlinger->btNrecIsOff(); 7502 for (size_t i = 0; i < mTracks.size(); i++) { 7503 sp<RecordTrack> track = mTracks[i]; 7504 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 7505 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 7506 } 7507 } 7508 7509 // store new source and send to effects 7510 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 7511 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 7512 for (size_t i = 0; i < mEffectChains.size(); i++) { 7513 mEffectChains[i]->setAudioSource_l(mAudioSource); 7514 } 7515 } 7516 7517 if (mInput->audioHwDev->supportsAudioPatches()) { 7518 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice(); 7519 status = hwDevice->createAudioPatch(patch->num_sources, 7520 patch->sources, 7521 patch->num_sinks, 7522 patch->sinks, 7523 handle); 7524 } else { 7525 char *address; 7526 if (strcmp(patch->sources[0].ext.device.address, "") != 0) { 7527 address = audio_device_address_to_parameter( 7528 patch->sources[0].ext.device.type, 7529 patch->sources[0].ext.device.address); 7530 } else { 7531 address = (char *)calloc(1, 1); 7532 } 7533 AudioParameter param = AudioParameter(String8(address)); 7534 free(address); 7535 param.addInt(String8(AudioParameter::keyRouting), 7536 (int)patch->sources[0].ext.device.type); 7537 param.addInt(String8(AudioParameter::keyInputSource), 7538 (int)patch->sinks[0].ext.mix.usecase.source); 7539 status = mInput->stream->setParameters(param.toString()); 7540 *handle = AUDIO_PATCH_HANDLE_NONE; 7541 } 7542 7543 if (mInDevice != mPrevInDevice) { 7544 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7545 mPrevInDevice = mInDevice; 7546 } 7547 7548 return status; 7549} 7550 7551status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 7552{ 7553 status_t status = NO_ERROR; 7554 7555 mInDevice = AUDIO_DEVICE_NONE; 7556 7557 if (mInput->audioHwDev->supportsAudioPatches()) { 7558 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice(); 7559 status = hwDevice->releaseAudioPatch(handle); 7560 } else { 7561 AudioParameter param; 7562 param.addInt(String8(AudioParameter::keyRouting), 0); 7563 status = mInput->stream->setParameters(param.toString()); 7564 } 7565 return status; 7566} 7567 7568void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record) 7569{ 7570 Mutex::Autolock _l(mLock); 7571 mTracks.add(record); 7572} 7573 7574void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record) 7575{ 7576 Mutex::Autolock _l(mLock); 7577 destroyTrack_l(record); 7578} 7579 7580void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config) 7581{ 7582 ThreadBase::getAudioPortConfig(config); 7583 config->role = AUDIO_PORT_ROLE_SINK; 7584 config->ext.mix.hw_module = mInput->audioHwDev->handle(); 7585 config->ext.mix.usecase.source = mAudioSource; 7586} 7587 7588} // namespace android 7589