Threads.cpp revision 65575de268f4c0d75e6c1172469001ace765fc14
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 // Allow draining the buffer in case the client 4098 // app does not call stop() and relies on underrun to stop: 4099 // hence the test on (track->mRetryCount > 1). 4100 // If retryCount<=1 then track is about to underrun and be removed. 4101 uint32_t minFrames; 4102 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing() 4103 && (track->mRetryCount > 1)) { 4104 minFrames = mNormalFrameCount; 4105 } else { 4106 minFrames = 1; 4107 } 4108 4109 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() && 4110 !track->isStopping_2() && !track->isStopped()) 4111 { 4112 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 4113 4114 if (track->mFillingUpStatus == Track::FS_FILLED) { 4115 track->mFillingUpStatus = Track::FS_ACTIVE; 4116 // make sure processVolume_l() will apply new volume even if 0 4117 mLeftVolFloat = mRightVolFloat = -1.0; 4118 if (track->mState == TrackBase::RESUMING) { 4119 track->mState = TrackBase::ACTIVE; 4120 } 4121 } 4122 4123 // compute volume for this track 4124 processVolume_l(track, last); 4125 if (last) { 4126 // reset retry count 4127 track->mRetryCount = kMaxTrackRetriesDirect; 4128 mActiveTrack = t; 4129 mixerStatus = MIXER_TRACKS_READY; 4130 } 4131 } else { 4132 // clear effect chain input buffer if the last active track started underruns 4133 // to avoid sending previous audio buffer again to effects 4134 if (!mEffectChains.isEmpty() && last) { 4135 mEffectChains[0]->clearInputBuffer(); 4136 } 4137 if (track->isStopping_1()) { 4138 track->mState = TrackBase::STOPPING_2; 4139 } 4140 if ((track->sharedBuffer() != 0) || track->isStopped() || 4141 track->isStopping_2() || track->isPaused()) { 4142 // We have consumed all the buffers of this track. 4143 // Remove it from the list of active tracks. 4144 size_t audioHALFrames; 4145 if (audio_is_linear_pcm(mFormat)) { 4146 audioHALFrames = (latency_l() * mSampleRate) / 1000; 4147 } else { 4148 audioHALFrames = 0; 4149 } 4150 4151 size_t framesWritten = mBytesWritten / mFrameSize; 4152 if (mStandby || !last || 4153 track->presentationComplete(framesWritten, audioHALFrames)) { 4154 if (track->isStopping_2()) { 4155 track->mState = TrackBase::STOPPED; 4156 } 4157 if (track->isStopped()) { 4158 if (track->mState == TrackBase::FLUSHED) { 4159 flushHw_l(); 4160 } 4161 track->reset(); 4162 } 4163 tracksToRemove->add(track); 4164 } 4165 } else { 4166 // No buffers for this track. Give it a few chances to 4167 // fill a buffer, then remove it from active list. 4168 // Only consider last track started for mixer state control 4169 if (--(track->mRetryCount) <= 0) { 4170 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 4171 tracksToRemove->add(track); 4172 // indicate to client process that the track was disabled because of underrun; 4173 // it will then automatically call start() when data is available 4174 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4175 } else if (last) { 4176 mixerStatus = MIXER_TRACKS_ENABLED; 4177 } 4178 } 4179 } 4180 } 4181 4182 // remove all the tracks that need to be... 4183 removeTracks_l(*tracksToRemove); 4184 4185 return mixerStatus; 4186} 4187 4188void AudioFlinger::DirectOutputThread::threadLoop_mix() 4189{ 4190 size_t frameCount = mFrameCount; 4191 int8_t *curBuf = (int8_t *)mSinkBuffer; 4192 // output audio to hardware 4193 while (frameCount) { 4194 AudioBufferProvider::Buffer buffer; 4195 buffer.frameCount = frameCount; 4196 mActiveTrack->getNextBuffer(&buffer); 4197 if (buffer.raw == NULL) { 4198 memset(curBuf, 0, frameCount * mFrameSize); 4199 break; 4200 } 4201 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 4202 frameCount -= buffer.frameCount; 4203 curBuf += buffer.frameCount * mFrameSize; 4204 mActiveTrack->releaseBuffer(&buffer); 4205 } 4206 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer; 4207 sleepTime = 0; 4208 standbyTime = systemTime() + standbyDelay; 4209 mActiveTrack.clear(); 4210} 4211 4212void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 4213{ 4214 if (sleepTime == 0) { 4215 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4216 sleepTime = activeSleepTime; 4217 } else { 4218 sleepTime = idleSleepTime; 4219 } 4220 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 4221 memset(mSinkBuffer, 0, mFrameCount * mFrameSize); 4222 sleepTime = 0; 4223 } 4224} 4225 4226// getTrackName_l() must be called with ThreadBase::mLock held 4227int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 4228 audio_format_t format __unused, int sessionId __unused) 4229{ 4230 return 0; 4231} 4232 4233// deleteTrackName_l() must be called with ThreadBase::mLock held 4234void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 4235{ 4236} 4237 4238// checkForNewParameter_l() must be called with ThreadBase::mLock held 4239bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair, 4240 status_t& status) 4241{ 4242 bool reconfig = false; 4243 4244 status = NO_ERROR; 4245 4246 AudioParameter param = AudioParameter(keyValuePair); 4247 int value; 4248 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4249 // forward device change to effects that have requested to be 4250 // aware of attached audio device. 4251 if (value != AUDIO_DEVICE_NONE) { 4252 mOutDevice = value; 4253 for (size_t i = 0; i < mEffectChains.size(); i++) { 4254 mEffectChains[i]->setDevice_l(mOutDevice); 4255 } 4256 } 4257 } 4258 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4259 // do not accept frame count changes if tracks are open as the track buffer 4260 // size depends on frame count and correct behavior would not be garantied 4261 // if frame count is changed after track creation 4262 if (!mTracks.isEmpty()) { 4263 status = INVALID_OPERATION; 4264 } else { 4265 reconfig = true; 4266 } 4267 } 4268 if (status == NO_ERROR) { 4269 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4270 keyValuePair.string()); 4271 if (!mStandby && status == INVALID_OPERATION) { 4272 mOutput->stream->common.standby(&mOutput->stream->common); 4273 mStandby = true; 4274 mBytesWritten = 0; 4275 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4276 keyValuePair.string()); 4277 } 4278 if (status == NO_ERROR && reconfig) { 4279 readOutputParameters_l(); 4280 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 4281 } 4282 } 4283 4284 return reconfig; 4285} 4286 4287uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 4288{ 4289 uint32_t time; 4290 if (audio_is_linear_pcm(mFormat)) { 4291 time = PlaybackThread::activeSleepTimeUs(); 4292 } else { 4293 time = 10000; 4294 } 4295 return time; 4296} 4297 4298uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 4299{ 4300 uint32_t time; 4301 if (audio_is_linear_pcm(mFormat)) { 4302 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 4303 } else { 4304 time = 10000; 4305 } 4306 return time; 4307} 4308 4309uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 4310{ 4311 uint32_t time; 4312 if (audio_is_linear_pcm(mFormat)) { 4313 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 4314 } else { 4315 time = 10000; 4316 } 4317 return time; 4318} 4319 4320void AudioFlinger::DirectOutputThread::cacheParameters_l() 4321{ 4322 PlaybackThread::cacheParameters_l(); 4323 4324 // use shorter standby delay as on normal output to release 4325 // hardware resources as soon as possible 4326 if (audio_is_linear_pcm(mFormat)) { 4327 standbyDelay = microseconds(activeSleepTime*2); 4328 } else { 4329 standbyDelay = kOffloadStandbyDelayNs; 4330 } 4331} 4332 4333void AudioFlinger::DirectOutputThread::flushHw_l() 4334{ 4335 if (mOutput->stream->flush != NULL) 4336 mOutput->stream->flush(mOutput->stream); 4337} 4338 4339// ---------------------------------------------------------------------------- 4340 4341AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 4342 const wp<AudioFlinger::PlaybackThread>& playbackThread) 4343 : Thread(false /*canCallJava*/), 4344 mPlaybackThread(playbackThread), 4345 mWriteAckSequence(0), 4346 mDrainSequence(0) 4347{ 4348} 4349 4350AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 4351{ 4352} 4353 4354void AudioFlinger::AsyncCallbackThread::onFirstRef() 4355{ 4356 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 4357} 4358 4359bool AudioFlinger::AsyncCallbackThread::threadLoop() 4360{ 4361 while (!exitPending()) { 4362 uint32_t writeAckSequence; 4363 uint32_t drainSequence; 4364 4365 { 4366 Mutex::Autolock _l(mLock); 4367 while (!((mWriteAckSequence & 1) || 4368 (mDrainSequence & 1) || 4369 exitPending())) { 4370 mWaitWorkCV.wait(mLock); 4371 } 4372 4373 if (exitPending()) { 4374 break; 4375 } 4376 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 4377 mWriteAckSequence, mDrainSequence); 4378 writeAckSequence = mWriteAckSequence; 4379 mWriteAckSequence &= ~1; 4380 drainSequence = mDrainSequence; 4381 mDrainSequence &= ~1; 4382 } 4383 { 4384 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 4385 if (playbackThread != 0) { 4386 if (writeAckSequence & 1) { 4387 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 4388 } 4389 if (drainSequence & 1) { 4390 playbackThread->resetDraining(drainSequence >> 1); 4391 } 4392 } 4393 } 4394 } 4395 return false; 4396} 4397 4398void AudioFlinger::AsyncCallbackThread::exit() 4399{ 4400 ALOGV("AsyncCallbackThread::exit"); 4401 Mutex::Autolock _l(mLock); 4402 requestExit(); 4403 mWaitWorkCV.broadcast(); 4404} 4405 4406void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 4407{ 4408 Mutex::Autolock _l(mLock); 4409 // bit 0 is cleared 4410 mWriteAckSequence = sequence << 1; 4411} 4412 4413void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 4414{ 4415 Mutex::Autolock _l(mLock); 4416 // ignore unexpected callbacks 4417 if (mWriteAckSequence & 2) { 4418 mWriteAckSequence |= 1; 4419 mWaitWorkCV.signal(); 4420 } 4421} 4422 4423void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 4424{ 4425 Mutex::Autolock _l(mLock); 4426 // bit 0 is cleared 4427 mDrainSequence = sequence << 1; 4428} 4429 4430void AudioFlinger::AsyncCallbackThread::resetDraining() 4431{ 4432 Mutex::Autolock _l(mLock); 4433 // ignore unexpected callbacks 4434 if (mDrainSequence & 2) { 4435 mDrainSequence |= 1; 4436 mWaitWorkCV.signal(); 4437 } 4438} 4439 4440 4441// ---------------------------------------------------------------------------- 4442AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 4443 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 4444 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 4445 mHwPaused(false), 4446 mFlushPending(false), 4447 mPausedBytesRemaining(0) 4448{ 4449 //FIXME: mStandby should be set to true by ThreadBase constructor 4450 mStandby = true; 4451} 4452 4453void AudioFlinger::OffloadThread::threadLoop_exit() 4454{ 4455 if (mFlushPending || mHwPaused) { 4456 // If a flush is pending or track was paused, just discard buffered data 4457 flushHw_l(); 4458 } else { 4459 mMixerStatus = MIXER_DRAIN_ALL; 4460 threadLoop_drain(); 4461 } 4462 if (mUseAsyncWrite) { 4463 ALOG_ASSERT(mCallbackThread != 0); 4464 mCallbackThread->exit(); 4465 } 4466 PlaybackThread::threadLoop_exit(); 4467} 4468 4469AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 4470 Vector< sp<Track> > *tracksToRemove 4471) 4472{ 4473 size_t count = mActiveTracks.size(); 4474 4475 mixer_state mixerStatus = MIXER_IDLE; 4476 bool doHwPause = false; 4477 bool doHwResume = false; 4478 4479 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 4480 4481 // find out which tracks need to be processed 4482 for (size_t i = 0; i < count; i++) { 4483 sp<Track> t = mActiveTracks[i].promote(); 4484 // The track died recently 4485 if (t == 0) { 4486 continue; 4487 } 4488 Track* const track = t.get(); 4489 audio_track_cblk_t* cblk = track->cblk(); 4490 // Only consider last track started for volume and mixer state control. 4491 // In theory an older track could underrun and restart after the new one starts 4492 // but as we only care about the transition phase between two tracks on a 4493 // direct output, it is not a problem to ignore the underrun case. 4494 sp<Track> l = mLatestActiveTrack.promote(); 4495 bool last = l.get() == track; 4496 4497 if (track->isInvalid()) { 4498 ALOGW("An invalidated track shouldn't be in active list"); 4499 tracksToRemove->add(track); 4500 continue; 4501 } 4502 4503 if (track->mState == TrackBase::IDLE) { 4504 ALOGW("An idle track shouldn't be in active list"); 4505 continue; 4506 } 4507 4508 if (track->isPausing()) { 4509 track->setPaused(); 4510 if (last) { 4511 if (!mHwPaused) { 4512 doHwPause = true; 4513 mHwPaused = true; 4514 } 4515 // If we were part way through writing the mixbuffer to 4516 // the HAL we must save this until we resume 4517 // BUG - this will be wrong if a different track is made active, 4518 // in that case we want to discard the pending data in the 4519 // mixbuffer and tell the client to present it again when the 4520 // track is resumed 4521 mPausedWriteLength = mCurrentWriteLength; 4522 mPausedBytesRemaining = mBytesRemaining; 4523 mBytesRemaining = 0; // stop writing 4524 } 4525 tracksToRemove->add(track); 4526 } else if (track->isFlushPending()) { 4527 track->flushAck(); 4528 if (last) { 4529 mFlushPending = true; 4530 } 4531 } else if (track->isResumePending()){ 4532 track->resumeAck(); 4533 if (last) { 4534 if (mPausedBytesRemaining) { 4535 // Need to continue write that was interrupted 4536 mCurrentWriteLength = mPausedWriteLength; 4537 mBytesRemaining = mPausedBytesRemaining; 4538 mPausedBytesRemaining = 0; 4539 } 4540 if (mHwPaused) { 4541 doHwResume = true; 4542 mHwPaused = false; 4543 // threadLoop_mix() will handle the case that we need to 4544 // resume an interrupted write 4545 } 4546 // enable write to audio HAL 4547 sleepTime = 0; 4548 4549 // Do not handle new data in this iteration even if track->framesReady() 4550 mixerStatus = MIXER_TRACKS_ENABLED; 4551 } 4552 } else if (track->framesReady() && track->isReady() && 4553 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 4554 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 4555 if (track->mFillingUpStatus == Track::FS_FILLED) { 4556 track->mFillingUpStatus = Track::FS_ACTIVE; 4557 // make sure processVolume_l() will apply new volume even if 0 4558 mLeftVolFloat = mRightVolFloat = -1.0; 4559 } 4560 4561 if (last) { 4562 sp<Track> previousTrack = mPreviousTrack.promote(); 4563 if (previousTrack != 0) { 4564 if (track != previousTrack.get()) { 4565 // Flush any data still being written from last track 4566 mBytesRemaining = 0; 4567 if (mPausedBytesRemaining) { 4568 // Last track was paused so we also need to flush saved 4569 // mixbuffer state and invalidate track so that it will 4570 // re-submit that unwritten data when it is next resumed 4571 mPausedBytesRemaining = 0; 4572 // Invalidate is a bit drastic - would be more efficient 4573 // to have a flag to tell client that some of the 4574 // previously written data was lost 4575 previousTrack->invalidate(); 4576 } 4577 // flush data already sent to the DSP if changing audio session as audio 4578 // comes from a different source. Also invalidate previous track to force a 4579 // seek when resuming. 4580 if (previousTrack->sessionId() != track->sessionId()) { 4581 previousTrack->invalidate(); 4582 } 4583 } 4584 } 4585 mPreviousTrack = track; 4586 // reset retry count 4587 track->mRetryCount = kMaxTrackRetriesOffload; 4588 mActiveTrack = t; 4589 mixerStatus = MIXER_TRACKS_READY; 4590 } 4591 } else { 4592 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 4593 if (track->isStopping_1()) { 4594 // Hardware buffer can hold a large amount of audio so we must 4595 // wait for all current track's data to drain before we say 4596 // that the track is stopped. 4597 if (mBytesRemaining == 0) { 4598 // Only start draining when all data in mixbuffer 4599 // has been written 4600 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 4601 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 4602 // do not drain if no data was ever sent to HAL (mStandby == true) 4603 if (last && !mStandby) { 4604 // do not modify drain sequence if we are already draining. This happens 4605 // when resuming from pause after drain. 4606 if ((mDrainSequence & 1) == 0) { 4607 sleepTime = 0; 4608 standbyTime = systemTime() + standbyDelay; 4609 mixerStatus = MIXER_DRAIN_TRACK; 4610 mDrainSequence += 2; 4611 } 4612 if (mHwPaused) { 4613 // It is possible to move from PAUSED to STOPPING_1 without 4614 // a resume so we must ensure hardware is running 4615 doHwResume = true; 4616 mHwPaused = false; 4617 } 4618 } 4619 } 4620 } else if (track->isStopping_2()) { 4621 // Drain has completed or we are in standby, signal presentation complete 4622 if (!(mDrainSequence & 1) || !last || mStandby) { 4623 track->mState = TrackBase::STOPPED; 4624 size_t audioHALFrames = 4625 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 4626 size_t framesWritten = 4627 mBytesWritten / audio_stream_out_frame_size(mOutput->stream); 4628 track->presentationComplete(framesWritten, audioHALFrames); 4629 track->reset(); 4630 tracksToRemove->add(track); 4631 } 4632 } else { 4633 // No buffers for this track. Give it a few chances to 4634 // fill a buffer, then remove it from active list. 4635 if (--(track->mRetryCount) <= 0) { 4636 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 4637 track->name()); 4638 tracksToRemove->add(track); 4639 // indicate to client process that the track was disabled because of underrun; 4640 // it will then automatically call start() when data is available 4641 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4642 } else if (last){ 4643 mixerStatus = MIXER_TRACKS_ENABLED; 4644 } 4645 } 4646 } 4647 // compute volume for this track 4648 processVolume_l(track, last); 4649 } 4650 4651 // make sure the pause/flush/resume sequence is executed in the right order. 4652 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 4653 // before flush and then resume HW. This can happen in case of pause/flush/resume 4654 // if resume is received before pause is executed. 4655 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 4656 mOutput->stream->pause(mOutput->stream); 4657 } 4658 if (mFlushPending) { 4659 flushHw_l(); 4660 mFlushPending = false; 4661 } 4662 if (!mStandby && doHwResume) { 4663 mOutput->stream->resume(mOutput->stream); 4664 } 4665 4666 // remove all the tracks that need to be... 4667 removeTracks_l(*tracksToRemove); 4668 4669 return mixerStatus; 4670} 4671 4672// must be called with thread mutex locked 4673bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 4674{ 4675 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 4676 mWriteAckSequence, mDrainSequence); 4677 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 4678 return true; 4679 } 4680 return false; 4681} 4682 4683// must be called with thread mutex locked 4684bool AudioFlinger::OffloadThread::shouldStandby_l() 4685{ 4686 bool trackPaused = false; 4687 4688 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4689 // after a timeout and we will enter standby then. 4690 if (mTracks.size() > 0) { 4691 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4692 } 4693 4694 return !mStandby && !trackPaused; 4695} 4696 4697 4698bool AudioFlinger::OffloadThread::waitingAsyncCallback() 4699{ 4700 Mutex::Autolock _l(mLock); 4701 return waitingAsyncCallback_l(); 4702} 4703 4704void AudioFlinger::OffloadThread::flushHw_l() 4705{ 4706 DirectOutputThread::flushHw_l(); 4707 // Flush anything still waiting in the mixbuffer 4708 mCurrentWriteLength = 0; 4709 mBytesRemaining = 0; 4710 mPausedWriteLength = 0; 4711 mPausedBytesRemaining = 0; 4712 mHwPaused = false; 4713 4714 if (mUseAsyncWrite) { 4715 // discard any pending drain or write ack by incrementing sequence 4716 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 4717 mDrainSequence = (mDrainSequence + 2) & ~1; 4718 ALOG_ASSERT(mCallbackThread != 0); 4719 mCallbackThread->setWriteBlocked(mWriteAckSequence); 4720 mCallbackThread->setDraining(mDrainSequence); 4721 } 4722} 4723 4724void AudioFlinger::OffloadThread::onAddNewTrack_l() 4725{ 4726 sp<Track> previousTrack = mPreviousTrack.promote(); 4727 sp<Track> latestTrack = mLatestActiveTrack.promote(); 4728 4729 if (previousTrack != 0 && latestTrack != 0 && 4730 (previousTrack->sessionId() != latestTrack->sessionId())) { 4731 mFlushPending = true; 4732 } 4733 PlaybackThread::onAddNewTrack_l(); 4734} 4735 4736// ---------------------------------------------------------------------------- 4737 4738AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4739 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4740 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4741 DUPLICATING), 4742 mWaitTimeMs(UINT_MAX) 4743{ 4744 addOutputTrack(mainThread); 4745} 4746 4747AudioFlinger::DuplicatingThread::~DuplicatingThread() 4748{ 4749 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4750 mOutputTracks[i]->destroy(); 4751 } 4752} 4753 4754void AudioFlinger::DuplicatingThread::threadLoop_mix() 4755{ 4756 // mix buffers... 4757 if (outputsReady(outputTracks)) { 4758 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4759 } else { 4760 if (mMixerBufferValid) { 4761 memset(mMixerBuffer, 0, mMixerBufferSize); 4762 } else { 4763 memset(mSinkBuffer, 0, mSinkBufferSize); 4764 } 4765 } 4766 sleepTime = 0; 4767 writeFrames = mNormalFrameCount; 4768 mCurrentWriteLength = mSinkBufferSize; 4769 standbyTime = systemTime() + standbyDelay; 4770} 4771 4772void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4773{ 4774 if (sleepTime == 0) { 4775 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4776 sleepTime = activeSleepTime; 4777 } else { 4778 sleepTime = idleSleepTime; 4779 } 4780 } else if (mBytesWritten != 0) { 4781 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4782 writeFrames = mNormalFrameCount; 4783 memset(mSinkBuffer, 0, mSinkBufferSize); 4784 } else { 4785 // flush remaining overflow buffers in output tracks 4786 writeFrames = 0; 4787 } 4788 sleepTime = 0; 4789 } 4790} 4791 4792ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4793{ 4794 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT 4795 // for delivery downstream as needed. This in-place conversion is safe as 4796 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format 4797 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here). 4798 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 4799 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT, 4800 mSinkBuffer, mFormat, writeFrames * mChannelCount); 4801 } 4802 for (size_t i = 0; i < outputTracks.size(); i++) { 4803 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames); 4804 } 4805 mStandby = false; 4806 return (ssize_t)mSinkBufferSize; 4807} 4808 4809void AudioFlinger::DuplicatingThread::threadLoop_standby() 4810{ 4811 // DuplicatingThread implements standby by stopping all tracks 4812 for (size_t i = 0; i < outputTracks.size(); i++) { 4813 outputTracks[i]->stop(); 4814 } 4815} 4816 4817void AudioFlinger::DuplicatingThread::saveOutputTracks() 4818{ 4819 outputTracks = mOutputTracks; 4820} 4821 4822void AudioFlinger::DuplicatingThread::clearOutputTracks() 4823{ 4824 outputTracks.clear(); 4825} 4826 4827void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4828{ 4829 Mutex::Autolock _l(mLock); 4830 // FIXME explain this formula 4831 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4832 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat 4833 // due to current usage case and restrictions on the AudioBufferProvider. 4834 // Actual buffer conversion is done in threadLoop_write(). 4835 // 4836 // TODO: This may change in the future, depending on multichannel 4837 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack 4838 OutputTrack *outputTrack = new OutputTrack(thread, 4839 this, 4840 mSampleRate, 4841 AUDIO_FORMAT_PCM_16_BIT, 4842 mChannelMask, 4843 frameCount, 4844 IPCThreadState::self()->getCallingUid()); 4845 if (outputTrack->cblk() != NULL) { 4846 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f); 4847 mOutputTracks.add(outputTrack); 4848 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4849 updateWaitTime_l(); 4850 } 4851} 4852 4853void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4854{ 4855 Mutex::Autolock _l(mLock); 4856 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4857 if (mOutputTracks[i]->thread() == thread) { 4858 mOutputTracks[i]->destroy(); 4859 mOutputTracks.removeAt(i); 4860 updateWaitTime_l(); 4861 return; 4862 } 4863 } 4864 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4865} 4866 4867// caller must hold mLock 4868void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4869{ 4870 mWaitTimeMs = UINT_MAX; 4871 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4872 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4873 if (strong != 0) { 4874 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4875 if (waitTimeMs < mWaitTimeMs) { 4876 mWaitTimeMs = waitTimeMs; 4877 } 4878 } 4879 } 4880} 4881 4882 4883bool AudioFlinger::DuplicatingThread::outputsReady( 4884 const SortedVector< sp<OutputTrack> > &outputTracks) 4885{ 4886 for (size_t i = 0; i < outputTracks.size(); i++) { 4887 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4888 if (thread == 0) { 4889 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4890 outputTracks[i].get()); 4891 return false; 4892 } 4893 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4894 // see note at standby() declaration 4895 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4896 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4897 thread.get()); 4898 return false; 4899 } 4900 } 4901 return true; 4902} 4903 4904uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4905{ 4906 return (mWaitTimeMs * 1000) / 2; 4907} 4908 4909void AudioFlinger::DuplicatingThread::cacheParameters_l() 4910{ 4911 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4912 updateWaitTime_l(); 4913 4914 MixerThread::cacheParameters_l(); 4915} 4916 4917// ---------------------------------------------------------------------------- 4918// Record 4919// ---------------------------------------------------------------------------- 4920 4921AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4922 AudioStreamIn *input, 4923 audio_io_handle_t id, 4924 audio_devices_t outDevice, 4925 audio_devices_t inDevice 4926#ifdef TEE_SINK 4927 , const sp<NBAIO_Sink>& teeSink 4928#endif 4929 ) : 4930 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4931 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL), 4932 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l() 4933 mRsmpInRear(0) 4934#ifdef TEE_SINK 4935 , mTeeSink(teeSink) 4936#endif 4937 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize, 4938 "RecordThreadRO", MemoryHeapBase::READ_ONLY)) 4939 // mFastCapture below 4940 , mFastCaptureFutex(0) 4941 // mInputSource 4942 // mPipeSink 4943 // mPipeSource 4944 , mPipeFramesP2(0) 4945 // mPipeMemory 4946 // mFastCaptureNBLogWriter 4947 , mFastTrackAvail(false) 4948{ 4949 snprintf(mName, kNameLength, "AudioIn_%X", id); 4950 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 4951 4952 readInputParameters_l(); 4953 4954 // create an NBAIO source for the HAL input stream, and negotiate 4955 mInputSource = new AudioStreamInSource(input->stream); 4956 size_t numCounterOffers = 0; 4957 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 4958 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers); 4959 ALOG_ASSERT(index == 0); 4960 4961 // initialize fast capture depending on configuration 4962 bool initFastCapture; 4963 switch (kUseFastCapture) { 4964 case FastCapture_Never: 4965 initFastCapture = false; 4966 break; 4967 case FastCapture_Always: 4968 initFastCapture = true; 4969 break; 4970 case FastCapture_Static: 4971 uint32_t primaryOutputSampleRate; 4972 { 4973 AutoMutex _l(audioFlinger->mHardwareLock); 4974 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate; 4975 } 4976 initFastCapture = 4977 // either capture sample rate is same as (a reasonable) primary output sample rate 4978 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) && 4979 (mSampleRate == primaryOutputSampleRate)) || 4980 // or primary output sample rate is unknown, and capture sample rate is reasonable 4981 ((primaryOutputSampleRate == 0) && 4982 ((mSampleRate == 44100 || mSampleRate == 48000)))) && 4983 // and the buffer size is < 12 ms 4984 (mFrameCount * 1000) / mSampleRate < 12; 4985 break; 4986 // case FastCapture_Dynamic: 4987 } 4988 4989 if (initFastCapture) { 4990 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from 4991 NBAIO_Format format = mInputSource->format(); 4992 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each 4993 size_t pipeSize = pipeFramesP2 * Format_frameSize(format); 4994 void *pipeBuffer; 4995 const sp<MemoryDealer> roHeap(readOnlyHeap()); 4996 sp<IMemory> pipeMemory; 4997 if ((roHeap == 0) || 4998 (pipeMemory = roHeap->allocate(pipeSize)) == 0 || 4999 (pipeBuffer = pipeMemory->pointer()) == NULL) { 5000 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize); 5001 goto failed; 5002 } 5003 // pipe will be shared directly with fast clients, so clear to avoid leaking old information 5004 memset(pipeBuffer, 0, pipeSize); 5005 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer); 5006 const NBAIO_Format offers[1] = {format}; 5007 size_t numCounterOffers = 0; 5008 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 5009 ALOG_ASSERT(index == 0); 5010 mPipeSink = pipe; 5011 PipeReader *pipeReader = new PipeReader(*pipe); 5012 numCounterOffers = 0; 5013 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 5014 ALOG_ASSERT(index == 0); 5015 mPipeSource = pipeReader; 5016 mPipeFramesP2 = pipeFramesP2; 5017 mPipeMemory = pipeMemory; 5018 5019 // create fast capture 5020 mFastCapture = new FastCapture(); 5021 FastCaptureStateQueue *sq = mFastCapture->sq(); 5022#ifdef STATE_QUEUE_DUMP 5023 // FIXME 5024#endif 5025 FastCaptureState *state = sq->begin(); 5026 state->mCblk = NULL; 5027 state->mInputSource = mInputSource.get(); 5028 state->mInputSourceGen++; 5029 state->mPipeSink = pipe; 5030 state->mPipeSinkGen++; 5031 state->mFrameCount = mFrameCount; 5032 state->mCommand = FastCaptureState::COLD_IDLE; 5033 // already done in constructor initialization list 5034 //mFastCaptureFutex = 0; 5035 state->mColdFutexAddr = &mFastCaptureFutex; 5036 state->mColdGen++; 5037 state->mDumpState = &mFastCaptureDumpState; 5038#ifdef TEE_SINK 5039 // FIXME 5040#endif 5041 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture"); 5042 state->mNBLogWriter = mFastCaptureNBLogWriter.get(); 5043 sq->end(); 5044 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5045 5046 // start the fast capture 5047 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO); 5048 pid_t tid = mFastCapture->getTid(); 5049 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 5050 if (err != 0) { 5051 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 5052 kPriorityFastCapture, getpid_cached, tid, err); 5053 } 5054 5055#ifdef AUDIO_WATCHDOG 5056 // FIXME 5057#endif 5058 5059 mFastTrackAvail = true; 5060 } 5061failed: ; 5062 5063 // FIXME mNormalSource 5064} 5065 5066 5067AudioFlinger::RecordThread::~RecordThread() 5068{ 5069 if (mFastCapture != 0) { 5070 FastCaptureStateQueue *sq = mFastCapture->sq(); 5071 FastCaptureState *state = sq->begin(); 5072 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5073 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5074 if (old == -1) { 5075 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5076 } 5077 } 5078 state->mCommand = FastCaptureState::EXIT; 5079 sq->end(); 5080 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5081 mFastCapture->join(); 5082 mFastCapture.clear(); 5083 } 5084 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter); 5085 mAudioFlinger->unregisterWriter(mNBLogWriter); 5086 delete[] mRsmpInBuffer; 5087} 5088 5089void AudioFlinger::RecordThread::onFirstRef() 5090{ 5091 run(mName, PRIORITY_URGENT_AUDIO); 5092} 5093 5094bool AudioFlinger::RecordThread::threadLoop() 5095{ 5096 nsecs_t lastWarning = 0; 5097 5098 inputStandBy(); 5099 5100reacquire_wakelock: 5101 sp<RecordTrack> activeTrack; 5102 int activeTracksGen; 5103 { 5104 Mutex::Autolock _l(mLock); 5105 size_t size = mActiveTracks.size(); 5106 activeTracksGen = mActiveTracksGen; 5107 if (size > 0) { 5108 // FIXME an arbitrary choice 5109 activeTrack = mActiveTracks[0]; 5110 acquireWakeLock_l(activeTrack->uid()); 5111 if (size > 1) { 5112 SortedVector<int> tmp; 5113 for (size_t i = 0; i < size; i++) { 5114 tmp.add(mActiveTracks[i]->uid()); 5115 } 5116 updateWakeLockUids_l(tmp); 5117 } 5118 } else { 5119 acquireWakeLock_l(-1); 5120 } 5121 } 5122 5123 // used to request a deferred sleep, to be executed later while mutex is unlocked 5124 uint32_t sleepUs = 0; 5125 5126 // loop while there is work to do 5127 for (;;) { 5128 Vector< sp<EffectChain> > effectChains; 5129 5130 // sleep with mutex unlocked 5131 if (sleepUs > 0) { 5132 ATRACE_BEGIN("sleep"); 5133 usleep(sleepUs); 5134 ATRACE_END(); 5135 sleepUs = 0; 5136 } 5137 5138 // activeTracks accumulates a copy of a subset of mActiveTracks 5139 Vector< sp<RecordTrack> > activeTracks; 5140 5141 // reference to the (first and only) active fast track 5142 sp<RecordTrack> fastTrack; 5143 5144 // reference to a fast track which is about to be removed 5145 sp<RecordTrack> fastTrackToRemove; 5146 5147 { // scope for mLock 5148 Mutex::Autolock _l(mLock); 5149 5150 processConfigEvents_l(); 5151 5152 // check exitPending here because checkForNewParameters_l() and 5153 // checkForNewParameters_l() can temporarily release mLock 5154 if (exitPending()) { 5155 break; 5156 } 5157 5158 // if no active track(s), then standby and release wakelock 5159 size_t size = mActiveTracks.size(); 5160 if (size == 0) { 5161 standbyIfNotAlreadyInStandby(); 5162 // exitPending() can't become true here 5163 releaseWakeLock_l(); 5164 ALOGV("RecordThread: loop stopping"); 5165 // go to sleep 5166 mWaitWorkCV.wait(mLock); 5167 ALOGV("RecordThread: loop starting"); 5168 goto reacquire_wakelock; 5169 } 5170 5171 if (mActiveTracksGen != activeTracksGen) { 5172 activeTracksGen = mActiveTracksGen; 5173 SortedVector<int> tmp; 5174 for (size_t i = 0; i < size; i++) { 5175 tmp.add(mActiveTracks[i]->uid()); 5176 } 5177 updateWakeLockUids_l(tmp); 5178 } 5179 5180 bool doBroadcast = false; 5181 for (size_t i = 0; i < size; ) { 5182 5183 activeTrack = mActiveTracks[i]; 5184 if (activeTrack->isTerminated()) { 5185 if (activeTrack->isFastTrack()) { 5186 ALOG_ASSERT(fastTrackToRemove == 0); 5187 fastTrackToRemove = activeTrack; 5188 } 5189 removeTrack_l(activeTrack); 5190 mActiveTracks.remove(activeTrack); 5191 mActiveTracksGen++; 5192 size--; 5193 continue; 5194 } 5195 5196 TrackBase::track_state activeTrackState = activeTrack->mState; 5197 switch (activeTrackState) { 5198 5199 case TrackBase::PAUSING: 5200 mActiveTracks.remove(activeTrack); 5201 mActiveTracksGen++; 5202 doBroadcast = true; 5203 size--; 5204 continue; 5205 5206 case TrackBase::STARTING_1: 5207 sleepUs = 10000; 5208 i++; 5209 continue; 5210 5211 case TrackBase::STARTING_2: 5212 doBroadcast = true; 5213 mStandby = false; 5214 activeTrack->mState = TrackBase::ACTIVE; 5215 break; 5216 5217 case TrackBase::ACTIVE: 5218 break; 5219 5220 case TrackBase::IDLE: 5221 i++; 5222 continue; 5223 5224 default: 5225 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState); 5226 } 5227 5228 activeTracks.add(activeTrack); 5229 i++; 5230 5231 if (activeTrack->isFastTrack()) { 5232 ALOG_ASSERT(!mFastTrackAvail); 5233 ALOG_ASSERT(fastTrack == 0); 5234 fastTrack = activeTrack; 5235 } 5236 } 5237 if (doBroadcast) { 5238 mStartStopCond.broadcast(); 5239 } 5240 5241 // sleep if there are no active tracks to process 5242 if (activeTracks.size() == 0) { 5243 if (sleepUs == 0) { 5244 sleepUs = kRecordThreadSleepUs; 5245 } 5246 continue; 5247 } 5248 sleepUs = 0; 5249 5250 lockEffectChains_l(effectChains); 5251 } 5252 5253 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0 5254 5255 size_t size = effectChains.size(); 5256 for (size_t i = 0; i < size; i++) { 5257 // thread mutex is not locked, but effect chain is locked 5258 effectChains[i]->process_l(); 5259 } 5260 5261 // Push a new fast capture state if fast capture is not already running, or cblk change 5262 if (mFastCapture != 0) { 5263 FastCaptureStateQueue *sq = mFastCapture->sq(); 5264 FastCaptureState *state = sq->begin(); 5265 bool didModify = false; 5266 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED; 5267 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME && 5268 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) { 5269 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5270 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5271 if (old == -1) { 5272 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5273 } 5274 } 5275 state->mCommand = FastCaptureState::READ_WRITE; 5276#if 0 // FIXME 5277 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 5278 FastCaptureDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 5279#endif 5280 didModify = true; 5281 } 5282 audio_track_cblk_t *cblkOld = state->mCblk; 5283 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL; 5284 if (cblkNew != cblkOld) { 5285 state->mCblk = cblkNew; 5286 // block until acked if removing a fast track 5287 if (cblkOld != NULL) { 5288 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED; 5289 } 5290 didModify = true; 5291 } 5292 sq->end(didModify); 5293 if (didModify) { 5294 sq->push(block); 5295#if 0 5296 if (kUseFastCapture == FastCapture_Dynamic) { 5297 mNormalSource = mPipeSource; 5298 } 5299#endif 5300 } 5301 } 5302 5303 // now run the fast track destructor with thread mutex unlocked 5304 fastTrackToRemove.clear(); 5305 5306 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one. 5307 // Only the client(s) that are too slow will overrun. But if even the fastest client is too 5308 // slow, then this RecordThread will overrun by not calling HAL read often enough. 5309 // If destination is non-contiguous, first read past the nominal end of buffer, then 5310 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 5311 5312 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1); 5313 ssize_t framesRead; 5314 5315 // If an NBAIO source is present, use it to read the normal capture's data 5316 if (mPipeSource != 0) { 5317 size_t framesToRead = mBufferSize / mFrameSize; 5318 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount], 5319 framesToRead, AudioBufferProvider::kInvalidPTS); 5320 if (framesRead == 0) { 5321 // since pipe is non-blocking, simulate blocking input 5322 sleepUs = (framesToRead * 1000000LL) / mSampleRate; 5323 } 5324 // otherwise use the HAL / AudioStreamIn directly 5325 } else { 5326 ssize_t bytesRead = mInput->stream->read(mInput->stream, 5327 &mRsmpInBuffer[rear * mChannelCount], mBufferSize); 5328 if (bytesRead < 0) { 5329 framesRead = bytesRead; 5330 } else { 5331 framesRead = bytesRead / mFrameSize; 5332 } 5333 } 5334 5335 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) { 5336 ALOGE("read failed: framesRead=%d", framesRead); 5337 // Force input into standby so that it tries to recover at next read attempt 5338 inputStandBy(); 5339 sleepUs = kRecordThreadSleepUs; 5340 } 5341 if (framesRead <= 0) { 5342 goto unlock; 5343 } 5344 ALOG_ASSERT(framesRead > 0); 5345 5346 if (mTeeSink != 0) { 5347 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead); 5348 } 5349 // If destination is non-contiguous, we now correct for reading past end of buffer. 5350 { 5351 size_t part1 = mRsmpInFramesP2 - rear; 5352 if ((size_t) framesRead > part1) { 5353 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount], 5354 (framesRead - part1) * mFrameSize); 5355 } 5356 } 5357 rear = mRsmpInRear += framesRead; 5358 5359 size = activeTracks.size(); 5360 // loop over each active track 5361 for (size_t i = 0; i < size; i++) { 5362 activeTrack = activeTracks[i]; 5363 5364 // skip fast tracks, as those are handled directly by FastCapture 5365 if (activeTrack->isFastTrack()) { 5366 continue; 5367 } 5368 5369 enum { 5370 OVERRUN_UNKNOWN, 5371 OVERRUN_TRUE, 5372 OVERRUN_FALSE 5373 } overrun = OVERRUN_UNKNOWN; 5374 5375 // loop over getNextBuffer to handle circular sink 5376 for (;;) { 5377 5378 activeTrack->mSink.frameCount = ~0; 5379 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink); 5380 size_t framesOut = activeTrack->mSink.frameCount; 5381 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0)); 5382 5383 int32_t front = activeTrack->mRsmpInFront; 5384 ssize_t filled = rear - front; 5385 size_t framesIn; 5386 5387 if (filled < 0) { 5388 // should not happen, but treat like a massive overrun and re-sync 5389 framesIn = 0; 5390 activeTrack->mRsmpInFront = rear; 5391 overrun = OVERRUN_TRUE; 5392 } else if ((size_t) filled <= mRsmpInFrames) { 5393 framesIn = (size_t) filled; 5394 } else { 5395 // client is not keeping up with server, but give it latest data 5396 framesIn = mRsmpInFrames; 5397 activeTrack->mRsmpInFront = front = rear - framesIn; 5398 overrun = OVERRUN_TRUE; 5399 } 5400 5401 if (framesOut == 0 || framesIn == 0) { 5402 break; 5403 } 5404 5405 if (activeTrack->mResampler == NULL) { 5406 // no resampling 5407 if (framesIn > framesOut) { 5408 framesIn = framesOut; 5409 } else { 5410 framesOut = framesIn; 5411 } 5412 int8_t *dst = activeTrack->mSink.i8; 5413 while (framesIn > 0) { 5414 front &= mRsmpInFramesP2 - 1; 5415 size_t part1 = mRsmpInFramesP2 - front; 5416 if (part1 > framesIn) { 5417 part1 = framesIn; 5418 } 5419 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize); 5420 if (mChannelCount == activeTrack->mChannelCount) { 5421 memcpy(dst, src, part1 * mFrameSize); 5422 } else if (mChannelCount == 1) { 5423 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src, 5424 part1); 5425 } else { 5426 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (const int16_t *)src, 5427 part1); 5428 } 5429 dst += part1 * activeTrack->mFrameSize; 5430 front += part1; 5431 framesIn -= part1; 5432 } 5433 activeTrack->mRsmpInFront += framesOut; 5434 5435 } else { 5436 // resampling 5437 // FIXME framesInNeeded should really be part of resampler API, and should 5438 // depend on the SRC ratio 5439 // to keep mRsmpInBuffer full so resampler always has sufficient input 5440 size_t framesInNeeded; 5441 // FIXME only re-calculate when it changes, and optimize for common ratios 5442 // Do not precompute in/out because floating point is not associative 5443 // e.g. a*b/c != a*(b/c). 5444 const double in(mSampleRate); 5445 const double out(activeTrack->mSampleRate); 5446 framesInNeeded = ceil(framesOut * in / out) + 1; 5447 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g", 5448 framesInNeeded, framesOut, in / out); 5449 // Although we theoretically have framesIn in circular buffer, some of those are 5450 // unreleased frames, and thus must be discounted for purpose of budgeting. 5451 size_t unreleased = activeTrack->mRsmpInUnrel; 5452 framesIn = framesIn > unreleased ? framesIn - unreleased : 0; 5453 if (framesIn < framesInNeeded) { 5454 ALOGV("not enough to resample: have %u frames in but need %u in to " 5455 "produce %u out given in/out ratio of %.4g", 5456 framesIn, framesInNeeded, framesOut, in / out); 5457 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0; 5458 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut); 5459 if (newFramesOut == 0) { 5460 break; 5461 } 5462 framesInNeeded = ceil(newFramesOut * in / out) + 1; 5463 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g", 5464 framesInNeeded, newFramesOut, out / in); 5465 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded); 5466 ALOGV("success 2: have %u frames in and need %u in to produce %u out " 5467 "given in/out ratio of %.4g", 5468 framesIn, framesInNeeded, newFramesOut, in / out); 5469 framesOut = newFramesOut; 5470 } else { 5471 ALOGV("success 1: have %u in and need %u in to produce %u out " 5472 "given in/out ratio of %.4g", 5473 framesIn, framesInNeeded, framesOut, in / out); 5474 } 5475 5476 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink 5477 if (activeTrack->mRsmpOutFrameCount < framesOut) { 5478 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share? 5479 delete[] activeTrack->mRsmpOutBuffer; 5480 // resampler always outputs stereo 5481 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2]; 5482 activeTrack->mRsmpOutFrameCount = framesOut; 5483 } 5484 5485 // resampler accumulates, but we only have one source track 5486 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 5487 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut, 5488 // FIXME how about having activeTrack implement this interface itself? 5489 activeTrack->mResamplerBufferProvider 5490 /*this*/ /* AudioBufferProvider* */); 5491 // ditherAndClamp() works as long as all buffers returned by 5492 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true. 5493 if (activeTrack->mChannelCount == 1) { 5494 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t 5495 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer, 5496 framesOut); 5497 // the resampler always outputs stereo samples: 5498 // do post stereo to mono conversion 5499 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16, 5500 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut); 5501 } else { 5502 ditherAndClamp((int32_t *)activeTrack->mSink.raw, 5503 activeTrack->mRsmpOutBuffer, framesOut); 5504 } 5505 // now done with mRsmpOutBuffer 5506 5507 } 5508 5509 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) { 5510 overrun = OVERRUN_FALSE; 5511 } 5512 5513 if (activeTrack->mFramesToDrop == 0) { 5514 if (framesOut > 0) { 5515 activeTrack->mSink.frameCount = framesOut; 5516 activeTrack->releaseBuffer(&activeTrack->mSink); 5517 } 5518 } else { 5519 // FIXME could do a partial drop of framesOut 5520 if (activeTrack->mFramesToDrop > 0) { 5521 activeTrack->mFramesToDrop -= framesOut; 5522 if (activeTrack->mFramesToDrop <= 0) { 5523 activeTrack->clearSyncStartEvent(); 5524 } 5525 } else { 5526 activeTrack->mFramesToDrop += framesOut; 5527 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 || 5528 activeTrack->mSyncStartEvent->isCancelled()) { 5529 ALOGW("Synced record %s, session %d, trigger session %d", 5530 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled", 5531 activeTrack->sessionId(), 5532 (activeTrack->mSyncStartEvent != 0) ? 5533 activeTrack->mSyncStartEvent->triggerSession() : 0); 5534 activeTrack->clearSyncStartEvent(); 5535 } 5536 } 5537 } 5538 5539 if (framesOut == 0) { 5540 break; 5541 } 5542 } 5543 5544 switch (overrun) { 5545 case OVERRUN_TRUE: 5546 // client isn't retrieving buffers fast enough 5547 if (!activeTrack->setOverflow()) { 5548 nsecs_t now = systemTime(); 5549 // FIXME should lastWarning per track? 5550 if ((now - lastWarning) > kWarningThrottleNs) { 5551 ALOGW("RecordThread: buffer overflow"); 5552 lastWarning = now; 5553 } 5554 } 5555 break; 5556 case OVERRUN_FALSE: 5557 activeTrack->clearOverflow(); 5558 break; 5559 case OVERRUN_UNKNOWN: 5560 break; 5561 } 5562 5563 } 5564 5565unlock: 5566 // enable changes in effect chain 5567 unlockEffectChains(effectChains); 5568 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 5569 } 5570 5571 standbyIfNotAlreadyInStandby(); 5572 5573 { 5574 Mutex::Autolock _l(mLock); 5575 for (size_t i = 0; i < mTracks.size(); i++) { 5576 sp<RecordTrack> track = mTracks[i]; 5577 track->invalidate(); 5578 } 5579 mActiveTracks.clear(); 5580 mActiveTracksGen++; 5581 mStartStopCond.broadcast(); 5582 } 5583 5584 releaseWakeLock(); 5585 5586 ALOGV("RecordThread %p exiting", this); 5587 return false; 5588} 5589 5590void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 5591{ 5592 if (!mStandby) { 5593 inputStandBy(); 5594 mStandby = true; 5595 } 5596} 5597 5598void AudioFlinger::RecordThread::inputStandBy() 5599{ 5600 // Idle the fast capture if it's currently running 5601 if (mFastCapture != 0) { 5602 FastCaptureStateQueue *sq = mFastCapture->sq(); 5603 FastCaptureState *state = sq->begin(); 5604 if (!(state->mCommand & FastCaptureState::IDLE)) { 5605 state->mCommand = FastCaptureState::COLD_IDLE; 5606 state->mColdFutexAddr = &mFastCaptureFutex; 5607 state->mColdGen++; 5608 mFastCaptureFutex = 0; 5609 sq->end(); 5610 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 5611 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED); 5612#if 0 5613 if (kUseFastCapture == FastCapture_Dynamic) { 5614 // FIXME 5615 } 5616#endif 5617#ifdef AUDIO_WATCHDOG 5618 // FIXME 5619#endif 5620 } else { 5621 sq->end(false /*didModify*/); 5622 } 5623 } 5624 mInput->stream->common.standby(&mInput->stream->common); 5625} 5626 5627// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held 5628sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 5629 const sp<AudioFlinger::Client>& client, 5630 uint32_t sampleRate, 5631 audio_format_t format, 5632 audio_channel_mask_t channelMask, 5633 size_t *pFrameCount, 5634 int sessionId, 5635 size_t *notificationFrames, 5636 int uid, 5637 IAudioFlinger::track_flags_t *flags, 5638 pid_t tid, 5639 status_t *status) 5640{ 5641 size_t frameCount = *pFrameCount; 5642 sp<RecordTrack> track; 5643 status_t lStatus; 5644 5645 // client expresses a preference for FAST, but we get the final say 5646 if (*flags & IAudioFlinger::TRACK_FAST) { 5647 if ( 5648 // use case: callback handler 5649 (tid != -1) && 5650 // frame count is not specified, or is exactly the pipe depth 5651 ((frameCount == 0) || (frameCount == mPipeFramesP2)) && 5652 // PCM data 5653 audio_is_linear_pcm(format) && 5654 // native format 5655 (format == mFormat) && 5656 // native channel mask 5657 (channelMask == mChannelMask) && 5658 // native hardware sample rate 5659 (sampleRate == mSampleRate) && 5660 // record thread has an associated fast capture 5661 hasFastCapture() && 5662 // there are sufficient fast track slots available 5663 mFastTrackAvail 5664 ) { 5665 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u", 5666 frameCount, mFrameCount); 5667 } else { 5668 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u " 5669 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 5670 "hasFastCapture=%d tid=%d mFastTrackAvail=%d", 5671 frameCount, mFrameCount, mPipeFramesP2, 5672 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate, 5673 hasFastCapture(), tid, mFastTrackAvail); 5674 *flags &= ~IAudioFlinger::TRACK_FAST; 5675 } 5676 } 5677 5678 // compute track buffer size in frames, and suggest the notification frame count 5679 if (*flags & IAudioFlinger::TRACK_FAST) { 5680 // fast track: frame count is exactly the pipe depth 5681 frameCount = mPipeFramesP2; 5682 // ignore requested notificationFrames, and always notify exactly once every HAL buffer 5683 *notificationFrames = mFrameCount; 5684 } else { 5685 // not fast track: max notification period is resampled equivalent of one HAL buffer time 5686 // or 20 ms if there is a fast capture 5687 // TODO This could be a roundupRatio inline, and const 5688 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount) 5689 * sampleRate + mSampleRate - 1) / mSampleRate; 5690 // minimum number of notification periods is at least kMinNotifications, 5691 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs) 5692 static const size_t kMinNotifications = 3; 5693 static const uint32_t kMinMs = 30; 5694 // TODO This could be a roundupRatio inline 5695 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000; 5696 // TODO This could be a roundupRatio inline 5697 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) / 5698 maxNotificationFrames; 5699 const size_t minFrameCount = maxNotificationFrames * 5700 max(kMinNotifications, minNotificationsByMs); 5701 frameCount = max(frameCount, minFrameCount); 5702 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) { 5703 *notificationFrames = maxNotificationFrames; 5704 } 5705 } 5706 *pFrameCount = frameCount; 5707 5708 lStatus = initCheck(); 5709 if (lStatus != NO_ERROR) { 5710 ALOGE("createRecordTrack_l() audio driver not initialized"); 5711 goto Exit; 5712 } 5713 5714 { // scope for mLock 5715 Mutex::Autolock _l(mLock); 5716 5717 track = new RecordTrack(this, client, sampleRate, 5718 format, channelMask, frameCount, NULL, sessionId, uid, 5719 *flags, TrackBase::TYPE_DEFAULT); 5720 5721 lStatus = track->initCheck(); 5722 if (lStatus != NO_ERROR) { 5723 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 5724 // track must be cleared from the caller as the caller has the AF lock 5725 goto Exit; 5726 } 5727 mTracks.add(track); 5728 5729 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 5730 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 5731 mAudioFlinger->btNrecIsOff(); 5732 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 5733 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 5734 5735 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 5736 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 5737 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 5738 // so ask activity manager to do this on our behalf 5739 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 5740 } 5741 } 5742 5743 lStatus = NO_ERROR; 5744 5745Exit: 5746 *status = lStatus; 5747 return track; 5748} 5749 5750status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 5751 AudioSystem::sync_event_t event, 5752 int triggerSession) 5753{ 5754 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 5755 sp<ThreadBase> strongMe = this; 5756 status_t status = NO_ERROR; 5757 5758 if (event == AudioSystem::SYNC_EVENT_NONE) { 5759 recordTrack->clearSyncStartEvent(); 5760 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 5761 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 5762 triggerSession, 5763 recordTrack->sessionId(), 5764 syncStartEventCallback, 5765 recordTrack); 5766 // Sync event can be cancelled by the trigger session if the track is not in a 5767 // compatible state in which case we start record immediately 5768 if (recordTrack->mSyncStartEvent->isCancelled()) { 5769 recordTrack->clearSyncStartEvent(); 5770 } else { 5771 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 5772 recordTrack->mFramesToDrop = - 5773 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000); 5774 } 5775 } 5776 5777 { 5778 // This section is a rendezvous between binder thread executing start() and RecordThread 5779 AutoMutex lock(mLock); 5780 if (mActiveTracks.indexOf(recordTrack) >= 0) { 5781 if (recordTrack->mState == TrackBase::PAUSING) { 5782 ALOGV("active record track PAUSING -> ACTIVE"); 5783 recordTrack->mState = TrackBase::ACTIVE; 5784 } else { 5785 ALOGV("active record track state %d", recordTrack->mState); 5786 } 5787 return status; 5788 } 5789 5790 // TODO consider other ways of handling this, such as changing the state to :STARTING and 5791 // adding the track to mActiveTracks after returning from AudioSystem::startInput(), 5792 // or using a separate command thread 5793 recordTrack->mState = TrackBase::STARTING_1; 5794 mActiveTracks.add(recordTrack); 5795 mActiveTracksGen++; 5796 status_t status = NO_ERROR; 5797 if (recordTrack->isExternalTrack()) { 5798 mLock.unlock(); 5799 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId()); 5800 mLock.lock(); 5801 // FIXME should verify that recordTrack is still in mActiveTracks 5802 if (status != NO_ERROR) { 5803 mActiveTracks.remove(recordTrack); 5804 mActiveTracksGen++; 5805 recordTrack->clearSyncStartEvent(); 5806 ALOGV("RecordThread::start error %d", status); 5807 return status; 5808 } 5809 } 5810 // Catch up with current buffer indices if thread is already running. 5811 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront 5812 // was initialized to some value closer to the thread's mRsmpInFront, then the track could 5813 // see previously buffered data before it called start(), but with greater risk of overrun. 5814 5815 recordTrack->mRsmpInFront = mRsmpInRear; 5816 recordTrack->mRsmpInUnrel = 0; 5817 // FIXME why reset? 5818 if (recordTrack->mResampler != NULL) { 5819 recordTrack->mResampler->reset(); 5820 } 5821 recordTrack->mState = TrackBase::STARTING_2; 5822 // signal thread to start 5823 mWaitWorkCV.broadcast(); 5824 if (mActiveTracks.indexOf(recordTrack) < 0) { 5825 ALOGV("Record failed to start"); 5826 status = BAD_VALUE; 5827 goto startError; 5828 } 5829 return status; 5830 } 5831 5832startError: 5833 if (recordTrack->isExternalTrack()) { 5834 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId()); 5835 } 5836 recordTrack->clearSyncStartEvent(); 5837 // FIXME I wonder why we do not reset the state here? 5838 return status; 5839} 5840 5841void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 5842{ 5843 sp<SyncEvent> strongEvent = event.promote(); 5844 5845 if (strongEvent != 0) { 5846 sp<RefBase> ptr = strongEvent->cookie().promote(); 5847 if (ptr != 0) { 5848 RecordTrack *recordTrack = (RecordTrack *)ptr.get(); 5849 recordTrack->handleSyncStartEvent(strongEvent); 5850 } 5851 } 5852} 5853 5854bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 5855 ALOGV("RecordThread::stop"); 5856 AutoMutex _l(mLock); 5857 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 5858 return false; 5859 } 5860 // note that threadLoop may still be processing the track at this point [without lock] 5861 recordTrack->mState = TrackBase::PAUSING; 5862 // do not wait for mStartStopCond if exiting 5863 if (exitPending()) { 5864 return true; 5865 } 5866 // FIXME incorrect usage of wait: no explicit predicate or loop 5867 mStartStopCond.wait(mLock); 5868 // if we have been restarted, recordTrack is in mActiveTracks here 5869 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 5870 ALOGV("Record stopped OK"); 5871 return true; 5872 } 5873 return false; 5874} 5875 5876bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 5877{ 5878 return false; 5879} 5880 5881status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 5882{ 5883#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 5884 if (!isValidSyncEvent(event)) { 5885 return BAD_VALUE; 5886 } 5887 5888 int eventSession = event->triggerSession(); 5889 status_t ret = NAME_NOT_FOUND; 5890 5891 Mutex::Autolock _l(mLock); 5892 5893 for (size_t i = 0; i < mTracks.size(); i++) { 5894 sp<RecordTrack> track = mTracks[i]; 5895 if (eventSession == track->sessionId()) { 5896 (void) track->setSyncEvent(event); 5897 ret = NO_ERROR; 5898 } 5899 } 5900 return ret; 5901#else 5902 return BAD_VALUE; 5903#endif 5904} 5905 5906// destroyTrack_l() must be called with ThreadBase::mLock held 5907void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 5908{ 5909 track->terminate(); 5910 track->mState = TrackBase::STOPPED; 5911 // active tracks are removed by threadLoop() 5912 if (mActiveTracks.indexOf(track) < 0) { 5913 removeTrack_l(track); 5914 } 5915} 5916 5917void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 5918{ 5919 mTracks.remove(track); 5920 // need anything related to effects here? 5921 if (track->isFastTrack()) { 5922 ALOG_ASSERT(!mFastTrackAvail); 5923 mFastTrackAvail = true; 5924 } 5925} 5926 5927void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 5928{ 5929 dumpInternals(fd, args); 5930 dumpTracks(fd, args); 5931 dumpEffectChains(fd, args); 5932} 5933 5934void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 5935{ 5936 dprintf(fd, "\nInput thread %p:\n", this); 5937 5938 if (mActiveTracks.size() > 0) { 5939 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize); 5940 } else { 5941 dprintf(fd, " No active record clients\n"); 5942 } 5943 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no"); 5944 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no"); 5945 5946 dumpBase(fd, args); 5947} 5948 5949void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 5950{ 5951 const size_t SIZE = 256; 5952 char buffer[SIZE]; 5953 String8 result; 5954 5955 size_t numtracks = mTracks.size(); 5956 size_t numactive = mActiveTracks.size(); 5957 size_t numactiveseen = 0; 5958 dprintf(fd, " %d Tracks", numtracks); 5959 if (numtracks) { 5960 dprintf(fd, " of which %d are active\n", numactive); 5961 RecordTrack::appendDumpHeader(result); 5962 for (size_t i = 0; i < numtracks ; ++i) { 5963 sp<RecordTrack> track = mTracks[i]; 5964 if (track != 0) { 5965 bool active = mActiveTracks.indexOf(track) >= 0; 5966 if (active) { 5967 numactiveseen++; 5968 } 5969 track->dump(buffer, SIZE, active); 5970 result.append(buffer); 5971 } 5972 } 5973 } else { 5974 dprintf(fd, "\n"); 5975 } 5976 5977 if (numactiveseen != numactive) { 5978 snprintf(buffer, SIZE, " The following tracks are in the active list but" 5979 " not in the track list\n"); 5980 result.append(buffer); 5981 RecordTrack::appendDumpHeader(result); 5982 for (size_t i = 0; i < numactive; ++i) { 5983 sp<RecordTrack> track = mActiveTracks[i]; 5984 if (mTracks.indexOf(track) < 0) { 5985 track->dump(buffer, SIZE, true); 5986 result.append(buffer); 5987 } 5988 } 5989 5990 } 5991 write(fd, result.string(), result.size()); 5992} 5993 5994// AudioBufferProvider interface 5995status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer( 5996 AudioBufferProvider::Buffer* buffer, int64_t pts __unused) 5997{ 5998 RecordTrack *activeTrack = mRecordTrack; 5999 sp<ThreadBase> threadBase = activeTrack->mThread.promote(); 6000 if (threadBase == 0) { 6001 buffer->frameCount = 0; 6002 buffer->raw = NULL; 6003 return NOT_ENOUGH_DATA; 6004 } 6005 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6006 int32_t rear = recordThread->mRsmpInRear; 6007 int32_t front = activeTrack->mRsmpInFront; 6008 ssize_t filled = rear - front; 6009 // FIXME should not be P2 (don't want to increase latency) 6010 // FIXME if client not keeping up, discard 6011 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames)); 6012 // 'filled' may be non-contiguous, so return only the first contiguous chunk 6013 front &= recordThread->mRsmpInFramesP2 - 1; 6014 size_t part1 = recordThread->mRsmpInFramesP2 - front; 6015 if (part1 > (size_t) filled) { 6016 part1 = filled; 6017 } 6018 size_t ask = buffer->frameCount; 6019 ALOG_ASSERT(ask > 0); 6020 if (part1 > ask) { 6021 part1 = ask; 6022 } 6023 if (part1 == 0) { 6024 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty 6025 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved"); 6026 buffer->raw = NULL; 6027 buffer->frameCount = 0; 6028 activeTrack->mRsmpInUnrel = 0; 6029 return NOT_ENOUGH_DATA; 6030 } 6031 6032 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount; 6033 buffer->frameCount = part1; 6034 activeTrack->mRsmpInUnrel = part1; 6035 return NO_ERROR; 6036} 6037 6038// AudioBufferProvider interface 6039void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer( 6040 AudioBufferProvider::Buffer* buffer) 6041{ 6042 RecordTrack *activeTrack = mRecordTrack; 6043 size_t stepCount = buffer->frameCount; 6044 if (stepCount == 0) { 6045 return; 6046 } 6047 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel); 6048 activeTrack->mRsmpInUnrel -= stepCount; 6049 activeTrack->mRsmpInFront += stepCount; 6050 buffer->raw = NULL; 6051 buffer->frameCount = 0; 6052} 6053 6054bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair, 6055 status_t& status) 6056{ 6057 bool reconfig = false; 6058 6059 status = NO_ERROR; 6060 6061 audio_format_t reqFormat = mFormat; 6062 uint32_t samplingRate = mSampleRate; 6063 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount); 6064 6065 AudioParameter param = AudioParameter(keyValuePair); 6066 int value; 6067 // TODO Investigate when this code runs. Check with audio policy when a sample rate and 6068 // channel count change can be requested. Do we mandate the first client defines the 6069 // HAL sampling rate and channel count or do we allow changes on the fly? 6070 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 6071 samplingRate = value; 6072 reconfig = true; 6073 } 6074 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 6075 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 6076 status = BAD_VALUE; 6077 } else { 6078 reqFormat = (audio_format_t) value; 6079 reconfig = true; 6080 } 6081 } 6082 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 6083 audio_channel_mask_t mask = (audio_channel_mask_t) value; 6084 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) { 6085 status = BAD_VALUE; 6086 } else { 6087 channelMask = mask; 6088 reconfig = true; 6089 } 6090 } 6091 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 6092 // do not accept frame count changes if tracks are open as the track buffer 6093 // size depends on frame count and correct behavior would not be guaranteed 6094 // if frame count is changed after track creation 6095 if (mActiveTracks.size() > 0) { 6096 status = INVALID_OPERATION; 6097 } else { 6098 reconfig = true; 6099 } 6100 } 6101 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 6102 // forward device change to effects that have requested to be 6103 // aware of attached audio device. 6104 for (size_t i = 0; i < mEffectChains.size(); i++) { 6105 mEffectChains[i]->setDevice_l(value); 6106 } 6107 6108 // store input device and output device but do not forward output device to audio HAL. 6109 // Note that status is ignored by the caller for output device 6110 // (see AudioFlinger::setParameters() 6111 if (audio_is_output_devices(value)) { 6112 mOutDevice = value; 6113 status = BAD_VALUE; 6114 } else { 6115 mInDevice = value; 6116 // disable AEC and NS if the device is a BT SCO headset supporting those 6117 // pre processings 6118 if (mTracks.size() > 0) { 6119 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6120 mAudioFlinger->btNrecIsOff(); 6121 for (size_t i = 0; i < mTracks.size(); i++) { 6122 sp<RecordTrack> track = mTracks[i]; 6123 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6124 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6125 } 6126 } 6127 } 6128 } 6129 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 6130 mAudioSource != (audio_source_t)value) { 6131 // forward device change to effects that have requested to be 6132 // aware of attached audio device. 6133 for (size_t i = 0; i < mEffectChains.size(); i++) { 6134 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 6135 } 6136 mAudioSource = (audio_source_t)value; 6137 } 6138 6139 if (status == NO_ERROR) { 6140 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6141 keyValuePair.string()); 6142 if (status == INVALID_OPERATION) { 6143 inputStandBy(); 6144 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6145 keyValuePair.string()); 6146 } 6147 if (reconfig) { 6148 if (status == BAD_VALUE && 6149 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 6150 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 6151 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 6152 <= (2 * samplingRate)) && 6153 audio_channel_count_from_in_mask( 6154 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 && 6155 (channelMask == AUDIO_CHANNEL_IN_MONO || 6156 channelMask == AUDIO_CHANNEL_IN_STEREO)) { 6157 status = NO_ERROR; 6158 } 6159 if (status == NO_ERROR) { 6160 readInputParameters_l(); 6161 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 6162 } 6163 } 6164 } 6165 6166 return reconfig; 6167} 6168 6169String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 6170{ 6171 Mutex::Autolock _l(mLock); 6172 if (initCheck() != NO_ERROR) { 6173 return String8(); 6174 } 6175 6176 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 6177 const String8 out_s8(s); 6178 free(s); 6179 return out_s8; 6180} 6181 6182void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) { 6183 AudioSystem::OutputDescriptor desc; 6184 const void *param2 = NULL; 6185 6186 switch (event) { 6187 case AudioSystem::INPUT_OPENED: 6188 case AudioSystem::INPUT_CONFIG_CHANGED: 6189 desc.channelMask = mChannelMask; 6190 desc.samplingRate = mSampleRate; 6191 desc.format = mFormat; 6192 desc.frameCount = mFrameCount; 6193 desc.latency = 0; 6194 param2 = &desc; 6195 break; 6196 6197 case AudioSystem::INPUT_CLOSED: 6198 default: 6199 break; 6200 } 6201 mAudioFlinger->audioConfigChanged(event, mId, param2); 6202} 6203 6204void AudioFlinger::RecordThread::readInputParameters_l() 6205{ 6206 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 6207 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 6208 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 6209 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common); 6210 mFormat = mHALFormat; 6211 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 6212 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 6213 } 6214 mFrameSize = audio_stream_in_frame_size(mInput->stream); 6215 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 6216 mFrameCount = mBufferSize / mFrameSize; 6217 // This is the formula for calculating the temporary buffer size. 6218 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to 6219 // 1 full output buffer, regardless of the alignment of the available input. 6220 // The value is somewhat arbitrary, and could probably be even larger. 6221 // A larger value should allow more old data to be read after a track calls start(), 6222 // without increasing latency. 6223 mRsmpInFrames = mFrameCount * 7; 6224 mRsmpInFramesP2 = roundup(mRsmpInFrames); 6225 delete[] mRsmpInBuffer; 6226 6227 // TODO optimize audio capture buffer sizes ... 6228 // Here we calculate the size of the sliding buffer used as a source 6229 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7). 6230 // For current HAL frame counts, this is usually 2048 = 40 ms. It would 6231 // be better to have it derived from the pipe depth in the long term. 6232 // The current value is higher than necessary. However it should not add to latency. 6233 6234 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 6235 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount]; 6236 6237 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints. 6238 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks? 6239} 6240 6241uint32_t AudioFlinger::RecordThread::getInputFramesLost() 6242{ 6243 Mutex::Autolock _l(mLock); 6244 if (initCheck() != NO_ERROR) { 6245 return 0; 6246 } 6247 6248 return mInput->stream->get_input_frames_lost(mInput->stream); 6249} 6250 6251uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 6252{ 6253 Mutex::Autolock _l(mLock); 6254 uint32_t result = 0; 6255 if (getEffectChain_l(sessionId) != 0) { 6256 result = EFFECT_SESSION; 6257 } 6258 6259 for (size_t i = 0; i < mTracks.size(); ++i) { 6260 if (sessionId == mTracks[i]->sessionId()) { 6261 result |= TRACK_SESSION; 6262 break; 6263 } 6264 } 6265 6266 return result; 6267} 6268 6269KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 6270{ 6271 KeyedVector<int, bool> ids; 6272 Mutex::Autolock _l(mLock); 6273 for (size_t j = 0; j < mTracks.size(); ++j) { 6274 sp<RecordThread::RecordTrack> track = mTracks[j]; 6275 int sessionId = track->sessionId(); 6276 if (ids.indexOfKey(sessionId) < 0) { 6277 ids.add(sessionId, true); 6278 } 6279 } 6280 return ids; 6281} 6282 6283AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 6284{ 6285 Mutex::Autolock _l(mLock); 6286 AudioStreamIn *input = mInput; 6287 mInput = NULL; 6288 return input; 6289} 6290 6291// this method must always be called either with ThreadBase mLock held or inside the thread loop 6292audio_stream_t* AudioFlinger::RecordThread::stream() const 6293{ 6294 if (mInput == NULL) { 6295 return NULL; 6296 } 6297 return &mInput->stream->common; 6298} 6299 6300status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 6301{ 6302 // only one chain per input thread 6303 if (mEffectChains.size() != 0) { 6304 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this); 6305 return INVALID_OPERATION; 6306 } 6307 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 6308 chain->setThread(this); 6309 chain->setInBuffer(NULL); 6310 chain->setOutBuffer(NULL); 6311 6312 checkSuspendOnAddEffectChain_l(chain); 6313 6314 // make sure enabled pre processing effects state is communicated to the HAL as we 6315 // just moved them to a new input stream. 6316 chain->syncHalEffectsState(); 6317 6318 mEffectChains.add(chain); 6319 6320 return NO_ERROR; 6321} 6322 6323size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 6324{ 6325 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 6326 ALOGW_IF(mEffectChains.size() != 1, 6327 "removeEffectChain_l() %p invalid chain size %d on thread %p", 6328 chain.get(), mEffectChains.size(), this); 6329 if (mEffectChains.size() == 1) { 6330 mEffectChains.removeAt(0); 6331 } 6332 return 0; 6333} 6334 6335status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch, 6336 audio_patch_handle_t *handle) 6337{ 6338 status_t status = NO_ERROR; 6339 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 6340 // store new device and send to effects 6341 mInDevice = patch->sources[0].ext.device.type; 6342 for (size_t i = 0; i < mEffectChains.size(); i++) { 6343 mEffectChains[i]->setDevice_l(mInDevice); 6344 } 6345 6346 // disable AEC and NS if the device is a BT SCO headset supporting those 6347 // pre processings 6348 if (mTracks.size() > 0) { 6349 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6350 mAudioFlinger->btNrecIsOff(); 6351 for (size_t i = 0; i < mTracks.size(); i++) { 6352 sp<RecordTrack> track = mTracks[i]; 6353 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6354 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6355 } 6356 } 6357 6358 // store new source and send to effects 6359 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 6360 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 6361 for (size_t i = 0; i < mEffectChains.size(); i++) { 6362 mEffectChains[i]->setAudioSource_l(mAudioSource); 6363 } 6364 } 6365 6366 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 6367 status = hwDevice->create_audio_patch(hwDevice, 6368 patch->num_sources, 6369 patch->sources, 6370 patch->num_sinks, 6371 patch->sinks, 6372 handle); 6373 } else { 6374 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL"); 6375 } 6376 return status; 6377} 6378 6379status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 6380{ 6381 status_t status = NO_ERROR; 6382 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 6383 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 6384 status = hwDevice->release_audio_patch(hwDevice, handle); 6385 } else { 6386 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL"); 6387 } 6388 return status; 6389} 6390 6391void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record) 6392{ 6393 Mutex::Autolock _l(mLock); 6394 mTracks.add(record); 6395} 6396 6397void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record) 6398{ 6399 Mutex::Autolock _l(mLock); 6400 destroyTrack_l(record); 6401} 6402 6403void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config) 6404{ 6405 ThreadBase::getAudioPortConfig(config); 6406 config->role = AUDIO_PORT_ROLE_SINK; 6407 config->ext.mix.hw_module = mInput->audioHwDev->handle(); 6408 config->ext.mix.usecase.source = mAudioSource; 6409} 6410 6411}; // namespace android 6412