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