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