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