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