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