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