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