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