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