Threads.cpp revision 9cd7ad101315e0bff4c5f171706c6f80c7e22644
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 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) { 5000 return !mStandby; 5001 } 5002 5003 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 5004 // after a timeout and we will enter standby then. 5005 if (mTracks.size() > 0) { 5006 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 5007 trackStopped = mTracks[mTracks.size() - 1]->isStopped() || 5008 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE; 5009 } 5010 5011 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped)); 5012} 5013 5014// getTrackName_l() must be called with ThreadBase::mLock held 5015int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 5016 audio_format_t format __unused, audio_session_t sessionId __unused) 5017{ 5018 return 0; 5019} 5020 5021// deleteTrackName_l() must be called with ThreadBase::mLock held 5022void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 5023{ 5024} 5025 5026// checkForNewParameter_l() must be called with ThreadBase::mLock held 5027bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair, 5028 status_t& status) 5029{ 5030 bool reconfig = false; 5031 bool a2dpDeviceChanged = false; 5032 5033 status = NO_ERROR; 5034 5035 AudioParameter param = AudioParameter(keyValuePair); 5036 int value; 5037 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 5038 // forward device change to effects that have requested to be 5039 // aware of attached audio device. 5040 if (value != AUDIO_DEVICE_NONE) { 5041 a2dpDeviceChanged = 5042 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP); 5043 mOutDevice = value; 5044 for (size_t i = 0; i < mEffectChains.size(); i++) { 5045 mEffectChains[i]->setDevice_l(mOutDevice); 5046 } 5047 } 5048 } 5049 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 5050 // do not accept frame count changes if tracks are open as the track buffer 5051 // size depends on frame count and correct behavior would not be garantied 5052 // if frame count is changed after track creation 5053 if (!mTracks.isEmpty()) { 5054 status = INVALID_OPERATION; 5055 } else { 5056 reconfig = true; 5057 } 5058 } 5059 if (status == NO_ERROR) { 5060 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 5061 keyValuePair.string()); 5062 if (!mStandby && status == INVALID_OPERATION) { 5063 mOutput->standby(); 5064 mStandby = true; 5065 mBytesWritten = 0; 5066 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 5067 keyValuePair.string()); 5068 } 5069 if (status == NO_ERROR && reconfig) { 5070 readOutputParameters_l(); 5071 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 5072 } 5073 } 5074 5075 return reconfig || a2dpDeviceChanged; 5076} 5077 5078uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 5079{ 5080 uint32_t time; 5081 if (audio_has_proportional_frames(mFormat)) { 5082 time = PlaybackThread::activeSleepTimeUs(); 5083 } else { 5084 time = kDirectMinSleepTimeUs; 5085 } 5086 return time; 5087} 5088 5089uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 5090{ 5091 uint32_t time; 5092 if (audio_has_proportional_frames(mFormat)) { 5093 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 5094 } else { 5095 time = kDirectMinSleepTimeUs; 5096 } 5097 return time; 5098} 5099 5100uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 5101{ 5102 uint32_t time; 5103 if (audio_has_proportional_frames(mFormat)) { 5104 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 5105 } else { 5106 time = kDirectMinSleepTimeUs; 5107 } 5108 return time; 5109} 5110 5111void AudioFlinger::DirectOutputThread::cacheParameters_l() 5112{ 5113 PlaybackThread::cacheParameters_l(); 5114 5115 // use shorter standby delay as on normal output to release 5116 // hardware resources as soon as possible 5117 // no delay on outputs with HW A/V sync 5118 if (usesHwAvSync()) { 5119 mStandbyDelayNs = 0; 5120 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) { 5121 mStandbyDelayNs = kOffloadStandbyDelayNs; 5122 } else { 5123 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2); 5124 } 5125} 5126 5127void AudioFlinger::DirectOutputThread::flushHw_l() 5128{ 5129 mOutput->flush(); 5130 mHwPaused = false; 5131 mFlushPending = false; 5132} 5133 5134// ---------------------------------------------------------------------------- 5135 5136AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 5137 const wp<AudioFlinger::PlaybackThread>& playbackThread) 5138 : Thread(false /*canCallJava*/), 5139 mPlaybackThread(playbackThread), 5140 mWriteAckSequence(0), 5141 mDrainSequence(0) 5142{ 5143} 5144 5145AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 5146{ 5147} 5148 5149void AudioFlinger::AsyncCallbackThread::onFirstRef() 5150{ 5151 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 5152} 5153 5154bool AudioFlinger::AsyncCallbackThread::threadLoop() 5155{ 5156 while (!exitPending()) { 5157 uint32_t writeAckSequence; 5158 uint32_t drainSequence; 5159 5160 { 5161 Mutex::Autolock _l(mLock); 5162 while (!((mWriteAckSequence & 1) || 5163 (mDrainSequence & 1) || 5164 exitPending())) { 5165 mWaitWorkCV.wait(mLock); 5166 } 5167 5168 if (exitPending()) { 5169 break; 5170 } 5171 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 5172 mWriteAckSequence, mDrainSequence); 5173 writeAckSequence = mWriteAckSequence; 5174 mWriteAckSequence &= ~1; 5175 drainSequence = mDrainSequence; 5176 mDrainSequence &= ~1; 5177 } 5178 { 5179 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 5180 if (playbackThread != 0) { 5181 if (writeAckSequence & 1) { 5182 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 5183 } 5184 if (drainSequence & 1) { 5185 playbackThread->resetDraining(drainSequence >> 1); 5186 } 5187 } 5188 } 5189 } 5190 return false; 5191} 5192 5193void AudioFlinger::AsyncCallbackThread::exit() 5194{ 5195 ALOGV("AsyncCallbackThread::exit"); 5196 Mutex::Autolock _l(mLock); 5197 requestExit(); 5198 mWaitWorkCV.broadcast(); 5199} 5200 5201void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 5202{ 5203 Mutex::Autolock _l(mLock); 5204 // bit 0 is cleared 5205 mWriteAckSequence = sequence << 1; 5206} 5207 5208void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 5209{ 5210 Mutex::Autolock _l(mLock); 5211 // ignore unexpected callbacks 5212 if (mWriteAckSequence & 2) { 5213 mWriteAckSequence |= 1; 5214 mWaitWorkCV.signal(); 5215 } 5216} 5217 5218void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 5219{ 5220 Mutex::Autolock _l(mLock); 5221 // bit 0 is cleared 5222 mDrainSequence = sequence << 1; 5223} 5224 5225void AudioFlinger::AsyncCallbackThread::resetDraining() 5226{ 5227 Mutex::Autolock _l(mLock); 5228 // ignore unexpected callbacks 5229 if (mDrainSequence & 2) { 5230 mDrainSequence |= 1; 5231 mWaitWorkCV.signal(); 5232 } 5233} 5234 5235 5236// ---------------------------------------------------------------------------- 5237AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 5238 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady, 5239 uint32_t bitRate) 5240 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate), 5241 mPausedBytesRemaining(0) 5242{ 5243 //FIXME: mStandby should be set to true by ThreadBase constructor 5244 mStandby = true; 5245} 5246 5247void AudioFlinger::OffloadThread::threadLoop_exit() 5248{ 5249 if (mFlushPending || mHwPaused) { 5250 // If a flush is pending or track was paused, just discard buffered data 5251 flushHw_l(); 5252 } else { 5253 mMixerStatus = MIXER_DRAIN_ALL; 5254 threadLoop_drain(); 5255 } 5256 if (mUseAsyncWrite) { 5257 ALOG_ASSERT(mCallbackThread != 0); 5258 mCallbackThread->exit(); 5259 } 5260 PlaybackThread::threadLoop_exit(); 5261} 5262 5263AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 5264 Vector< sp<Track> > *tracksToRemove 5265) 5266{ 5267 size_t count = mActiveTracks.size(); 5268 5269 mixer_state mixerStatus = MIXER_IDLE; 5270 bool doHwPause = false; 5271 bool doHwResume = false; 5272 5273 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 5274 5275 // find out which tracks need to be processed 5276 for (size_t i = 0; i < count; i++) { 5277 sp<Track> t = mActiveTracks[i].promote(); 5278 // The track died recently 5279 if (t == 0) { 5280 continue; 5281 } 5282 Track* const track = t.get(); 5283 audio_track_cblk_t* cblk = track->cblk(); 5284 // Only consider last track started for volume and mixer state control. 5285 // In theory an older track could underrun and restart after the new one starts 5286 // but as we only care about the transition phase between two tracks on a 5287 // direct output, it is not a problem to ignore the underrun case. 5288 sp<Track> l = mLatestActiveTrack.promote(); 5289 bool last = l.get() == track; 5290 5291 if (track->isInvalid()) { 5292 ALOGW("An invalidated track shouldn't be in active list"); 5293 tracksToRemove->add(track); 5294 continue; 5295 } 5296 5297 if (track->mState == TrackBase::IDLE) { 5298 ALOGW("An idle track shouldn't be in active list"); 5299 continue; 5300 } 5301 5302 if (track->isPausing()) { 5303 track->setPaused(); 5304 if (last) { 5305 if (mHwSupportsPause && !mHwPaused) { 5306 doHwPause = true; 5307 mHwPaused = true; 5308 } 5309 // If we were part way through writing the mixbuffer to 5310 // the HAL we must save this until we resume 5311 // BUG - this will be wrong if a different track is made active, 5312 // in that case we want to discard the pending data in the 5313 // mixbuffer and tell the client to present it again when the 5314 // track is resumed 5315 mPausedWriteLength = mCurrentWriteLength; 5316 mPausedBytesRemaining = mBytesRemaining; 5317 mBytesRemaining = 0; // stop writing 5318 } 5319 tracksToRemove->add(track); 5320 } else if (track->isFlushPending()) { 5321 track->mRetryCount = kMaxTrackRetriesOffload; 5322 track->flushAck(); 5323 if (last) { 5324 mFlushPending = true; 5325 } 5326 } else if (track->isResumePending()){ 5327 track->resumeAck(); 5328 if (last) { 5329 if (mPausedBytesRemaining) { 5330 // Need to continue write that was interrupted 5331 mCurrentWriteLength = mPausedWriteLength; 5332 mBytesRemaining = mPausedBytesRemaining; 5333 mPausedBytesRemaining = 0; 5334 } 5335 if (mHwPaused) { 5336 doHwResume = true; 5337 mHwPaused = false; 5338 // threadLoop_mix() will handle the case that we need to 5339 // resume an interrupted write 5340 } 5341 // enable write to audio HAL 5342 mSleepTimeUs = 0; 5343 5344 // Do not handle new data in this iteration even if track->framesReady() 5345 mixerStatus = MIXER_TRACKS_ENABLED; 5346 } 5347 } else if (track->framesReady() && track->isReady() && 5348 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 5349 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 5350 if (track->mFillingUpStatus == Track::FS_FILLED) { 5351 track->mFillingUpStatus = Track::FS_ACTIVE; 5352 // make sure processVolume_l() will apply new volume even if 0 5353 mLeftVolFloat = mRightVolFloat = -1.0; 5354 } 5355 5356 if (last) { 5357 sp<Track> previousTrack = mPreviousTrack.promote(); 5358 if (previousTrack != 0) { 5359 if (track != previousTrack.get()) { 5360 // Flush any data still being written from last track 5361 mBytesRemaining = 0; 5362 if (mPausedBytesRemaining) { 5363 // Last track was paused so we also need to flush saved 5364 // mixbuffer state and invalidate track so that it will 5365 // re-submit that unwritten data when it is next resumed 5366 mPausedBytesRemaining = 0; 5367 // Invalidate is a bit drastic - would be more efficient 5368 // to have a flag to tell client that some of the 5369 // previously written data was lost 5370 previousTrack->invalidate(); 5371 } 5372 // flush data already sent to the DSP if changing audio session as audio 5373 // comes from a different source. Also invalidate previous track to force a 5374 // seek when resuming. 5375 if (previousTrack->sessionId() != track->sessionId()) { 5376 previousTrack->invalidate(); 5377 } 5378 } 5379 } 5380 mPreviousTrack = track; 5381 // reset retry count 5382 track->mRetryCount = kMaxTrackRetriesOffload; 5383 mActiveTrack = t; 5384 mixerStatus = MIXER_TRACKS_READY; 5385 } 5386 } else { 5387 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 5388 if (track->isStopping_1()) { 5389 // Hardware buffer can hold a large amount of audio so we must 5390 // wait for all current track's data to drain before we say 5391 // that the track is stopped. 5392 if (mBytesRemaining == 0) { 5393 // Only start draining when all data in mixbuffer 5394 // has been written 5395 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 5396 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 5397 // do not drain if no data was ever sent to HAL (mStandby == true) 5398 if (last && !mStandby) { 5399 // do not modify drain sequence if we are already draining. This happens 5400 // when resuming from pause after drain. 5401 if ((mDrainSequence & 1) == 0) { 5402 mSleepTimeUs = 0; 5403 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5404 mixerStatus = MIXER_DRAIN_TRACK; 5405 mDrainSequence += 2; 5406 } 5407 if (mHwPaused) { 5408 // It is possible to move from PAUSED to STOPPING_1 without 5409 // a resume so we must ensure hardware is running 5410 doHwResume = true; 5411 mHwPaused = false; 5412 } 5413 } 5414 } 5415 } else if (track->isStopping_2()) { 5416 // Drain has completed or we are in standby, signal presentation complete 5417 if (!(mDrainSequence & 1) || !last || mStandby) { 5418 track->mState = TrackBase::STOPPED; 5419 size_t audioHALFrames = 5420 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 5421 int64_t framesWritten = 5422 mBytesWritten / mOutput->getFrameSize(); 5423 track->presentationComplete(framesWritten, audioHALFrames); 5424 track->reset(); 5425 tracksToRemove->add(track); 5426 } 5427 } else { 5428 // No buffers for this track. Give it a few chances to 5429 // fill a buffer, then remove it from active list. 5430 if (--(track->mRetryCount) <= 0) { 5431 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 5432 track->name()); 5433 tracksToRemove->add(track); 5434 // indicate to client process that the track was disabled because of underrun; 5435 // it will then automatically call start() when data is available 5436 track->disable(); 5437 } else if (last){ 5438 mixerStatus = MIXER_TRACKS_ENABLED; 5439 } 5440 } 5441 } 5442 // compute volume for this track 5443 processVolume_l(track, last); 5444 } 5445 5446 // make sure the pause/flush/resume sequence is executed in the right order. 5447 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 5448 // before flush and then resume HW. This can happen in case of pause/flush/resume 5449 // if resume is received before pause is executed. 5450 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 5451 mOutput->stream->pause(mOutput->stream); 5452 } 5453 if (mFlushPending) { 5454 flushHw_l(); 5455 } 5456 if (!mStandby && doHwResume) { 5457 mOutput->stream->resume(mOutput->stream); 5458 } 5459 5460 // remove all the tracks that need to be... 5461 removeTracks_l(*tracksToRemove); 5462 5463 return mixerStatus; 5464} 5465 5466// must be called with thread mutex locked 5467bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 5468{ 5469 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 5470 mWriteAckSequence, mDrainSequence); 5471 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 5472 return true; 5473 } 5474 return false; 5475} 5476 5477bool AudioFlinger::OffloadThread::waitingAsyncCallback() 5478{ 5479 Mutex::Autolock _l(mLock); 5480 return waitingAsyncCallback_l(); 5481} 5482 5483void AudioFlinger::OffloadThread::flushHw_l() 5484{ 5485 DirectOutputThread::flushHw_l(); 5486 // Flush anything still waiting in the mixbuffer 5487 mCurrentWriteLength = 0; 5488 mBytesRemaining = 0; 5489 mPausedWriteLength = 0; 5490 mPausedBytesRemaining = 0; 5491 5492 if (mUseAsyncWrite) { 5493 // discard any pending drain or write ack by incrementing sequence 5494 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 5495 mDrainSequence = (mDrainSequence + 2) & ~1; 5496 ALOG_ASSERT(mCallbackThread != 0); 5497 mCallbackThread->setWriteBlocked(mWriteAckSequence); 5498 mCallbackThread->setDraining(mDrainSequence); 5499 } 5500} 5501 5502uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const 5503{ 5504 uint32_t time; 5505 if (audio_has_proportional_frames(mFormat)) { 5506 time = PlaybackThread::activeSleepTimeUs(); 5507 } else { 5508 // sleep time is half the duration of an audio HAL buffer. 5509 // Note: This can be problematic in case of underrun with variable bit rate and 5510 // current rate is much less than initial rate. 5511 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2); 5512 } 5513 return time; 5514} 5515 5516// ---------------------------------------------------------------------------- 5517 5518AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 5519 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady) 5520 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 5521 systemReady, DUPLICATING), 5522 mWaitTimeMs(UINT_MAX) 5523{ 5524 addOutputTrack(mainThread); 5525} 5526 5527AudioFlinger::DuplicatingThread::~DuplicatingThread() 5528{ 5529 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5530 mOutputTracks[i]->destroy(); 5531 } 5532} 5533 5534void AudioFlinger::DuplicatingThread::threadLoop_mix() 5535{ 5536 // mix buffers... 5537 if (outputsReady(outputTracks)) { 5538 mAudioMixer->process(); 5539 } else { 5540 if (mMixerBufferValid) { 5541 memset(mMixerBuffer, 0, mMixerBufferSize); 5542 } else { 5543 memset(mSinkBuffer, 0, mSinkBufferSize); 5544 } 5545 } 5546 mSleepTimeUs = 0; 5547 writeFrames = mNormalFrameCount; 5548 mCurrentWriteLength = mSinkBufferSize; 5549 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5550} 5551 5552void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 5553{ 5554 if (mSleepTimeUs == 0) { 5555 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5556 mSleepTimeUs = mActiveSleepTimeUs; 5557 } else { 5558 mSleepTimeUs = mIdleSleepTimeUs; 5559 } 5560 } else if (mBytesWritten != 0) { 5561 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5562 writeFrames = mNormalFrameCount; 5563 memset(mSinkBuffer, 0, mSinkBufferSize); 5564 } else { 5565 // flush remaining overflow buffers in output tracks 5566 writeFrames = 0; 5567 } 5568 mSleepTimeUs = 0; 5569 } 5570} 5571 5572ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 5573{ 5574 for (size_t i = 0; i < outputTracks.size(); i++) { 5575 outputTracks[i]->write(mSinkBuffer, writeFrames); 5576 } 5577 mStandby = false; 5578 return (ssize_t)mSinkBufferSize; 5579} 5580 5581void AudioFlinger::DuplicatingThread::threadLoop_standby() 5582{ 5583 // DuplicatingThread implements standby by stopping all tracks 5584 for (size_t i = 0; i < outputTracks.size(); i++) { 5585 outputTracks[i]->stop(); 5586 } 5587} 5588 5589void AudioFlinger::DuplicatingThread::saveOutputTracks() 5590{ 5591 outputTracks = mOutputTracks; 5592} 5593 5594void AudioFlinger::DuplicatingThread::clearOutputTracks() 5595{ 5596 outputTracks.clear(); 5597} 5598 5599void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 5600{ 5601 Mutex::Autolock _l(mLock); 5602 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass. 5603 // Adjust for thread->sampleRate() to determine minimum buffer frame count. 5604 // Then triple buffer because Threads do not run synchronously and may not be clock locked. 5605 const size_t frameCount = 5606 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate()); 5607 // TODO: Consider asynchronous sample rate conversion to handle clock disparity 5608 // from different OutputTracks and their associated MixerThreads (e.g. one may 5609 // nearly empty and the other may be dropping data). 5610 5611 sp<OutputTrack> outputTrack = new OutputTrack(thread, 5612 this, 5613 mSampleRate, 5614 mFormat, 5615 mChannelMask, 5616 frameCount, 5617 IPCThreadState::self()->getCallingUid()); 5618 if (outputTrack->cblk() != NULL) { 5619 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f); 5620 mOutputTracks.add(outputTrack); 5621 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread); 5622 updateWaitTime_l(); 5623 } 5624} 5625 5626void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 5627{ 5628 Mutex::Autolock _l(mLock); 5629 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5630 if (mOutputTracks[i]->thread() == thread) { 5631 mOutputTracks[i]->destroy(); 5632 mOutputTracks.removeAt(i); 5633 updateWaitTime_l(); 5634 if (thread->getOutput() == mOutput) { 5635 mOutput = NULL; 5636 } 5637 return; 5638 } 5639 } 5640 ALOGV("removeOutputTrack(): unknown thread: %p", thread); 5641} 5642 5643// caller must hold mLock 5644void AudioFlinger::DuplicatingThread::updateWaitTime_l() 5645{ 5646 mWaitTimeMs = UINT_MAX; 5647 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5648 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 5649 if (strong != 0) { 5650 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 5651 if (waitTimeMs < mWaitTimeMs) { 5652 mWaitTimeMs = waitTimeMs; 5653 } 5654 } 5655 } 5656} 5657 5658 5659bool AudioFlinger::DuplicatingThread::outputsReady( 5660 const SortedVector< sp<OutputTrack> > &outputTracks) 5661{ 5662 for (size_t i = 0; i < outputTracks.size(); i++) { 5663 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 5664 if (thread == 0) { 5665 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 5666 outputTracks[i].get()); 5667 return false; 5668 } 5669 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 5670 // see note at standby() declaration 5671 if (playbackThread->standby() && !playbackThread->isSuspended()) { 5672 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 5673 thread.get()); 5674 return false; 5675 } 5676 } 5677 return true; 5678} 5679 5680uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 5681{ 5682 return (mWaitTimeMs * 1000) / 2; 5683} 5684 5685void AudioFlinger::DuplicatingThread::cacheParameters_l() 5686{ 5687 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 5688 updateWaitTime_l(); 5689 5690 MixerThread::cacheParameters_l(); 5691} 5692 5693// ---------------------------------------------------------------------------- 5694// Record 5695// ---------------------------------------------------------------------------- 5696 5697AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 5698 AudioStreamIn *input, 5699 audio_io_handle_t id, 5700 audio_devices_t outDevice, 5701 audio_devices_t inDevice, 5702 bool systemReady 5703#ifdef TEE_SINK 5704 , const sp<NBAIO_Sink>& teeSink 5705#endif 5706 ) : 5707 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady), 5708 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL), 5709 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l() 5710 mRsmpInRear(0) 5711#ifdef TEE_SINK 5712 , mTeeSink(teeSink) 5713#endif 5714 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize, 5715 "RecordThreadRO", MemoryHeapBase::READ_ONLY)) 5716 // mFastCapture below 5717 , mFastCaptureFutex(0) 5718 // mInputSource 5719 // mPipeSink 5720 // mPipeSource 5721 , mPipeFramesP2(0) 5722 // mPipeMemory 5723 // mFastCaptureNBLogWriter 5724 , mFastTrackAvail(false) 5725{ 5726 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id); 5727 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 5728 5729 readInputParameters_l(); 5730 5731 // create an NBAIO source for the HAL input stream, and negotiate 5732 mInputSource = new AudioStreamInSource(input->stream); 5733 size_t numCounterOffers = 0; 5734 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 5735 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers); 5736 ALOG_ASSERT(index == 0); 5737 5738 // initialize fast capture depending on configuration 5739 bool initFastCapture; 5740 switch (kUseFastCapture) { 5741 case FastCapture_Never: 5742 initFastCapture = false; 5743 break; 5744 case FastCapture_Always: 5745 initFastCapture = true; 5746 break; 5747 case FastCapture_Static: 5748 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs; 5749 break; 5750 // case FastCapture_Dynamic: 5751 } 5752 5753 if (initFastCapture) { 5754 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from 5755 NBAIO_Format format = mInputSource->format(); 5756 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each 5757 size_t pipeSize = pipeFramesP2 * Format_frameSize(format); 5758 void *pipeBuffer; 5759 const sp<MemoryDealer> roHeap(readOnlyHeap()); 5760 sp<IMemory> pipeMemory; 5761 if ((roHeap == 0) || 5762 (pipeMemory = roHeap->allocate(pipeSize)) == 0 || 5763 (pipeBuffer = pipeMemory->pointer()) == NULL) { 5764 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize); 5765 goto failed; 5766 } 5767 // pipe will be shared directly with fast clients, so clear to avoid leaking old information 5768 memset(pipeBuffer, 0, pipeSize); 5769 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer); 5770 const NBAIO_Format offers[1] = {format}; 5771 size_t numCounterOffers = 0; 5772 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 5773 ALOG_ASSERT(index == 0); 5774 mPipeSink = pipe; 5775 PipeReader *pipeReader = new PipeReader(*pipe); 5776 numCounterOffers = 0; 5777 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 5778 ALOG_ASSERT(index == 0); 5779 mPipeSource = pipeReader; 5780 mPipeFramesP2 = pipeFramesP2; 5781 mPipeMemory = pipeMemory; 5782 5783 // create fast capture 5784 mFastCapture = new FastCapture(); 5785 FastCaptureStateQueue *sq = mFastCapture->sq(); 5786#ifdef STATE_QUEUE_DUMP 5787 // FIXME 5788#endif 5789 FastCaptureState *state = sq->begin(); 5790 state->mCblk = NULL; 5791 state->mInputSource = mInputSource.get(); 5792 state->mInputSourceGen++; 5793 state->mPipeSink = pipe; 5794 state->mPipeSinkGen++; 5795 state->mFrameCount = mFrameCount; 5796 state->mCommand = FastCaptureState::COLD_IDLE; 5797 // already done in constructor initialization list 5798 //mFastCaptureFutex = 0; 5799 state->mColdFutexAddr = &mFastCaptureFutex; 5800 state->mColdGen++; 5801 state->mDumpState = &mFastCaptureDumpState; 5802#ifdef TEE_SINK 5803 // FIXME 5804#endif 5805 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture"); 5806 state->mNBLogWriter = mFastCaptureNBLogWriter.get(); 5807 sq->end(); 5808 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5809 5810 // start the fast capture 5811 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO); 5812 pid_t tid = mFastCapture->getTid(); 5813 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 5814#ifdef AUDIO_WATCHDOG 5815 // FIXME 5816#endif 5817 5818 mFastTrackAvail = true; 5819 } 5820failed: ; 5821 5822 // FIXME mNormalSource 5823} 5824 5825AudioFlinger::RecordThread::~RecordThread() 5826{ 5827 if (mFastCapture != 0) { 5828 FastCaptureStateQueue *sq = mFastCapture->sq(); 5829 FastCaptureState *state = sq->begin(); 5830 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5831 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5832 if (old == -1) { 5833 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5834 } 5835 } 5836 state->mCommand = FastCaptureState::EXIT; 5837 sq->end(); 5838 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5839 mFastCapture->join(); 5840 mFastCapture.clear(); 5841 } 5842 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter); 5843 mAudioFlinger->unregisterWriter(mNBLogWriter); 5844 free(mRsmpInBuffer); 5845} 5846 5847void AudioFlinger::RecordThread::onFirstRef() 5848{ 5849 run(mThreadName, PRIORITY_URGENT_AUDIO); 5850} 5851 5852bool AudioFlinger::RecordThread::threadLoop() 5853{ 5854 nsecs_t lastWarning = 0; 5855 5856 inputStandBy(); 5857 5858reacquire_wakelock: 5859 sp<RecordTrack> activeTrack; 5860 int activeTracksGen; 5861 { 5862 Mutex::Autolock _l(mLock); 5863 size_t size = mActiveTracks.size(); 5864 activeTracksGen = mActiveTracksGen; 5865 if (size > 0) { 5866 // FIXME an arbitrary choice 5867 activeTrack = mActiveTracks[0]; 5868 acquireWakeLock_l(activeTrack->uid()); 5869 if (size > 1) { 5870 SortedVector<int> tmp; 5871 for (size_t i = 0; i < size; i++) { 5872 tmp.add(mActiveTracks[i]->uid()); 5873 } 5874 updateWakeLockUids_l(tmp); 5875 } 5876 } else { 5877 acquireWakeLock_l(-1); 5878 } 5879 } 5880 5881 // used to request a deferred sleep, to be executed later while mutex is unlocked 5882 uint32_t sleepUs = 0; 5883 5884 // loop while there is work to do 5885 for (;;) { 5886 Vector< sp<EffectChain> > effectChains; 5887 5888 // sleep with mutex unlocked 5889 if (sleepUs > 0) { 5890 ATRACE_BEGIN("sleep"); 5891 usleep(sleepUs); 5892 ATRACE_END(); 5893 sleepUs = 0; 5894 } 5895 5896 // activeTracks accumulates a copy of a subset of mActiveTracks 5897 Vector< sp<RecordTrack> > activeTracks; 5898 5899 // reference to the (first and only) active fast track 5900 sp<RecordTrack> fastTrack; 5901 5902 // reference to a fast track which is about to be removed 5903 sp<RecordTrack> fastTrackToRemove; 5904 5905 { // scope for mLock 5906 Mutex::Autolock _l(mLock); 5907 5908 processConfigEvents_l(); 5909 5910 // check exitPending here because checkForNewParameters_l() and 5911 // checkForNewParameters_l() can temporarily release mLock 5912 if (exitPending()) { 5913 break; 5914 } 5915 5916 // if no active track(s), then standby and release wakelock 5917 size_t size = mActiveTracks.size(); 5918 if (size == 0) { 5919 standbyIfNotAlreadyInStandby(); 5920 // exitPending() can't become true here 5921 releaseWakeLock_l(); 5922 ALOGV("RecordThread: loop stopping"); 5923 // go to sleep 5924 mWaitWorkCV.wait(mLock); 5925 ALOGV("RecordThread: loop starting"); 5926 goto reacquire_wakelock; 5927 } 5928 5929 if (mActiveTracksGen != activeTracksGen) { 5930 activeTracksGen = mActiveTracksGen; 5931 SortedVector<int> tmp; 5932 for (size_t i = 0; i < size; i++) { 5933 tmp.add(mActiveTracks[i]->uid()); 5934 } 5935 updateWakeLockUids_l(tmp); 5936 } 5937 5938 bool doBroadcast = false; 5939 for (size_t i = 0; i < size; ) { 5940 5941 activeTrack = mActiveTracks[i]; 5942 if (activeTrack->isTerminated()) { 5943 if (activeTrack->isFastTrack()) { 5944 ALOG_ASSERT(fastTrackToRemove == 0); 5945 fastTrackToRemove = activeTrack; 5946 } 5947 removeTrack_l(activeTrack); 5948 mActiveTracks.remove(activeTrack); 5949 mActiveTracksGen++; 5950 size--; 5951 continue; 5952 } 5953 5954 TrackBase::track_state activeTrackState = activeTrack->mState; 5955 switch (activeTrackState) { 5956 5957 case TrackBase::PAUSING: 5958 mActiveTracks.remove(activeTrack); 5959 mActiveTracksGen++; 5960 doBroadcast = true; 5961 size--; 5962 continue; 5963 5964 case TrackBase::STARTING_1: 5965 sleepUs = 10000; 5966 i++; 5967 continue; 5968 5969 case TrackBase::STARTING_2: 5970 doBroadcast = true; 5971 mStandby = false; 5972 activeTrack->mState = TrackBase::ACTIVE; 5973 break; 5974 5975 case TrackBase::ACTIVE: 5976 break; 5977 5978 case TrackBase::IDLE: 5979 i++; 5980 continue; 5981 5982 default: 5983 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState); 5984 } 5985 5986 activeTracks.add(activeTrack); 5987 i++; 5988 5989 if (activeTrack->isFastTrack()) { 5990 ALOG_ASSERT(!mFastTrackAvail); 5991 ALOG_ASSERT(fastTrack == 0); 5992 fastTrack = activeTrack; 5993 } 5994 } 5995 if (doBroadcast) { 5996 mStartStopCond.broadcast(); 5997 } 5998 5999 // sleep if there are no active tracks to process 6000 if (activeTracks.size() == 0) { 6001 if (sleepUs == 0) { 6002 sleepUs = kRecordThreadSleepUs; 6003 } 6004 continue; 6005 } 6006 sleepUs = 0; 6007 6008 lockEffectChains_l(effectChains); 6009 } 6010 6011 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0 6012 6013 size_t size = effectChains.size(); 6014 for (size_t i = 0; i < size; i++) { 6015 // thread mutex is not locked, but effect chain is locked 6016 effectChains[i]->process_l(); 6017 } 6018 6019 // Push a new fast capture state if fast capture is not already running, or cblk change 6020 if (mFastCapture != 0) { 6021 FastCaptureStateQueue *sq = mFastCapture->sq(); 6022 FastCaptureState *state = sq->begin(); 6023 bool didModify = false; 6024 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED; 6025 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME && 6026 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) { 6027 if (state->mCommand == FastCaptureState::COLD_IDLE) { 6028 int32_t old = android_atomic_inc(&mFastCaptureFutex); 6029 if (old == -1) { 6030 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 6031 } 6032 } 6033 state->mCommand = FastCaptureState::READ_WRITE; 6034#if 0 // FIXME 6035 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 6036 FastThreadDumpState::kSamplingNforLowRamDevice : 6037 FastThreadDumpState::kSamplingN); 6038#endif 6039 didModify = true; 6040 } 6041 audio_track_cblk_t *cblkOld = state->mCblk; 6042 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL; 6043 if (cblkNew != cblkOld) { 6044 state->mCblk = cblkNew; 6045 // block until acked if removing a fast track 6046 if (cblkOld != NULL) { 6047 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED; 6048 } 6049 didModify = true; 6050 } 6051 sq->end(didModify); 6052 if (didModify) { 6053 sq->push(block); 6054#if 0 6055 if (kUseFastCapture == FastCapture_Dynamic) { 6056 mNormalSource = mPipeSource; 6057 } 6058#endif 6059 } 6060 } 6061 6062 // now run the fast track destructor with thread mutex unlocked 6063 fastTrackToRemove.clear(); 6064 6065 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one. 6066 // Only the client(s) that are too slow will overrun. But if even the fastest client is too 6067 // slow, then this RecordThread will overrun by not calling HAL read often enough. 6068 // If destination is non-contiguous, first read past the nominal end of buffer, then 6069 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 6070 6071 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1); 6072 ssize_t framesRead; 6073 6074 // If an NBAIO source is present, use it to read the normal capture's data 6075 if (mPipeSource != 0) { 6076 size_t framesToRead = mBufferSize / mFrameSize; 6077 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize, 6078 framesToRead); 6079 if (framesRead == 0) { 6080 // since pipe is non-blocking, simulate blocking input 6081 sleepUs = (framesToRead * 1000000LL) / mSampleRate; 6082 } 6083 // otherwise use the HAL / AudioStreamIn directly 6084 } else { 6085 ssize_t bytesRead = mInput->stream->read(mInput->stream, 6086 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize); 6087 if (bytesRead < 0) { 6088 framesRead = bytesRead; 6089 } else { 6090 framesRead = bytesRead / mFrameSize; 6091 } 6092 } 6093 6094 // Update server timestamp with server stats 6095 // systemTime() is optional if the hardware supports timestamps. 6096 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead; 6097 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime(); 6098 6099 // Update server timestamp with kernel stats 6100 if (mInput->stream->get_capture_position != nullptr) { 6101 int64_t position, time; 6102 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time); 6103 if (ret == NO_ERROR) { 6104 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position; 6105 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time; 6106 // Note: In general record buffers should tend to be empty in 6107 // a properly running pipeline. 6108 // 6109 // Also, it is not advantageous to call get_presentation_position during the read 6110 // as the read obtains a lock, preventing the timestamp call from executing. 6111 } 6112 } 6113 // Use this to track timestamp information 6114 // ALOGD("%s", mTimestamp.toString().c_str()); 6115 6116 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) { 6117 ALOGE("read failed: framesRead=%d", framesRead); 6118 // Force input into standby so that it tries to recover at next read attempt 6119 inputStandBy(); 6120 sleepUs = kRecordThreadSleepUs; 6121 } 6122 if (framesRead <= 0) { 6123 goto unlock; 6124 } 6125 ALOG_ASSERT(framesRead > 0); 6126 6127 if (mTeeSink != 0) { 6128 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead); 6129 } 6130 // If destination is non-contiguous, we now correct for reading past end of buffer. 6131 { 6132 size_t part1 = mRsmpInFramesP2 - rear; 6133 if ((size_t) framesRead > part1) { 6134 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize, 6135 (framesRead - part1) * mFrameSize); 6136 } 6137 } 6138 rear = mRsmpInRear += framesRead; 6139 6140 size = activeTracks.size(); 6141 // loop over each active track 6142 for (size_t i = 0; i < size; i++) { 6143 activeTrack = activeTracks[i]; 6144 6145 // skip fast tracks, as those are handled directly by FastCapture 6146 if (activeTrack->isFastTrack()) { 6147 continue; 6148 } 6149 6150 // TODO: This code probably should be moved to RecordTrack. 6151 // TODO: Update the activeTrack buffer converter in case of reconfigure. 6152 6153 enum { 6154 OVERRUN_UNKNOWN, 6155 OVERRUN_TRUE, 6156 OVERRUN_FALSE 6157 } overrun = OVERRUN_UNKNOWN; 6158 6159 // loop over getNextBuffer to handle circular sink 6160 for (;;) { 6161 6162 activeTrack->mSink.frameCount = ~0; 6163 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink); 6164 size_t framesOut = activeTrack->mSink.frameCount; 6165 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0)); 6166 6167 // check available frames and handle overrun conditions 6168 // if the record track isn't draining fast enough. 6169 bool hasOverrun; 6170 size_t framesIn; 6171 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun); 6172 if (hasOverrun) { 6173 overrun = OVERRUN_TRUE; 6174 } 6175 if (framesOut == 0 || framesIn == 0) { 6176 break; 6177 } 6178 6179 // Don't allow framesOut to be larger than what is possible with resampling 6180 // from framesIn. 6181 // This isn't strictly necessary but helps limit buffer resizing in 6182 // RecordBufferConverter. TODO: remove when no longer needed. 6183 framesOut = min(framesOut, 6184 destinationFramesPossible( 6185 framesIn, mSampleRate, activeTrack->mSampleRate)); 6186 // process frames from the RecordThread buffer provider to the RecordTrack buffer 6187 framesOut = activeTrack->mRecordBufferConverter->convert( 6188 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut); 6189 6190 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) { 6191 overrun = OVERRUN_FALSE; 6192 } 6193 6194 if (activeTrack->mFramesToDrop == 0) { 6195 if (framesOut > 0) { 6196 activeTrack->mSink.frameCount = framesOut; 6197 activeTrack->releaseBuffer(&activeTrack->mSink); 6198 } 6199 } else { 6200 // FIXME could do a partial drop of framesOut 6201 if (activeTrack->mFramesToDrop > 0) { 6202 activeTrack->mFramesToDrop -= framesOut; 6203 if (activeTrack->mFramesToDrop <= 0) { 6204 activeTrack->clearSyncStartEvent(); 6205 } 6206 } else { 6207 activeTrack->mFramesToDrop += framesOut; 6208 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 || 6209 activeTrack->mSyncStartEvent->isCancelled()) { 6210 ALOGW("Synced record %s, session %d, trigger session %d", 6211 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled", 6212 activeTrack->sessionId(), 6213 (activeTrack->mSyncStartEvent != 0) ? 6214 activeTrack->mSyncStartEvent->triggerSession() : 6215 AUDIO_SESSION_NONE); 6216 activeTrack->clearSyncStartEvent(); 6217 } 6218 } 6219 } 6220 6221 if (framesOut == 0) { 6222 break; 6223 } 6224 } 6225 6226 switch (overrun) { 6227 case OVERRUN_TRUE: 6228 // client isn't retrieving buffers fast enough 6229 if (!activeTrack->setOverflow()) { 6230 nsecs_t now = systemTime(); 6231 // FIXME should lastWarning per track? 6232 if ((now - lastWarning) > kWarningThrottleNs) { 6233 ALOGW("RecordThread: buffer overflow"); 6234 lastWarning = now; 6235 } 6236 } 6237 break; 6238 case OVERRUN_FALSE: 6239 activeTrack->clearOverflow(); 6240 break; 6241 case OVERRUN_UNKNOWN: 6242 break; 6243 } 6244 6245 // update frame information and push timestamp out 6246 activeTrack->updateTrackFrameInfo( 6247 activeTrack->mServerProxy->framesReleased(), 6248 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER], 6249 mSampleRate, mTimestamp); 6250 } 6251 6252unlock: 6253 // enable changes in effect chain 6254 unlockEffectChains(effectChains); 6255 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 6256 } 6257 6258 standbyIfNotAlreadyInStandby(); 6259 6260 { 6261 Mutex::Autolock _l(mLock); 6262 for (size_t i = 0; i < mTracks.size(); i++) { 6263 sp<RecordTrack> track = mTracks[i]; 6264 track->invalidate(); 6265 } 6266 mActiveTracks.clear(); 6267 mActiveTracksGen++; 6268 mStartStopCond.broadcast(); 6269 } 6270 6271 releaseWakeLock(); 6272 6273 ALOGV("RecordThread %p exiting", this); 6274 return false; 6275} 6276 6277void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 6278{ 6279 if (!mStandby) { 6280 inputStandBy(); 6281 mStandby = true; 6282 } 6283} 6284 6285void AudioFlinger::RecordThread::inputStandBy() 6286{ 6287 // Idle the fast capture if it's currently running 6288 if (mFastCapture != 0) { 6289 FastCaptureStateQueue *sq = mFastCapture->sq(); 6290 FastCaptureState *state = sq->begin(); 6291 if (!(state->mCommand & FastCaptureState::IDLE)) { 6292 state->mCommand = FastCaptureState::COLD_IDLE; 6293 state->mColdFutexAddr = &mFastCaptureFutex; 6294 state->mColdGen++; 6295 mFastCaptureFutex = 0; 6296 sq->end(); 6297 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 6298 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED); 6299#if 0 6300 if (kUseFastCapture == FastCapture_Dynamic) { 6301 // FIXME 6302 } 6303#endif 6304#ifdef AUDIO_WATCHDOG 6305 // FIXME 6306#endif 6307 } else { 6308 sq->end(false /*didModify*/); 6309 } 6310 } 6311 mInput->stream->common.standby(&mInput->stream->common); 6312} 6313 6314// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held 6315sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 6316 const sp<AudioFlinger::Client>& client, 6317 uint32_t sampleRate, 6318 audio_format_t format, 6319 audio_channel_mask_t channelMask, 6320 size_t *pFrameCount, 6321 audio_session_t sessionId, 6322 size_t *notificationFrames, 6323 int uid, 6324 IAudioFlinger::track_flags_t *flags, 6325 pid_t tid, 6326 status_t *status) 6327{ 6328 size_t frameCount = *pFrameCount; 6329 sp<RecordTrack> track; 6330 status_t lStatus; 6331 6332 // client expresses a preference for FAST, but we get the final say 6333 if (*flags & IAudioFlinger::TRACK_FAST) { 6334 if ( 6335 // we formerly checked for a callback handler (non-0 tid), 6336 // but that is no longer required for TRANSFER_OBTAIN mode 6337 // 6338 // frame count is not specified, or is exactly the pipe depth 6339 ((frameCount == 0) || (frameCount == mPipeFramesP2)) && 6340 // PCM data 6341 audio_is_linear_pcm(format) && 6342 // hardware format 6343 (format == mFormat) && 6344 // hardware channel mask 6345 (channelMask == mChannelMask) && 6346 // hardware sample rate 6347 (sampleRate == mSampleRate) && 6348 // record thread has an associated fast capture 6349 hasFastCapture() && 6350 // there are sufficient fast track slots available 6351 mFastTrackAvail 6352 ) { 6353 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u", 6354 frameCount, mFrameCount); 6355 } else { 6356 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u " 6357 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 6358 "hasFastCapture=%d tid=%d mFastTrackAvail=%d", 6359 frameCount, mFrameCount, mPipeFramesP2, 6360 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate, 6361 hasFastCapture(), tid, mFastTrackAvail); 6362 *flags &= ~IAudioFlinger::TRACK_FAST; 6363 } 6364 } 6365 6366 // compute track buffer size in frames, and suggest the notification frame count 6367 if (*flags & IAudioFlinger::TRACK_FAST) { 6368 // fast track: frame count is exactly the pipe depth 6369 frameCount = mPipeFramesP2; 6370 // ignore requested notificationFrames, and always notify exactly once every HAL buffer 6371 *notificationFrames = mFrameCount; 6372 } else { 6373 // not fast track: max notification period is resampled equivalent of one HAL buffer time 6374 // or 20 ms if there is a fast capture 6375 // TODO This could be a roundupRatio inline, and const 6376 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount) 6377 * sampleRate + mSampleRate - 1) / mSampleRate; 6378 // minimum number of notification periods is at least kMinNotifications, 6379 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs) 6380 static const size_t kMinNotifications = 3; 6381 static const uint32_t kMinMs = 30; 6382 // TODO This could be a roundupRatio inline 6383 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000; 6384 // TODO This could be a roundupRatio inline 6385 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) / 6386 maxNotificationFrames; 6387 const size_t minFrameCount = maxNotificationFrames * 6388 max(kMinNotifications, minNotificationsByMs); 6389 frameCount = max(frameCount, minFrameCount); 6390 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) { 6391 *notificationFrames = maxNotificationFrames; 6392 } 6393 } 6394 *pFrameCount = frameCount; 6395 6396 lStatus = initCheck(); 6397 if (lStatus != NO_ERROR) { 6398 ALOGE("createRecordTrack_l() audio driver not initialized"); 6399 goto Exit; 6400 } 6401 6402 { // scope for mLock 6403 Mutex::Autolock _l(mLock); 6404 6405 track = new RecordTrack(this, client, sampleRate, 6406 format, channelMask, frameCount, NULL, sessionId, uid, 6407 *flags, TrackBase::TYPE_DEFAULT); 6408 6409 lStatus = track->initCheck(); 6410 if (lStatus != NO_ERROR) { 6411 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 6412 // track must be cleared from the caller as the caller has the AF lock 6413 goto Exit; 6414 } 6415 mTracks.add(track); 6416 6417 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6418 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6419 mAudioFlinger->btNrecIsOff(); 6420 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 6421 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 6422 6423 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 6424 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 6425 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 6426 // so ask activity manager to do this on our behalf 6427 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 6428 } 6429 } 6430 6431 lStatus = NO_ERROR; 6432 6433Exit: 6434 *status = lStatus; 6435 return track; 6436} 6437 6438status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 6439 AudioSystem::sync_event_t event, 6440 audio_session_t triggerSession) 6441{ 6442 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 6443 sp<ThreadBase> strongMe = this; 6444 status_t status = NO_ERROR; 6445 6446 if (event == AudioSystem::SYNC_EVENT_NONE) { 6447 recordTrack->clearSyncStartEvent(); 6448 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 6449 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 6450 triggerSession, 6451 recordTrack->sessionId(), 6452 syncStartEventCallback, 6453 recordTrack); 6454 // Sync event can be cancelled by the trigger session if the track is not in a 6455 // compatible state in which case we start record immediately 6456 if (recordTrack->mSyncStartEvent->isCancelled()) { 6457 recordTrack->clearSyncStartEvent(); 6458 } else { 6459 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 6460 recordTrack->mFramesToDrop = - 6461 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000); 6462 } 6463 } 6464 6465 { 6466 // This section is a rendezvous between binder thread executing start() and RecordThread 6467 AutoMutex lock(mLock); 6468 if (mActiveTracks.indexOf(recordTrack) >= 0) { 6469 if (recordTrack->mState == TrackBase::PAUSING) { 6470 ALOGV("active record track PAUSING -> ACTIVE"); 6471 recordTrack->mState = TrackBase::ACTIVE; 6472 } else { 6473 ALOGV("active record track state %d", recordTrack->mState); 6474 } 6475 return status; 6476 } 6477 6478 // TODO consider other ways of handling this, such as changing the state to :STARTING and 6479 // adding the track to mActiveTracks after returning from AudioSystem::startInput(), 6480 // or using a separate command thread 6481 recordTrack->mState = TrackBase::STARTING_1; 6482 mActiveTracks.add(recordTrack); 6483 mActiveTracksGen++; 6484 status_t status = NO_ERROR; 6485 if (recordTrack->isExternalTrack()) { 6486 mLock.unlock(); 6487 status = AudioSystem::startInput(mId, recordTrack->sessionId()); 6488 mLock.lock(); 6489 // FIXME should verify that recordTrack is still in mActiveTracks 6490 if (status != NO_ERROR) { 6491 mActiveTracks.remove(recordTrack); 6492 mActiveTracksGen++; 6493 recordTrack->clearSyncStartEvent(); 6494 ALOGV("RecordThread::start error %d", status); 6495 return status; 6496 } 6497 } 6498 // Catch up with current buffer indices if thread is already running. 6499 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront 6500 // was initialized to some value closer to the thread's mRsmpInFront, then the track could 6501 // see previously buffered data before it called start(), but with greater risk of overrun. 6502 6503 recordTrack->mResamplerBufferProvider->reset(); 6504 // clear any converter state as new data will be discontinuous 6505 recordTrack->mRecordBufferConverter->reset(); 6506 recordTrack->mState = TrackBase::STARTING_2; 6507 // signal thread to start 6508 mWaitWorkCV.broadcast(); 6509 if (mActiveTracks.indexOf(recordTrack) < 0) { 6510 ALOGV("Record failed to start"); 6511 status = BAD_VALUE; 6512 goto startError; 6513 } 6514 return status; 6515 } 6516 6517startError: 6518 if (recordTrack->isExternalTrack()) { 6519 AudioSystem::stopInput(mId, recordTrack->sessionId()); 6520 } 6521 recordTrack->clearSyncStartEvent(); 6522 // FIXME I wonder why we do not reset the state here? 6523 return status; 6524} 6525 6526void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 6527{ 6528 sp<SyncEvent> strongEvent = event.promote(); 6529 6530 if (strongEvent != 0) { 6531 sp<RefBase> ptr = strongEvent->cookie().promote(); 6532 if (ptr != 0) { 6533 RecordTrack *recordTrack = (RecordTrack *)ptr.get(); 6534 recordTrack->handleSyncStartEvent(strongEvent); 6535 } 6536 } 6537} 6538 6539bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 6540 ALOGV("RecordThread::stop"); 6541 AutoMutex _l(mLock); 6542 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 6543 return false; 6544 } 6545 // note that threadLoop may still be processing the track at this point [without lock] 6546 recordTrack->mState = TrackBase::PAUSING; 6547 // do not wait for mStartStopCond if exiting 6548 if (exitPending()) { 6549 return true; 6550 } 6551 // FIXME incorrect usage of wait: no explicit predicate or loop 6552 mStartStopCond.wait(mLock); 6553 // if we have been restarted, recordTrack is in mActiveTracks here 6554 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 6555 ALOGV("Record stopped OK"); 6556 return true; 6557 } 6558 return false; 6559} 6560 6561bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 6562{ 6563 return false; 6564} 6565 6566status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 6567{ 6568#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 6569 if (!isValidSyncEvent(event)) { 6570 return BAD_VALUE; 6571 } 6572 6573 audio_session_t eventSession = event->triggerSession(); 6574 status_t ret = NAME_NOT_FOUND; 6575 6576 Mutex::Autolock _l(mLock); 6577 6578 for (size_t i = 0; i < mTracks.size(); i++) { 6579 sp<RecordTrack> track = mTracks[i]; 6580 if (eventSession == track->sessionId()) { 6581 (void) track->setSyncEvent(event); 6582 ret = NO_ERROR; 6583 } 6584 } 6585 return ret; 6586#else 6587 return BAD_VALUE; 6588#endif 6589} 6590 6591// destroyTrack_l() must be called with ThreadBase::mLock held 6592void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 6593{ 6594 track->terminate(); 6595 track->mState = TrackBase::STOPPED; 6596 // active tracks are removed by threadLoop() 6597 if (mActiveTracks.indexOf(track) < 0) { 6598 removeTrack_l(track); 6599 } 6600} 6601 6602void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 6603{ 6604 mTracks.remove(track); 6605 // need anything related to effects here? 6606 if (track->isFastTrack()) { 6607 ALOG_ASSERT(!mFastTrackAvail); 6608 mFastTrackAvail = true; 6609 } 6610} 6611 6612void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 6613{ 6614 dumpInternals(fd, args); 6615 dumpTracks(fd, args); 6616 dumpEffectChains(fd, args); 6617} 6618 6619void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 6620{ 6621 dprintf(fd, "\nInput thread %p:\n", this); 6622 6623 dumpBase(fd, args); 6624 6625 if (mActiveTracks.size() == 0) { 6626 dprintf(fd, " No active record clients\n"); 6627 } 6628 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no"); 6629 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no"); 6630 6631 // Make a non-atomic copy of fast capture dump state so it won't change underneath us 6632 // while we are dumping it. It may be inconsistent, but it won't mutate! 6633 // This is a large object so we place it on the heap. 6634 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages. 6635 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState); 6636 copy->dump(fd); 6637 delete copy; 6638} 6639 6640void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 6641{ 6642 const size_t SIZE = 256; 6643 char buffer[SIZE]; 6644 String8 result; 6645 6646 size_t numtracks = mTracks.size(); 6647 size_t numactive = mActiveTracks.size(); 6648 size_t numactiveseen = 0; 6649 dprintf(fd, " %d Tracks", numtracks); 6650 if (numtracks) { 6651 dprintf(fd, " of which %d are active\n", numactive); 6652 RecordTrack::appendDumpHeader(result); 6653 for (size_t i = 0; i < numtracks ; ++i) { 6654 sp<RecordTrack> track = mTracks[i]; 6655 if (track != 0) { 6656 bool active = mActiveTracks.indexOf(track) >= 0; 6657 if (active) { 6658 numactiveseen++; 6659 } 6660 track->dump(buffer, SIZE, active); 6661 result.append(buffer); 6662 } 6663 } 6664 } else { 6665 dprintf(fd, "\n"); 6666 } 6667 6668 if (numactiveseen != numactive) { 6669 snprintf(buffer, SIZE, " The following tracks are in the active list but" 6670 " not in the track list\n"); 6671 result.append(buffer); 6672 RecordTrack::appendDumpHeader(result); 6673 for (size_t i = 0; i < numactive; ++i) { 6674 sp<RecordTrack> track = mActiveTracks[i]; 6675 if (mTracks.indexOf(track) < 0) { 6676 track->dump(buffer, SIZE, true); 6677 result.append(buffer); 6678 } 6679 } 6680 6681 } 6682 write(fd, result.string(), result.size()); 6683} 6684 6685 6686void AudioFlinger::RecordThread::ResamplerBufferProvider::reset() 6687{ 6688 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6689 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6690 mRsmpInFront = recordThread->mRsmpInRear; 6691 mRsmpInUnrel = 0; 6692} 6693 6694void AudioFlinger::RecordThread::ResamplerBufferProvider::sync( 6695 size_t *framesAvailable, bool *hasOverrun) 6696{ 6697 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6698 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6699 const int32_t rear = recordThread->mRsmpInRear; 6700 const int32_t front = mRsmpInFront; 6701 const ssize_t filled = rear - front; 6702 6703 size_t framesIn; 6704 bool overrun = false; 6705 if (filled < 0) { 6706 // should not happen, but treat like a massive overrun and re-sync 6707 framesIn = 0; 6708 mRsmpInFront = rear; 6709 overrun = true; 6710 } else if ((size_t) filled <= recordThread->mRsmpInFrames) { 6711 framesIn = (size_t) filled; 6712 } else { 6713 // client is not keeping up with server, but give it latest data 6714 framesIn = recordThread->mRsmpInFrames; 6715 mRsmpInFront = /* front = */ rear - framesIn; 6716 overrun = true; 6717 } 6718 if (framesAvailable != NULL) { 6719 *framesAvailable = framesIn; 6720 } 6721 if (hasOverrun != NULL) { 6722 *hasOverrun = overrun; 6723 } 6724} 6725 6726// AudioBufferProvider interface 6727status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer( 6728 AudioBufferProvider::Buffer* buffer) 6729{ 6730 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6731 if (threadBase == 0) { 6732 buffer->frameCount = 0; 6733 buffer->raw = NULL; 6734 return NOT_ENOUGH_DATA; 6735 } 6736 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6737 int32_t rear = recordThread->mRsmpInRear; 6738 int32_t front = mRsmpInFront; 6739 ssize_t filled = rear - front; 6740 // FIXME should not be P2 (don't want to increase latency) 6741 // FIXME if client not keeping up, discard 6742 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames)); 6743 // 'filled' may be non-contiguous, so return only the first contiguous chunk 6744 front &= recordThread->mRsmpInFramesP2 - 1; 6745 size_t part1 = recordThread->mRsmpInFramesP2 - front; 6746 if (part1 > (size_t) filled) { 6747 part1 = filled; 6748 } 6749 size_t ask = buffer->frameCount; 6750 ALOG_ASSERT(ask > 0); 6751 if (part1 > ask) { 6752 part1 = ask; 6753 } 6754 if (part1 == 0) { 6755 // out of data is fine since the resampler will return a short-count. 6756 buffer->raw = NULL; 6757 buffer->frameCount = 0; 6758 mRsmpInUnrel = 0; 6759 return NOT_ENOUGH_DATA; 6760 } 6761 6762 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize; 6763 buffer->frameCount = part1; 6764 mRsmpInUnrel = part1; 6765 return NO_ERROR; 6766} 6767 6768// AudioBufferProvider interface 6769void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer( 6770 AudioBufferProvider::Buffer* buffer) 6771{ 6772 size_t stepCount = buffer->frameCount; 6773 if (stepCount == 0) { 6774 return; 6775 } 6776 ALOG_ASSERT(stepCount <= mRsmpInUnrel); 6777 mRsmpInUnrel -= stepCount; 6778 mRsmpInFront += stepCount; 6779 buffer->raw = NULL; 6780 buffer->frameCount = 0; 6781} 6782 6783AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter( 6784 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat, 6785 uint32_t srcSampleRate, 6786 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat, 6787 uint32_t dstSampleRate) : 6788 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars 6789 // mSrcFormat 6790 // mSrcSampleRate 6791 // mDstChannelMask 6792 // mDstFormat 6793 // mDstSampleRate 6794 // mSrcChannelCount 6795 // mDstChannelCount 6796 // mDstFrameSize 6797 mBuf(NULL), mBufFrames(0), mBufFrameSize(0), 6798 mResampler(NULL), 6799 mIsLegacyDownmix(false), 6800 mIsLegacyUpmix(false), 6801 mRequiresFloat(false), 6802 mInputConverterProvider(NULL) 6803{ 6804 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate, 6805 dstChannelMask, dstFormat, dstSampleRate); 6806} 6807 6808AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() { 6809 free(mBuf); 6810 delete mResampler; 6811 delete mInputConverterProvider; 6812} 6813 6814size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst, 6815 AudioBufferProvider *provider, size_t frames) 6816{ 6817 if (mInputConverterProvider != NULL) { 6818 mInputConverterProvider->setBufferProvider(provider); 6819 provider = mInputConverterProvider; 6820 } 6821 6822 if (mResampler == NULL) { 6823 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x", 6824 mSrcSampleRate, mSrcFormat, mDstFormat); 6825 6826 AudioBufferProvider::Buffer buffer; 6827 for (size_t i = frames; i > 0; ) { 6828 buffer.frameCount = i; 6829 status_t status = provider->getNextBuffer(&buffer); 6830 if (status != OK || buffer.frameCount == 0) { 6831 frames -= i; // cannot fill request. 6832 break; 6833 } 6834 // format convert to destination buffer 6835 convertNoResampler(dst, buffer.raw, buffer.frameCount); 6836 6837 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize; 6838 i -= buffer.frameCount; 6839 provider->releaseBuffer(&buffer); 6840 } 6841 } else { 6842 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x", 6843 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat); 6844 6845 // reallocate buffer if needed 6846 if (mBufFrameSize != 0 && mBufFrames < frames) { 6847 free(mBuf); 6848 mBufFrames = frames; 6849 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize); 6850 } 6851 // resampler accumulates, but we only have one source track 6852 memset(mBuf, 0, frames * mBufFrameSize); 6853 frames = mResampler->resample((int32_t*)mBuf, frames, provider); 6854 // format convert to destination buffer 6855 convertResampler(dst, mBuf, frames); 6856 } 6857 return frames; 6858} 6859 6860status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters( 6861 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat, 6862 uint32_t srcSampleRate, 6863 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat, 6864 uint32_t dstSampleRate) 6865{ 6866 // quick evaluation if there is any change. 6867 if (mSrcFormat == srcFormat 6868 && mSrcChannelMask == srcChannelMask 6869 && mSrcSampleRate == srcSampleRate 6870 && mDstFormat == dstFormat 6871 && mDstChannelMask == dstChannelMask 6872 && mDstSampleRate == dstSampleRate) { 6873 return NO_ERROR; 6874 } 6875 6876 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x" 6877 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u", 6878 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate); 6879 const bool valid = 6880 audio_is_input_channel(srcChannelMask) 6881 && audio_is_input_channel(dstChannelMask) 6882 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat) 6883 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat) 6884 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) 6885 ; // no upsampling checks for now 6886 if (!valid) { 6887 return BAD_VALUE; 6888 } 6889 6890 mSrcFormat = srcFormat; 6891 mSrcChannelMask = srcChannelMask; 6892 mSrcSampleRate = srcSampleRate; 6893 mDstFormat = dstFormat; 6894 mDstChannelMask = dstChannelMask; 6895 mDstSampleRate = dstSampleRate; 6896 6897 // compute derived parameters 6898 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask); 6899 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask); 6900 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat); 6901 6902 // do we need to resample? 6903 delete mResampler; 6904 mResampler = NULL; 6905 if (mSrcSampleRate != mDstSampleRate) { 6906 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT, 6907 mSrcChannelCount, mDstSampleRate); 6908 mResampler->setSampleRate(mSrcSampleRate); 6909 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT); 6910 } 6911 6912 // are we running legacy channel conversion modes? 6913 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO 6914 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK) 6915 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO; 6916 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO 6917 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO 6918 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK); 6919 6920 // do we need to process in float? 6921 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix; 6922 6923 // do we need a staging buffer to convert for destination (we can still optimize this)? 6924 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity 6925 if (mResampler != NULL) { 6926 mBufFrameSize = max(mSrcChannelCount, FCC_2) 6927 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT); 6928 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float 6929 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT); 6930 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) { 6931 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat); 6932 } else { 6933 mBufFrameSize = 0; 6934 } 6935 mBufFrames = 0; // force the buffer to be resized. 6936 6937 // do we need an input converter buffer provider to give us float? 6938 delete mInputConverterProvider; 6939 mInputConverterProvider = NULL; 6940 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) { 6941 mInputConverterProvider = new ReformatBufferProvider( 6942 audio_channel_count_from_in_mask(mSrcChannelMask), 6943 mSrcFormat, 6944 AUDIO_FORMAT_PCM_FLOAT, 6945 256 /* provider buffer frame count */); 6946 } 6947 6948 // do we need a remixer to do channel mask conversion 6949 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) { 6950 (void) memcpy_by_index_array_initialization_from_channel_mask( 6951 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask); 6952 } 6953 return NO_ERROR; 6954} 6955 6956void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler( 6957 void *dst, const void *src, size_t frames) 6958{ 6959 // src is native type unless there is legacy upmix or downmix, whereupon it is float. 6960 if (mBufFrameSize != 0 && mBufFrames < frames) { 6961 free(mBuf); 6962 mBufFrames = frames; 6963 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize); 6964 } 6965 // do we need to do legacy upmix and downmix? 6966 if (mIsLegacyUpmix || mIsLegacyDownmix) { 6967 void *dstBuf = mBuf != NULL ? mBuf : dst; 6968 if (mIsLegacyUpmix) { 6969 upmix_to_stereo_float_from_mono_float((float *)dstBuf, 6970 (const float *)src, frames); 6971 } else /*mIsLegacyDownmix */ { 6972 downmix_to_mono_float_from_stereo_float((float *)dstBuf, 6973 (const float *)src, frames); 6974 } 6975 if (mBuf != NULL) { 6976 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT, 6977 frames * mDstChannelCount); 6978 } 6979 return; 6980 } 6981 // do we need to do channel mask conversion? 6982 if (mSrcChannelMask != mDstChannelMask) { 6983 void *dstBuf = mBuf != NULL ? mBuf : dst; 6984 memcpy_by_index_array(dstBuf, mDstChannelCount, 6985 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames); 6986 if (dstBuf == dst) { 6987 return; // format is the same 6988 } 6989 } 6990 // convert to destination buffer 6991 const void *convertBuf = mBuf != NULL ? mBuf : src; 6992 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat, 6993 frames * mDstChannelCount); 6994} 6995 6996void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler( 6997 void *dst, /*not-a-const*/ void *src, size_t frames) 6998{ 6999 // src buffer format is ALWAYS float when entering this routine 7000 if (mIsLegacyUpmix) { 7001 ; // mono to stereo already handled by resampler 7002 } else if (mIsLegacyDownmix 7003 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) { 7004 // the resampler outputs stereo for mono input channel (a feature?) 7005 // must convert to mono 7006 downmix_to_mono_float_from_stereo_float((float *)src, 7007 (const float *)src, frames); 7008 } else if (mSrcChannelMask != mDstChannelMask) { 7009 // convert to mono channel again for channel mask conversion (could be skipped 7010 // with further optimization). 7011 if (mSrcChannelCount == 1) { 7012 downmix_to_mono_float_from_stereo_float((float *)src, 7013 (const float *)src, frames); 7014 } 7015 // convert to destination format (in place, OK as float is larger than other types) 7016 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) { 7017 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT, 7018 frames * mSrcChannelCount); 7019 } 7020 // channel convert and save to dst 7021 memcpy_by_index_array(dst, mDstChannelCount, 7022 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames); 7023 return; 7024 } 7025 // convert to destination format and save to dst 7026 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT, 7027 frames * mDstChannelCount); 7028} 7029 7030bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair, 7031 status_t& status) 7032{ 7033 bool reconfig = false; 7034 7035 status = NO_ERROR; 7036 7037 audio_format_t reqFormat = mFormat; 7038 uint32_t samplingRate = mSampleRate; 7039 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs). 7040 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount); 7041 7042 AudioParameter param = AudioParameter(keyValuePair); 7043 int value; 7044 // TODO Investigate when this code runs. Check with audio policy when a sample rate and 7045 // channel count change can be requested. Do we mandate the first client defines the 7046 // HAL sampling rate and channel count or do we allow changes on the fly? 7047 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 7048 samplingRate = value; 7049 reconfig = true; 7050 } 7051 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 7052 if (!audio_is_linear_pcm((audio_format_t) value)) { 7053 status = BAD_VALUE; 7054 } else { 7055 reqFormat = (audio_format_t) value; 7056 reconfig = true; 7057 } 7058 } 7059 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 7060 audio_channel_mask_t mask = (audio_channel_mask_t) value; 7061 if (!audio_is_input_channel(mask) || 7062 audio_channel_count_from_in_mask(mask) > FCC_8) { 7063 status = BAD_VALUE; 7064 } else { 7065 channelMask = mask; 7066 reconfig = true; 7067 } 7068 } 7069 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 7070 // do not accept frame count changes if tracks are open as the track buffer 7071 // size depends on frame count and correct behavior would not be guaranteed 7072 // if frame count is changed after track creation 7073 if (mActiveTracks.size() > 0) { 7074 status = INVALID_OPERATION; 7075 } else { 7076 reconfig = true; 7077 } 7078 } 7079 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 7080 // forward device change to effects that have requested to be 7081 // aware of attached audio device. 7082 for (size_t i = 0; i < mEffectChains.size(); i++) { 7083 mEffectChains[i]->setDevice_l(value); 7084 } 7085 7086 // store input device and output device but do not forward output device to audio HAL. 7087 // Note that status is ignored by the caller for output device 7088 // (see AudioFlinger::setParameters() 7089 if (audio_is_output_devices(value)) { 7090 mOutDevice = value; 7091 status = BAD_VALUE; 7092 } else { 7093 mInDevice = value; 7094 if (value != AUDIO_DEVICE_NONE) { 7095 mPrevInDevice = value; 7096 } 7097 // disable AEC and NS if the device is a BT SCO headset supporting those 7098 // pre processings 7099 if (mTracks.size() > 0) { 7100 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 7101 mAudioFlinger->btNrecIsOff(); 7102 for (size_t i = 0; i < mTracks.size(); i++) { 7103 sp<RecordTrack> track = mTracks[i]; 7104 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 7105 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 7106 } 7107 } 7108 } 7109 } 7110 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 7111 mAudioSource != (audio_source_t)value) { 7112 // forward device change to effects that have requested to be 7113 // aware of attached audio device. 7114 for (size_t i = 0; i < mEffectChains.size(); i++) { 7115 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 7116 } 7117 mAudioSource = (audio_source_t)value; 7118 } 7119 7120 if (status == NO_ERROR) { 7121 status = mInput->stream->common.set_parameters(&mInput->stream->common, 7122 keyValuePair.string()); 7123 if (status == INVALID_OPERATION) { 7124 inputStandBy(); 7125 status = mInput->stream->common.set_parameters(&mInput->stream->common, 7126 keyValuePair.string()); 7127 } 7128 if (reconfig) { 7129 if (status == BAD_VALUE && 7130 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) && 7131 audio_is_linear_pcm(reqFormat) && 7132 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 7133 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) && 7134 audio_channel_count_from_in_mask( 7135 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) { 7136 status = NO_ERROR; 7137 } 7138 if (status == NO_ERROR) { 7139 readInputParameters_l(); 7140 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7141 } 7142 } 7143 } 7144 7145 return reconfig; 7146} 7147 7148String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 7149{ 7150 Mutex::Autolock _l(mLock); 7151 if (initCheck() != NO_ERROR) { 7152 return String8(); 7153 } 7154 7155 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 7156 const String8 out_s8(s); 7157 free(s); 7158 return out_s8; 7159} 7160 7161void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 7162 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 7163 7164 desc->mIoHandle = mId; 7165 7166 switch (event) { 7167 case AUDIO_INPUT_OPENED: 7168 case AUDIO_INPUT_CONFIG_CHANGED: 7169 desc->mPatch = mPatch; 7170 desc->mChannelMask = mChannelMask; 7171 desc->mSamplingRate = mSampleRate; 7172 desc->mFormat = mFormat; 7173 desc->mFrameCount = mFrameCount; 7174 desc->mLatency = 0; 7175 break; 7176 7177 case AUDIO_INPUT_CLOSED: 7178 default: 7179 break; 7180 } 7181 mAudioFlinger->ioConfigChanged(event, desc, pid); 7182} 7183 7184void AudioFlinger::RecordThread::readInputParameters_l() 7185{ 7186 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 7187 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 7188 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 7189 if (mChannelCount > FCC_8) { 7190 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8); 7191 } 7192 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common); 7193 mFormat = mHALFormat; 7194 if (!audio_is_linear_pcm(mFormat)) { 7195 ALOGE("HAL format %#x is not linear pcm", mFormat); 7196 } 7197 mFrameSize = audio_stream_in_frame_size(mInput->stream); 7198 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 7199 mFrameCount = mBufferSize / mFrameSize; 7200 // This is the formula for calculating the temporary buffer size. 7201 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to 7202 // 1 full output buffer, regardless of the alignment of the available input. 7203 // The value is somewhat arbitrary, and could probably be even larger. 7204 // A larger value should allow more old data to be read after a track calls start(), 7205 // without increasing latency. 7206 // 7207 // Note this is independent of the maximum downsampling ratio permitted for capture. 7208 mRsmpInFrames = mFrameCount * 7; 7209 mRsmpInFramesP2 = roundup(mRsmpInFrames); 7210 free(mRsmpInBuffer); 7211 mRsmpInBuffer = NULL; 7212 7213 // TODO optimize audio capture buffer sizes ... 7214 // Here we calculate the size of the sliding buffer used as a source 7215 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7). 7216 // For current HAL frame counts, this is usually 2048 = 40 ms. It would 7217 // be better to have it derived from the pipe depth in the long term. 7218 // The current value is higher than necessary. However it should not add to latency. 7219 7220 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 7221 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize; 7222 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize); 7223 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here. 7224 7225 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints. 7226 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks? 7227} 7228 7229uint32_t AudioFlinger::RecordThread::getInputFramesLost() 7230{ 7231 Mutex::Autolock _l(mLock); 7232 if (initCheck() != NO_ERROR) { 7233 return 0; 7234 } 7235 7236 return mInput->stream->get_input_frames_lost(mInput->stream); 7237} 7238 7239uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const 7240{ 7241 Mutex::Autolock _l(mLock); 7242 uint32_t result = 0; 7243 if (getEffectChain_l(sessionId) != 0) { 7244 result = EFFECT_SESSION; 7245 } 7246 7247 for (size_t i = 0; i < mTracks.size(); ++i) { 7248 if (sessionId == mTracks[i]->sessionId()) { 7249 result |= TRACK_SESSION; 7250 break; 7251 } 7252 } 7253 7254 return result; 7255} 7256 7257KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const 7258{ 7259 KeyedVector<audio_session_t, bool> ids; 7260 Mutex::Autolock _l(mLock); 7261 for (size_t j = 0; j < mTracks.size(); ++j) { 7262 sp<RecordThread::RecordTrack> track = mTracks[j]; 7263 audio_session_t sessionId = track->sessionId(); 7264 if (ids.indexOfKey(sessionId) < 0) { 7265 ids.add(sessionId, true); 7266 } 7267 } 7268 return ids; 7269} 7270 7271AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 7272{ 7273 Mutex::Autolock _l(mLock); 7274 AudioStreamIn *input = mInput; 7275 mInput = NULL; 7276 return input; 7277} 7278 7279// this method must always be called either with ThreadBase mLock held or inside the thread loop 7280audio_stream_t* AudioFlinger::RecordThread::stream() const 7281{ 7282 if (mInput == NULL) { 7283 return NULL; 7284 } 7285 return &mInput->stream->common; 7286} 7287 7288status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 7289{ 7290 // only one chain per input thread 7291 if (mEffectChains.size() != 0) { 7292 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this); 7293 return INVALID_OPERATION; 7294 } 7295 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 7296 chain->setThread(this); 7297 chain->setInBuffer(NULL); 7298 chain->setOutBuffer(NULL); 7299 7300 checkSuspendOnAddEffectChain_l(chain); 7301 7302 // make sure enabled pre processing effects state is communicated to the HAL as we 7303 // just moved them to a new input stream. 7304 chain->syncHalEffectsState(); 7305 7306 mEffectChains.add(chain); 7307 7308 return NO_ERROR; 7309} 7310 7311size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 7312{ 7313 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 7314 ALOGW_IF(mEffectChains.size() != 1, 7315 "removeEffectChain_l() %p invalid chain size %d on thread %p", 7316 chain.get(), mEffectChains.size(), this); 7317 if (mEffectChains.size() == 1) { 7318 mEffectChains.removeAt(0); 7319 } 7320 return 0; 7321} 7322 7323status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch, 7324 audio_patch_handle_t *handle) 7325{ 7326 status_t status = NO_ERROR; 7327 7328 // store new device and send to effects 7329 mInDevice = patch->sources[0].ext.device.type; 7330 mPatch = *patch; 7331 for (size_t i = 0; i < mEffectChains.size(); i++) { 7332 mEffectChains[i]->setDevice_l(mInDevice); 7333 } 7334 7335 // disable AEC and NS if the device is a BT SCO headset supporting those 7336 // pre processings 7337 if (mTracks.size() > 0) { 7338 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 7339 mAudioFlinger->btNrecIsOff(); 7340 for (size_t i = 0; i < mTracks.size(); i++) { 7341 sp<RecordTrack> track = mTracks[i]; 7342 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 7343 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 7344 } 7345 } 7346 7347 // store new source and send to effects 7348 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 7349 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 7350 for (size_t i = 0; i < mEffectChains.size(); i++) { 7351 mEffectChains[i]->setAudioSource_l(mAudioSource); 7352 } 7353 } 7354 7355 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 7356 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 7357 status = hwDevice->create_audio_patch(hwDevice, 7358 patch->num_sources, 7359 patch->sources, 7360 patch->num_sinks, 7361 patch->sinks, 7362 handle); 7363 } else { 7364 char *address; 7365 if (strcmp(patch->sources[0].ext.device.address, "") != 0) { 7366 address = audio_device_address_to_parameter( 7367 patch->sources[0].ext.device.type, 7368 patch->sources[0].ext.device.address); 7369 } else { 7370 address = (char *)calloc(1, 1); 7371 } 7372 AudioParameter param = AudioParameter(String8(address)); 7373 free(address); 7374 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 7375 (int)patch->sources[0].ext.device.type); 7376 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE), 7377 (int)patch->sinks[0].ext.mix.usecase.source); 7378 status = mInput->stream->common.set_parameters(&mInput->stream->common, 7379 param.toString().string()); 7380 *handle = AUDIO_PATCH_HANDLE_NONE; 7381 } 7382 7383 if (mInDevice != mPrevInDevice) { 7384 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7385 mPrevInDevice = mInDevice; 7386 } 7387 7388 return status; 7389} 7390 7391status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 7392{ 7393 status_t status = NO_ERROR; 7394 7395 mInDevice = AUDIO_DEVICE_NONE; 7396 7397 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 7398 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 7399 status = hwDevice->release_audio_patch(hwDevice, handle); 7400 } else { 7401 AudioParameter param; 7402 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0); 7403 status = mInput->stream->common.set_parameters(&mInput->stream->common, 7404 param.toString().string()); 7405 } 7406 return status; 7407} 7408 7409void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record) 7410{ 7411 Mutex::Autolock _l(mLock); 7412 mTracks.add(record); 7413} 7414 7415void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record) 7416{ 7417 Mutex::Autolock _l(mLock); 7418 destroyTrack_l(record); 7419} 7420 7421void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config) 7422{ 7423 ThreadBase::getAudioPortConfig(config); 7424 config->role = AUDIO_PORT_ROLE_SINK; 7425 config->ext.mix.hw_module = mInput->audioHwDev->handle(); 7426 config->ext.mix.usecase.source = mAudioSource; 7427} 7428 7429} // namespace android 7430