Threads.cpp revision e77540228e1f60b1129a1615d2e43e0bf8015d3c
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 = mPowerManager->asBinder(); 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 // mLatchD, mLatchQ, 1260 mLatchDValid(false), mLatchQValid(false) 1261{ 1262 snprintf(mName, kNameLength, "AudioOut_%X", id); 1263 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 1264 1265 // Assumes constructor is called by AudioFlinger with it's mLock held, but 1266 // it would be safer to explicitly pass initial masterVolume/masterMute as 1267 // parameter. 1268 // 1269 // If the HAL we are using has support for master volume or master mute, 1270 // then do not attenuate or mute during mixing (just leave the volume at 1.0 1271 // and the mute set to false). 1272 mMasterVolume = audioFlinger->masterVolume_l(); 1273 mMasterMute = audioFlinger->masterMute_l(); 1274 if (mOutput && mOutput->audioHwDev) { 1275 if (mOutput->audioHwDev->canSetMasterVolume()) { 1276 mMasterVolume = 1.0; 1277 } 1278 1279 if (mOutput->audioHwDev->canSetMasterMute()) { 1280 mMasterMute = false; 1281 } 1282 } 1283 1284 readOutputParameters_l(); 1285 1286 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 1287 // There is no AUDIO_STREAM_MIN, and ++ 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 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, 1294 // because mAudioFlinger doesn't have one to copy from 1295} 1296 1297AudioFlinger::PlaybackThread::~PlaybackThread() 1298{ 1299 mAudioFlinger->unregisterWriter(mNBLogWriter); 1300 free(mSinkBuffer); 1301 free(mMixerBuffer); 1302 free(mEffectBuffer); 1303} 1304 1305void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1306{ 1307 dumpInternals(fd, args); 1308 dumpTracks(fd, args); 1309 dumpEffectChains(fd, args); 1310} 1311 1312void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused) 1313{ 1314 const size_t SIZE = 256; 1315 char buffer[SIZE]; 1316 String8 result; 1317 1318 result.appendFormat(" Stream volumes in dB: "); 1319 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1320 const stream_type_t *st = &mStreamTypes[i]; 1321 if (i > 0) { 1322 result.appendFormat(", "); 1323 } 1324 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1325 if (st->mute) { 1326 result.append("M"); 1327 } 1328 } 1329 result.append("\n"); 1330 write(fd, result.string(), result.length()); 1331 result.clear(); 1332 1333 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1334 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1335 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n", 1336 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1337 1338 size_t numtracks = mTracks.size(); 1339 size_t numactive = mActiveTracks.size(); 1340 dprintf(fd, " %d Tracks", numtracks); 1341 size_t numactiveseen = 0; 1342 if (numtracks) { 1343 dprintf(fd, " of which %d are active\n", numactive); 1344 Track::appendDumpHeader(result); 1345 for (size_t i = 0; i < numtracks; ++i) { 1346 sp<Track> track = mTracks[i]; 1347 if (track != 0) { 1348 bool active = mActiveTracks.indexOf(track) >= 0; 1349 if (active) { 1350 numactiveseen++; 1351 } 1352 track->dump(buffer, SIZE, active); 1353 result.append(buffer); 1354 } 1355 } 1356 } else { 1357 result.append("\n"); 1358 } 1359 if (numactiveseen != numactive) { 1360 // some tracks in the active list were not in the tracks list 1361 snprintf(buffer, SIZE, " The following tracks are in the active list but" 1362 " not in the track list\n"); 1363 result.append(buffer); 1364 Track::appendDumpHeader(result); 1365 for (size_t i = 0; i < numactive; ++i) { 1366 sp<Track> track = mActiveTracks[i].promote(); 1367 if (track != 0 && mTracks.indexOf(track) < 0) { 1368 track->dump(buffer, SIZE, true); 1369 result.append(buffer); 1370 } 1371 } 1372 } 1373 1374 write(fd, result.string(), result.size()); 1375} 1376 1377void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1378{ 1379 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type())); 1380 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount); 1381 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime)); 1382 dprintf(fd, " Total writes: %d\n", mNumWrites); 1383 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites); 1384 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no"); 1385 dprintf(fd, " Suspend count: %d\n", mSuspended); 1386 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer); 1387 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer); 1388 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer); 1389 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask); 1390 AudioStreamOut *output = mOutput; 1391 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE; 1392 String8 flagsAsString = outputFlagsToString(flags); 1393 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string()); 1394 1395 dumpBase(fd, args); 1396} 1397 1398// Thread virtuals 1399 1400void AudioFlinger::PlaybackThread::onFirstRef() 1401{ 1402 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1403} 1404 1405// ThreadBase virtuals 1406void AudioFlinger::PlaybackThread::preExit() 1407{ 1408 ALOGV(" preExit()"); 1409 // FIXME this is using hard-coded strings but in the future, this functionality will be 1410 // converted to use audio HAL extensions required to support tunneling 1411 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1"); 1412} 1413 1414// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1415sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1416 const sp<AudioFlinger::Client>& client, 1417 audio_stream_type_t streamType, 1418 uint32_t sampleRate, 1419 audio_format_t format, 1420 audio_channel_mask_t channelMask, 1421 size_t *pFrameCount, 1422 const sp<IMemory>& sharedBuffer, 1423 int sessionId, 1424 IAudioFlinger::track_flags_t *flags, 1425 pid_t tid, 1426 int uid, 1427 status_t *status) 1428{ 1429 size_t frameCount = *pFrameCount; 1430 sp<Track> track; 1431 status_t lStatus; 1432 1433 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0; 1434 1435 // client expresses a preference for FAST, but we get the final say 1436 if (*flags & IAudioFlinger::TRACK_FAST) { 1437 if ( 1438 // not timed 1439 (!isTimed) && 1440 // either of these use cases: 1441 ( 1442 // use case 1: shared buffer with any frame count 1443 ( 1444 (sharedBuffer != 0) 1445 ) || 1446 // use case 2: callback handler and frame count is default or at least as large as HAL 1447 ( 1448 (tid != -1) && 1449 ((frameCount == 0) || 1450 (frameCount >= mFrameCount)) 1451 ) 1452 ) && 1453 // PCM data 1454 audio_is_linear_pcm(format) && 1455 // identical channel mask to sink, or mono in and stereo sink 1456 (channelMask == mChannelMask || 1457 (channelMask == AUDIO_CHANNEL_OUT_MONO && 1458 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) && 1459 // hardware sample rate 1460 (sampleRate == mSampleRate) && 1461 // normal mixer has an associated fast mixer 1462 hasFastMixer() && 1463 // there are sufficient fast track slots available 1464 (mFastTrackAvailMask != 0) 1465 // FIXME test that MixerThread for this fast track has a capable output HAL 1466 // FIXME add a permission test also? 1467 ) { 1468 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count 1469 if (frameCount == 0) { 1470 // read the fast track multiplier property the first time it is needed 1471 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit); 1472 if (ok != 0) { 1473 ALOGE("%s pthread_once failed: %d", __func__, ok); 1474 } 1475 frameCount = mFrameCount * sFastTrackMultiplier; 1476 } 1477 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 1478 frameCount, mFrameCount); 1479 } else { 1480 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " 1481 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x " 1482 "sampleRate=%u mSampleRate=%u " 1483 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1484 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat, 1485 audio_is_linear_pcm(format), 1486 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1487 *flags &= ~IAudioFlinger::TRACK_FAST; 1488 // For compatibility with AudioTrack calculation, buffer depth is forced 1489 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1490 // This is probably too conservative, but legacy application code may depend on it. 1491 // If you change this calculation, also review the start threshold which is related. 1492 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); 1493 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1494 if (minBufCount < 2) { 1495 minBufCount = 2; 1496 } 1497 size_t minFrameCount = mNormalFrameCount * minBufCount; 1498 if (frameCount < minFrameCount) { 1499 frameCount = minFrameCount; 1500 } 1501 } 1502 } 1503 *pFrameCount = frameCount; 1504 1505 switch (mType) { 1506 1507 case DIRECT: 1508 if (audio_is_linear_pcm(format)) { 1509 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1510 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x " 1511 "for output %p with format %#x", 1512 sampleRate, format, channelMask, mOutput, mFormat); 1513 lStatus = BAD_VALUE; 1514 goto Exit; 1515 } 1516 } 1517 break; 1518 1519 case OFFLOAD: 1520 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1521 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \"" 1522 "for output %p with format %#x", 1523 sampleRate, format, channelMask, mOutput, mFormat); 1524 lStatus = BAD_VALUE; 1525 goto Exit; 1526 } 1527 break; 1528 1529 default: 1530 if (!audio_is_linear_pcm(format)) { 1531 ALOGE("createTrack_l() Bad parameter: format %#x \"" 1532 "for output %p with format %#x", 1533 format, mOutput, mFormat); 1534 lStatus = BAD_VALUE; 1535 goto Exit; 1536 } 1537 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) { 1538 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1539 lStatus = BAD_VALUE; 1540 goto Exit; 1541 } 1542 break; 1543 1544 } 1545 1546 lStatus = initCheck(); 1547 if (lStatus != NO_ERROR) { 1548 ALOGE("createTrack_l() audio driver not initialized"); 1549 goto Exit; 1550 } 1551 1552 { // scope for mLock 1553 Mutex::Autolock _l(mLock); 1554 1555 // all tracks in same audio session must share the same routing strategy otherwise 1556 // conflicts will happen when tracks are moved from one output to another by audio policy 1557 // manager 1558 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1559 for (size_t i = 0; i < mTracks.size(); ++i) { 1560 sp<Track> t = mTracks[i]; 1561 if (t != 0 && t->isExternalTrack()) { 1562 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1563 if (sessionId == t->sessionId() && strategy != actual) { 1564 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1565 strategy, actual); 1566 lStatus = BAD_VALUE; 1567 goto Exit; 1568 } 1569 } 1570 } 1571 1572 if (!isTimed) { 1573 track = new Track(this, client, streamType, sampleRate, format, 1574 channelMask, frameCount, NULL, sharedBuffer, 1575 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT); 1576 } else { 1577 track = TimedTrack::create(this, client, streamType, sampleRate, format, 1578 channelMask, frameCount, sharedBuffer, sessionId, uid); 1579 } 1580 1581 // new Track always returns non-NULL, 1582 // but TimedTrack::create() is a factory that could fail by returning NULL 1583 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; 1584 if (lStatus != NO_ERROR) { 1585 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus); 1586 // track must be cleared from the caller as the caller has the AF lock 1587 goto Exit; 1588 } 1589 mTracks.add(track); 1590 1591 sp<EffectChain> chain = getEffectChain_l(sessionId); 1592 if (chain != 0) { 1593 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1594 track->setMainBuffer(chain->inBuffer()); 1595 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 1596 chain->incTrackCnt(); 1597 } 1598 1599 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 1600 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1601 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 1602 // so ask activity manager to do this on our behalf 1603 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 1604 } 1605 } 1606 1607 lStatus = NO_ERROR; 1608 1609Exit: 1610 *status = lStatus; 1611 return track; 1612} 1613 1614uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 1615{ 1616 return latency; 1617} 1618 1619uint32_t AudioFlinger::PlaybackThread::latency() const 1620{ 1621 Mutex::Autolock _l(mLock); 1622 return latency_l(); 1623} 1624uint32_t AudioFlinger::PlaybackThread::latency_l() const 1625{ 1626 if (initCheck() == NO_ERROR) { 1627 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream)); 1628 } else { 1629 return 0; 1630 } 1631} 1632 1633void AudioFlinger::PlaybackThread::setMasterVolume(float value) 1634{ 1635 Mutex::Autolock _l(mLock); 1636 // Don't apply master volume in SW if our HAL can do it for us. 1637 if (mOutput && mOutput->audioHwDev && 1638 mOutput->audioHwDev->canSetMasterVolume()) { 1639 mMasterVolume = 1.0; 1640 } else { 1641 mMasterVolume = value; 1642 } 1643} 1644 1645void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1646{ 1647 Mutex::Autolock _l(mLock); 1648 // Don't apply master mute in SW if our HAL can do it for us. 1649 if (mOutput && mOutput->audioHwDev && 1650 mOutput->audioHwDev->canSetMasterMute()) { 1651 mMasterMute = false; 1652 } else { 1653 mMasterMute = muted; 1654 } 1655} 1656 1657void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1658{ 1659 Mutex::Autolock _l(mLock); 1660 mStreamTypes[stream].volume = value; 1661 broadcast_l(); 1662} 1663 1664void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1665{ 1666 Mutex::Autolock _l(mLock); 1667 mStreamTypes[stream].mute = muted; 1668 broadcast_l(); 1669} 1670 1671float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1672{ 1673 Mutex::Autolock _l(mLock); 1674 return mStreamTypes[stream].volume; 1675} 1676 1677// addTrack_l() must be called with ThreadBase::mLock held 1678status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1679{ 1680 status_t status = ALREADY_EXISTS; 1681 1682 // set retry count for buffer fill 1683 track->mRetryCount = kMaxTrackStartupRetries; 1684 if (mActiveTracks.indexOf(track) < 0) { 1685 // the track is newly added, make sure it fills up all its 1686 // buffers before playing. This is to ensure the client will 1687 // effectively get the latency it requested. 1688 if (track->isExternalTrack()) { 1689 TrackBase::track_state state = track->mState; 1690 mLock.unlock(); 1691 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId()); 1692 mLock.lock(); 1693 // abort track was stopped/paused while we released the lock 1694 if (state != track->mState) { 1695 if (status == NO_ERROR) { 1696 mLock.unlock(); 1697 AudioSystem::stopOutput(mId, track->streamType(), 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 // Calculate size of normal sink buffer relative to the HAL output buffer size 1915 double multiplier = 1.0; 1916 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 1917 kUseFastMixer == FastMixer_Dynamic)) { 1918 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000; 1919 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000; 1920 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 1921 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 1922 maxNormalFrameCount = maxNormalFrameCount & ~15; 1923 if (maxNormalFrameCount < minNormalFrameCount) { 1924 maxNormalFrameCount = minNormalFrameCount; 1925 } 1926 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 1927 if (multiplier <= 1.0) { 1928 multiplier = 1.0; 1929 } else if (multiplier <= 2.0) { 1930 if (2 * mFrameCount <= maxNormalFrameCount) { 1931 multiplier = 2.0; 1932 } else { 1933 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 1934 } 1935 } else { 1936 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL 1937 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast 1938 // track, but we sometimes have to do this to satisfy the maximum frame count 1939 // constraint) 1940 // FIXME this rounding up should not be done if no HAL SRC 1941 uint32_t truncMult = (uint32_t) multiplier; 1942 if ((truncMult & 1)) { 1943 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { 1944 ++truncMult; 1945 } 1946 } 1947 multiplier = (double) truncMult; 1948 } 1949 } 1950 mNormalFrameCount = multiplier * mFrameCount; 1951 // round up to nearest 16 frames to satisfy AudioMixer 1952 if (mType == MIXER || mType == DUPLICATING) { 1953 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 1954 } 1955 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount, 1956 mNormalFrameCount); 1957 1958 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames. 1959 // Originally this was int16_t[] array, need to remove legacy implications. 1960 free(mSinkBuffer); 1961 mSinkBuffer = NULL; 1962 // For sink buffer size, we use the frame size from the downstream sink to avoid problems 1963 // with non PCM formats for compressed music, e.g. AAC, and Offload threads. 1964 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 1965 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 1966 1967 // We resize the mMixerBuffer according to the requirements of the sink buffer which 1968 // drives the output. 1969 free(mMixerBuffer); 1970 mMixerBuffer = NULL; 1971 if (mMixerBufferEnabled) { 1972 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT. 1973 mMixerBufferSize = mNormalFrameCount * mChannelCount 1974 * audio_bytes_per_sample(mMixerBufferFormat); 1975 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize); 1976 } 1977 free(mEffectBuffer); 1978 mEffectBuffer = NULL; 1979 if (mEffectBufferEnabled) { 1980 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only 1981 mEffectBufferSize = mNormalFrameCount * mChannelCount 1982 * audio_bytes_per_sample(mEffectBufferFormat); 1983 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize); 1984 } 1985 1986 // force reconfiguration of effect chains and engines to take new buffer size and audio 1987 // parameters into account 1988 // Note that mLock is not held when readOutputParameters_l() is called from the constructor 1989 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 1990 // matter. 1991 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 1992 Vector< sp<EffectChain> > effectChains = mEffectChains; 1993 for (size_t i = 0; i < effectChains.size(); i ++) { 1994 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 1995 } 1996} 1997 1998 1999status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 2000{ 2001 if (halFrames == NULL || dspFrames == NULL) { 2002 return BAD_VALUE; 2003 } 2004 Mutex::Autolock _l(mLock); 2005 if (initCheck() != NO_ERROR) { 2006 return INVALID_OPERATION; 2007 } 2008 size_t framesWritten = mBytesWritten / mFrameSize; 2009 *halFrames = framesWritten; 2010 2011 if (isSuspended()) { 2012 // return an estimation of rendered frames when the output is suspended 2013 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 2014 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; 2015 return NO_ERROR; 2016 } else { 2017 status_t status; 2018 uint32_t frames; 2019 status = mOutput->stream->get_render_position(mOutput->stream, &frames); 2020 *dspFrames = (size_t)frames; 2021 return status; 2022 } 2023} 2024 2025uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 2026{ 2027 Mutex::Autolock _l(mLock); 2028 uint32_t result = 0; 2029 if (getEffectChain_l(sessionId) != 0) { 2030 result = EFFECT_SESSION; 2031 } 2032 2033 for (size_t i = 0; i < mTracks.size(); ++i) { 2034 sp<Track> track = mTracks[i]; 2035 if (sessionId == track->sessionId() && !track->isInvalid()) { 2036 result |= TRACK_SESSION; 2037 break; 2038 } 2039 } 2040 2041 return result; 2042} 2043 2044uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 2045{ 2046 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2047 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2048 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2049 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2050 } 2051 for (size_t i = 0; i < mTracks.size(); i++) { 2052 sp<Track> track = mTracks[i]; 2053 if (sessionId == track->sessionId() && !track->isInvalid()) { 2054 return AudioSystem::getStrategyForStream(track->streamType()); 2055 } 2056 } 2057 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2058} 2059 2060 2061AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2062{ 2063 Mutex::Autolock _l(mLock); 2064 return mOutput; 2065} 2066 2067AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2068{ 2069 Mutex::Autolock _l(mLock); 2070 AudioStreamOut *output = mOutput; 2071 mOutput = NULL; 2072 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2073 // must push a NULL and wait for ack 2074 mOutputSink.clear(); 2075 mPipeSink.clear(); 2076 mNormalSink.clear(); 2077 return output; 2078} 2079 2080// this method must always be called either with ThreadBase mLock held or inside the thread loop 2081audio_stream_t* AudioFlinger::PlaybackThread::stream() const 2082{ 2083 if (mOutput == NULL) { 2084 return NULL; 2085 } 2086 return &mOutput->stream->common; 2087} 2088 2089uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2090{ 2091 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2092} 2093 2094status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2095{ 2096 if (!isValidSyncEvent(event)) { 2097 return BAD_VALUE; 2098 } 2099 2100 Mutex::Autolock _l(mLock); 2101 2102 for (size_t i = 0; i < mTracks.size(); ++i) { 2103 sp<Track> track = mTracks[i]; 2104 if (event->triggerSession() == track->sessionId()) { 2105 (void) track->setSyncEvent(event); 2106 return NO_ERROR; 2107 } 2108 } 2109 2110 return NAME_NOT_FOUND; 2111} 2112 2113bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 2114{ 2115 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 2116} 2117 2118void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 2119 const Vector< sp<Track> >& tracksToRemove) 2120{ 2121 size_t count = tracksToRemove.size(); 2122 if (count > 0) { 2123 for (size_t i = 0 ; i < count ; i++) { 2124 const sp<Track>& track = tracksToRemove.itemAt(i); 2125 if (track->isExternalTrack()) { 2126 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 2127#ifdef ADD_BATTERY_DATA 2128 // to track the speaker usage 2129 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 2130#endif 2131 if (track->isTerminated()) { 2132 AudioSystem::releaseOutput(mId); 2133 } 2134 } 2135 } 2136 } 2137} 2138 2139void AudioFlinger::PlaybackThread::checkSilentMode_l() 2140{ 2141 if (!mMasterMute) { 2142 char value[PROPERTY_VALUE_MAX]; 2143 if (property_get("ro.audio.silent", value, "0") > 0) { 2144 char *endptr; 2145 unsigned long ul = strtoul(value, &endptr, 0); 2146 if (*endptr == '\0' && ul != 0) { 2147 ALOGD("Silence is golden"); 2148 // The setprop command will not allow a property to be changed after 2149 // the first time it is set, so we don't have to worry about un-muting. 2150 setMasterMute_l(true); 2151 } 2152 } 2153 } 2154} 2155 2156// shared by MIXER and DIRECT, overridden by DUPLICATING 2157ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 2158{ 2159 // FIXME rewrite to reduce number of system calls 2160 mLastWriteTime = systemTime(); 2161 mInWrite = true; 2162 ssize_t bytesWritten; 2163 const size_t offset = mCurrentWriteLength - mBytesRemaining; 2164 2165 // If an NBAIO sink is present, use it to write the normal mixer's submix 2166 if (mNormalSink != 0) { 2167 2168 const size_t count = mBytesRemaining / mFrameSize; 2169 2170 ATRACE_BEGIN("write"); 2171 // update the setpoint when AudioFlinger::mScreenState changes 2172 uint32_t screenState = AudioFlinger::mScreenState; 2173 if (screenState != mScreenState) { 2174 mScreenState = screenState; 2175 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2176 if (pipe != NULL) { 2177 pipe->setAvgFrames((mScreenState & 1) ? 2178 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2179 } 2180 } 2181 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count); 2182 ATRACE_END(); 2183 if (framesWritten > 0) { 2184 bytesWritten = framesWritten * mFrameSize; 2185 } else { 2186 bytesWritten = framesWritten; 2187 } 2188 mLatchDValid = false; 2189 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp); 2190 if (status == NO_ERROR) { 2191 size_t totalFramesWritten = mNormalSink->framesWritten(); 2192 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) { 2193 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition; 2194 // mLatchD.mFramesReleased is set immediately before D is clocked into Q 2195 mLatchDValid = true; 2196 } 2197 } 2198 // otherwise use the HAL / AudioStreamOut directly 2199 } else { 2200 // Direct output and offload threads 2201 2202 if (mUseAsyncWrite) { 2203 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 2204 mWriteAckSequence += 2; 2205 mWriteAckSequence |= 1; 2206 ALOG_ASSERT(mCallbackThread != 0); 2207 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2208 } 2209 // FIXME We should have an implementation of timestamps for direct output threads. 2210 // They are used e.g for multichannel PCM playback over HDMI. 2211 bytesWritten = mOutput->stream->write(mOutput->stream, 2212 (char *)mSinkBuffer + offset, mBytesRemaining); 2213 if (mUseAsyncWrite && 2214 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 2215 // do not wait for async callback in case of error of full write 2216 mWriteAckSequence &= ~1; 2217 ALOG_ASSERT(mCallbackThread != 0); 2218 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2219 } 2220 } 2221 2222 mNumWrites++; 2223 mInWrite = false; 2224 mStandby = false; 2225 return bytesWritten; 2226} 2227 2228void AudioFlinger::PlaybackThread::threadLoop_drain() 2229{ 2230 if (mOutput->stream->drain) { 2231 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 2232 if (mUseAsyncWrite) { 2233 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 2234 mDrainSequence |= 1; 2235 ALOG_ASSERT(mCallbackThread != 0); 2236 mCallbackThread->setDraining(mDrainSequence); 2237 } 2238 mOutput->stream->drain(mOutput->stream, 2239 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY 2240 : AUDIO_DRAIN_ALL); 2241 } 2242} 2243 2244void AudioFlinger::PlaybackThread::threadLoop_exit() 2245{ 2246 // Default implementation has nothing to do 2247} 2248 2249/* 2250The derived values that are cached: 2251 - mSinkBufferSize from frame count * frame size 2252 - activeSleepTime from activeSleepTimeUs() 2253 - idleSleepTime from idleSleepTimeUs() 2254 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 2255 - maxPeriod from frame count and sample rate (MIXER only) 2256 2257The parameters that affect these derived values are: 2258 - frame count 2259 - frame size 2260 - sample rate 2261 - device type: A2DP or not 2262 - device latency 2263 - format: PCM or not 2264 - active sleep time 2265 - idle sleep time 2266*/ 2267 2268void AudioFlinger::PlaybackThread::cacheParameters_l() 2269{ 2270 mSinkBufferSize = mNormalFrameCount * mFrameSize; 2271 activeSleepTime = activeSleepTimeUs(); 2272 idleSleepTime = idleSleepTimeUs(); 2273} 2274 2275void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 2276{ 2277 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 2278 this, streamType, mTracks.size()); 2279 Mutex::Autolock _l(mLock); 2280 2281 size_t size = mTracks.size(); 2282 for (size_t i = 0; i < size; i++) { 2283 sp<Track> t = mTracks[i]; 2284 if (t->streamType() == streamType) { 2285 t->invalidate(); 2286 } 2287 } 2288} 2289 2290status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 2291{ 2292 int session = chain->sessionId(); 2293 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled 2294 ? mEffectBuffer : mSinkBuffer); 2295 bool ownsBuffer = false; 2296 2297 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 2298 if (session > 0) { 2299 // Only one effect chain can be present in direct output thread and it uses 2300 // the sink buffer as input 2301 if (mType != DIRECT) { 2302 size_t numSamples = mNormalFrameCount * mChannelCount; 2303 buffer = new int16_t[numSamples]; 2304 memset(buffer, 0, numSamples * sizeof(int16_t)); 2305 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 2306 ownsBuffer = true; 2307 } 2308 2309 // Attach all tracks with same session ID to this chain. 2310 for (size_t i = 0; i < mTracks.size(); ++i) { 2311 sp<Track> track = mTracks[i]; 2312 if (session == track->sessionId()) { 2313 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 2314 buffer); 2315 track->setMainBuffer(buffer); 2316 chain->incTrackCnt(); 2317 } 2318 } 2319 2320 // indicate all active tracks in the chain 2321 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2322 sp<Track> track = mActiveTracks[i].promote(); 2323 if (track == 0) { 2324 continue; 2325 } 2326 if (session == track->sessionId()) { 2327 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 2328 chain->incActiveTrackCnt(); 2329 } 2330 } 2331 } 2332 chain->setThread(this); 2333 chain->setInBuffer(buffer, ownsBuffer); 2334 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled 2335 ? mEffectBuffer : mSinkBuffer)); 2336 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 2337 // chains list in order to be processed last as it contains output stage effects 2338 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 2339 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 2340 // after track specific effects and before output stage 2341 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 2342 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 2343 // Effect chain for other sessions are inserted at beginning of effect 2344 // chains list to be processed before output mix effects. Relative order between other 2345 // sessions is not important 2346 size_t size = mEffectChains.size(); 2347 size_t i = 0; 2348 for (i = 0; i < size; i++) { 2349 if (mEffectChains[i]->sessionId() < session) { 2350 break; 2351 } 2352 } 2353 mEffectChains.insertAt(chain, i); 2354 checkSuspendOnAddEffectChain_l(chain); 2355 2356 return NO_ERROR; 2357} 2358 2359size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2360{ 2361 int session = chain->sessionId(); 2362 2363 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2364 2365 for (size_t i = 0; i < mEffectChains.size(); i++) { 2366 if (chain == mEffectChains[i]) { 2367 mEffectChains.removeAt(i); 2368 // detach all active tracks from the chain 2369 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2370 sp<Track> track = mActiveTracks[i].promote(); 2371 if (track == 0) { 2372 continue; 2373 } 2374 if (session == track->sessionId()) { 2375 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2376 chain.get(), session); 2377 chain->decActiveTrackCnt(); 2378 } 2379 } 2380 2381 // detach all tracks with same session ID from this chain 2382 for (size_t i = 0; i < mTracks.size(); ++i) { 2383 sp<Track> track = mTracks[i]; 2384 if (session == track->sessionId()) { 2385 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer)); 2386 chain->decTrackCnt(); 2387 } 2388 } 2389 break; 2390 } 2391 } 2392 return mEffectChains.size(); 2393} 2394 2395status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2396 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2397{ 2398 Mutex::Autolock _l(mLock); 2399 return attachAuxEffect_l(track, EffectId); 2400} 2401 2402status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2403 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2404{ 2405 status_t status = NO_ERROR; 2406 2407 if (EffectId == 0) { 2408 track->setAuxBuffer(0, NULL); 2409 } else { 2410 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2411 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2412 if (effect != 0) { 2413 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2414 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2415 } else { 2416 status = INVALID_OPERATION; 2417 } 2418 } else { 2419 status = BAD_VALUE; 2420 } 2421 } 2422 return status; 2423} 2424 2425void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2426{ 2427 for (size_t i = 0; i < mTracks.size(); ++i) { 2428 sp<Track> track = mTracks[i]; 2429 if (track->auxEffectId() == effectId) { 2430 attachAuxEffect_l(track, 0); 2431 } 2432 } 2433} 2434 2435bool AudioFlinger::PlaybackThread::threadLoop() 2436{ 2437 Vector< sp<Track> > tracksToRemove; 2438 2439 standbyTime = systemTime(); 2440 2441 // MIXER 2442 nsecs_t lastWarning = 0; 2443 2444 // DUPLICATING 2445 // FIXME could this be made local to while loop? 2446 writeFrames = 0; 2447 2448 int lastGeneration = 0; 2449 2450 cacheParameters_l(); 2451 sleepTime = idleSleepTime; 2452 2453 if (mType == MIXER) { 2454 sleepTimeShift = 0; 2455 } 2456 2457 CpuStats cpuStats; 2458 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2459 2460 acquireWakeLock(); 2461 2462 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2463 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2464 // and then that string will be logged at the next convenient opportunity. 2465 const char *logString = NULL; 2466 2467 checkSilentMode_l(); 2468 2469 while (!exitPending()) 2470 { 2471 cpuStats.sample(myName); 2472 2473 Vector< sp<EffectChain> > effectChains; 2474 2475 { // scope for mLock 2476 2477 Mutex::Autolock _l(mLock); 2478 2479 processConfigEvents_l(); 2480 2481 if (logString != NULL) { 2482 mNBLogWriter->logTimestamp(); 2483 mNBLogWriter->log(logString); 2484 logString = NULL; 2485 } 2486 2487 // Gather the framesReleased counters for all active tracks, 2488 // and latch them atomically with the timestamp. 2489 // FIXME We're using raw pointers as indices. A unique track ID would be a better index. 2490 mLatchD.mFramesReleased.clear(); 2491 size_t size = mActiveTracks.size(); 2492 for (size_t i = 0; i < size; i++) { 2493 sp<Track> t = mActiveTracks[i].promote(); 2494 if (t != 0) { 2495 mLatchD.mFramesReleased.add(t.get(), 2496 t->mAudioTrackServerProxy->framesReleased()); 2497 } 2498 } 2499 if (mLatchDValid) { 2500 mLatchQ = mLatchD; 2501 mLatchDValid = false; 2502 mLatchQValid = true; 2503 } 2504 2505 saveOutputTracks(); 2506 if (mSignalPending) { 2507 // A signal was raised while we were unlocked 2508 mSignalPending = false; 2509 } else if (waitingAsyncCallback_l()) { 2510 if (exitPending()) { 2511 break; 2512 } 2513 releaseWakeLock_l(); 2514 mWakeLockUids.clear(); 2515 mActiveTracksGeneration++; 2516 ALOGV("wait async completion"); 2517 mWaitWorkCV.wait(mLock); 2518 ALOGV("async completion/wake"); 2519 acquireWakeLock_l(); 2520 standbyTime = systemTime() + standbyDelay; 2521 sleepTime = 0; 2522 2523 continue; 2524 } 2525 if ((!mActiveTracks.size() && systemTime() > standbyTime) || 2526 isSuspended()) { 2527 // put audio hardware into standby after short delay 2528 if (shouldStandby_l()) { 2529 2530 threadLoop_standby(); 2531 2532 mStandby = true; 2533 } 2534 2535 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2536 // we're about to wait, flush the binder command buffer 2537 IPCThreadState::self()->flushCommands(); 2538 2539 clearOutputTracks(); 2540 2541 if (exitPending()) { 2542 break; 2543 } 2544 2545 releaseWakeLock_l(); 2546 mWakeLockUids.clear(); 2547 mActiveTracksGeneration++; 2548 // wait until we have something to do... 2549 ALOGV("%s going to sleep", myName.string()); 2550 mWaitWorkCV.wait(mLock); 2551 ALOGV("%s waking up", myName.string()); 2552 acquireWakeLock_l(); 2553 2554 mMixerStatus = MIXER_IDLE; 2555 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2556 mBytesWritten = 0; 2557 mBytesRemaining = 0; 2558 checkSilentMode_l(); 2559 2560 standbyTime = systemTime() + standbyDelay; 2561 sleepTime = idleSleepTime; 2562 if (mType == MIXER) { 2563 sleepTimeShift = 0; 2564 } 2565 2566 continue; 2567 } 2568 } 2569 // mMixerStatusIgnoringFastTracks is also updated internally 2570 mMixerStatus = prepareTracks_l(&tracksToRemove); 2571 2572 // compare with previously applied list 2573 if (lastGeneration != mActiveTracksGeneration) { 2574 // update wakelock 2575 updateWakeLockUids_l(mWakeLockUids); 2576 lastGeneration = mActiveTracksGeneration; 2577 } 2578 2579 // prevent any changes in effect chain list and in each effect chain 2580 // during mixing and effect process as the audio buffers could be deleted 2581 // or modified if an effect is created or deleted 2582 lockEffectChains_l(effectChains); 2583 } // mLock scope ends 2584 2585 if (mBytesRemaining == 0) { 2586 mCurrentWriteLength = 0; 2587 if (mMixerStatus == MIXER_TRACKS_READY) { 2588 // threadLoop_mix() sets mCurrentWriteLength 2589 threadLoop_mix(); 2590 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 2591 && (mMixerStatus != MIXER_DRAIN_ALL)) { 2592 // threadLoop_sleepTime sets sleepTime to 0 if data 2593 // must be written to HAL 2594 threadLoop_sleepTime(); 2595 if (sleepTime == 0) { 2596 mCurrentWriteLength = mSinkBufferSize; 2597 } 2598 } 2599 // Either threadLoop_mix() or threadLoop_sleepTime() should have set 2600 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0. 2601 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid) 2602 // or mSinkBuffer (if there are no effects). 2603 // 2604 // This is done pre-effects computation; if effects change to 2605 // support higher precision, this needs to move. 2606 // 2607 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l(). 2608 // TODO use sleepTime == 0 as an additional condition. 2609 if (mMixerBufferValid) { 2610 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer; 2611 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat; 2612 2613 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat, 2614 mNormalFrameCount * mChannelCount); 2615 } 2616 2617 mBytesRemaining = mCurrentWriteLength; 2618 if (isSuspended()) { 2619 sleepTime = suspendSleepTimeUs(); 2620 // simulate write to HAL when suspended 2621 mBytesWritten += mSinkBufferSize; 2622 mBytesRemaining = 0; 2623 } 2624 2625 // only process effects if we're going to write 2626 if (sleepTime == 0 && mType != OFFLOAD) { 2627 for (size_t i = 0; i < effectChains.size(); i ++) { 2628 effectChains[i]->process_l(); 2629 } 2630 } 2631 } 2632 // Process effect chains for offloaded thread even if no audio 2633 // was read from audio track: process only updates effect state 2634 // and thus does have to be synchronized with audio writes but may have 2635 // to be called while waiting for async write callback 2636 if (mType == OFFLOAD) { 2637 for (size_t i = 0; i < effectChains.size(); i ++) { 2638 effectChains[i]->process_l(); 2639 } 2640 } 2641 2642 // Only if the Effects buffer is enabled and there is data in the 2643 // Effects buffer (buffer valid), we need to 2644 // copy into the sink buffer. 2645 // TODO use sleepTime == 0 as an additional condition. 2646 if (mEffectBufferValid) { 2647 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat); 2648 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat, 2649 mNormalFrameCount * mChannelCount); 2650 } 2651 2652 // enable changes in effect chain 2653 unlockEffectChains(effectChains); 2654 2655 if (!waitingAsyncCallback()) { 2656 // sleepTime == 0 means we must write to audio hardware 2657 if (sleepTime == 0) { 2658 if (mBytesRemaining) { 2659 ssize_t ret = threadLoop_write(); 2660 if (ret < 0) { 2661 mBytesRemaining = 0; 2662 } else { 2663 mBytesWritten += ret; 2664 mBytesRemaining -= ret; 2665 } 2666 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 2667 (mMixerStatus == MIXER_DRAIN_ALL)) { 2668 threadLoop_drain(); 2669 } 2670 if (mType == MIXER) { 2671 // write blocked detection 2672 nsecs_t now = systemTime(); 2673 nsecs_t delta = now - mLastWriteTime; 2674 if (!mStandby && delta > maxPeriod) { 2675 mNumDelayedWrites++; 2676 if ((now - lastWarning) > kWarningThrottleNs) { 2677 ATRACE_NAME("underrun"); 2678 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2679 ns2ms(delta), mNumDelayedWrites, this); 2680 lastWarning = now; 2681 } 2682 } 2683 } 2684 2685 } else { 2686 ATRACE_BEGIN("sleep"); 2687 usleep(sleepTime); 2688 ATRACE_END(); 2689 } 2690 } 2691 2692 // Finally let go of removed track(s), without the lock held 2693 // since we can't guarantee the destructors won't acquire that 2694 // same lock. This will also mutate and push a new fast mixer state. 2695 threadLoop_removeTracks(tracksToRemove); 2696 tracksToRemove.clear(); 2697 2698 // FIXME I don't understand the need for this here; 2699 // it was in the original code but maybe the 2700 // assignment in saveOutputTracks() makes this unnecessary? 2701 clearOutputTracks(); 2702 2703 // Effect chains will be actually deleted here if they were removed from 2704 // mEffectChains list during mixing or effects processing 2705 effectChains.clear(); 2706 2707 // FIXME Note that the above .clear() is no longer necessary since effectChains 2708 // is now local to this block, but will keep it for now (at least until merge done). 2709 } 2710 2711 threadLoop_exit(); 2712 2713 if (!mStandby) { 2714 threadLoop_standby(); 2715 mStandby = true; 2716 } 2717 2718 releaseWakeLock(); 2719 mWakeLockUids.clear(); 2720 mActiveTracksGeneration++; 2721 2722 ALOGV("Thread %p type %d exiting", this, mType); 2723 return false; 2724} 2725 2726// removeTracks_l() must be called with ThreadBase::mLock held 2727void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 2728{ 2729 size_t count = tracksToRemove.size(); 2730 if (count > 0) { 2731 for (size_t i=0 ; i<count ; i++) { 2732 const sp<Track>& track = tracksToRemove.itemAt(i); 2733 mActiveTracks.remove(track); 2734 mWakeLockUids.remove(track->uid()); 2735 mActiveTracksGeneration++; 2736 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 2737 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2738 if (chain != 0) { 2739 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 2740 track->sessionId()); 2741 chain->decActiveTrackCnt(); 2742 } 2743 if (track->isTerminated()) { 2744 removeTrack_l(track); 2745 } 2746 } 2747 } 2748 2749} 2750 2751status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 2752{ 2753 if (mNormalSink != 0) { 2754 return mNormalSink->getTimestamp(timestamp); 2755 } 2756 if ((mType == OFFLOAD || mType == DIRECT) && mOutput->stream->get_presentation_position) { 2757 uint64_t position64; 2758 int ret = mOutput->stream->get_presentation_position( 2759 mOutput->stream, &position64, ×tamp.mTime); 2760 if (ret == 0) { 2761 timestamp.mPosition = (uint32_t)position64; 2762 return NO_ERROR; 2763 } 2764 } 2765 return INVALID_OPERATION; 2766} 2767 2768status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch, 2769 audio_patch_handle_t *handle) 2770{ 2771 status_t status = NO_ERROR; 2772 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 2773 // store new device and send to effects 2774 audio_devices_t type = AUDIO_DEVICE_NONE; 2775 for (unsigned int i = 0; i < patch->num_sinks; i++) { 2776 type |= patch->sinks[i].ext.device.type; 2777 } 2778 mOutDevice = type; 2779 for (size_t i = 0; i < mEffectChains.size(); i++) { 2780 mEffectChains[i]->setDevice_l(mOutDevice); 2781 } 2782 2783 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice(); 2784 status = hwDevice->create_audio_patch(hwDevice, 2785 patch->num_sources, 2786 patch->sources, 2787 patch->num_sinks, 2788 patch->sinks, 2789 handle); 2790 } else { 2791 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL"); 2792 } 2793 return status; 2794} 2795 2796status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 2797{ 2798 status_t status = NO_ERROR; 2799 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 2800 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice(); 2801 status = hwDevice->release_audio_patch(hwDevice, handle); 2802 } else { 2803 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL"); 2804 } 2805 return status; 2806} 2807 2808void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track) 2809{ 2810 Mutex::Autolock _l(mLock); 2811 mTracks.add(track); 2812} 2813 2814void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track) 2815{ 2816 Mutex::Autolock _l(mLock); 2817 destroyTrack_l(track); 2818} 2819 2820void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config) 2821{ 2822 ThreadBase::getAudioPortConfig(config); 2823 config->role = AUDIO_PORT_ROLE_SOURCE; 2824 config->ext.mix.hw_module = mOutput->audioHwDev->handle(); 2825 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT; 2826} 2827 2828// ---------------------------------------------------------------------------- 2829 2830AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2831 audio_io_handle_t id, audio_devices_t device, type_t type) 2832 : PlaybackThread(audioFlinger, output, id, device, type), 2833 // mAudioMixer below 2834 // mFastMixer below 2835 mFastMixerFutex(0) 2836 // mOutputSink below 2837 // mPipeSink below 2838 // mNormalSink below 2839{ 2840 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2841 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 2842 "mFrameCount=%d, mNormalFrameCount=%d", 2843 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2844 mNormalFrameCount); 2845 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2846 2847 // create an NBAIO sink for the HAL output stream, and negotiate 2848 mOutputSink = new AudioStreamOutSink(output->stream); 2849 size_t numCounterOffers = 0; 2850 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 2851 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2852 ALOG_ASSERT(index == 0); 2853 2854 // initialize fast mixer depending on configuration 2855 bool initFastMixer; 2856 switch (kUseFastMixer) { 2857 case FastMixer_Never: 2858 initFastMixer = false; 2859 break; 2860 case FastMixer_Always: 2861 initFastMixer = true; 2862 break; 2863 case FastMixer_Static: 2864 case FastMixer_Dynamic: 2865 initFastMixer = mFrameCount < mNormalFrameCount; 2866 break; 2867 } 2868 if (initFastMixer) { 2869 audio_format_t fastMixerFormat; 2870 if (mMixerBufferEnabled && mEffectBufferEnabled) { 2871 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT; 2872 } else { 2873 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT; 2874 } 2875 if (mFormat != fastMixerFormat) { 2876 // change our Sink format to accept our intermediate precision 2877 mFormat = fastMixerFormat; 2878 free(mSinkBuffer); 2879 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 2880 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 2881 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 2882 } 2883 2884 // create a MonoPipe to connect our submix to FastMixer 2885 NBAIO_Format format = mOutputSink->format(); 2886 NBAIO_Format origformat = format; 2887 // adjust format to match that of the Fast Mixer 2888 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat); 2889 format.mFormat = fastMixerFormat; 2890 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount; 2891 2892 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2893 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2894 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2895 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2896 const NBAIO_Format offers[1] = {format}; 2897 size_t numCounterOffers = 0; 2898 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2899 ALOG_ASSERT(index == 0); 2900 monoPipe->setAvgFrames((mScreenState & 1) ? 2901 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2902 mPipeSink = monoPipe; 2903 2904#ifdef TEE_SINK 2905 if (mTeeSinkOutputEnabled) { 2906 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2907 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat); 2908 const NBAIO_Format offers2[1] = {origformat}; 2909 numCounterOffers = 0; 2910 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers); 2911 ALOG_ASSERT(index == 0); 2912 mTeeSink = teeSink; 2913 PipeReader *teeSource = new PipeReader(*teeSink); 2914 numCounterOffers = 0; 2915 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers); 2916 ALOG_ASSERT(index == 0); 2917 mTeeSource = teeSource; 2918 } 2919#endif 2920 2921 // create fast mixer and configure it initially with just one fast track for our submix 2922 mFastMixer = new FastMixer(); 2923 FastMixerStateQueue *sq = mFastMixer->sq(); 2924#ifdef STATE_QUEUE_DUMP 2925 sq->setObserverDump(&mStateQueueObserverDump); 2926 sq->setMutatorDump(&mStateQueueMutatorDump); 2927#endif 2928 FastMixerState *state = sq->begin(); 2929 FastTrack *fastTrack = &state->mFastTracks[0]; 2930 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2931 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2932 fastTrack->mVolumeProvider = NULL; 2933 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer 2934 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer 2935 fastTrack->mGeneration++; 2936 state->mFastTracksGen++; 2937 state->mTrackMask = 1; 2938 // fast mixer will use the HAL output sink 2939 state->mOutputSink = mOutputSink.get(); 2940 state->mOutputSinkGen++; 2941 state->mFrameCount = mFrameCount; 2942 state->mCommand = FastMixerState::COLD_IDLE; 2943 // already done in constructor initialization list 2944 //mFastMixerFutex = 0; 2945 state->mColdFutexAddr = &mFastMixerFutex; 2946 state->mColdGen++; 2947 state->mDumpState = &mFastMixerDumpState; 2948#ifdef TEE_SINK 2949 state->mTeeSink = mTeeSink.get(); 2950#endif 2951 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 2952 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 2953 sq->end(); 2954 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2955 2956 // start the fast mixer 2957 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2958 pid_t tid = mFastMixer->getTid(); 2959 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2960 if (err != 0) { 2961 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2962 kPriorityFastMixer, getpid_cached, tid, err); 2963 } 2964 2965#ifdef AUDIO_WATCHDOG 2966 // create and start the watchdog 2967 mAudioWatchdog = new AudioWatchdog(); 2968 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2969 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2970 tid = mAudioWatchdog->getTid(); 2971 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2972 if (err != 0) { 2973 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2974 kPriorityFastMixer, getpid_cached, tid, err); 2975 } 2976#endif 2977 2978 } 2979 2980 switch (kUseFastMixer) { 2981 case FastMixer_Never: 2982 case FastMixer_Dynamic: 2983 mNormalSink = mOutputSink; 2984 break; 2985 case FastMixer_Always: 2986 mNormalSink = mPipeSink; 2987 break; 2988 case FastMixer_Static: 2989 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2990 break; 2991 } 2992} 2993 2994AudioFlinger::MixerThread::~MixerThread() 2995{ 2996 if (mFastMixer != 0) { 2997 FastMixerStateQueue *sq = mFastMixer->sq(); 2998 FastMixerState *state = sq->begin(); 2999 if (state->mCommand == FastMixerState::COLD_IDLE) { 3000 int32_t old = android_atomic_inc(&mFastMixerFutex); 3001 if (old == -1) { 3002 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3003 } 3004 } 3005 state->mCommand = FastMixerState::EXIT; 3006 sq->end(); 3007 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3008 mFastMixer->join(); 3009 // Though the fast mixer thread has exited, it's state queue is still valid. 3010 // We'll use that extract the final state which contains one remaining fast track 3011 // corresponding to our sub-mix. 3012 state = sq->begin(); 3013 ALOG_ASSERT(state->mTrackMask == 1); 3014 FastTrack *fastTrack = &state->mFastTracks[0]; 3015 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 3016 delete fastTrack->mBufferProvider; 3017 sq->end(false /*didModify*/); 3018 mFastMixer.clear(); 3019#ifdef AUDIO_WATCHDOG 3020 if (mAudioWatchdog != 0) { 3021 mAudioWatchdog->requestExit(); 3022 mAudioWatchdog->requestExitAndWait(); 3023 mAudioWatchdog.clear(); 3024 } 3025#endif 3026 } 3027 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 3028 delete mAudioMixer; 3029} 3030 3031 3032uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 3033{ 3034 if (mFastMixer != 0) { 3035 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 3036 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 3037 } 3038 return latency; 3039} 3040 3041 3042void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 3043{ 3044 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 3045} 3046 3047ssize_t AudioFlinger::MixerThread::threadLoop_write() 3048{ 3049 // FIXME we should only do one push per cycle; confirm this is true 3050 // Start the fast mixer if it's not already running 3051 if (mFastMixer != 0) { 3052 FastMixerStateQueue *sq = mFastMixer->sq(); 3053 FastMixerState *state = sq->begin(); 3054 if (state->mCommand != FastMixerState::MIX_WRITE && 3055 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 3056 if (state->mCommand == FastMixerState::COLD_IDLE) { 3057 int32_t old = android_atomic_inc(&mFastMixerFutex); 3058 if (old == -1) { 3059 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3060 } 3061#ifdef AUDIO_WATCHDOG 3062 if (mAudioWatchdog != 0) { 3063 mAudioWatchdog->resume(); 3064 } 3065#endif 3066 } 3067 state->mCommand = FastMixerState::MIX_WRITE; 3068 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 3069 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 3070 sq->end(); 3071 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3072 if (kUseFastMixer == FastMixer_Dynamic) { 3073 mNormalSink = mPipeSink; 3074 } 3075 } else { 3076 sq->end(false /*didModify*/); 3077 } 3078 } 3079 return PlaybackThread::threadLoop_write(); 3080} 3081 3082void AudioFlinger::MixerThread::threadLoop_standby() 3083{ 3084 // Idle the fast mixer if it's currently running 3085 if (mFastMixer != 0) { 3086 FastMixerStateQueue *sq = mFastMixer->sq(); 3087 FastMixerState *state = sq->begin(); 3088 if (!(state->mCommand & FastMixerState::IDLE)) { 3089 state->mCommand = FastMixerState::COLD_IDLE; 3090 state->mColdFutexAddr = &mFastMixerFutex; 3091 state->mColdGen++; 3092 mFastMixerFutex = 0; 3093 sq->end(); 3094 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 3095 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3096 if (kUseFastMixer == FastMixer_Dynamic) { 3097 mNormalSink = mOutputSink; 3098 } 3099#ifdef AUDIO_WATCHDOG 3100 if (mAudioWatchdog != 0) { 3101 mAudioWatchdog->pause(); 3102 } 3103#endif 3104 } else { 3105 sq->end(false /*didModify*/); 3106 } 3107 } 3108 PlaybackThread::threadLoop_standby(); 3109} 3110 3111bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 3112{ 3113 return false; 3114} 3115 3116bool AudioFlinger::PlaybackThread::shouldStandby_l() 3117{ 3118 return !mStandby; 3119} 3120 3121bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 3122{ 3123 Mutex::Autolock _l(mLock); 3124 return waitingAsyncCallback_l(); 3125} 3126 3127// shared by MIXER and DIRECT, overridden by DUPLICATING 3128void AudioFlinger::PlaybackThread::threadLoop_standby() 3129{ 3130 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 3131 mOutput->stream->common.standby(&mOutput->stream->common); 3132 if (mUseAsyncWrite != 0) { 3133 // discard any pending drain or write ack by incrementing sequence 3134 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 3135 mDrainSequence = (mDrainSequence + 2) & ~1; 3136 ALOG_ASSERT(mCallbackThread != 0); 3137 mCallbackThread->setWriteBlocked(mWriteAckSequence); 3138 mCallbackThread->setDraining(mDrainSequence); 3139 } 3140} 3141 3142void AudioFlinger::PlaybackThread::onAddNewTrack_l() 3143{ 3144 ALOGV("signal playback thread"); 3145 broadcast_l(); 3146} 3147 3148void AudioFlinger::MixerThread::threadLoop_mix() 3149{ 3150 // obtain the presentation timestamp of the next output buffer 3151 int64_t pts; 3152 status_t status = INVALID_OPERATION; 3153 3154 if (mNormalSink != 0) { 3155 status = mNormalSink->getNextWriteTimestamp(&pts); 3156 } else { 3157 status = mOutputSink->getNextWriteTimestamp(&pts); 3158 } 3159 3160 if (status != NO_ERROR) { 3161 pts = AudioBufferProvider::kInvalidPTS; 3162 } 3163 3164 // mix buffers... 3165 mAudioMixer->process(pts); 3166 mCurrentWriteLength = mSinkBufferSize; 3167 // increase sleep time progressively when application underrun condition clears. 3168 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 3169 // that a steady state of alternating ready/not ready conditions keeps the sleep time 3170 // such that we would underrun the audio HAL. 3171 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 3172 sleepTimeShift--; 3173 } 3174 sleepTime = 0; 3175 standbyTime = systemTime() + standbyDelay; 3176 //TODO: delay standby when effects have a tail 3177 3178} 3179 3180void AudioFlinger::MixerThread::threadLoop_sleepTime() 3181{ 3182 // If no tracks are ready, sleep once for the duration of an output 3183 // buffer size, then write 0s to the output 3184 if (sleepTime == 0) { 3185 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3186 sleepTime = activeSleepTime >> sleepTimeShift; 3187 if (sleepTime < kMinThreadSleepTimeUs) { 3188 sleepTime = kMinThreadSleepTimeUs; 3189 } 3190 // reduce sleep time in case of consecutive application underruns to avoid 3191 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 3192 // duration we would end up writing less data than needed by the audio HAL if 3193 // the condition persists. 3194 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 3195 sleepTimeShift++; 3196 } 3197 } else { 3198 sleepTime = idleSleepTime; 3199 } 3200 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 3201 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared 3202 // before effects processing or output. 3203 if (mMixerBufferValid) { 3204 memset(mMixerBuffer, 0, mMixerBufferSize); 3205 } else { 3206 memset(mSinkBuffer, 0, mSinkBufferSize); 3207 } 3208 sleepTime = 0; 3209 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 3210 "anticipated start"); 3211 } 3212 // TODO add standby time extension fct of effect tail 3213} 3214 3215// prepareTracks_l() must be called with ThreadBase::mLock held 3216AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 3217 Vector< sp<Track> > *tracksToRemove) 3218{ 3219 3220 mixer_state mixerStatus = MIXER_IDLE; 3221 // find out which tracks need to be processed 3222 size_t count = mActiveTracks.size(); 3223 size_t mixedTracks = 0; 3224 size_t tracksWithEffect = 0; 3225 // counts only _active_ fast tracks 3226 size_t fastTracks = 0; 3227 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 3228 3229 float masterVolume = mMasterVolume; 3230 bool masterMute = mMasterMute; 3231 3232 if (masterMute) { 3233 masterVolume = 0; 3234 } 3235 // Delegate master volume control to effect in output mix effect chain if needed 3236 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 3237 if (chain != 0) { 3238 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 3239 chain->setVolume_l(&v, &v); 3240 masterVolume = (float)((v + (1 << 23)) >> 24); 3241 chain.clear(); 3242 } 3243 3244 // prepare a new state to push 3245 FastMixerStateQueue *sq = NULL; 3246 FastMixerState *state = NULL; 3247 bool didModify = false; 3248 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 3249 if (mFastMixer != 0) { 3250 sq = mFastMixer->sq(); 3251 state = sq->begin(); 3252 } 3253 3254 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found. 3255 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found. 3256 3257 for (size_t i=0 ; i<count ; i++) { 3258 const sp<Track> t = mActiveTracks[i].promote(); 3259 if (t == 0) { 3260 continue; 3261 } 3262 3263 // this const just means the local variable doesn't change 3264 Track* const track = t.get(); 3265 3266 // process fast tracks 3267 if (track->isFastTrack()) { 3268 3269 // It's theoretically possible (though unlikely) for a fast track to be created 3270 // and then removed within the same normal mix cycle. This is not a problem, as 3271 // the track never becomes active so it's fast mixer slot is never touched. 3272 // The converse, of removing an (active) track and then creating a new track 3273 // at the identical fast mixer slot within the same normal mix cycle, 3274 // is impossible because the slot isn't marked available until the end of each cycle. 3275 int j = track->mFastIndex; 3276 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 3277 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 3278 FastTrack *fastTrack = &state->mFastTracks[j]; 3279 3280 // Determine whether the track is currently in underrun condition, 3281 // and whether it had a recent underrun. 3282 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 3283 FastTrackUnderruns underruns = ftDump->mUnderruns; 3284 uint32_t recentFull = (underruns.mBitFields.mFull - 3285 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 3286 uint32_t recentPartial = (underruns.mBitFields.mPartial - 3287 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 3288 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 3289 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 3290 uint32_t recentUnderruns = recentPartial + recentEmpty; 3291 track->mObservedUnderruns = underruns; 3292 // don't count underruns that occur while stopping or pausing 3293 // or stopped which can occur when flush() is called while active 3294 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 3295 recentUnderruns > 0) { 3296 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 3297 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 3298 } 3299 3300 // This is similar to the state machine for normal tracks, 3301 // with a few modifications for fast tracks. 3302 bool isActive = true; 3303 switch (track->mState) { 3304 case TrackBase::STOPPING_1: 3305 // track stays active in STOPPING_1 state until first underrun 3306 if (recentUnderruns > 0 || track->isTerminated()) { 3307 track->mState = TrackBase::STOPPING_2; 3308 } 3309 break; 3310 case TrackBase::PAUSING: 3311 // ramp down is not yet implemented 3312 track->setPaused(); 3313 break; 3314 case TrackBase::RESUMING: 3315 // ramp up is not yet implemented 3316 track->mState = TrackBase::ACTIVE; 3317 break; 3318 case TrackBase::ACTIVE: 3319 if (recentFull > 0 || recentPartial > 0) { 3320 // track has provided at least some frames recently: reset retry count 3321 track->mRetryCount = kMaxTrackRetries; 3322 } 3323 if (recentUnderruns == 0) { 3324 // no recent underruns: stay active 3325 break; 3326 } 3327 // there has recently been an underrun of some kind 3328 if (track->sharedBuffer() == 0) { 3329 // were any of the recent underruns "empty" (no frames available)? 3330 if (recentEmpty == 0) { 3331 // no, then ignore the partial underruns as they are allowed indefinitely 3332 break; 3333 } 3334 // there has recently been an "empty" underrun: decrement the retry counter 3335 if (--(track->mRetryCount) > 0) { 3336 break; 3337 } 3338 // indicate to client process that the track was disabled because of underrun; 3339 // it will then automatically call start() when data is available 3340 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 3341 // remove from active list, but state remains ACTIVE [confusing but true] 3342 isActive = false; 3343 break; 3344 } 3345 // fall through 3346 case TrackBase::STOPPING_2: 3347 case TrackBase::PAUSED: 3348 case TrackBase::STOPPED: 3349 case TrackBase::FLUSHED: // flush() while active 3350 // Check for presentation complete if track is inactive 3351 // We have consumed all the buffers of this track. 3352 // This would be incomplete if we auto-paused on underrun 3353 { 3354 size_t audioHALFrames = 3355 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3356 size_t framesWritten = mBytesWritten / mFrameSize; 3357 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 3358 // track stays in active list until presentation is complete 3359 break; 3360 } 3361 } 3362 if (track->isStopping_2()) { 3363 track->mState = TrackBase::STOPPED; 3364 } 3365 if (track->isStopped()) { 3366 // Can't reset directly, as fast mixer is still polling this track 3367 // track->reset(); 3368 // So instead mark this track as needing to be reset after push with ack 3369 resetMask |= 1 << i; 3370 } 3371 isActive = false; 3372 break; 3373 case TrackBase::IDLE: 3374 default: 3375 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState); 3376 } 3377 3378 if (isActive) { 3379 // was it previously inactive? 3380 if (!(state->mTrackMask & (1 << j))) { 3381 ExtendedAudioBufferProvider *eabp = track; 3382 VolumeProvider *vp = track; 3383 fastTrack->mBufferProvider = eabp; 3384 fastTrack->mVolumeProvider = vp; 3385 fastTrack->mChannelMask = track->mChannelMask; 3386 fastTrack->mFormat = track->mFormat; 3387 fastTrack->mGeneration++; 3388 state->mTrackMask |= 1 << j; 3389 didModify = true; 3390 // no acknowledgement required for newly active tracks 3391 } 3392 // cache the combined master volume and stream type volume for fast mixer; this 3393 // lacks any synchronization or barrier so VolumeProvider may read a stale value 3394 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 3395 ++fastTracks; 3396 } else { 3397 // was it previously active? 3398 if (state->mTrackMask & (1 << j)) { 3399 fastTrack->mBufferProvider = NULL; 3400 fastTrack->mGeneration++; 3401 state->mTrackMask &= ~(1 << j); 3402 didModify = true; 3403 // If any fast tracks were removed, we must wait for acknowledgement 3404 // because we're about to decrement the last sp<> on those tracks. 3405 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3406 } else { 3407 LOG_ALWAYS_FATAL("fast track %d should have been active", j); 3408 } 3409 tracksToRemove->add(track); 3410 // Avoids a misleading display in dumpsys 3411 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 3412 } 3413 continue; 3414 } 3415 3416 { // local variable scope to avoid goto warning 3417 3418 audio_track_cblk_t* cblk = track->cblk(); 3419 3420 // The first time a track is added we wait 3421 // for all its buffers to be filled before processing it 3422 int name = track->name(); 3423 // make sure that we have enough frames to mix one full buffer. 3424 // enforce this condition only once to enable draining the buffer in case the client 3425 // app does not call stop() and relies on underrun to stop: 3426 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 3427 // during last round 3428 size_t desiredFrames; 3429 uint32_t sr = track->sampleRate(); 3430 if (sr == mSampleRate) { 3431 desiredFrames = mNormalFrameCount; 3432 } else { 3433 // +1 for rounding and +1 for additional sample needed for interpolation 3434 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1; 3435 // add frames already consumed but not yet released by the resampler 3436 // because mAudioTrackServerProxy->framesReady() will include these frames 3437 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 3438#if 0 3439 // the minimum track buffer size is normally twice the number of frames necessary 3440 // to fill one buffer and the resampler should not leave more than one buffer worth 3441 // of unreleased frames after each pass, but just in case... 3442 ALOG_ASSERT(desiredFrames <= cblk->frameCount_); 3443#endif 3444 } 3445 uint32_t minFrames = 1; 3446 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 3447 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 3448 minFrames = desiredFrames; 3449 } 3450 3451 size_t framesReady = track->framesReady(); 3452 if (ATRACE_ENABLED()) { 3453 // I wish we had formatted trace names 3454 char traceName[16]; 3455 strcpy(traceName, "nRdy"); 3456 int name = track->name(); 3457 if (AudioMixer::TRACK0 <= name && 3458 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) { 3459 name -= AudioMixer::TRACK0; 3460 traceName[4] = (name / 10) + '0'; 3461 traceName[5] = (name % 10) + '0'; 3462 } else { 3463 traceName[4] = '?'; 3464 traceName[5] = '?'; 3465 } 3466 traceName[6] = '\0'; 3467 ATRACE_INT(traceName, framesReady); 3468 } 3469 if ((framesReady >= minFrames) && track->isReady() && 3470 !track->isPaused() && !track->isTerminated()) 3471 { 3472 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 3473 3474 mixedTracks++; 3475 3476 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means 3477 // there is an effect chain connected to the track 3478 chain.clear(); 3479 if (track->mainBuffer() != mSinkBuffer && 3480 track->mainBuffer() != mMixerBuffer) { 3481 if (mEffectBufferEnabled) { 3482 mEffectBufferValid = true; // Later can set directly. 3483 } 3484 chain = getEffectChain_l(track->sessionId()); 3485 // Delegate volume control to effect in track effect chain if needed 3486 if (chain != 0) { 3487 tracksWithEffect++; 3488 } else { 3489 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 3490 "session %d", 3491 name, track->sessionId()); 3492 } 3493 } 3494 3495 3496 int param = AudioMixer::VOLUME; 3497 if (track->mFillingUpStatus == Track::FS_FILLED) { 3498 // no ramp for the first volume setting 3499 track->mFillingUpStatus = Track::FS_ACTIVE; 3500 if (track->mState == TrackBase::RESUMING) { 3501 track->mState = TrackBase::ACTIVE; 3502 param = AudioMixer::RAMP_VOLUME; 3503 } 3504 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3505 // FIXME should not make a decision based on mServer 3506 } else if (cblk->mServer != 0) { 3507 // If the track is stopped before the first frame was mixed, 3508 // do not apply ramp 3509 param = AudioMixer::RAMP_VOLUME; 3510 } 3511 3512 // compute volume for this track 3513 uint32_t vl, vr; // in U8.24 integer format 3514 float vlf, vrf, vaf; // in [0.0, 1.0] float format 3515 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 3516 vl = vr = 0; 3517 vlf = vrf = vaf = 0.; 3518 if (track->isPausing()) { 3519 track->setPaused(); 3520 } 3521 } else { 3522 3523 // read original volumes with volume control 3524 float typeVolume = mStreamTypes[track->streamType()].volume; 3525 float v = masterVolume * typeVolume; 3526 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3527 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 3528 vlf = float_from_gain(gain_minifloat_unpack_left(vlr)); 3529 vrf = float_from_gain(gain_minifloat_unpack_right(vlr)); 3530 // track volumes come from shared memory, so can't be trusted and must be clamped 3531 if (vlf > GAIN_FLOAT_UNITY) { 3532 ALOGV("Track left volume out of range: %.3g", vlf); 3533 vlf = GAIN_FLOAT_UNITY; 3534 } 3535 if (vrf > GAIN_FLOAT_UNITY) { 3536 ALOGV("Track right volume out of range: %.3g", vrf); 3537 vrf = GAIN_FLOAT_UNITY; 3538 } 3539 // now apply the master volume and stream type volume 3540 vlf *= v; 3541 vrf *= v; 3542 // assuming master volume and stream type volume each go up to 1.0, 3543 // then derive vl and vr as U8.24 versions for the effect chain 3544 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT; 3545 vl = (uint32_t) (scaleto8_24 * vlf); 3546 vr = (uint32_t) (scaleto8_24 * vrf); 3547 // vl and vr are now in U8.24 format 3548 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 3549 // send level comes from shared memory and so may be corrupt 3550 if (sendLevel > MAX_GAIN_INT) { 3551 ALOGV("Track send level out of range: %04X", sendLevel); 3552 sendLevel = MAX_GAIN_INT; 3553 } 3554 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel 3555 vaf = v * sendLevel * (1. / MAX_GAIN_INT); 3556 } 3557 3558 // Delegate volume control to effect in track effect chain if needed 3559 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3560 // Do not ramp volume if volume is controlled by effect 3561 param = AudioMixer::VOLUME; 3562 // Update remaining floating point volume levels 3563 vlf = (float)vl / (1 << 24); 3564 vrf = (float)vr / (1 << 24); 3565 track->mHasVolumeController = true; 3566 } else { 3567 // force no volume ramp when volume controller was just disabled or removed 3568 // from effect chain to avoid volume spike 3569 if (track->mHasVolumeController) { 3570 param = AudioMixer::VOLUME; 3571 } 3572 track->mHasVolumeController = false; 3573 } 3574 3575 // XXX: these things DON'T need to be done each time 3576 mAudioMixer->setBufferProvider(name, track); 3577 mAudioMixer->enable(name); 3578 3579 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf); 3580 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf); 3581 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf); 3582 mAudioMixer->setParameter( 3583 name, 3584 AudioMixer::TRACK, 3585 AudioMixer::FORMAT, (void *)track->format()); 3586 mAudioMixer->setParameter( 3587 name, 3588 AudioMixer::TRACK, 3589 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask()); 3590 mAudioMixer->setParameter( 3591 name, 3592 AudioMixer::TRACK, 3593 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask); 3594 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3595 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX; 3596 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3597 if (reqSampleRate == 0) { 3598 reqSampleRate = mSampleRate; 3599 } else if (reqSampleRate > maxSampleRate) { 3600 reqSampleRate = maxSampleRate; 3601 } 3602 mAudioMixer->setParameter( 3603 name, 3604 AudioMixer::RESAMPLE, 3605 AudioMixer::SAMPLE_RATE, 3606 (void *)(uintptr_t)reqSampleRate); 3607 /* 3608 * Select the appropriate output buffer for the track. 3609 * 3610 * Tracks with effects go into their own effects chain buffer 3611 * and from there into either mEffectBuffer or mSinkBuffer. 3612 * 3613 * Other tracks can use mMixerBuffer for higher precision 3614 * channel accumulation. If this buffer is enabled 3615 * (mMixerBufferEnabled true), then selected tracks will accumulate 3616 * into it. 3617 * 3618 */ 3619 if (mMixerBufferEnabled 3620 && (track->mainBuffer() == mSinkBuffer 3621 || track->mainBuffer() == mMixerBuffer)) { 3622 mAudioMixer->setParameter( 3623 name, 3624 AudioMixer::TRACK, 3625 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat); 3626 mAudioMixer->setParameter( 3627 name, 3628 AudioMixer::TRACK, 3629 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer); 3630 // TODO: override track->mainBuffer()? 3631 mMixerBufferValid = true; 3632 } else { 3633 mAudioMixer->setParameter( 3634 name, 3635 AudioMixer::TRACK, 3636 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT); 3637 mAudioMixer->setParameter( 3638 name, 3639 AudioMixer::TRACK, 3640 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3641 } 3642 mAudioMixer->setParameter( 3643 name, 3644 AudioMixer::TRACK, 3645 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3646 3647 // reset retry count 3648 track->mRetryCount = kMaxTrackRetries; 3649 3650 // If one track is ready, set the mixer ready if: 3651 // - the mixer was not ready during previous round OR 3652 // - no other track is not ready 3653 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3654 mixerStatus != MIXER_TRACKS_ENABLED) { 3655 mixerStatus = MIXER_TRACKS_READY; 3656 } 3657 } else { 3658 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 3659 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 3660 } 3661 // clear effect chain input buffer if an active track underruns to avoid sending 3662 // previous audio buffer again to effects 3663 chain = getEffectChain_l(track->sessionId()); 3664 if (chain != 0) { 3665 chain->clearInputBuffer(); 3666 } 3667 3668 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 3669 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3670 track->isStopped() || track->isPaused()) { 3671 // We have consumed all the buffers of this track. 3672 // Remove it from the list of active tracks. 3673 // TODO: use actual buffer filling status instead of latency when available from 3674 // audio HAL 3675 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3676 size_t framesWritten = mBytesWritten / mFrameSize; 3677 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3678 if (track->isStopped()) { 3679 track->reset(); 3680 } 3681 tracksToRemove->add(track); 3682 } 3683 } else { 3684 // No buffers for this track. Give it a few chances to 3685 // fill a buffer, then remove it from active list. 3686 if (--(track->mRetryCount) <= 0) { 3687 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3688 tracksToRemove->add(track); 3689 // indicate to client process that the track was disabled because of underrun; 3690 // it will then automatically call start() when data is available 3691 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3692 // If one track is not ready, mark the mixer also not ready if: 3693 // - the mixer was ready during previous round OR 3694 // - no other track is ready 3695 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3696 mixerStatus != MIXER_TRACKS_READY) { 3697 mixerStatus = MIXER_TRACKS_ENABLED; 3698 } 3699 } 3700 mAudioMixer->disable(name); 3701 } 3702 3703 } // local variable scope to avoid goto warning 3704track_is_ready: ; 3705 3706 } 3707 3708 // Push the new FastMixer state if necessary 3709 bool pauseAudioWatchdog = false; 3710 if (didModify) { 3711 state->mFastTracksGen++; 3712 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3713 if (kUseFastMixer == FastMixer_Dynamic && 3714 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3715 state->mCommand = FastMixerState::COLD_IDLE; 3716 state->mColdFutexAddr = &mFastMixerFutex; 3717 state->mColdGen++; 3718 mFastMixerFutex = 0; 3719 if (kUseFastMixer == FastMixer_Dynamic) { 3720 mNormalSink = mOutputSink; 3721 } 3722 // If we go into cold idle, need to wait for acknowledgement 3723 // so that fast mixer stops doing I/O. 3724 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3725 pauseAudioWatchdog = true; 3726 } 3727 } 3728 if (sq != NULL) { 3729 sq->end(didModify); 3730 sq->push(block); 3731 } 3732#ifdef AUDIO_WATCHDOG 3733 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3734 mAudioWatchdog->pause(); 3735 } 3736#endif 3737 3738 // Now perform the deferred reset on fast tracks that have stopped 3739 while (resetMask != 0) { 3740 size_t i = __builtin_ctz(resetMask); 3741 ALOG_ASSERT(i < count); 3742 resetMask &= ~(1 << i); 3743 sp<Track> t = mActiveTracks[i].promote(); 3744 if (t == 0) { 3745 continue; 3746 } 3747 Track* track = t.get(); 3748 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3749 track->reset(); 3750 } 3751 3752 // remove all the tracks that need to be... 3753 removeTracks_l(*tracksToRemove); 3754 3755 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) { 3756 mEffectBufferValid = true; 3757 } 3758 3759 if (mEffectBufferValid) { 3760 // as long as there are effects we should clear the effects buffer, to avoid 3761 // passing a non-clean buffer to the effect chain 3762 memset(mEffectBuffer, 0, mEffectBufferSize); 3763 } 3764 // sink or mix buffer must be cleared if all tracks are connected to an 3765 // effect chain as in this case the mixer will not write to the sink or mix buffer 3766 // and track effects will accumulate into it 3767 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3768 (mixedTracks == 0 && fastTracks > 0))) { 3769 // FIXME as a performance optimization, should remember previous zero status 3770 if (mMixerBufferValid) { 3771 memset(mMixerBuffer, 0, mMixerBufferSize); 3772 // TODO: In testing, mSinkBuffer below need not be cleared because 3773 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer 3774 // after mixing. 3775 // 3776 // To enforce this guarantee: 3777 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3778 // (mixedTracks == 0 && fastTracks > 0)) 3779 // must imply MIXER_TRACKS_READY. 3780 // Later, we may clear buffers regardless, and skip much of this logic. 3781 } 3782 // FIXME as a performance optimization, should remember previous zero status 3783 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize); 3784 } 3785 3786 // if any fast tracks, then status is ready 3787 mMixerStatusIgnoringFastTracks = mixerStatus; 3788 if (fastTracks > 0) { 3789 mixerStatus = MIXER_TRACKS_READY; 3790 } 3791 return mixerStatus; 3792} 3793 3794// getTrackName_l() must be called with ThreadBase::mLock held 3795int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, 3796 audio_format_t format, int sessionId) 3797{ 3798 return mAudioMixer->getTrackName(channelMask, format, sessionId); 3799} 3800 3801// deleteTrackName_l() must be called with ThreadBase::mLock held 3802void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3803{ 3804 ALOGV("remove track (%d) and delete from mixer", name); 3805 mAudioMixer->deleteTrackName(name); 3806} 3807 3808// checkForNewParameter_l() must be called with ThreadBase::mLock held 3809bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair, 3810 status_t& status) 3811{ 3812 bool reconfig = false; 3813 3814 status = NO_ERROR; 3815 3816 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3817 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3818 if (mFastMixer != 0) { 3819 FastMixerStateQueue *sq = mFastMixer->sq(); 3820 FastMixerState *state = sq->begin(); 3821 if (!(state->mCommand & FastMixerState::IDLE)) { 3822 previousCommand = state->mCommand; 3823 state->mCommand = FastMixerState::HOT_IDLE; 3824 sq->end(); 3825 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3826 } else { 3827 sq->end(false /*didModify*/); 3828 } 3829 } 3830 3831 AudioParameter param = AudioParameter(keyValuePair); 3832 int value; 3833 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3834 reconfig = true; 3835 } 3836 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3837 if (!isValidPcmSinkFormat((audio_format_t) value)) { 3838 status = BAD_VALUE; 3839 } else { 3840 // no need to save value, since it's constant 3841 reconfig = true; 3842 } 3843 } 3844 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3845 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) { 3846 status = BAD_VALUE; 3847 } else { 3848 // no need to save value, since it's constant 3849 reconfig = true; 3850 } 3851 } 3852 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3853 // do not accept frame count changes if tracks are open as the track buffer 3854 // size depends on frame count and correct behavior would not be guaranteed 3855 // if frame count is changed after track creation 3856 if (!mTracks.isEmpty()) { 3857 status = INVALID_OPERATION; 3858 } else { 3859 reconfig = true; 3860 } 3861 } 3862 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3863#ifdef ADD_BATTERY_DATA 3864 // when changing the audio output device, call addBatteryData to notify 3865 // the change 3866 if (mOutDevice != value) { 3867 uint32_t params = 0; 3868 // check whether speaker is on 3869 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3870 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3871 } 3872 3873 audio_devices_t deviceWithoutSpeaker 3874 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3875 // check if any other device (except speaker) is on 3876 if (value & deviceWithoutSpeaker ) { 3877 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3878 } 3879 3880 if (params != 0) { 3881 addBatteryData(params); 3882 } 3883 } 3884#endif 3885 3886 // forward device change to effects that have requested to be 3887 // aware of attached audio device. 3888 if (value != AUDIO_DEVICE_NONE) { 3889 mOutDevice = value; 3890 for (size_t i = 0; i < mEffectChains.size(); i++) { 3891 mEffectChains[i]->setDevice_l(mOutDevice); 3892 } 3893 } 3894 } 3895 3896 if (status == NO_ERROR) { 3897 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3898 keyValuePair.string()); 3899 if (!mStandby && status == INVALID_OPERATION) { 3900 mOutput->stream->common.standby(&mOutput->stream->common); 3901 mStandby = true; 3902 mBytesWritten = 0; 3903 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3904 keyValuePair.string()); 3905 } 3906 if (status == NO_ERROR && reconfig) { 3907 readOutputParameters_l(); 3908 delete mAudioMixer; 3909 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3910 for (size_t i = 0; i < mTracks.size() ; i++) { 3911 int name = getTrackName_l(mTracks[i]->mChannelMask, 3912 mTracks[i]->mFormat, mTracks[i]->mSessionId); 3913 if (name < 0) { 3914 break; 3915 } 3916 mTracks[i]->mName = name; 3917 } 3918 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3919 } 3920 } 3921 3922 if (!(previousCommand & FastMixerState::IDLE)) { 3923 ALOG_ASSERT(mFastMixer != 0); 3924 FastMixerStateQueue *sq = mFastMixer->sq(); 3925 FastMixerState *state = sq->begin(); 3926 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3927 state->mCommand = previousCommand; 3928 sq->end(); 3929 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3930 } 3931 3932 return reconfig; 3933} 3934 3935 3936void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3937{ 3938 const size_t SIZE = 256; 3939 char buffer[SIZE]; 3940 String8 result; 3941 3942 PlaybackThread::dumpInternals(fd, args); 3943 3944 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames()); 3945 3946 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3947 const FastMixerDumpState copy(mFastMixerDumpState); 3948 copy.dump(fd); 3949 3950#ifdef STATE_QUEUE_DUMP 3951 // Similar for state queue 3952 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3953 observerCopy.dump(fd); 3954 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3955 mutatorCopy.dump(fd); 3956#endif 3957 3958#ifdef TEE_SINK 3959 // Write the tee output to a .wav file 3960 dumpTee(fd, mTeeSource, mId); 3961#endif 3962 3963#ifdef AUDIO_WATCHDOG 3964 if (mAudioWatchdog != 0) { 3965 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3966 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3967 wdCopy.dump(fd); 3968 } 3969#endif 3970} 3971 3972uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3973{ 3974 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3975} 3976 3977uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3978{ 3979 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3980} 3981 3982void AudioFlinger::MixerThread::cacheParameters_l() 3983{ 3984 PlaybackThread::cacheParameters_l(); 3985 3986 // FIXME: Relaxed timing because of a certain device that can't meet latency 3987 // Should be reduced to 2x after the vendor fixes the driver issue 3988 // increase threshold again due to low power audio mode. The way this warning 3989 // threshold is calculated and its usefulness should be reconsidered anyway. 3990 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3991} 3992 3993// ---------------------------------------------------------------------------- 3994 3995AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3996 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3997 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3998 // mLeftVolFloat, mRightVolFloat 3999{ 4000} 4001 4002AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4003 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 4004 ThreadBase::type_t type) 4005 : PlaybackThread(audioFlinger, output, id, device, type) 4006 // mLeftVolFloat, mRightVolFloat 4007{ 4008} 4009 4010AudioFlinger::DirectOutputThread::~DirectOutputThread() 4011{ 4012} 4013 4014void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 4015{ 4016 audio_track_cblk_t* cblk = track->cblk(); 4017 float left, right; 4018 4019 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 4020 left = right = 0; 4021 } else { 4022 float typeVolume = mStreamTypes[track->streamType()].volume; 4023 float v = mMasterVolume * typeVolume; 4024 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 4025 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 4026 left = float_from_gain(gain_minifloat_unpack_left(vlr)); 4027 if (left > GAIN_FLOAT_UNITY) { 4028 left = GAIN_FLOAT_UNITY; 4029 } 4030 left *= v; 4031 right = float_from_gain(gain_minifloat_unpack_right(vlr)); 4032 if (right > GAIN_FLOAT_UNITY) { 4033 right = GAIN_FLOAT_UNITY; 4034 } 4035 right *= v; 4036 } 4037 4038 if (lastTrack) { 4039 if (left != mLeftVolFloat || right != mRightVolFloat) { 4040 mLeftVolFloat = left; 4041 mRightVolFloat = right; 4042 4043 // Convert volumes from float to 8.24 4044 uint32_t vl = (uint32_t)(left * (1 << 24)); 4045 uint32_t vr = (uint32_t)(right * (1 << 24)); 4046 4047 // Delegate volume control to effect in track effect chain if needed 4048 // only one effect chain can be present on DirectOutputThread, so if 4049 // there is one, the track is connected to it 4050 if (!mEffectChains.isEmpty()) { 4051 mEffectChains[0]->setVolume_l(&vl, &vr); 4052 left = (float)vl / (1 << 24); 4053 right = (float)vr / (1 << 24); 4054 } 4055 if (mOutput->stream->set_volume) { 4056 mOutput->stream->set_volume(mOutput->stream, left, right); 4057 } 4058 } 4059 } 4060} 4061 4062 4063AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 4064 Vector< sp<Track> > *tracksToRemove 4065) 4066{ 4067 size_t count = mActiveTracks.size(); 4068 mixer_state mixerStatus = MIXER_IDLE; 4069 4070 // find out which tracks need to be processed 4071 for (size_t i = 0; i < count; i++) { 4072 sp<Track> t = mActiveTracks[i].promote(); 4073 // The track died recently 4074 if (t == 0) { 4075 continue; 4076 } 4077 4078 Track* const track = t.get(); 4079 audio_track_cblk_t* cblk = track->cblk(); 4080 // Only consider last track started for volume and mixer state control. 4081 // In theory an older track could underrun and restart after the new one starts 4082 // but as we only care about the transition phase between two tracks on a 4083 // direct output, it is not a problem to ignore the underrun case. 4084 sp<Track> l = mLatestActiveTrack.promote(); 4085 bool last = l.get() == track; 4086 4087 // The first time a track is added we wait 4088 // for all its buffers to be filled before processing it 4089 uint32_t minFrames; 4090 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()) { 4091 minFrames = mNormalFrameCount; 4092 } else { 4093 minFrames = 1; 4094 } 4095 4096 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() && 4097 !track->isStopping_2() && !track->isStopped()) 4098 { 4099 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 4100 4101 if (track->mFillingUpStatus == Track::FS_FILLED) { 4102 track->mFillingUpStatus = Track::FS_ACTIVE; 4103 // make sure processVolume_l() will apply new volume even if 0 4104 mLeftVolFloat = mRightVolFloat = -1.0; 4105 if (track->mState == TrackBase::RESUMING) { 4106 track->mState = TrackBase::ACTIVE; 4107 } 4108 } 4109 4110 // compute volume for this track 4111 processVolume_l(track, last); 4112 if (last) { 4113 // reset retry count 4114 track->mRetryCount = kMaxTrackRetriesDirect; 4115 mActiveTrack = t; 4116 mixerStatus = MIXER_TRACKS_READY; 4117 } 4118 } else { 4119 // clear effect chain input buffer if the last active track started underruns 4120 // to avoid sending previous audio buffer again to effects 4121 if (!mEffectChains.isEmpty() && last) { 4122 mEffectChains[0]->clearInputBuffer(); 4123 } 4124 if (track->isStopping_1()) { 4125 track->mState = TrackBase::STOPPING_2; 4126 } 4127 if ((track->sharedBuffer() != 0) || track->isStopped() || 4128 track->isStopping_2() || track->isPaused()) { 4129 // We have consumed all the buffers of this track. 4130 // Remove it from the list of active tracks. 4131 size_t audioHALFrames; 4132 if (audio_is_linear_pcm(mFormat)) { 4133 audioHALFrames = (latency_l() * mSampleRate) / 1000; 4134 } else { 4135 audioHALFrames = 0; 4136 } 4137 4138 size_t framesWritten = mBytesWritten / mFrameSize; 4139 if (mStandby || !last || 4140 track->presentationComplete(framesWritten, audioHALFrames)) { 4141 if (track->isStopping_2()) { 4142 track->mState = TrackBase::STOPPED; 4143 } 4144 if (track->isStopped()) { 4145 if (track->mState == TrackBase::FLUSHED) { 4146 flushHw_l(); 4147 } 4148 track->reset(); 4149 } 4150 tracksToRemove->add(track); 4151 } 4152 } else { 4153 // No buffers for this track. Give it a few chances to 4154 // fill a buffer, then remove it from active list. 4155 // Only consider last track started for mixer state control 4156 if (--(track->mRetryCount) <= 0) { 4157 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 4158 tracksToRemove->add(track); 4159 // indicate to client process that the track was disabled because of underrun; 4160 // it will then automatically call start() when data is available 4161 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4162 } else if (last) { 4163 mixerStatus = MIXER_TRACKS_ENABLED; 4164 } 4165 } 4166 } 4167 } 4168 4169 // remove all the tracks that need to be... 4170 removeTracks_l(*tracksToRemove); 4171 4172 return mixerStatus; 4173} 4174 4175void AudioFlinger::DirectOutputThread::threadLoop_mix() 4176{ 4177 size_t frameCount = mFrameCount; 4178 int8_t *curBuf = (int8_t *)mSinkBuffer; 4179 // output audio to hardware 4180 while (frameCount) { 4181 AudioBufferProvider::Buffer buffer; 4182 buffer.frameCount = frameCount; 4183 mActiveTrack->getNextBuffer(&buffer); 4184 if (buffer.raw == NULL) { 4185 memset(curBuf, 0, frameCount * mFrameSize); 4186 break; 4187 } 4188 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 4189 frameCount -= buffer.frameCount; 4190 curBuf += buffer.frameCount * mFrameSize; 4191 mActiveTrack->releaseBuffer(&buffer); 4192 } 4193 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer; 4194 sleepTime = 0; 4195 standbyTime = systemTime() + standbyDelay; 4196 mActiveTrack.clear(); 4197} 4198 4199void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 4200{ 4201 if (sleepTime == 0) { 4202 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4203 sleepTime = activeSleepTime; 4204 } else { 4205 sleepTime = idleSleepTime; 4206 } 4207 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 4208 memset(mSinkBuffer, 0, mFrameCount * mFrameSize); 4209 sleepTime = 0; 4210 } 4211} 4212 4213// getTrackName_l() must be called with ThreadBase::mLock held 4214int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 4215 audio_format_t format __unused, int sessionId __unused) 4216{ 4217 return 0; 4218} 4219 4220// deleteTrackName_l() must be called with ThreadBase::mLock held 4221void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 4222{ 4223} 4224 4225// checkForNewParameter_l() must be called with ThreadBase::mLock held 4226bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair, 4227 status_t& status) 4228{ 4229 bool reconfig = false; 4230 4231 status = NO_ERROR; 4232 4233 AudioParameter param = AudioParameter(keyValuePair); 4234 int value; 4235 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4236 // forward device change to effects that have requested to be 4237 // aware of attached audio device. 4238 if (value != AUDIO_DEVICE_NONE) { 4239 mOutDevice = value; 4240 for (size_t i = 0; i < mEffectChains.size(); i++) { 4241 mEffectChains[i]->setDevice_l(mOutDevice); 4242 } 4243 } 4244 } 4245 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4246 // do not accept frame count changes if tracks are open as the track buffer 4247 // size depends on frame count and correct behavior would not be garantied 4248 // if frame count is changed after track creation 4249 if (!mTracks.isEmpty()) { 4250 status = INVALID_OPERATION; 4251 } else { 4252 reconfig = true; 4253 } 4254 } 4255 if (status == NO_ERROR) { 4256 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4257 keyValuePair.string()); 4258 if (!mStandby && status == INVALID_OPERATION) { 4259 mOutput->stream->common.standby(&mOutput->stream->common); 4260 mStandby = true; 4261 mBytesWritten = 0; 4262 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4263 keyValuePair.string()); 4264 } 4265 if (status == NO_ERROR && reconfig) { 4266 readOutputParameters_l(); 4267 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 4268 } 4269 } 4270 4271 return reconfig; 4272} 4273 4274uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 4275{ 4276 uint32_t time; 4277 if (audio_is_linear_pcm(mFormat)) { 4278 time = PlaybackThread::activeSleepTimeUs(); 4279 } else { 4280 time = 10000; 4281 } 4282 return time; 4283} 4284 4285uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 4286{ 4287 uint32_t time; 4288 if (audio_is_linear_pcm(mFormat)) { 4289 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 4290 } else { 4291 time = 10000; 4292 } 4293 return time; 4294} 4295 4296uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 4297{ 4298 uint32_t time; 4299 if (audio_is_linear_pcm(mFormat)) { 4300 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 4301 } else { 4302 time = 10000; 4303 } 4304 return time; 4305} 4306 4307void AudioFlinger::DirectOutputThread::cacheParameters_l() 4308{ 4309 PlaybackThread::cacheParameters_l(); 4310 4311 // use shorter standby delay as on normal output to release 4312 // hardware resources as soon as possible 4313 if (audio_is_linear_pcm(mFormat)) { 4314 standbyDelay = microseconds(activeSleepTime*2); 4315 } else { 4316 standbyDelay = kOffloadStandbyDelayNs; 4317 } 4318} 4319 4320void AudioFlinger::DirectOutputThread::flushHw_l() 4321{ 4322 if (mOutput->stream->flush != NULL) 4323 mOutput->stream->flush(mOutput->stream); 4324} 4325 4326// ---------------------------------------------------------------------------- 4327 4328AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 4329 const wp<AudioFlinger::PlaybackThread>& playbackThread) 4330 : Thread(false /*canCallJava*/), 4331 mPlaybackThread(playbackThread), 4332 mWriteAckSequence(0), 4333 mDrainSequence(0) 4334{ 4335} 4336 4337AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 4338{ 4339} 4340 4341void AudioFlinger::AsyncCallbackThread::onFirstRef() 4342{ 4343 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 4344} 4345 4346bool AudioFlinger::AsyncCallbackThread::threadLoop() 4347{ 4348 while (!exitPending()) { 4349 uint32_t writeAckSequence; 4350 uint32_t drainSequence; 4351 4352 { 4353 Mutex::Autolock _l(mLock); 4354 while (!((mWriteAckSequence & 1) || 4355 (mDrainSequence & 1) || 4356 exitPending())) { 4357 mWaitWorkCV.wait(mLock); 4358 } 4359 4360 if (exitPending()) { 4361 break; 4362 } 4363 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 4364 mWriteAckSequence, mDrainSequence); 4365 writeAckSequence = mWriteAckSequence; 4366 mWriteAckSequence &= ~1; 4367 drainSequence = mDrainSequence; 4368 mDrainSequence &= ~1; 4369 } 4370 { 4371 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 4372 if (playbackThread != 0) { 4373 if (writeAckSequence & 1) { 4374 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 4375 } 4376 if (drainSequence & 1) { 4377 playbackThread->resetDraining(drainSequence >> 1); 4378 } 4379 } 4380 } 4381 } 4382 return false; 4383} 4384 4385void AudioFlinger::AsyncCallbackThread::exit() 4386{ 4387 ALOGV("AsyncCallbackThread::exit"); 4388 Mutex::Autolock _l(mLock); 4389 requestExit(); 4390 mWaitWorkCV.broadcast(); 4391} 4392 4393void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 4394{ 4395 Mutex::Autolock _l(mLock); 4396 // bit 0 is cleared 4397 mWriteAckSequence = sequence << 1; 4398} 4399 4400void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 4401{ 4402 Mutex::Autolock _l(mLock); 4403 // ignore unexpected callbacks 4404 if (mWriteAckSequence & 2) { 4405 mWriteAckSequence |= 1; 4406 mWaitWorkCV.signal(); 4407 } 4408} 4409 4410void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 4411{ 4412 Mutex::Autolock _l(mLock); 4413 // bit 0 is cleared 4414 mDrainSequence = sequence << 1; 4415} 4416 4417void AudioFlinger::AsyncCallbackThread::resetDraining() 4418{ 4419 Mutex::Autolock _l(mLock); 4420 // ignore unexpected callbacks 4421 if (mDrainSequence & 2) { 4422 mDrainSequence |= 1; 4423 mWaitWorkCV.signal(); 4424 } 4425} 4426 4427 4428// ---------------------------------------------------------------------------- 4429AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 4430 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 4431 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 4432 mHwPaused(false), 4433 mFlushPending(false), 4434 mPausedBytesRemaining(0) 4435{ 4436 //FIXME: mStandby should be set to true by ThreadBase constructor 4437 mStandby = true; 4438} 4439 4440void AudioFlinger::OffloadThread::threadLoop_exit() 4441{ 4442 if (mFlushPending || mHwPaused) { 4443 // If a flush is pending or track was paused, just discard buffered data 4444 flushHw_l(); 4445 } else { 4446 mMixerStatus = MIXER_DRAIN_ALL; 4447 threadLoop_drain(); 4448 } 4449 if (mUseAsyncWrite) { 4450 ALOG_ASSERT(mCallbackThread != 0); 4451 mCallbackThread->exit(); 4452 } 4453 PlaybackThread::threadLoop_exit(); 4454} 4455 4456AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 4457 Vector< sp<Track> > *tracksToRemove 4458) 4459{ 4460 size_t count = mActiveTracks.size(); 4461 4462 mixer_state mixerStatus = MIXER_IDLE; 4463 bool doHwPause = false; 4464 bool doHwResume = false; 4465 4466 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 4467 4468 // find out which tracks need to be processed 4469 for (size_t i = 0; i < count; i++) { 4470 sp<Track> t = mActiveTracks[i].promote(); 4471 // The track died recently 4472 if (t == 0) { 4473 continue; 4474 } 4475 Track* const track = t.get(); 4476 audio_track_cblk_t* cblk = track->cblk(); 4477 // Only consider last track started for volume and mixer state control. 4478 // In theory an older track could underrun and restart after the new one starts 4479 // but as we only care about the transition phase between two tracks on a 4480 // direct output, it is not a problem to ignore the underrun case. 4481 sp<Track> l = mLatestActiveTrack.promote(); 4482 bool last = l.get() == track; 4483 4484 if (track->isInvalid()) { 4485 ALOGW("An invalidated track shouldn't be in active list"); 4486 tracksToRemove->add(track); 4487 continue; 4488 } 4489 4490 if (track->mState == TrackBase::IDLE) { 4491 ALOGW("An idle track shouldn't be in active list"); 4492 continue; 4493 } 4494 4495 if (track->isPausing()) { 4496 track->setPaused(); 4497 if (last) { 4498 if (!mHwPaused) { 4499 doHwPause = true; 4500 mHwPaused = true; 4501 } 4502 // If we were part way through writing the mixbuffer to 4503 // the HAL we must save this until we resume 4504 // BUG - this will be wrong if a different track is made active, 4505 // in that case we want to discard the pending data in the 4506 // mixbuffer and tell the client to present it again when the 4507 // track is resumed 4508 mPausedWriteLength = mCurrentWriteLength; 4509 mPausedBytesRemaining = mBytesRemaining; 4510 mBytesRemaining = 0; // stop writing 4511 } 4512 tracksToRemove->add(track); 4513 } else if (track->isFlushPending()) { 4514 track->flushAck(); 4515 if (last) { 4516 mFlushPending = true; 4517 } 4518 } else if (track->isResumePending()){ 4519 track->resumeAck(); 4520 if (last) { 4521 if (mPausedBytesRemaining) { 4522 // Need to continue write that was interrupted 4523 mCurrentWriteLength = mPausedWriteLength; 4524 mBytesRemaining = mPausedBytesRemaining; 4525 mPausedBytesRemaining = 0; 4526 } 4527 if (mHwPaused) { 4528 doHwResume = true; 4529 mHwPaused = false; 4530 // threadLoop_mix() will handle the case that we need to 4531 // resume an interrupted write 4532 } 4533 // enable write to audio HAL 4534 sleepTime = 0; 4535 4536 // Do not handle new data in this iteration even if track->framesReady() 4537 mixerStatus = MIXER_TRACKS_ENABLED; 4538 } 4539 } else if (track->framesReady() && track->isReady() && 4540 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 4541 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 4542 if (track->mFillingUpStatus == Track::FS_FILLED) { 4543 track->mFillingUpStatus = Track::FS_ACTIVE; 4544 // make sure processVolume_l() will apply new volume even if 0 4545 mLeftVolFloat = mRightVolFloat = -1.0; 4546 } 4547 4548 if (last) { 4549 sp<Track> previousTrack = mPreviousTrack.promote(); 4550 if (previousTrack != 0) { 4551 if (track != previousTrack.get()) { 4552 // Flush any data still being written from last track 4553 mBytesRemaining = 0; 4554 if (mPausedBytesRemaining) { 4555 // Last track was paused so we also need to flush saved 4556 // mixbuffer state and invalidate track so that it will 4557 // re-submit that unwritten data when it is next resumed 4558 mPausedBytesRemaining = 0; 4559 // Invalidate is a bit drastic - would be more efficient 4560 // to have a flag to tell client that some of the 4561 // previously written data was lost 4562 previousTrack->invalidate(); 4563 } 4564 // flush data already sent to the DSP if changing audio session as audio 4565 // comes from a different source. Also invalidate previous track to force a 4566 // seek when resuming. 4567 if (previousTrack->sessionId() != track->sessionId()) { 4568 previousTrack->invalidate(); 4569 } 4570 } 4571 } 4572 mPreviousTrack = track; 4573 // reset retry count 4574 track->mRetryCount = kMaxTrackRetriesOffload; 4575 mActiveTrack = t; 4576 mixerStatus = MIXER_TRACKS_READY; 4577 } 4578 } else { 4579 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 4580 if (track->isStopping_1()) { 4581 // Hardware buffer can hold a large amount of audio so we must 4582 // wait for all current track's data to drain before we say 4583 // that the track is stopped. 4584 if (mBytesRemaining == 0) { 4585 // Only start draining when all data in mixbuffer 4586 // has been written 4587 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 4588 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 4589 // do not drain if no data was ever sent to HAL (mStandby == true) 4590 if (last && !mStandby) { 4591 // do not modify drain sequence if we are already draining. This happens 4592 // when resuming from pause after drain. 4593 if ((mDrainSequence & 1) == 0) { 4594 sleepTime = 0; 4595 standbyTime = systemTime() + standbyDelay; 4596 mixerStatus = MIXER_DRAIN_TRACK; 4597 mDrainSequence += 2; 4598 } 4599 if (mHwPaused) { 4600 // It is possible to move from PAUSED to STOPPING_1 without 4601 // a resume so we must ensure hardware is running 4602 doHwResume = true; 4603 mHwPaused = false; 4604 } 4605 } 4606 } 4607 } else if (track->isStopping_2()) { 4608 // Drain has completed or we are in standby, signal presentation complete 4609 if (!(mDrainSequence & 1) || !last || mStandby) { 4610 track->mState = TrackBase::STOPPED; 4611 size_t audioHALFrames = 4612 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 4613 size_t framesWritten = 4614 mBytesWritten / audio_stream_out_frame_size(mOutput->stream); 4615 track->presentationComplete(framesWritten, audioHALFrames); 4616 track->reset(); 4617 tracksToRemove->add(track); 4618 } 4619 } else { 4620 // No buffers for this track. Give it a few chances to 4621 // fill a buffer, then remove it from active list. 4622 if (--(track->mRetryCount) <= 0) { 4623 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 4624 track->name()); 4625 tracksToRemove->add(track); 4626 // indicate to client process that the track was disabled because of underrun; 4627 // it will then automatically call start() when data is available 4628 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4629 } else if (last){ 4630 mixerStatus = MIXER_TRACKS_ENABLED; 4631 } 4632 } 4633 } 4634 // compute volume for this track 4635 processVolume_l(track, last); 4636 } 4637 4638 // make sure the pause/flush/resume sequence is executed in the right order. 4639 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 4640 // before flush and then resume HW. This can happen in case of pause/flush/resume 4641 // if resume is received before pause is executed. 4642 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 4643 mOutput->stream->pause(mOutput->stream); 4644 } 4645 if (mFlushPending) { 4646 flushHw_l(); 4647 mFlushPending = false; 4648 } 4649 if (!mStandby && doHwResume) { 4650 mOutput->stream->resume(mOutput->stream); 4651 } 4652 4653 // remove all the tracks that need to be... 4654 removeTracks_l(*tracksToRemove); 4655 4656 return mixerStatus; 4657} 4658 4659// must be called with thread mutex locked 4660bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 4661{ 4662 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 4663 mWriteAckSequence, mDrainSequence); 4664 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 4665 return true; 4666 } 4667 return false; 4668} 4669 4670// must be called with thread mutex locked 4671bool AudioFlinger::OffloadThread::shouldStandby_l() 4672{ 4673 bool trackPaused = false; 4674 4675 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4676 // after a timeout and we will enter standby then. 4677 if (mTracks.size() > 0) { 4678 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4679 } 4680 4681 return !mStandby && !trackPaused; 4682} 4683 4684 4685bool AudioFlinger::OffloadThread::waitingAsyncCallback() 4686{ 4687 Mutex::Autolock _l(mLock); 4688 return waitingAsyncCallback_l(); 4689} 4690 4691void AudioFlinger::OffloadThread::flushHw_l() 4692{ 4693 DirectOutputThread::flushHw_l(); 4694 // Flush anything still waiting in the mixbuffer 4695 mCurrentWriteLength = 0; 4696 mBytesRemaining = 0; 4697 mPausedWriteLength = 0; 4698 mPausedBytesRemaining = 0; 4699 mHwPaused = false; 4700 4701 if (mUseAsyncWrite) { 4702 // discard any pending drain or write ack by incrementing sequence 4703 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 4704 mDrainSequence = (mDrainSequence + 2) & ~1; 4705 ALOG_ASSERT(mCallbackThread != 0); 4706 mCallbackThread->setWriteBlocked(mWriteAckSequence); 4707 mCallbackThread->setDraining(mDrainSequence); 4708 } 4709} 4710 4711void AudioFlinger::OffloadThread::onAddNewTrack_l() 4712{ 4713 sp<Track> previousTrack = mPreviousTrack.promote(); 4714 sp<Track> latestTrack = mLatestActiveTrack.promote(); 4715 4716 if (previousTrack != 0 && latestTrack != 0 && 4717 (previousTrack->sessionId() != latestTrack->sessionId())) { 4718 mFlushPending = true; 4719 } 4720 PlaybackThread::onAddNewTrack_l(); 4721} 4722 4723// ---------------------------------------------------------------------------- 4724 4725AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4726 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4727 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4728 DUPLICATING), 4729 mWaitTimeMs(UINT_MAX) 4730{ 4731 addOutputTrack(mainThread); 4732} 4733 4734AudioFlinger::DuplicatingThread::~DuplicatingThread() 4735{ 4736 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4737 mOutputTracks[i]->destroy(); 4738 } 4739} 4740 4741void AudioFlinger::DuplicatingThread::threadLoop_mix() 4742{ 4743 // mix buffers... 4744 if (outputsReady(outputTracks)) { 4745 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4746 } else { 4747 if (mMixerBufferValid) { 4748 memset(mMixerBuffer, 0, mMixerBufferSize); 4749 } else { 4750 memset(mSinkBuffer, 0, mSinkBufferSize); 4751 } 4752 } 4753 sleepTime = 0; 4754 writeFrames = mNormalFrameCount; 4755 mCurrentWriteLength = mSinkBufferSize; 4756 standbyTime = systemTime() + standbyDelay; 4757} 4758 4759void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4760{ 4761 if (sleepTime == 0) { 4762 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4763 sleepTime = activeSleepTime; 4764 } else { 4765 sleepTime = idleSleepTime; 4766 } 4767 } else if (mBytesWritten != 0) { 4768 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4769 writeFrames = mNormalFrameCount; 4770 memset(mSinkBuffer, 0, mSinkBufferSize); 4771 } else { 4772 // flush remaining overflow buffers in output tracks 4773 writeFrames = 0; 4774 } 4775 sleepTime = 0; 4776 } 4777} 4778 4779ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4780{ 4781 for (size_t i = 0; i < outputTracks.size(); i++) { 4782 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT 4783 // for delivery downstream as needed. This in-place conversion is safe as 4784 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format 4785 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here). 4786 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 4787 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT, 4788 mSinkBuffer, mFormat, writeFrames * mChannelCount); 4789 } 4790 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames); 4791 } 4792 mStandby = false; 4793 return (ssize_t)mSinkBufferSize; 4794} 4795 4796void AudioFlinger::DuplicatingThread::threadLoop_standby() 4797{ 4798 // DuplicatingThread implements standby by stopping all tracks 4799 for (size_t i = 0; i < outputTracks.size(); i++) { 4800 outputTracks[i]->stop(); 4801 } 4802} 4803 4804void AudioFlinger::DuplicatingThread::saveOutputTracks() 4805{ 4806 outputTracks = mOutputTracks; 4807} 4808 4809void AudioFlinger::DuplicatingThread::clearOutputTracks() 4810{ 4811 outputTracks.clear(); 4812} 4813 4814void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4815{ 4816 Mutex::Autolock _l(mLock); 4817 // FIXME explain this formula 4818 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4819 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat 4820 // due to current usage case and restrictions on the AudioBufferProvider. 4821 // Actual buffer conversion is done in threadLoop_write(). 4822 // 4823 // TODO: This may change in the future, depending on multichannel 4824 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack 4825 OutputTrack *outputTrack = new OutputTrack(thread, 4826 this, 4827 mSampleRate, 4828 AUDIO_FORMAT_PCM_16_BIT, 4829 mChannelMask, 4830 frameCount, 4831 IPCThreadState::self()->getCallingUid()); 4832 if (outputTrack->cblk() != NULL) { 4833 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4834 mOutputTracks.add(outputTrack); 4835 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4836 updateWaitTime_l(); 4837 } 4838} 4839 4840void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4841{ 4842 Mutex::Autolock _l(mLock); 4843 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4844 if (mOutputTracks[i]->thread() == thread) { 4845 mOutputTracks[i]->destroy(); 4846 mOutputTracks.removeAt(i); 4847 updateWaitTime_l(); 4848 return; 4849 } 4850 } 4851 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4852} 4853 4854// caller must hold mLock 4855void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4856{ 4857 mWaitTimeMs = UINT_MAX; 4858 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4859 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4860 if (strong != 0) { 4861 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4862 if (waitTimeMs < mWaitTimeMs) { 4863 mWaitTimeMs = waitTimeMs; 4864 } 4865 } 4866 } 4867} 4868 4869 4870bool AudioFlinger::DuplicatingThread::outputsReady( 4871 const SortedVector< sp<OutputTrack> > &outputTracks) 4872{ 4873 for (size_t i = 0; i < outputTracks.size(); i++) { 4874 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4875 if (thread == 0) { 4876 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4877 outputTracks[i].get()); 4878 return false; 4879 } 4880 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4881 // see note at standby() declaration 4882 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4883 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4884 thread.get()); 4885 return false; 4886 } 4887 } 4888 return true; 4889} 4890 4891uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4892{ 4893 return (mWaitTimeMs * 1000) / 2; 4894} 4895 4896void AudioFlinger::DuplicatingThread::cacheParameters_l() 4897{ 4898 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4899 updateWaitTime_l(); 4900 4901 MixerThread::cacheParameters_l(); 4902} 4903 4904// ---------------------------------------------------------------------------- 4905// Record 4906// ---------------------------------------------------------------------------- 4907 4908AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4909 AudioStreamIn *input, 4910 audio_io_handle_t id, 4911 audio_devices_t outDevice, 4912 audio_devices_t inDevice 4913#ifdef TEE_SINK 4914 , const sp<NBAIO_Sink>& teeSink 4915#endif 4916 ) : 4917 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4918 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL), 4919 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l() 4920 mRsmpInRear(0) 4921#ifdef TEE_SINK 4922 , mTeeSink(teeSink) 4923#endif 4924 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize, 4925 "RecordThreadRO", MemoryHeapBase::READ_ONLY)) 4926 // mFastCapture below 4927 , mFastCaptureFutex(0) 4928 // mInputSource 4929 // mPipeSink 4930 // mPipeSource 4931 , mPipeFramesP2(0) 4932 // mPipeMemory 4933 // mFastCaptureNBLogWriter 4934 , mFastTrackAvail(false) 4935{ 4936 snprintf(mName, kNameLength, "AudioIn_%X", id); 4937 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 4938 4939 readInputParameters_l(); 4940 4941 // create an NBAIO source for the HAL input stream, and negotiate 4942 mInputSource = new AudioStreamInSource(input->stream); 4943 size_t numCounterOffers = 0; 4944 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 4945 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers); 4946 ALOG_ASSERT(index == 0); 4947 4948 // initialize fast capture depending on configuration 4949 bool initFastCapture; 4950 switch (kUseFastCapture) { 4951 case FastCapture_Never: 4952 initFastCapture = false; 4953 break; 4954 case FastCapture_Always: 4955 initFastCapture = true; 4956 break; 4957 case FastCapture_Static: 4958 uint32_t primaryOutputSampleRate; 4959 { 4960 AutoMutex _l(audioFlinger->mHardwareLock); 4961 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate; 4962 } 4963 initFastCapture = 4964 // either capture sample rate is same as (a reasonable) primary output sample rate 4965 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) && 4966 (mSampleRate == primaryOutputSampleRate)) || 4967 // or primary output sample rate is unknown, and capture sample rate is reasonable 4968 ((primaryOutputSampleRate == 0) && 4969 ((mSampleRate == 44100 || mSampleRate == 48000)))) && 4970 // and the buffer size is < 12 ms 4971 (mFrameCount * 1000) / mSampleRate < 12; 4972 break; 4973 // case FastCapture_Dynamic: 4974 } 4975 4976 if (initFastCapture) { 4977 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from 4978 NBAIO_Format format = mInputSource->format(); 4979 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each 4980 size_t pipeSize = pipeFramesP2 * Format_frameSize(format); 4981 void *pipeBuffer; 4982 const sp<MemoryDealer> roHeap(readOnlyHeap()); 4983 sp<IMemory> pipeMemory; 4984 if ((roHeap == 0) || 4985 (pipeMemory = roHeap->allocate(pipeSize)) == 0 || 4986 (pipeBuffer = pipeMemory->pointer()) == NULL) { 4987 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize); 4988 goto failed; 4989 } 4990 // pipe will be shared directly with fast clients, so clear to avoid leaking old information 4991 memset(pipeBuffer, 0, pipeSize); 4992 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer); 4993 const NBAIO_Format offers[1] = {format}; 4994 size_t numCounterOffers = 0; 4995 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 4996 ALOG_ASSERT(index == 0); 4997 mPipeSink = pipe; 4998 PipeReader *pipeReader = new PipeReader(*pipe); 4999 numCounterOffers = 0; 5000 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 5001 ALOG_ASSERT(index == 0); 5002 mPipeSource = pipeReader; 5003 mPipeFramesP2 = pipeFramesP2; 5004 mPipeMemory = pipeMemory; 5005 5006 // create fast capture 5007 mFastCapture = new FastCapture(); 5008 FastCaptureStateQueue *sq = mFastCapture->sq(); 5009#ifdef STATE_QUEUE_DUMP 5010 // FIXME 5011#endif 5012 FastCaptureState *state = sq->begin(); 5013 state->mCblk = NULL; 5014 state->mInputSource = mInputSource.get(); 5015 state->mInputSourceGen++; 5016 state->mPipeSink = pipe; 5017 state->mPipeSinkGen++; 5018 state->mFrameCount = mFrameCount; 5019 state->mCommand = FastCaptureState::COLD_IDLE; 5020 // already done in constructor initialization list 5021 //mFastCaptureFutex = 0; 5022 state->mColdFutexAddr = &mFastCaptureFutex; 5023 state->mColdGen++; 5024 state->mDumpState = &mFastCaptureDumpState; 5025#ifdef TEE_SINK 5026 // FIXME 5027#endif 5028 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture"); 5029 state->mNBLogWriter = mFastCaptureNBLogWriter.get(); 5030 sq->end(); 5031 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5032 5033 // start the fast capture 5034 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO); 5035 pid_t tid = mFastCapture->getTid(); 5036 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 5037 if (err != 0) { 5038 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 5039 kPriorityFastCapture, getpid_cached, tid, err); 5040 } 5041 5042#ifdef AUDIO_WATCHDOG 5043 // FIXME 5044#endif 5045 5046 mFastTrackAvail = true; 5047 } 5048failed: ; 5049 5050 // FIXME mNormalSource 5051} 5052 5053 5054AudioFlinger::RecordThread::~RecordThread() 5055{ 5056 if (mFastCapture != 0) { 5057 FastCaptureStateQueue *sq = mFastCapture->sq(); 5058 FastCaptureState *state = sq->begin(); 5059 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5060 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5061 if (old == -1) { 5062 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5063 } 5064 } 5065 state->mCommand = FastCaptureState::EXIT; 5066 sq->end(); 5067 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5068 mFastCapture->join(); 5069 mFastCapture.clear(); 5070 } 5071 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter); 5072 mAudioFlinger->unregisterWriter(mNBLogWriter); 5073 delete[] mRsmpInBuffer; 5074} 5075 5076void AudioFlinger::RecordThread::onFirstRef() 5077{ 5078 run(mName, PRIORITY_URGENT_AUDIO); 5079} 5080 5081bool AudioFlinger::RecordThread::threadLoop() 5082{ 5083 nsecs_t lastWarning = 0; 5084 5085 inputStandBy(); 5086 5087reacquire_wakelock: 5088 sp<RecordTrack> activeTrack; 5089 int activeTracksGen; 5090 { 5091 Mutex::Autolock _l(mLock); 5092 size_t size = mActiveTracks.size(); 5093 activeTracksGen = mActiveTracksGen; 5094 if (size > 0) { 5095 // FIXME an arbitrary choice 5096 activeTrack = mActiveTracks[0]; 5097 acquireWakeLock_l(activeTrack->uid()); 5098 if (size > 1) { 5099 SortedVector<int> tmp; 5100 for (size_t i = 0; i < size; i++) { 5101 tmp.add(mActiveTracks[i]->uid()); 5102 } 5103 updateWakeLockUids_l(tmp); 5104 } 5105 } else { 5106 acquireWakeLock_l(-1); 5107 } 5108 } 5109 5110 // used to request a deferred sleep, to be executed later while mutex is unlocked 5111 uint32_t sleepUs = 0; 5112 5113 // loop while there is work to do 5114 for (;;) { 5115 Vector< sp<EffectChain> > effectChains; 5116 5117 // sleep with mutex unlocked 5118 if (sleepUs > 0) { 5119 ATRACE_BEGIN("sleep"); 5120 usleep(sleepUs); 5121 ATRACE_END(); 5122 sleepUs = 0; 5123 } 5124 5125 // activeTracks accumulates a copy of a subset of mActiveTracks 5126 Vector< sp<RecordTrack> > activeTracks; 5127 5128 // reference to the (first and only) active fast track 5129 sp<RecordTrack> fastTrack; 5130 5131 // reference to a fast track which is about to be removed 5132 sp<RecordTrack> fastTrackToRemove; 5133 5134 { // scope for mLock 5135 Mutex::Autolock _l(mLock); 5136 5137 processConfigEvents_l(); 5138 5139 // check exitPending here because checkForNewParameters_l() and 5140 // checkForNewParameters_l() can temporarily release mLock 5141 if (exitPending()) { 5142 break; 5143 } 5144 5145 // if no active track(s), then standby and release wakelock 5146 size_t size = mActiveTracks.size(); 5147 if (size == 0) { 5148 standbyIfNotAlreadyInStandby(); 5149 // exitPending() can't become true here 5150 releaseWakeLock_l(); 5151 ALOGV("RecordThread: loop stopping"); 5152 // go to sleep 5153 mWaitWorkCV.wait(mLock); 5154 ALOGV("RecordThread: loop starting"); 5155 goto reacquire_wakelock; 5156 } 5157 5158 if (mActiveTracksGen != activeTracksGen) { 5159 activeTracksGen = mActiveTracksGen; 5160 SortedVector<int> tmp; 5161 for (size_t i = 0; i < size; i++) { 5162 tmp.add(mActiveTracks[i]->uid()); 5163 } 5164 updateWakeLockUids_l(tmp); 5165 } 5166 5167 bool doBroadcast = false; 5168 for (size_t i = 0; i < size; ) { 5169 5170 activeTrack = mActiveTracks[i]; 5171 if (activeTrack->isTerminated()) { 5172 if (activeTrack->isFastTrack()) { 5173 ALOG_ASSERT(fastTrackToRemove == 0); 5174 fastTrackToRemove = activeTrack; 5175 } 5176 removeTrack_l(activeTrack); 5177 mActiveTracks.remove(activeTrack); 5178 mActiveTracksGen++; 5179 size--; 5180 continue; 5181 } 5182 5183 TrackBase::track_state activeTrackState = activeTrack->mState; 5184 switch (activeTrackState) { 5185 5186 case TrackBase::PAUSING: 5187 mActiveTracks.remove(activeTrack); 5188 mActiveTracksGen++; 5189 doBroadcast = true; 5190 size--; 5191 continue; 5192 5193 case TrackBase::STARTING_1: 5194 sleepUs = 10000; 5195 i++; 5196 continue; 5197 5198 case TrackBase::STARTING_2: 5199 doBroadcast = true; 5200 mStandby = false; 5201 activeTrack->mState = TrackBase::ACTIVE; 5202 break; 5203 5204 case TrackBase::ACTIVE: 5205 break; 5206 5207 case TrackBase::IDLE: 5208 i++; 5209 continue; 5210 5211 default: 5212 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState); 5213 } 5214 5215 activeTracks.add(activeTrack); 5216 i++; 5217 5218 if (activeTrack->isFastTrack()) { 5219 ALOG_ASSERT(!mFastTrackAvail); 5220 ALOG_ASSERT(fastTrack == 0); 5221 fastTrack = activeTrack; 5222 } 5223 } 5224 if (doBroadcast) { 5225 mStartStopCond.broadcast(); 5226 } 5227 5228 // sleep if there are no active tracks to process 5229 if (activeTracks.size() == 0) { 5230 if (sleepUs == 0) { 5231 sleepUs = kRecordThreadSleepUs; 5232 } 5233 continue; 5234 } 5235 sleepUs = 0; 5236 5237 lockEffectChains_l(effectChains); 5238 } 5239 5240 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0 5241 5242 size_t size = effectChains.size(); 5243 for (size_t i = 0; i < size; i++) { 5244 // thread mutex is not locked, but effect chain is locked 5245 effectChains[i]->process_l(); 5246 } 5247 5248 // Push a new fast capture state if fast capture is not already running, or cblk change 5249 if (mFastCapture != 0) { 5250 FastCaptureStateQueue *sq = mFastCapture->sq(); 5251 FastCaptureState *state = sq->begin(); 5252 bool didModify = false; 5253 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED; 5254 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME && 5255 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) { 5256 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5257 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5258 if (old == -1) { 5259 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5260 } 5261 } 5262 state->mCommand = FastCaptureState::READ_WRITE; 5263#if 0 // FIXME 5264 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 5265 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 5266#endif 5267 didModify = true; 5268 } 5269 audio_track_cblk_t *cblkOld = state->mCblk; 5270 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL; 5271 if (cblkNew != cblkOld) { 5272 state->mCblk = cblkNew; 5273 // block until acked if removing a fast track 5274 if (cblkOld != NULL) { 5275 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED; 5276 } 5277 didModify = true; 5278 } 5279 sq->end(didModify); 5280 if (didModify) { 5281 sq->push(block); 5282#if 0 5283 if (kUseFastCapture == FastCapture_Dynamic) { 5284 mNormalSource = mPipeSource; 5285 } 5286#endif 5287 } 5288 } 5289 5290 // now run the fast track destructor with thread mutex unlocked 5291 fastTrackToRemove.clear(); 5292 5293 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one. 5294 // Only the client(s) that are too slow will overrun. But if even the fastest client is too 5295 // slow, then this RecordThread will overrun by not calling HAL read often enough. 5296 // If destination is non-contiguous, first read past the nominal end of buffer, then 5297 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 5298 5299 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1); 5300 ssize_t framesRead; 5301 5302 // If an NBAIO source is present, use it to read the normal capture's data 5303 if (mPipeSource != 0) { 5304 size_t framesToRead = mBufferSize / mFrameSize; 5305 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount], 5306 framesToRead, AudioBufferProvider::kInvalidPTS); 5307 if (framesRead == 0) { 5308 // since pipe is non-blocking, simulate blocking input 5309 sleepUs = (framesToRead * 1000000LL) / mSampleRate; 5310 } 5311 // otherwise use the HAL / AudioStreamIn directly 5312 } else { 5313 ssize_t bytesRead = mInput->stream->read(mInput->stream, 5314 &mRsmpInBuffer[rear * mChannelCount], mBufferSize); 5315 if (bytesRead < 0) { 5316 framesRead = bytesRead; 5317 } else { 5318 framesRead = bytesRead / mFrameSize; 5319 } 5320 } 5321 5322 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) { 5323 ALOGE("read failed: framesRead=%d", framesRead); 5324 // Force input into standby so that it tries to recover at next read attempt 5325 inputStandBy(); 5326 sleepUs = kRecordThreadSleepUs; 5327 } 5328 if (framesRead <= 0) { 5329 goto unlock; 5330 } 5331 ALOG_ASSERT(framesRead > 0); 5332 5333 if (mTeeSink != 0) { 5334 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead); 5335 } 5336 // If destination is non-contiguous, we now correct for reading past end of buffer. 5337 { 5338 size_t part1 = mRsmpInFramesP2 - rear; 5339 if ((size_t) framesRead > part1) { 5340 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount], 5341 (framesRead - part1) * mFrameSize); 5342 } 5343 } 5344 rear = mRsmpInRear += framesRead; 5345 5346 size = activeTracks.size(); 5347 // loop over each active track 5348 for (size_t i = 0; i < size; i++) { 5349 activeTrack = activeTracks[i]; 5350 5351 // skip fast tracks, as those are handled directly by FastCapture 5352 if (activeTrack->isFastTrack()) { 5353 continue; 5354 } 5355 5356 enum { 5357 OVERRUN_UNKNOWN, 5358 OVERRUN_TRUE, 5359 OVERRUN_FALSE 5360 } overrun = OVERRUN_UNKNOWN; 5361 5362 // loop over getNextBuffer to handle circular sink 5363 for (;;) { 5364 5365 activeTrack->mSink.frameCount = ~0; 5366 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink); 5367 size_t framesOut = activeTrack->mSink.frameCount; 5368 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0)); 5369 5370 int32_t front = activeTrack->mRsmpInFront; 5371 ssize_t filled = rear - front; 5372 size_t framesIn; 5373 5374 if (filled < 0) { 5375 // should not happen, but treat like a massive overrun and re-sync 5376 framesIn = 0; 5377 activeTrack->mRsmpInFront = rear; 5378 overrun = OVERRUN_TRUE; 5379 } else if ((size_t) filled <= mRsmpInFrames) { 5380 framesIn = (size_t) filled; 5381 } else { 5382 // client is not keeping up with server, but give it latest data 5383 framesIn = mRsmpInFrames; 5384 activeTrack->mRsmpInFront = front = rear - framesIn; 5385 overrun = OVERRUN_TRUE; 5386 } 5387 5388 if (framesOut == 0 || framesIn == 0) { 5389 break; 5390 } 5391 5392 if (activeTrack->mResampler == NULL) { 5393 // no resampling 5394 if (framesIn > framesOut) { 5395 framesIn = framesOut; 5396 } else { 5397 framesOut = framesIn; 5398 } 5399 int8_t *dst = activeTrack->mSink.i8; 5400 while (framesIn > 0) { 5401 front &= mRsmpInFramesP2 - 1; 5402 size_t part1 = mRsmpInFramesP2 - front; 5403 if (part1 > framesIn) { 5404 part1 = framesIn; 5405 } 5406 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize); 5407 if (mChannelCount == activeTrack->mChannelCount) { 5408 memcpy(dst, src, part1 * mFrameSize); 5409 } else if (mChannelCount == 1) { 5410 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src, 5411 part1); 5412 } else { 5413 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src, 5414 part1); 5415 } 5416 dst += part1 * activeTrack->mFrameSize; 5417 front += part1; 5418 framesIn -= part1; 5419 } 5420 activeTrack->mRsmpInFront += framesOut; 5421 5422 } else { 5423 // resampling 5424 // FIXME framesInNeeded should really be part of resampler API, and should 5425 // depend on the SRC ratio 5426 // to keep mRsmpInBuffer full so resampler always has sufficient input 5427 size_t framesInNeeded; 5428 // FIXME only re-calculate when it changes, and optimize for common ratios 5429 // Do not precompute in/out because floating point is not associative 5430 // e.g. a*b/c != a*(b/c). 5431 const double in(mSampleRate); 5432 const double out(activeTrack->mSampleRate); 5433 framesInNeeded = ceil(framesOut * in / out) + 1; 5434 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g", 5435 framesInNeeded, framesOut, in / out); 5436 // Although we theoretically have framesIn in circular buffer, some of those are 5437 // unreleased frames, and thus must be discounted for purpose of budgeting. 5438 size_t unreleased = activeTrack->mRsmpInUnrel; 5439 framesIn = framesIn > unreleased ? framesIn - unreleased : 0; 5440 if (framesIn < framesInNeeded) { 5441 ALOGV("not enough to resample: have %u frames in but need %u in to " 5442 "produce %u out given in/out ratio of %.4g", 5443 framesIn, framesInNeeded, framesOut, in / out); 5444 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0; 5445 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut); 5446 if (newFramesOut == 0) { 5447 break; 5448 } 5449 framesInNeeded = ceil(newFramesOut * in / out) + 1; 5450 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g", 5451 framesInNeeded, newFramesOut, out / in); 5452 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded); 5453 ALOGV("success 2: have %u frames in and need %u in to produce %u out " 5454 "given in/out ratio of %.4g", 5455 framesIn, framesInNeeded, newFramesOut, in / out); 5456 framesOut = newFramesOut; 5457 } else { 5458 ALOGV("success 1: have %u in and need %u in to produce %u out " 5459 "given in/out ratio of %.4g", 5460 framesIn, framesInNeeded, framesOut, in / out); 5461 } 5462 5463 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink 5464 if (activeTrack->mRsmpOutFrameCount < framesOut) { 5465 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share? 5466 delete[] activeTrack->mRsmpOutBuffer; 5467 // resampler always outputs stereo 5468 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2]; 5469 activeTrack->mRsmpOutFrameCount = framesOut; 5470 } 5471 5472 // resampler accumulates, but we only have one source track 5473 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 5474 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut, 5475 // FIXME how about having activeTrack implement this interface itself? 5476 activeTrack->mResamplerBufferProvider 5477 /*this*/ /* AudioBufferProvider* */); 5478 // ditherAndClamp() works as long as all buffers returned by 5479 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true. 5480 if (activeTrack->mChannelCount == 1) { 5481 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t 5482 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer, 5483 framesOut); 5484 // the resampler always outputs stereo samples: 5485 // do post stereo to mono conversion 5486 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16, 5487 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut); 5488 } else { 5489 ditherAndClamp((int32_t *)activeTrack->mSink.raw, 5490 activeTrack->mRsmpOutBuffer, framesOut); 5491 } 5492 // now done with mRsmpOutBuffer 5493 5494 } 5495 5496 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) { 5497 overrun = OVERRUN_FALSE; 5498 } 5499 5500 if (activeTrack->mFramesToDrop == 0) { 5501 if (framesOut > 0) { 5502 activeTrack->mSink.frameCount = framesOut; 5503 activeTrack->releaseBuffer(&activeTrack->mSink); 5504 } 5505 } else { 5506 // FIXME could do a partial drop of framesOut 5507 if (activeTrack->mFramesToDrop > 0) { 5508 activeTrack->mFramesToDrop -= framesOut; 5509 if (activeTrack->mFramesToDrop <= 0) { 5510 activeTrack->clearSyncStartEvent(); 5511 } 5512 } else { 5513 activeTrack->mFramesToDrop += framesOut; 5514 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 || 5515 activeTrack->mSyncStartEvent->isCancelled()) { 5516 ALOGW("Synced record %s, session %d, trigger session %d", 5517 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled", 5518 activeTrack->sessionId(), 5519 (activeTrack->mSyncStartEvent != 0) ? 5520 activeTrack->mSyncStartEvent->triggerSession() : 0); 5521 activeTrack->clearSyncStartEvent(); 5522 } 5523 } 5524 } 5525 5526 if (framesOut == 0) { 5527 break; 5528 } 5529 } 5530 5531 switch (overrun) { 5532 case OVERRUN_TRUE: 5533 // client isn't retrieving buffers fast enough 5534 if (!activeTrack->setOverflow()) { 5535 nsecs_t now = systemTime(); 5536 // FIXME should lastWarning per track? 5537 if ((now - lastWarning) > kWarningThrottleNs) { 5538 ALOGW("RecordThread: buffer overflow"); 5539 lastWarning = now; 5540 } 5541 } 5542 break; 5543 case OVERRUN_FALSE: 5544 activeTrack->clearOverflow(); 5545 break; 5546 case OVERRUN_UNKNOWN: 5547 break; 5548 } 5549 5550 } 5551 5552unlock: 5553 // enable changes in effect chain 5554 unlockEffectChains(effectChains); 5555 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 5556 } 5557 5558 standbyIfNotAlreadyInStandby(); 5559 5560 { 5561 Mutex::Autolock _l(mLock); 5562 for (size_t i = 0; i < mTracks.size(); i++) { 5563 sp<RecordTrack> track = mTracks[i]; 5564 track->invalidate(); 5565 } 5566 mActiveTracks.clear(); 5567 mActiveTracksGen++; 5568 mStartStopCond.broadcast(); 5569 } 5570 5571 releaseWakeLock(); 5572 5573 ALOGV("RecordThread %p exiting", this); 5574 return false; 5575} 5576 5577void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 5578{ 5579 if (!mStandby) { 5580 inputStandBy(); 5581 mStandby = true; 5582 } 5583} 5584 5585void AudioFlinger::RecordThread::inputStandBy() 5586{ 5587 // Idle the fast capture if it's currently running 5588 if (mFastCapture != 0) { 5589 FastCaptureStateQueue *sq = mFastCapture->sq(); 5590 FastCaptureState *state = sq->begin(); 5591 if (!(state->mCommand & FastCaptureState::IDLE)) { 5592 state->mCommand = FastCaptureState::COLD_IDLE; 5593 state->mColdFutexAddr = &mFastCaptureFutex; 5594 state->mColdGen++; 5595 mFastCaptureFutex = 0; 5596 sq->end(); 5597 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 5598 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED); 5599#if 0 5600 if (kUseFastCapture == FastCapture_Dynamic) { 5601 // FIXME 5602 } 5603#endif 5604#ifdef AUDIO_WATCHDOG 5605 // FIXME 5606#endif 5607 } else { 5608 sq->end(false /*didModify*/); 5609 } 5610 } 5611 mInput->stream->common.standby(&mInput->stream->common); 5612} 5613 5614// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held 5615sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 5616 const sp<AudioFlinger::Client>& client, 5617 uint32_t sampleRate, 5618 audio_format_t format, 5619 audio_channel_mask_t channelMask, 5620 size_t *pFrameCount, 5621 int sessionId, 5622 size_t *notificationFrames, 5623 int uid, 5624 IAudioFlinger::track_flags_t *flags, 5625 pid_t tid, 5626 status_t *status) 5627{ 5628 size_t frameCount = *pFrameCount; 5629 sp<RecordTrack> track; 5630 status_t lStatus; 5631 5632 // client expresses a preference for FAST, but we get the final say 5633 if (*flags & IAudioFlinger::TRACK_FAST) { 5634 if ( 5635 // use case: callback handler 5636 (tid != -1) && 5637 // frame count is not specified, or is exactly the pipe depth 5638 ((frameCount == 0) || (frameCount == mPipeFramesP2)) && 5639 // PCM data 5640 audio_is_linear_pcm(format) && 5641 // native format 5642 (format == mFormat) && 5643 // native channel mask 5644 (channelMask == mChannelMask) && 5645 // native hardware sample rate 5646 (sampleRate == mSampleRate) && 5647 // record thread has an associated fast capture 5648 hasFastCapture() && 5649 // there are sufficient fast track slots available 5650 mFastTrackAvail 5651 ) { 5652 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u", 5653 frameCount, mFrameCount); 5654 } else { 5655 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u " 5656 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 5657 "hasFastCapture=%d tid=%d mFastTrackAvail=%d", 5658 frameCount, mFrameCount, mPipeFramesP2, 5659 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate, 5660 hasFastCapture(), tid, mFastTrackAvail); 5661 *flags &= ~IAudioFlinger::TRACK_FAST; 5662 } 5663 } 5664 5665 // compute track buffer size in frames, and suggest the notification frame count 5666 if (*flags & IAudioFlinger::TRACK_FAST) { 5667 // fast track: frame count is exactly the pipe depth 5668 frameCount = mPipeFramesP2; 5669 // ignore requested notificationFrames, and always notify exactly once every HAL buffer 5670 *notificationFrames = mFrameCount; 5671 } else { 5672 // not fast track: max notification period is resampled equivalent of one HAL buffer time 5673 // or 20 ms if there is a fast capture 5674 // TODO This could be a roundupRatio inline, and const 5675 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount) 5676 * sampleRate + mSampleRate - 1) / mSampleRate; 5677 // minimum number of notification periods is at least kMinNotifications, 5678 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs) 5679 static const size_t kMinNotifications = 3; 5680 static const uint32_t kMinMs = 30; 5681 // TODO This could be a roundupRatio inline 5682 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000; 5683 // TODO This could be a roundupRatio inline 5684 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) / 5685 maxNotificationFrames; 5686 const size_t minFrameCount = maxNotificationFrames * 5687 max(kMinNotifications, minNotificationsByMs); 5688 frameCount = max(frameCount, minFrameCount); 5689 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) { 5690 *notificationFrames = maxNotificationFrames; 5691 } 5692 } 5693 *pFrameCount = frameCount; 5694 5695 lStatus = initCheck(); 5696 if (lStatus != NO_ERROR) { 5697 ALOGE("createRecordTrack_l() audio driver not initialized"); 5698 goto Exit; 5699 } 5700 5701 { // scope for mLock 5702 Mutex::Autolock _l(mLock); 5703 5704 track = new RecordTrack(this, client, sampleRate, 5705 format, channelMask, frameCount, NULL, sessionId, uid, 5706 *flags, TrackBase::TYPE_DEFAULT); 5707 5708 lStatus = track->initCheck(); 5709 if (lStatus != NO_ERROR) { 5710 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 5711 // track must be cleared from the caller as the caller has the AF lock 5712 goto Exit; 5713 } 5714 mTracks.add(track); 5715 5716 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 5717 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 5718 mAudioFlinger->btNrecIsOff(); 5719 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 5720 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 5721 5722 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 5723 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 5724 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 5725 // so ask activity manager to do this on our behalf 5726 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 5727 } 5728 } 5729 5730 lStatus = NO_ERROR; 5731 5732Exit: 5733 *status = lStatus; 5734 return track; 5735} 5736 5737status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 5738 AudioSystem::sync_event_t event, 5739 int triggerSession) 5740{ 5741 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 5742 sp<ThreadBase> strongMe = this; 5743 status_t status = NO_ERROR; 5744 5745 if (event == AudioSystem::SYNC_EVENT_NONE) { 5746 recordTrack->clearSyncStartEvent(); 5747 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 5748 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 5749 triggerSession, 5750 recordTrack->sessionId(), 5751 syncStartEventCallback, 5752 recordTrack); 5753 // Sync event can be cancelled by the trigger session if the track is not in a 5754 // compatible state in which case we start record immediately 5755 if (recordTrack->mSyncStartEvent->isCancelled()) { 5756 recordTrack->clearSyncStartEvent(); 5757 } else { 5758 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 5759 recordTrack->mFramesToDrop = - 5760 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000); 5761 } 5762 } 5763 5764 { 5765 // This section is a rendezvous between binder thread executing start() and RecordThread 5766 AutoMutex lock(mLock); 5767 if (mActiveTracks.indexOf(recordTrack) >= 0) { 5768 if (recordTrack->mState == TrackBase::PAUSING) { 5769 ALOGV("active record track PAUSING -> ACTIVE"); 5770 recordTrack->mState = TrackBase::ACTIVE; 5771 } else { 5772 ALOGV("active record track state %d", recordTrack->mState); 5773 } 5774 return status; 5775 } 5776 5777 // TODO consider other ways of handling this, such as changing the state to :STARTING and 5778 // adding the track to mActiveTracks after returning from AudioSystem::startInput(), 5779 // or using a separate command thread 5780 recordTrack->mState = TrackBase::STARTING_1; 5781 mActiveTracks.add(recordTrack); 5782 mActiveTracksGen++; 5783 status_t status = NO_ERROR; 5784 if (recordTrack->isExternalTrack()) { 5785 mLock.unlock(); 5786 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId()); 5787 mLock.lock(); 5788 // FIXME should verify that recordTrack is still in mActiveTracks 5789 if (status != NO_ERROR) { 5790 mActiveTracks.remove(recordTrack); 5791 mActiveTracksGen++; 5792 recordTrack->clearSyncStartEvent(); 5793 ALOGV("RecordThread::start error %d", status); 5794 return status; 5795 } 5796 } 5797 // Catch up with current buffer indices if thread is already running. 5798 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront 5799 // was initialized to some value closer to the thread's mRsmpInFront, then the track could 5800 // see previously buffered data before it called start(), but with greater risk of overrun. 5801 5802 recordTrack->mRsmpInFront = mRsmpInRear; 5803 recordTrack->mRsmpInUnrel = 0; 5804 // FIXME why reset? 5805 if (recordTrack->mResampler != NULL) { 5806 recordTrack->mResampler->reset(); 5807 } 5808 recordTrack->mState = TrackBase::STARTING_2; 5809 // signal thread to start 5810 mWaitWorkCV.broadcast(); 5811 if (mActiveTracks.indexOf(recordTrack) < 0) { 5812 ALOGV("Record failed to start"); 5813 status = BAD_VALUE; 5814 goto startError; 5815 } 5816 return status; 5817 } 5818 5819startError: 5820 if (recordTrack->isExternalTrack()) { 5821 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId()); 5822 } 5823 recordTrack->clearSyncStartEvent(); 5824 // FIXME I wonder why we do not reset the state here? 5825 return status; 5826} 5827 5828void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 5829{ 5830 sp<SyncEvent> strongEvent = event.promote(); 5831 5832 if (strongEvent != 0) { 5833 sp<RefBase> ptr = strongEvent->cookie().promote(); 5834 if (ptr != 0) { 5835 RecordTrack *recordTrack = (RecordTrack *)ptr.get(); 5836 recordTrack->handleSyncStartEvent(strongEvent); 5837 } 5838 } 5839} 5840 5841bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 5842 ALOGV("RecordThread::stop"); 5843 AutoMutex _l(mLock); 5844 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 5845 return false; 5846 } 5847 // note that threadLoop may still be processing the track at this point [without lock] 5848 recordTrack->mState = TrackBase::PAUSING; 5849 // do not wait for mStartStopCond if exiting 5850 if (exitPending()) { 5851 return true; 5852 } 5853 // FIXME incorrect usage of wait: no explicit predicate or loop 5854 mStartStopCond.wait(mLock); 5855 // if we have been restarted, recordTrack is in mActiveTracks here 5856 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 5857 ALOGV("Record stopped OK"); 5858 return true; 5859 } 5860 return false; 5861} 5862 5863bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 5864{ 5865 return false; 5866} 5867 5868status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 5869{ 5870#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 5871 if (!isValidSyncEvent(event)) { 5872 return BAD_VALUE; 5873 } 5874 5875 int eventSession = event->triggerSession(); 5876 status_t ret = NAME_NOT_FOUND; 5877 5878 Mutex::Autolock _l(mLock); 5879 5880 for (size_t i = 0; i < mTracks.size(); i++) { 5881 sp<RecordTrack> track = mTracks[i]; 5882 if (eventSession == track->sessionId()) { 5883 (void) track->setSyncEvent(event); 5884 ret = NO_ERROR; 5885 } 5886 } 5887 return ret; 5888#else 5889 return BAD_VALUE; 5890#endif 5891} 5892 5893// destroyTrack_l() must be called with ThreadBase::mLock held 5894void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 5895{ 5896 track->terminate(); 5897 track->mState = TrackBase::STOPPED; 5898 // active tracks are removed by threadLoop() 5899 if (mActiveTracks.indexOf(track) < 0) { 5900 removeTrack_l(track); 5901 } 5902} 5903 5904void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 5905{ 5906 mTracks.remove(track); 5907 // need anything related to effects here? 5908 if (track->isFastTrack()) { 5909 ALOG_ASSERT(!mFastTrackAvail); 5910 mFastTrackAvail = true; 5911 } 5912} 5913 5914void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 5915{ 5916 dumpInternals(fd, args); 5917 dumpTracks(fd, args); 5918 dumpEffectChains(fd, args); 5919} 5920 5921void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 5922{ 5923 dprintf(fd, "\nInput thread %p:\n", this); 5924 5925 if (mActiveTracks.size() > 0) { 5926 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize); 5927 } else { 5928 dprintf(fd, " No active record clients\n"); 5929 } 5930 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no"); 5931 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no"); 5932 5933 dumpBase(fd, args); 5934} 5935 5936void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 5937{ 5938 const size_t SIZE = 256; 5939 char buffer[SIZE]; 5940 String8 result; 5941 5942 size_t numtracks = mTracks.size(); 5943 size_t numactive = mActiveTracks.size(); 5944 size_t numactiveseen = 0; 5945 dprintf(fd, " %d Tracks", numtracks); 5946 if (numtracks) { 5947 dprintf(fd, " of which %d are active\n", numactive); 5948 RecordTrack::appendDumpHeader(result); 5949 for (size_t i = 0; i < numtracks ; ++i) { 5950 sp<RecordTrack> track = mTracks[i]; 5951 if (track != 0) { 5952 bool active = mActiveTracks.indexOf(track) >= 0; 5953 if (active) { 5954 numactiveseen++; 5955 } 5956 track->dump(buffer, SIZE, active); 5957 result.append(buffer); 5958 } 5959 } 5960 } else { 5961 dprintf(fd, "\n"); 5962 } 5963 5964 if (numactiveseen != numactive) { 5965 snprintf(buffer, SIZE, " The following tracks are in the active list but" 5966 " not in the track list\n"); 5967 result.append(buffer); 5968 RecordTrack::appendDumpHeader(result); 5969 for (size_t i = 0; i < numactive; ++i) { 5970 sp<RecordTrack> track = mActiveTracks[i]; 5971 if (mTracks.indexOf(track) < 0) { 5972 track->dump(buffer, SIZE, true); 5973 result.append(buffer); 5974 } 5975 } 5976 5977 } 5978 write(fd, result.string(), result.size()); 5979} 5980 5981// AudioBufferProvider interface 5982status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer( 5983 AudioBufferProvider::Buffer* buffer, int64_t pts __unused) 5984{ 5985 RecordTrack *activeTrack = mRecordTrack; 5986 sp<ThreadBase> threadBase = activeTrack->mThread.promote(); 5987 if (threadBase == 0) { 5988 buffer->frameCount = 0; 5989 buffer->raw = NULL; 5990 return NOT_ENOUGH_DATA; 5991 } 5992 RecordThread *recordThread = (RecordThread *) threadBase.get(); 5993 int32_t rear = recordThread->mRsmpInRear; 5994 int32_t front = activeTrack->mRsmpInFront; 5995 ssize_t filled = rear - front; 5996 // FIXME should not be P2 (don't want to increase latency) 5997 // FIXME if client not keeping up, discard 5998 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames)); 5999 // 'filled' may be non-contiguous, so return only the first contiguous chunk 6000 front &= recordThread->mRsmpInFramesP2 - 1; 6001 size_t part1 = recordThread->mRsmpInFramesP2 - front; 6002 if (part1 > (size_t) filled) { 6003 part1 = filled; 6004 } 6005 size_t ask = buffer->frameCount; 6006 ALOG_ASSERT(ask > 0); 6007 if (part1 > ask) { 6008 part1 = ask; 6009 } 6010 if (part1 == 0) { 6011 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty 6012 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved"); 6013 buffer->raw = NULL; 6014 buffer->frameCount = 0; 6015 activeTrack->mRsmpInUnrel = 0; 6016 return NOT_ENOUGH_DATA; 6017 } 6018 6019 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount; 6020 buffer->frameCount = part1; 6021 activeTrack->mRsmpInUnrel = part1; 6022 return NO_ERROR; 6023} 6024 6025// AudioBufferProvider interface 6026void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer( 6027 AudioBufferProvider::Buffer* buffer) 6028{ 6029 RecordTrack *activeTrack = mRecordTrack; 6030 size_t stepCount = buffer->frameCount; 6031 if (stepCount == 0) { 6032 return; 6033 } 6034 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel); 6035 activeTrack->mRsmpInUnrel -= stepCount; 6036 activeTrack->mRsmpInFront += stepCount; 6037 buffer->raw = NULL; 6038 buffer->frameCount = 0; 6039} 6040 6041bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair, 6042 status_t& status) 6043{ 6044 bool reconfig = false; 6045 6046 status = NO_ERROR; 6047 6048 audio_format_t reqFormat = mFormat; 6049 uint32_t samplingRate = mSampleRate; 6050 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount); 6051 6052 AudioParameter param = AudioParameter(keyValuePair); 6053 int value; 6054 // TODO Investigate when this code runs. Check with audio policy when a sample rate and 6055 // channel count change can be requested. Do we mandate the first client defines the 6056 // HAL sampling rate and channel count or do we allow changes on the fly? 6057 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 6058 samplingRate = value; 6059 reconfig = true; 6060 } 6061 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 6062 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 6063 status = BAD_VALUE; 6064 } else { 6065 reqFormat = (audio_format_t) value; 6066 reconfig = true; 6067 } 6068 } 6069 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 6070 audio_channel_mask_t mask = (audio_channel_mask_t) value; 6071 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) { 6072 status = BAD_VALUE; 6073 } else { 6074 channelMask = mask; 6075 reconfig = true; 6076 } 6077 } 6078 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 6079 // do not accept frame count changes if tracks are open as the track buffer 6080 // size depends on frame count and correct behavior would not be guaranteed 6081 // if frame count is changed after track creation 6082 if (mActiveTracks.size() > 0) { 6083 status = INVALID_OPERATION; 6084 } else { 6085 reconfig = true; 6086 } 6087 } 6088 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 6089 // forward device change to effects that have requested to be 6090 // aware of attached audio device. 6091 for (size_t i = 0; i < mEffectChains.size(); i++) { 6092 mEffectChains[i]->setDevice_l(value); 6093 } 6094 6095 // store input device and output device but do not forward output device to audio HAL. 6096 // Note that status is ignored by the caller for output device 6097 // (see AudioFlinger::setParameters() 6098 if (audio_is_output_devices(value)) { 6099 mOutDevice = value; 6100 status = BAD_VALUE; 6101 } else { 6102 mInDevice = value; 6103 // disable AEC and NS if the device is a BT SCO headset supporting those 6104 // pre processings 6105 if (mTracks.size() > 0) { 6106 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6107 mAudioFlinger->btNrecIsOff(); 6108 for (size_t i = 0; i < mTracks.size(); i++) { 6109 sp<RecordTrack> track = mTracks[i]; 6110 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6111 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6112 } 6113 } 6114 } 6115 } 6116 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 6117 mAudioSource != (audio_source_t)value) { 6118 // forward device change to effects that have requested to be 6119 // aware of attached audio device. 6120 for (size_t i = 0; i < mEffectChains.size(); i++) { 6121 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 6122 } 6123 mAudioSource = (audio_source_t)value; 6124 } 6125 6126 if (status == NO_ERROR) { 6127 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6128 keyValuePair.string()); 6129 if (status == INVALID_OPERATION) { 6130 inputStandBy(); 6131 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6132 keyValuePair.string()); 6133 } 6134 if (reconfig) { 6135 if (status == BAD_VALUE && 6136 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 6137 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 6138 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 6139 <= (2 * samplingRate)) && 6140 audio_channel_count_from_in_mask( 6141 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 && 6142 (channelMask == AUDIO_CHANNEL_IN_MONO || 6143 channelMask == AUDIO_CHANNEL_IN_STEREO)) { 6144 status = NO_ERROR; 6145 } 6146 if (status == NO_ERROR) { 6147 readInputParameters_l(); 6148 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 6149 } 6150 } 6151 } 6152 6153 return reconfig; 6154} 6155 6156String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 6157{ 6158 Mutex::Autolock _l(mLock); 6159 if (initCheck() != NO_ERROR) { 6160 return String8(); 6161 } 6162 6163 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 6164 const String8 out_s8(s); 6165 free(s); 6166 return out_s8; 6167} 6168 6169void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) { 6170 AudioSystem::OutputDescriptor desc; 6171 const void *param2 = NULL; 6172 6173 switch (event) { 6174 case AudioSystem::INPUT_OPENED: 6175 case AudioSystem::INPUT_CONFIG_CHANGED: 6176 desc.channelMask = mChannelMask; 6177 desc.samplingRate = mSampleRate; 6178 desc.format = mFormat; 6179 desc.frameCount = mFrameCount; 6180 desc.latency = 0; 6181 param2 = &desc; 6182 break; 6183 6184 case AudioSystem::INPUT_CLOSED: 6185 default: 6186 break; 6187 } 6188 mAudioFlinger->audioConfigChanged(event, mId, param2); 6189} 6190 6191void AudioFlinger::RecordThread::readInputParameters_l() 6192{ 6193 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 6194 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 6195 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 6196 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common); 6197 mFormat = mHALFormat; 6198 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 6199 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 6200 } 6201 mFrameSize = audio_stream_in_frame_size(mInput->stream); 6202 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 6203 mFrameCount = mBufferSize / mFrameSize; 6204 // This is the formula for calculating the temporary buffer size. 6205 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to 6206 // 1 full output buffer, regardless of the alignment of the available input. 6207 // The value is somewhat arbitrary, and could probably be even larger. 6208 // A larger value should allow more old data to be read after a track calls start(), 6209 // without increasing latency. 6210 mRsmpInFrames = mFrameCount * 7; 6211 mRsmpInFramesP2 = roundup(mRsmpInFrames); 6212 delete[] mRsmpInBuffer; 6213 6214 // TODO optimize audio capture buffer sizes ... 6215 // Here we calculate the size of the sliding buffer used as a source 6216 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7). 6217 // For current HAL frame counts, this is usually 2048 = 40 ms. It would 6218 // be better to have it derived from the pipe depth in the long term. 6219 // The current value is higher than necessary. However it should not add to latency. 6220 6221 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 6222 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount]; 6223 6224 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints. 6225 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks? 6226} 6227 6228uint32_t AudioFlinger::RecordThread::getInputFramesLost() 6229{ 6230 Mutex::Autolock _l(mLock); 6231 if (initCheck() != NO_ERROR) { 6232 return 0; 6233 } 6234 6235 return mInput->stream->get_input_frames_lost(mInput->stream); 6236} 6237 6238uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 6239{ 6240 Mutex::Autolock _l(mLock); 6241 uint32_t result = 0; 6242 if (getEffectChain_l(sessionId) != 0) { 6243 result = EFFECT_SESSION; 6244 } 6245 6246 for (size_t i = 0; i < mTracks.size(); ++i) { 6247 if (sessionId == mTracks[i]->sessionId()) { 6248 result |= TRACK_SESSION; 6249 break; 6250 } 6251 } 6252 6253 return result; 6254} 6255 6256KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 6257{ 6258 KeyedVector<int, bool> ids; 6259 Mutex::Autolock _l(mLock); 6260 for (size_t j = 0; j < mTracks.size(); ++j) { 6261 sp<RecordThread::RecordTrack> track = mTracks[j]; 6262 int sessionId = track->sessionId(); 6263 if (ids.indexOfKey(sessionId) < 0) { 6264 ids.add(sessionId, true); 6265 } 6266 } 6267 return ids; 6268} 6269 6270AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 6271{ 6272 Mutex::Autolock _l(mLock); 6273 AudioStreamIn *input = mInput; 6274 mInput = NULL; 6275 return input; 6276} 6277 6278// this method must always be called either with ThreadBase mLock held or inside the thread loop 6279audio_stream_t* AudioFlinger::RecordThread::stream() const 6280{ 6281 if (mInput == NULL) { 6282 return NULL; 6283 } 6284 return &mInput->stream->common; 6285} 6286 6287status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 6288{ 6289 // only one chain per input thread 6290 if (mEffectChains.size() != 0) { 6291 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this); 6292 return INVALID_OPERATION; 6293 } 6294 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 6295 chain->setThread(this); 6296 chain->setInBuffer(NULL); 6297 chain->setOutBuffer(NULL); 6298 6299 checkSuspendOnAddEffectChain_l(chain); 6300 6301 // make sure enabled pre processing effects state is communicated to the HAL as we 6302 // just moved them to a new input stream. 6303 chain->syncHalEffectsState(); 6304 6305 mEffectChains.add(chain); 6306 6307 return NO_ERROR; 6308} 6309 6310size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 6311{ 6312 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 6313 ALOGW_IF(mEffectChains.size() != 1, 6314 "removeEffectChain_l() %p invalid chain size %d on thread %p", 6315 chain.get(), mEffectChains.size(), this); 6316 if (mEffectChains.size() == 1) { 6317 mEffectChains.removeAt(0); 6318 } 6319 return 0; 6320} 6321 6322status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch, 6323 audio_patch_handle_t *handle) 6324{ 6325 status_t status = NO_ERROR; 6326 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 6327 // store new device and send to effects 6328 mInDevice = patch->sources[0].ext.device.type; 6329 for (size_t i = 0; i < mEffectChains.size(); i++) { 6330 mEffectChains[i]->setDevice_l(mInDevice); 6331 } 6332 6333 // disable AEC and NS if the device is a BT SCO headset supporting those 6334 // pre processings 6335 if (mTracks.size() > 0) { 6336 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6337 mAudioFlinger->btNrecIsOff(); 6338 for (size_t i = 0; i < mTracks.size(); i++) { 6339 sp<RecordTrack> track = mTracks[i]; 6340 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6341 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6342 } 6343 } 6344 6345 // store new source and send to effects 6346 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 6347 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 6348 for (size_t i = 0; i < mEffectChains.size(); i++) { 6349 mEffectChains[i]->setAudioSource_l(mAudioSource); 6350 } 6351 } 6352 6353 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 6354 status = hwDevice->create_audio_patch(hwDevice, 6355 patch->num_sources, 6356 patch->sources, 6357 patch->num_sinks, 6358 patch->sinks, 6359 handle); 6360 } else { 6361 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL"); 6362 } 6363 return status; 6364} 6365 6366status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 6367{ 6368 status_t status = NO_ERROR; 6369 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 6370 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 6371 status = hwDevice->release_audio_patch(hwDevice, handle); 6372 } else { 6373 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL"); 6374 } 6375 return status; 6376} 6377 6378void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record) 6379{ 6380 Mutex::Autolock _l(mLock); 6381 mTracks.add(record); 6382} 6383 6384void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record) 6385{ 6386 Mutex::Autolock _l(mLock); 6387 destroyTrack_l(record); 6388} 6389 6390void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config) 6391{ 6392 ThreadBase::getAudioPortConfig(config); 6393 config->role = AUDIO_PORT_ROLE_SINK; 6394 config->ext.mix.hw_module = mInput->audioHwDev->handle(); 6395 config->ext.mix.usecase.source = mAudioSource; 6396} 6397 6398}; // namespace android 6399