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