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