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