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