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