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