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