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