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