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