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