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