Threads.cpp revision e1f939bf0e1bac806b7da1b316e70c96426dc1b6
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 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames. 2195 // Originally this was int16_t[] array, need to remove legacy implications. 2196 free(mSinkBuffer); 2197 mSinkBuffer = NULL; 2198 // For sink buffer size, we use the frame size from the downstream sink to avoid problems 2199 // with non PCM formats for compressed music, e.g. AAC, and Offload threads. 2200 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 2201 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 2202 2203 // We resize the mMixerBuffer according to the requirements of the sink buffer which 2204 // drives the output. 2205 free(mMixerBuffer); 2206 mMixerBuffer = NULL; 2207 if (mMixerBufferEnabled) { 2208 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT. 2209 mMixerBufferSize = mNormalFrameCount * mChannelCount 2210 * audio_bytes_per_sample(mMixerBufferFormat); 2211 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize); 2212 } 2213 free(mEffectBuffer); 2214 mEffectBuffer = NULL; 2215 if (mEffectBufferEnabled) { 2216 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only 2217 mEffectBufferSize = mNormalFrameCount * mChannelCount 2218 * audio_bytes_per_sample(mEffectBufferFormat); 2219 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize); 2220 } 2221 2222 // force reconfiguration of effect chains and engines to take new buffer size and audio 2223 // parameters into account 2224 // Note that mLock is not held when readOutputParameters_l() is called from the constructor 2225 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 2226 // matter. 2227 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 2228 Vector< sp<EffectChain> > effectChains = mEffectChains; 2229 for (size_t i = 0; i < effectChains.size(); i ++) { 2230 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 2231 } 2232} 2233 2234 2235status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 2236{ 2237 if (halFrames == NULL || dspFrames == NULL) { 2238 return BAD_VALUE; 2239 } 2240 Mutex::Autolock _l(mLock); 2241 if (initCheck() != NO_ERROR) { 2242 return INVALID_OPERATION; 2243 } 2244 size_t framesWritten = mBytesWritten / mFrameSize; 2245 *halFrames = framesWritten; 2246 2247 if (isSuspended()) { 2248 // return an estimation of rendered frames when the output is suspended 2249 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 2250 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; 2251 return NO_ERROR; 2252 } else { 2253 status_t status; 2254 uint32_t frames; 2255 status = mOutput->getRenderPosition(&frames); 2256 *dspFrames = (size_t)frames; 2257 return status; 2258 } 2259} 2260 2261uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 2262{ 2263 Mutex::Autolock _l(mLock); 2264 uint32_t result = 0; 2265 if (getEffectChain_l(sessionId) != 0) { 2266 result = EFFECT_SESSION; 2267 } 2268 2269 for (size_t i = 0; i < mTracks.size(); ++i) { 2270 sp<Track> track = mTracks[i]; 2271 if (sessionId == track->sessionId() && !track->isInvalid()) { 2272 result |= TRACK_SESSION; 2273 break; 2274 } 2275 } 2276 2277 return result; 2278} 2279 2280uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 2281{ 2282 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2283 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2284 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2285 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2286 } 2287 for (size_t i = 0; i < mTracks.size(); i++) { 2288 sp<Track> track = mTracks[i]; 2289 if (sessionId == track->sessionId() && !track->isInvalid()) { 2290 return AudioSystem::getStrategyForStream(track->streamType()); 2291 } 2292 } 2293 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2294} 2295 2296 2297AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2298{ 2299 Mutex::Autolock _l(mLock); 2300 return mOutput; 2301} 2302 2303AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2304{ 2305 Mutex::Autolock _l(mLock); 2306 AudioStreamOut *output = mOutput; 2307 mOutput = NULL; 2308 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2309 // must push a NULL and wait for ack 2310 mOutputSink.clear(); 2311 mPipeSink.clear(); 2312 mNormalSink.clear(); 2313 return output; 2314} 2315 2316// this method must always be called either with ThreadBase mLock held or inside the thread loop 2317audio_stream_t* AudioFlinger::PlaybackThread::stream() const 2318{ 2319 if (mOutput == NULL) { 2320 return NULL; 2321 } 2322 return &mOutput->stream->common; 2323} 2324 2325uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2326{ 2327 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2328} 2329 2330status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2331{ 2332 if (!isValidSyncEvent(event)) { 2333 return BAD_VALUE; 2334 } 2335 2336 Mutex::Autolock _l(mLock); 2337 2338 for (size_t i = 0; i < mTracks.size(); ++i) { 2339 sp<Track> track = mTracks[i]; 2340 if (event->triggerSession() == track->sessionId()) { 2341 (void) track->setSyncEvent(event); 2342 return NO_ERROR; 2343 } 2344 } 2345 2346 return NAME_NOT_FOUND; 2347} 2348 2349bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 2350{ 2351 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 2352} 2353 2354void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 2355 const Vector< sp<Track> >& tracksToRemove) 2356{ 2357 size_t count = tracksToRemove.size(); 2358 if (count > 0) { 2359 for (size_t i = 0 ; i < count ; i++) { 2360 const sp<Track>& track = tracksToRemove.itemAt(i); 2361 if (track->isExternalTrack()) { 2362 AudioSystem::stopOutput(mId, track->streamType(), 2363 (audio_session_t)track->sessionId()); 2364#ifdef ADD_BATTERY_DATA 2365 // to track the speaker usage 2366 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 2367#endif 2368 if (track->isTerminated()) { 2369 AudioSystem::releaseOutput(mId, track->streamType(), 2370 (audio_session_t)track->sessionId()); 2371 } 2372 } 2373 } 2374 } 2375} 2376 2377void AudioFlinger::PlaybackThread::checkSilentMode_l() 2378{ 2379 if (!mMasterMute) { 2380 char value[PROPERTY_VALUE_MAX]; 2381 if (property_get("ro.audio.silent", value, "0") > 0) { 2382 char *endptr; 2383 unsigned long ul = strtoul(value, &endptr, 0); 2384 if (*endptr == '\0' && ul != 0) { 2385 ALOGD("Silence is golden"); 2386 // The setprop command will not allow a property to be changed after 2387 // the first time it is set, so we don't have to worry about un-muting. 2388 setMasterMute_l(true); 2389 } 2390 } 2391 } 2392} 2393 2394// shared by MIXER and DIRECT, overridden by DUPLICATING 2395ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 2396{ 2397 // FIXME rewrite to reduce number of system calls 2398 mLastWriteTime = systemTime(); 2399 mInWrite = true; 2400 ssize_t bytesWritten; 2401 const size_t offset = mCurrentWriteLength - mBytesRemaining; 2402 2403 // If an NBAIO sink is present, use it to write the normal mixer's submix 2404 if (mNormalSink != 0) { 2405 2406 const size_t count = mBytesRemaining / mFrameSize; 2407 2408 ATRACE_BEGIN("write"); 2409 // update the setpoint when AudioFlinger::mScreenState changes 2410 uint32_t screenState = AudioFlinger::mScreenState; 2411 if (screenState != mScreenState) { 2412 mScreenState = screenState; 2413 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2414 if (pipe != NULL) { 2415 pipe->setAvgFrames((mScreenState & 1) ? 2416 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2417 } 2418 } 2419 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count); 2420 ATRACE_END(); 2421 if (framesWritten > 0) { 2422 bytesWritten = framesWritten * mFrameSize; 2423 } else { 2424 bytesWritten = framesWritten; 2425 } 2426 mLatchDValid = false; 2427 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp); 2428 if (status == NO_ERROR) { 2429 size_t totalFramesWritten = mNormalSink->framesWritten(); 2430 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) { 2431 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition; 2432 // mLatchD.mFramesReleased is set immediately before D is clocked into Q 2433 mLatchDValid = true; 2434 } 2435 } 2436 // otherwise use the HAL / AudioStreamOut directly 2437 } else { 2438 // Direct output and offload threads 2439 2440 if (mUseAsyncWrite) { 2441 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 2442 mWriteAckSequence += 2; 2443 mWriteAckSequence |= 1; 2444 ALOG_ASSERT(mCallbackThread != 0); 2445 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2446 } 2447 // FIXME We should have an implementation of timestamps for direct output threads. 2448 // They are used e.g for multichannel PCM playback over HDMI. 2449 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining); 2450 if (mUseAsyncWrite && 2451 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 2452 // do not wait for async callback in case of error of full write 2453 mWriteAckSequence &= ~1; 2454 ALOG_ASSERT(mCallbackThread != 0); 2455 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2456 } 2457 } 2458 2459 mNumWrites++; 2460 mInWrite = false; 2461 mStandby = false; 2462 return bytesWritten; 2463} 2464 2465void AudioFlinger::PlaybackThread::threadLoop_drain() 2466{ 2467 if (mOutput->stream->drain) { 2468 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 2469 if (mUseAsyncWrite) { 2470 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 2471 mDrainSequence |= 1; 2472 ALOG_ASSERT(mCallbackThread != 0); 2473 mCallbackThread->setDraining(mDrainSequence); 2474 } 2475 mOutput->stream->drain(mOutput->stream, 2476 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY 2477 : AUDIO_DRAIN_ALL); 2478 } 2479} 2480 2481void AudioFlinger::PlaybackThread::threadLoop_exit() 2482{ 2483 { 2484 Mutex::Autolock _l(mLock); 2485 for (size_t i = 0; i < mTracks.size(); i++) { 2486 sp<Track> track = mTracks[i]; 2487 track->invalidate(); 2488 } 2489 } 2490} 2491 2492/* 2493The derived values that are cached: 2494 - mSinkBufferSize from frame count * frame size 2495 - mActiveSleepTimeUs from activeSleepTimeUs() 2496 - mIdleSleepTimeUs from idleSleepTimeUs() 2497 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) 2498 - maxPeriod from frame count and sample rate (MIXER only) 2499 2500The parameters that affect these derived values are: 2501 - frame count 2502 - frame size 2503 - sample rate 2504 - device type: A2DP or not 2505 - device latency 2506 - format: PCM or not 2507 - active sleep time 2508 - idle sleep time 2509*/ 2510 2511void AudioFlinger::PlaybackThread::cacheParameters_l() 2512{ 2513 mSinkBufferSize = mNormalFrameCount * mFrameSize; 2514 mActiveSleepTimeUs = activeSleepTimeUs(); 2515 mIdleSleepTimeUs = idleSleepTimeUs(); 2516} 2517 2518void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 2519{ 2520 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 2521 this, streamType, mTracks.size()); 2522 Mutex::Autolock _l(mLock); 2523 2524 size_t size = mTracks.size(); 2525 for (size_t i = 0; i < size; i++) { 2526 sp<Track> t = mTracks[i]; 2527 if (t->streamType() == streamType) { 2528 t->invalidate(); 2529 } 2530 } 2531} 2532 2533status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 2534{ 2535 int session = chain->sessionId(); 2536 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled 2537 ? mEffectBuffer : mSinkBuffer); 2538 bool ownsBuffer = false; 2539 2540 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 2541 if (session > 0) { 2542 // Only one effect chain can be present in direct output thread and it uses 2543 // the sink buffer as input 2544 if (mType != DIRECT) { 2545 size_t numSamples = mNormalFrameCount * mChannelCount; 2546 buffer = new int16_t[numSamples]; 2547 memset(buffer, 0, numSamples * sizeof(int16_t)); 2548 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 2549 ownsBuffer = true; 2550 } 2551 2552 // Attach all tracks with same session ID to this chain. 2553 for (size_t i = 0; i < mTracks.size(); ++i) { 2554 sp<Track> track = mTracks[i]; 2555 if (session == track->sessionId()) { 2556 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 2557 buffer); 2558 track->setMainBuffer(buffer); 2559 chain->incTrackCnt(); 2560 } 2561 } 2562 2563 // indicate all active tracks in the chain 2564 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2565 sp<Track> track = mActiveTracks[i].promote(); 2566 if (track == 0) { 2567 continue; 2568 } 2569 if (session == track->sessionId()) { 2570 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 2571 chain->incActiveTrackCnt(); 2572 } 2573 } 2574 } 2575 chain->setThread(this); 2576 chain->setInBuffer(buffer, ownsBuffer); 2577 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled 2578 ? mEffectBuffer : mSinkBuffer)); 2579 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 2580 // chains list in order to be processed last as it contains output stage effects 2581 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 2582 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 2583 // after track specific effects and before output stage 2584 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 2585 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 2586 // Effect chain for other sessions are inserted at beginning of effect 2587 // chains list to be processed before output mix effects. Relative order between other 2588 // sessions is not important 2589 size_t size = mEffectChains.size(); 2590 size_t i = 0; 2591 for (i = 0; i < size; i++) { 2592 if (mEffectChains[i]->sessionId() < session) { 2593 break; 2594 } 2595 } 2596 mEffectChains.insertAt(chain, i); 2597 checkSuspendOnAddEffectChain_l(chain); 2598 2599 return NO_ERROR; 2600} 2601 2602size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2603{ 2604 int session = chain->sessionId(); 2605 2606 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2607 2608 for (size_t i = 0; i < mEffectChains.size(); i++) { 2609 if (chain == mEffectChains[i]) { 2610 mEffectChains.removeAt(i); 2611 // detach all active tracks from the chain 2612 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2613 sp<Track> track = mActiveTracks[i].promote(); 2614 if (track == 0) { 2615 continue; 2616 } 2617 if (session == track->sessionId()) { 2618 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2619 chain.get(), session); 2620 chain->decActiveTrackCnt(); 2621 } 2622 } 2623 2624 // detach all tracks with same session ID from this chain 2625 for (size_t i = 0; i < mTracks.size(); ++i) { 2626 sp<Track> track = mTracks[i]; 2627 if (session == track->sessionId()) { 2628 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer)); 2629 chain->decTrackCnt(); 2630 } 2631 } 2632 break; 2633 } 2634 } 2635 return mEffectChains.size(); 2636} 2637 2638status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2639 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2640{ 2641 Mutex::Autolock _l(mLock); 2642 return attachAuxEffect_l(track, EffectId); 2643} 2644 2645status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2646 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2647{ 2648 status_t status = NO_ERROR; 2649 2650 if (EffectId == 0) { 2651 track->setAuxBuffer(0, NULL); 2652 } else { 2653 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2654 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2655 if (effect != 0) { 2656 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2657 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2658 } else { 2659 status = INVALID_OPERATION; 2660 } 2661 } else { 2662 status = BAD_VALUE; 2663 } 2664 } 2665 return status; 2666} 2667 2668void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2669{ 2670 for (size_t i = 0; i < mTracks.size(); ++i) { 2671 sp<Track> track = mTracks[i]; 2672 if (track->auxEffectId() == effectId) { 2673 attachAuxEffect_l(track, 0); 2674 } 2675 } 2676} 2677 2678bool AudioFlinger::PlaybackThread::threadLoop() 2679{ 2680 Vector< sp<Track> > tracksToRemove; 2681 2682 mStandbyTimeNs = systemTime(); 2683 2684 // MIXER 2685 nsecs_t lastWarning = 0; 2686 2687 // DUPLICATING 2688 // FIXME could this be made local to while loop? 2689 writeFrames = 0; 2690 2691 int lastGeneration = 0; 2692 2693 cacheParameters_l(); 2694 mSleepTimeUs = mIdleSleepTimeUs; 2695 2696 if (mType == MIXER) { 2697 sleepTimeShift = 0; 2698 } 2699 2700 CpuStats cpuStats; 2701 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2702 2703 acquireWakeLock(); 2704 2705 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2706 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2707 // and then that string will be logged at the next convenient opportunity. 2708 const char *logString = NULL; 2709 2710 checkSilentMode_l(); 2711 2712 while (!exitPending()) 2713 { 2714 cpuStats.sample(myName); 2715 2716 Vector< sp<EffectChain> > effectChains; 2717 2718 { // scope for mLock 2719 2720 Mutex::Autolock _l(mLock); 2721 2722 processConfigEvents_l(); 2723 2724 if (logString != NULL) { 2725 mNBLogWriter->logTimestamp(); 2726 mNBLogWriter->log(logString); 2727 logString = NULL; 2728 } 2729 2730 // Gather the framesReleased counters for all active tracks, 2731 // and latch them atomically with the timestamp. 2732 // FIXME We're using raw pointers as indices. A unique track ID would be a better index. 2733 mLatchD.mFramesReleased.clear(); 2734 size_t size = mActiveTracks.size(); 2735 for (size_t i = 0; i < size; i++) { 2736 sp<Track> t = mActiveTracks[i].promote(); 2737 if (t != 0) { 2738 mLatchD.mFramesReleased.add(t.get(), 2739 t->mAudioTrackServerProxy->framesReleased()); 2740 } 2741 } 2742 if (mLatchDValid) { 2743 mLatchQ = mLatchD; 2744 mLatchDValid = false; 2745 mLatchQValid = true; 2746 } 2747 2748 saveOutputTracks(); 2749 if (mSignalPending) { 2750 // A signal was raised while we were unlocked 2751 mSignalPending = false; 2752 } else if (waitingAsyncCallback_l()) { 2753 if (exitPending()) { 2754 break; 2755 } 2756 bool released = false; 2757 // The following works around a bug in the offload driver. Ideally we would release 2758 // the wake lock every time, but that causes the last offload buffer(s) to be 2759 // dropped while the device is on battery, so we need to hold a wake lock during 2760 // the drain phase. 2761 if (mBytesRemaining && !(mDrainSequence & 1)) { 2762 releaseWakeLock_l(); 2763 released = true; 2764 } 2765 mWakeLockUids.clear(); 2766 mActiveTracksGeneration++; 2767 ALOGV("wait async completion"); 2768 mWaitWorkCV.wait(mLock); 2769 ALOGV("async completion/wake"); 2770 if (released) { 2771 acquireWakeLock_l(); 2772 } 2773 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 2774 mSleepTimeUs = 0; 2775 2776 continue; 2777 } 2778 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) || 2779 isSuspended()) { 2780 // put audio hardware into standby after short delay 2781 if (shouldStandby_l()) { 2782 2783 threadLoop_standby(); 2784 2785 mStandby = true; 2786 } 2787 2788 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2789 // we're about to wait, flush the binder command buffer 2790 IPCThreadState::self()->flushCommands(); 2791 2792 clearOutputTracks(); 2793 2794 if (exitPending()) { 2795 break; 2796 } 2797 2798 releaseWakeLock_l(); 2799 mWakeLockUids.clear(); 2800 mActiveTracksGeneration++; 2801 // wait until we have something to do... 2802 ALOGV("%s going to sleep", myName.string()); 2803 mWaitWorkCV.wait(mLock); 2804 ALOGV("%s waking up", myName.string()); 2805 acquireWakeLock_l(); 2806 2807 mMixerStatus = MIXER_IDLE; 2808 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2809 mBytesWritten = 0; 2810 mBytesRemaining = 0; 2811 checkSilentMode_l(); 2812 2813 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 2814 mSleepTimeUs = mIdleSleepTimeUs; 2815 if (mType == MIXER) { 2816 sleepTimeShift = 0; 2817 } 2818 2819 continue; 2820 } 2821 } 2822 // mMixerStatusIgnoringFastTracks is also updated internally 2823 mMixerStatus = prepareTracks_l(&tracksToRemove); 2824 2825 // compare with previously applied list 2826 if (lastGeneration != mActiveTracksGeneration) { 2827 // update wakelock 2828 updateWakeLockUids_l(mWakeLockUids); 2829 lastGeneration = mActiveTracksGeneration; 2830 } 2831 2832 // prevent any changes in effect chain list and in each effect chain 2833 // during mixing and effect process as the audio buffers could be deleted 2834 // or modified if an effect is created or deleted 2835 lockEffectChains_l(effectChains); 2836 } // mLock scope ends 2837 2838 if (mBytesRemaining == 0) { 2839 mCurrentWriteLength = 0; 2840 if (mMixerStatus == MIXER_TRACKS_READY) { 2841 // threadLoop_mix() sets mCurrentWriteLength 2842 threadLoop_mix(); 2843 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 2844 && (mMixerStatus != MIXER_DRAIN_ALL)) { 2845 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data 2846 // must be written to HAL 2847 threadLoop_sleepTime(); 2848 if (mSleepTimeUs == 0) { 2849 mCurrentWriteLength = mSinkBufferSize; 2850 } 2851 } 2852 // Either threadLoop_mix() or threadLoop_sleepTime() should have set 2853 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0. 2854 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid) 2855 // or mSinkBuffer (if there are no effects). 2856 // 2857 // This is done pre-effects computation; if effects change to 2858 // support higher precision, this needs to move. 2859 // 2860 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l(). 2861 // TODO use mSleepTimeUs == 0 as an additional condition. 2862 if (mMixerBufferValid) { 2863 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer; 2864 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat; 2865 2866 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat, 2867 mNormalFrameCount * mChannelCount); 2868 } 2869 2870 mBytesRemaining = mCurrentWriteLength; 2871 if (isSuspended()) { 2872 mSleepTimeUs = suspendSleepTimeUs(); 2873 // simulate write to HAL when suspended 2874 mBytesWritten += mSinkBufferSize; 2875 mBytesRemaining = 0; 2876 } 2877 2878 // only process effects if we're going to write 2879 if (mSleepTimeUs == 0 && mType != OFFLOAD) { 2880 for (size_t i = 0; i < effectChains.size(); i ++) { 2881 effectChains[i]->process_l(); 2882 } 2883 } 2884 } 2885 // Process effect chains for offloaded thread even if no audio 2886 // was read from audio track: process only updates effect state 2887 // and thus does have to be synchronized with audio writes but may have 2888 // to be called while waiting for async write callback 2889 if (mType == OFFLOAD) { 2890 for (size_t i = 0; i < effectChains.size(); i ++) { 2891 effectChains[i]->process_l(); 2892 } 2893 } 2894 2895 // Only if the Effects buffer is enabled and there is data in the 2896 // Effects buffer (buffer valid), we need to 2897 // copy into the sink buffer. 2898 // TODO use mSleepTimeUs == 0 as an additional condition. 2899 if (mEffectBufferValid) { 2900 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat); 2901 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat, 2902 mNormalFrameCount * mChannelCount); 2903 } 2904 2905 // enable changes in effect chain 2906 unlockEffectChains(effectChains); 2907 2908 if (!waitingAsyncCallback()) { 2909 // mSleepTimeUs == 0 means we must write to audio hardware 2910 if (mSleepTimeUs == 0) { 2911 if (mBytesRemaining) { 2912 ssize_t ret = threadLoop_write(); 2913 if (ret < 0) { 2914 mBytesRemaining = 0; 2915 } else { 2916 mBytesWritten += ret; 2917 mBytesRemaining -= ret; 2918 } 2919 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 2920 (mMixerStatus == MIXER_DRAIN_ALL)) { 2921 threadLoop_drain(); 2922 } 2923 if (mType == MIXER) { 2924 // write blocked detection 2925 nsecs_t now = systemTime(); 2926 nsecs_t delta = now - mLastWriteTime; 2927 if (!mStandby && delta > maxPeriod) { 2928 mNumDelayedWrites++; 2929 if ((now - lastWarning) > kWarningThrottleNs) { 2930 ATRACE_NAME("underrun"); 2931 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2932 ns2ms(delta), mNumDelayedWrites, this); 2933 lastWarning = now; 2934 } 2935 } 2936 } 2937 2938 } else { 2939 ATRACE_BEGIN("sleep"); 2940 usleep(mSleepTimeUs); 2941 ATRACE_END(); 2942 } 2943 } 2944 2945 // Finally let go of removed track(s), without the lock held 2946 // since we can't guarantee the destructors won't acquire that 2947 // same lock. This will also mutate and push a new fast mixer state. 2948 threadLoop_removeTracks(tracksToRemove); 2949 tracksToRemove.clear(); 2950 2951 // FIXME I don't understand the need for this here; 2952 // it was in the original code but maybe the 2953 // assignment in saveOutputTracks() makes this unnecessary? 2954 clearOutputTracks(); 2955 2956 // Effect chains will be actually deleted here if they were removed from 2957 // mEffectChains list during mixing or effects processing 2958 effectChains.clear(); 2959 2960 // FIXME Note that the above .clear() is no longer necessary since effectChains 2961 // is now local to this block, but will keep it for now (at least until merge done). 2962 } 2963 2964 threadLoop_exit(); 2965 2966 if (!mStandby) { 2967 threadLoop_standby(); 2968 mStandby = true; 2969 } 2970 2971 releaseWakeLock(); 2972 mWakeLockUids.clear(); 2973 mActiveTracksGeneration++; 2974 2975 ALOGV("Thread %p type %d exiting", this, mType); 2976 return false; 2977} 2978 2979// removeTracks_l() must be called with ThreadBase::mLock held 2980void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 2981{ 2982 size_t count = tracksToRemove.size(); 2983 if (count > 0) { 2984 for (size_t i=0 ; i<count ; i++) { 2985 const sp<Track>& track = tracksToRemove.itemAt(i); 2986 mActiveTracks.remove(track); 2987 mWakeLockUids.remove(track->uid()); 2988 mActiveTracksGeneration++; 2989 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 2990 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2991 if (chain != 0) { 2992 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 2993 track->sessionId()); 2994 chain->decActiveTrackCnt(); 2995 } 2996 if (track->isTerminated()) { 2997 removeTrack_l(track); 2998 } 2999 } 3000 } 3001 3002} 3003 3004status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 3005{ 3006 if (mNormalSink != 0) { 3007 return mNormalSink->getTimestamp(timestamp); 3008 } 3009 if ((mType == OFFLOAD || mType == DIRECT) 3010 && mOutput != NULL && mOutput->stream->get_presentation_position) { 3011 uint64_t position64; 3012 int ret = mOutput->getPresentationPosition(&position64, ×tamp.mTime); 3013 if (ret == 0) { 3014 timestamp.mPosition = (uint32_t)position64; 3015 return NO_ERROR; 3016 } 3017 } 3018 return INVALID_OPERATION; 3019} 3020 3021status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch, 3022 audio_patch_handle_t *handle) 3023{ 3024 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3025 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3026 if (mFastMixer != 0) { 3027 FastMixerStateQueue *sq = mFastMixer->sq(); 3028 FastMixerState *state = sq->begin(); 3029 if (!(state->mCommand & FastMixerState::IDLE)) { 3030 previousCommand = state->mCommand; 3031 state->mCommand = FastMixerState::HOT_IDLE; 3032 sq->end(); 3033 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3034 } else { 3035 sq->end(false /*didModify*/); 3036 } 3037 } 3038 status_t status = PlaybackThread::createAudioPatch_l(patch, handle); 3039 3040 if (!(previousCommand & FastMixerState::IDLE)) { 3041 ALOG_ASSERT(mFastMixer != 0); 3042 FastMixerStateQueue *sq = mFastMixer->sq(); 3043 FastMixerState *state = sq->begin(); 3044 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3045 state->mCommand = previousCommand; 3046 sq->end(); 3047 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3048 } 3049 3050 return status; 3051} 3052 3053status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch, 3054 audio_patch_handle_t *handle) 3055{ 3056 status_t status = NO_ERROR; 3057 3058 // store new device and send to effects 3059 audio_devices_t type = AUDIO_DEVICE_NONE; 3060 for (unsigned int i = 0; i < patch->num_sinks; i++) { 3061 type |= patch->sinks[i].ext.device.type; 3062 } 3063 3064#ifdef ADD_BATTERY_DATA 3065 // when changing the audio output device, call addBatteryData to notify 3066 // the change 3067 if (mOutDevice != type) { 3068 uint32_t params = 0; 3069 // check whether speaker is on 3070 if (type & AUDIO_DEVICE_OUT_SPEAKER) { 3071 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3072 } 3073 3074 audio_devices_t deviceWithoutSpeaker 3075 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3076 // check if any other device (except speaker) is on 3077 if (type & deviceWithoutSpeaker) { 3078 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3079 } 3080 3081 if (params != 0) { 3082 addBatteryData(params); 3083 } 3084 } 3085#endif 3086 3087 for (size_t i = 0; i < mEffectChains.size(); i++) { 3088 mEffectChains[i]->setDevice_l(type); 3089 } 3090 mOutDevice = type; 3091 mPatch = *patch; 3092 3093 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 3094 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice(); 3095 status = hwDevice->create_audio_patch(hwDevice, 3096 patch->num_sources, 3097 patch->sources, 3098 patch->num_sinks, 3099 patch->sinks, 3100 handle); 3101 } else { 3102 char *address; 3103 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) { 3104 //FIXME: we only support address on first sink with HAL version < 3.0 3105 address = audio_device_address_to_parameter( 3106 patch->sinks[0].ext.device.type, 3107 patch->sinks[0].ext.device.address); 3108 } else { 3109 address = (char *)calloc(1, 1); 3110 } 3111 AudioParameter param = AudioParameter(String8(address)); 3112 free(address); 3113 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type); 3114 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3115 param.toString().string()); 3116 *handle = AUDIO_PATCH_HANDLE_NONE; 3117 } 3118 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 3119 return status; 3120} 3121 3122status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 3123{ 3124 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3125 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3126 if (mFastMixer != 0) { 3127 FastMixerStateQueue *sq = mFastMixer->sq(); 3128 FastMixerState *state = sq->begin(); 3129 if (!(state->mCommand & FastMixerState::IDLE)) { 3130 previousCommand = state->mCommand; 3131 state->mCommand = FastMixerState::HOT_IDLE; 3132 sq->end(); 3133 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3134 } else { 3135 sq->end(false /*didModify*/); 3136 } 3137 } 3138 3139 status_t status = PlaybackThread::releaseAudioPatch_l(handle); 3140 3141 if (!(previousCommand & FastMixerState::IDLE)) { 3142 ALOG_ASSERT(mFastMixer != 0); 3143 FastMixerStateQueue *sq = mFastMixer->sq(); 3144 FastMixerState *state = sq->begin(); 3145 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3146 state->mCommand = previousCommand; 3147 sq->end(); 3148 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3149 } 3150 3151 return status; 3152} 3153 3154status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 3155{ 3156 status_t status = NO_ERROR; 3157 3158 mOutDevice = AUDIO_DEVICE_NONE; 3159 3160 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 3161 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice(); 3162 status = hwDevice->release_audio_patch(hwDevice, handle); 3163 } else { 3164 AudioParameter param; 3165 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0); 3166 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3167 param.toString().string()); 3168 } 3169 return status; 3170} 3171 3172void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track) 3173{ 3174 Mutex::Autolock _l(mLock); 3175 mTracks.add(track); 3176} 3177 3178void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track) 3179{ 3180 Mutex::Autolock _l(mLock); 3181 destroyTrack_l(track); 3182} 3183 3184void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config) 3185{ 3186 ThreadBase::getAudioPortConfig(config); 3187 config->role = AUDIO_PORT_ROLE_SOURCE; 3188 config->ext.mix.hw_module = mOutput->audioHwDev->handle(); 3189 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT; 3190} 3191 3192// ---------------------------------------------------------------------------- 3193 3194AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 3195 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type) 3196 : PlaybackThread(audioFlinger, output, id, device, type, systemReady), 3197 // mAudioMixer below 3198 // mFastMixer below 3199 mFastMixerFutex(0) 3200 // mOutputSink below 3201 // mPipeSink below 3202 // mNormalSink below 3203{ 3204 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 3205 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 3206 "mFrameCount=%d, mNormalFrameCount=%d", 3207 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 3208 mNormalFrameCount); 3209 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3210 3211 if (type == DUPLICATING) { 3212 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks 3213 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write(). 3214 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink. 3215 return; 3216 } 3217 // create an NBAIO sink for the HAL output stream, and negotiate 3218 mOutputSink = new AudioStreamOutSink(output->stream); 3219 size_t numCounterOffers = 0; 3220 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 3221 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 3222 ALOG_ASSERT(index == 0); 3223 3224 // initialize fast mixer depending on configuration 3225 bool initFastMixer; 3226 switch (kUseFastMixer) { 3227 case FastMixer_Never: 3228 initFastMixer = false; 3229 break; 3230 case FastMixer_Always: 3231 initFastMixer = true; 3232 break; 3233 case FastMixer_Static: 3234 case FastMixer_Dynamic: 3235 initFastMixer = mFrameCount < mNormalFrameCount; 3236 break; 3237 } 3238 if (initFastMixer) { 3239 audio_format_t fastMixerFormat; 3240 if (mMixerBufferEnabled && mEffectBufferEnabled) { 3241 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT; 3242 } else { 3243 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT; 3244 } 3245 if (mFormat != fastMixerFormat) { 3246 // change our Sink format to accept our intermediate precision 3247 mFormat = fastMixerFormat; 3248 free(mSinkBuffer); 3249 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 3250 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 3251 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 3252 } 3253 3254 // create a MonoPipe to connect our submix to FastMixer 3255 NBAIO_Format format = mOutputSink->format(); 3256 NBAIO_Format origformat = format; 3257 // adjust format to match that of the Fast Mixer 3258 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat); 3259 format.mFormat = fastMixerFormat; 3260 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount; 3261 3262 // This pipe depth compensates for scheduling latency of the normal mixer thread. 3263 // When it wakes up after a maximum latency, it runs a few cycles quickly before 3264 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 3265 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 3266 const NBAIO_Format offers[1] = {format}; 3267 size_t numCounterOffers = 0; 3268 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 3269 ALOG_ASSERT(index == 0); 3270 monoPipe->setAvgFrames((mScreenState & 1) ? 3271 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 3272 mPipeSink = monoPipe; 3273 3274#ifdef TEE_SINK 3275 if (mTeeSinkOutputEnabled) { 3276 // create a Pipe to archive a copy of FastMixer's output for dumpsys 3277 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat); 3278 const NBAIO_Format offers2[1] = {origformat}; 3279 numCounterOffers = 0; 3280 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers); 3281 ALOG_ASSERT(index == 0); 3282 mTeeSink = teeSink; 3283 PipeReader *teeSource = new PipeReader(*teeSink); 3284 numCounterOffers = 0; 3285 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers); 3286 ALOG_ASSERT(index == 0); 3287 mTeeSource = teeSource; 3288 } 3289#endif 3290 3291 // create fast mixer and configure it initially with just one fast track for our submix 3292 mFastMixer = new FastMixer(); 3293 FastMixerStateQueue *sq = mFastMixer->sq(); 3294#ifdef STATE_QUEUE_DUMP 3295 sq->setObserverDump(&mStateQueueObserverDump); 3296 sq->setMutatorDump(&mStateQueueMutatorDump); 3297#endif 3298 FastMixerState *state = sq->begin(); 3299 FastTrack *fastTrack = &state->mFastTracks[0]; 3300 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 3301 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 3302 fastTrack->mVolumeProvider = NULL; 3303 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer 3304 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer 3305 fastTrack->mGeneration++; 3306 state->mFastTracksGen++; 3307 state->mTrackMask = 1; 3308 // fast mixer will use the HAL output sink 3309 state->mOutputSink = mOutputSink.get(); 3310 state->mOutputSinkGen++; 3311 state->mFrameCount = mFrameCount; 3312 state->mCommand = FastMixerState::COLD_IDLE; 3313 // already done in constructor initialization list 3314 //mFastMixerFutex = 0; 3315 state->mColdFutexAddr = &mFastMixerFutex; 3316 state->mColdGen++; 3317 state->mDumpState = &mFastMixerDumpState; 3318#ifdef TEE_SINK 3319 state->mTeeSink = mTeeSink.get(); 3320#endif 3321 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 3322 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 3323 sq->end(); 3324 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3325 3326 // start the fast mixer 3327 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 3328 pid_t tid = mFastMixer->getTid(); 3329 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 3330 3331#ifdef AUDIO_WATCHDOG 3332 // create and start the watchdog 3333 mAudioWatchdog = new AudioWatchdog(); 3334 mAudioWatchdog->setDump(&mAudioWatchdogDump); 3335 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 3336 tid = mAudioWatchdog->getTid(); 3337 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 3338#endif 3339 3340 } 3341 3342 switch (kUseFastMixer) { 3343 case FastMixer_Never: 3344 case FastMixer_Dynamic: 3345 mNormalSink = mOutputSink; 3346 break; 3347 case FastMixer_Always: 3348 mNormalSink = mPipeSink; 3349 break; 3350 case FastMixer_Static: 3351 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 3352 break; 3353 } 3354} 3355 3356AudioFlinger::MixerThread::~MixerThread() 3357{ 3358 if (mFastMixer != 0) { 3359 FastMixerStateQueue *sq = mFastMixer->sq(); 3360 FastMixerState *state = sq->begin(); 3361 if (state->mCommand == FastMixerState::COLD_IDLE) { 3362 int32_t old = android_atomic_inc(&mFastMixerFutex); 3363 if (old == -1) { 3364 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3365 } 3366 } 3367 state->mCommand = FastMixerState::EXIT; 3368 sq->end(); 3369 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3370 mFastMixer->join(); 3371 // Though the fast mixer thread has exited, it's state queue is still valid. 3372 // We'll use that extract the final state which contains one remaining fast track 3373 // corresponding to our sub-mix. 3374 state = sq->begin(); 3375 ALOG_ASSERT(state->mTrackMask == 1); 3376 FastTrack *fastTrack = &state->mFastTracks[0]; 3377 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 3378 delete fastTrack->mBufferProvider; 3379 sq->end(false /*didModify*/); 3380 mFastMixer.clear(); 3381#ifdef AUDIO_WATCHDOG 3382 if (mAudioWatchdog != 0) { 3383 mAudioWatchdog->requestExit(); 3384 mAudioWatchdog->requestExitAndWait(); 3385 mAudioWatchdog.clear(); 3386 } 3387#endif 3388 } 3389 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 3390 delete mAudioMixer; 3391} 3392 3393 3394uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 3395{ 3396 if (mFastMixer != 0) { 3397 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 3398 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 3399 } 3400 return latency; 3401} 3402 3403 3404void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 3405{ 3406 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 3407} 3408 3409ssize_t AudioFlinger::MixerThread::threadLoop_write() 3410{ 3411 // FIXME we should only do one push per cycle; confirm this is true 3412 // Start the fast mixer if it's not already running 3413 if (mFastMixer != 0) { 3414 FastMixerStateQueue *sq = mFastMixer->sq(); 3415 FastMixerState *state = sq->begin(); 3416 if (state->mCommand != FastMixerState::MIX_WRITE && 3417 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 3418 if (state->mCommand == FastMixerState::COLD_IDLE) { 3419 int32_t old = android_atomic_inc(&mFastMixerFutex); 3420 if (old == -1) { 3421 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3422 } 3423#ifdef AUDIO_WATCHDOG 3424 if (mAudioWatchdog != 0) { 3425 mAudioWatchdog->resume(); 3426 } 3427#endif 3428 } 3429 state->mCommand = FastMixerState::MIX_WRITE; 3430#ifdef FAST_THREAD_STATISTICS 3431 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 3432 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN); 3433#endif 3434 sq->end(); 3435 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3436 if (kUseFastMixer == FastMixer_Dynamic) { 3437 mNormalSink = mPipeSink; 3438 } 3439 } else { 3440 sq->end(false /*didModify*/); 3441 } 3442 } 3443 return PlaybackThread::threadLoop_write(); 3444} 3445 3446void AudioFlinger::MixerThread::threadLoop_standby() 3447{ 3448 // Idle the fast mixer if it's currently running 3449 if (mFastMixer != 0) { 3450 FastMixerStateQueue *sq = mFastMixer->sq(); 3451 FastMixerState *state = sq->begin(); 3452 if (!(state->mCommand & FastMixerState::IDLE)) { 3453 state->mCommand = FastMixerState::COLD_IDLE; 3454 state->mColdFutexAddr = &mFastMixerFutex; 3455 state->mColdGen++; 3456 mFastMixerFutex = 0; 3457 sq->end(); 3458 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 3459 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3460 if (kUseFastMixer == FastMixer_Dynamic) { 3461 mNormalSink = mOutputSink; 3462 } 3463#ifdef AUDIO_WATCHDOG 3464 if (mAudioWatchdog != 0) { 3465 mAudioWatchdog->pause(); 3466 } 3467#endif 3468 } else { 3469 sq->end(false /*didModify*/); 3470 } 3471 } 3472 PlaybackThread::threadLoop_standby(); 3473} 3474 3475bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 3476{ 3477 return false; 3478} 3479 3480bool AudioFlinger::PlaybackThread::shouldStandby_l() 3481{ 3482 return !mStandby; 3483} 3484 3485bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 3486{ 3487 Mutex::Autolock _l(mLock); 3488 return waitingAsyncCallback_l(); 3489} 3490 3491// shared by MIXER and DIRECT, overridden by DUPLICATING 3492void AudioFlinger::PlaybackThread::threadLoop_standby() 3493{ 3494 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 3495 mOutput->standby(); 3496 if (mUseAsyncWrite != 0) { 3497 // discard any pending drain or write ack by incrementing sequence 3498 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 3499 mDrainSequence = (mDrainSequence + 2) & ~1; 3500 ALOG_ASSERT(mCallbackThread != 0); 3501 mCallbackThread->setWriteBlocked(mWriteAckSequence); 3502 mCallbackThread->setDraining(mDrainSequence); 3503 } 3504 mHwPaused = false; 3505} 3506 3507void AudioFlinger::PlaybackThread::onAddNewTrack_l() 3508{ 3509 ALOGV("signal playback thread"); 3510 broadcast_l(); 3511} 3512 3513void AudioFlinger::MixerThread::threadLoop_mix() 3514{ 3515 // obtain the presentation timestamp of the next output buffer 3516 int64_t pts; 3517 status_t status = INVALID_OPERATION; 3518 3519 if (mNormalSink != 0) { 3520 status = mNormalSink->getNextWriteTimestamp(&pts); 3521 } else { 3522 status = mOutputSink->getNextWriteTimestamp(&pts); 3523 } 3524 3525 if (status != NO_ERROR) { 3526 pts = AudioBufferProvider::kInvalidPTS; 3527 } 3528 3529 // mix buffers... 3530 mAudioMixer->process(pts); 3531 mCurrentWriteLength = mSinkBufferSize; 3532 // increase sleep time progressively when application underrun condition clears. 3533 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 3534 // that a steady state of alternating ready/not ready conditions keeps the sleep time 3535 // such that we would underrun the audio HAL. 3536 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) { 3537 sleepTimeShift--; 3538 } 3539 mSleepTimeUs = 0; 3540 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3541 //TODO: delay standby when effects have a tail 3542 3543} 3544 3545void AudioFlinger::MixerThread::threadLoop_sleepTime() 3546{ 3547 // If no tracks are ready, sleep once for the duration of an output 3548 // buffer size, then write 0s to the output 3549 if (mSleepTimeUs == 0) { 3550 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3551 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift; 3552 if (mSleepTimeUs < kMinThreadSleepTimeUs) { 3553 mSleepTimeUs = kMinThreadSleepTimeUs; 3554 } 3555 // reduce sleep time in case of consecutive application underruns to avoid 3556 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 3557 // duration we would end up writing less data than needed by the audio HAL if 3558 // the condition persists. 3559 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 3560 sleepTimeShift++; 3561 } 3562 } else { 3563 mSleepTimeUs = mIdleSleepTimeUs; 3564 } 3565 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 3566 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared 3567 // before effects processing or output. 3568 if (mMixerBufferValid) { 3569 memset(mMixerBuffer, 0, mMixerBufferSize); 3570 } else { 3571 memset(mSinkBuffer, 0, mSinkBufferSize); 3572 } 3573 mSleepTimeUs = 0; 3574 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 3575 "anticipated start"); 3576 } 3577 // TODO add standby time extension fct of effect tail 3578} 3579 3580// prepareTracks_l() must be called with ThreadBase::mLock held 3581AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 3582 Vector< sp<Track> > *tracksToRemove) 3583{ 3584 3585 mixer_state mixerStatus = MIXER_IDLE; 3586 // find out which tracks need to be processed 3587 size_t count = mActiveTracks.size(); 3588 size_t mixedTracks = 0; 3589 size_t tracksWithEffect = 0; 3590 // counts only _active_ fast tracks 3591 size_t fastTracks = 0; 3592 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 3593 3594 float masterVolume = mMasterVolume; 3595 bool masterMute = mMasterMute; 3596 3597 if (masterMute) { 3598 masterVolume = 0; 3599 } 3600 // Delegate master volume control to effect in output mix effect chain if needed 3601 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 3602 if (chain != 0) { 3603 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 3604 chain->setVolume_l(&v, &v); 3605 masterVolume = (float)((v + (1 << 23)) >> 24); 3606 chain.clear(); 3607 } 3608 3609 // prepare a new state to push 3610 FastMixerStateQueue *sq = NULL; 3611 FastMixerState *state = NULL; 3612 bool didModify = false; 3613 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 3614 if (mFastMixer != 0) { 3615 sq = mFastMixer->sq(); 3616 state = sq->begin(); 3617 } 3618 3619 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found. 3620 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found. 3621 3622 for (size_t i=0 ; i<count ; i++) { 3623 const sp<Track> t = mActiveTracks[i].promote(); 3624 if (t == 0) { 3625 continue; 3626 } 3627 3628 // this const just means the local variable doesn't change 3629 Track* const track = t.get(); 3630 3631 // process fast tracks 3632 if (track->isFastTrack()) { 3633 3634 // It's theoretically possible (though unlikely) for a fast track to be created 3635 // and then removed within the same normal mix cycle. This is not a problem, as 3636 // the track never becomes active so it's fast mixer slot is never touched. 3637 // The converse, of removing an (active) track and then creating a new track 3638 // at the identical fast mixer slot within the same normal mix cycle, 3639 // is impossible because the slot isn't marked available until the end of each cycle. 3640 int j = track->mFastIndex; 3641 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 3642 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 3643 FastTrack *fastTrack = &state->mFastTracks[j]; 3644 3645 // Determine whether the track is currently in underrun condition, 3646 // and whether it had a recent underrun. 3647 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 3648 FastTrackUnderruns underruns = ftDump->mUnderruns; 3649 uint32_t recentFull = (underruns.mBitFields.mFull - 3650 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 3651 uint32_t recentPartial = (underruns.mBitFields.mPartial - 3652 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 3653 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 3654 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 3655 uint32_t recentUnderruns = recentPartial + recentEmpty; 3656 track->mObservedUnderruns = underruns; 3657 // don't count underruns that occur while stopping or pausing 3658 // or stopped which can occur when flush() is called while active 3659 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 3660 recentUnderruns > 0) { 3661 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 3662 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 3663 } 3664 3665 // This is similar to the state machine for normal tracks, 3666 // with a few modifications for fast tracks. 3667 bool isActive = true; 3668 switch (track->mState) { 3669 case TrackBase::STOPPING_1: 3670 // track stays active in STOPPING_1 state until first underrun 3671 if (recentUnderruns > 0 || track->isTerminated()) { 3672 track->mState = TrackBase::STOPPING_2; 3673 } 3674 break; 3675 case TrackBase::PAUSING: 3676 // ramp down is not yet implemented 3677 track->setPaused(); 3678 break; 3679 case TrackBase::RESUMING: 3680 // ramp up is not yet implemented 3681 track->mState = TrackBase::ACTIVE; 3682 break; 3683 case TrackBase::ACTIVE: 3684 if (recentFull > 0 || recentPartial > 0) { 3685 // track has provided at least some frames recently: reset retry count 3686 track->mRetryCount = kMaxTrackRetries; 3687 } 3688 if (recentUnderruns == 0) { 3689 // no recent underruns: stay active 3690 break; 3691 } 3692 // there has recently been an underrun of some kind 3693 if (track->sharedBuffer() == 0) { 3694 // were any of the recent underruns "empty" (no frames available)? 3695 if (recentEmpty == 0) { 3696 // no, then ignore the partial underruns as they are allowed indefinitely 3697 break; 3698 } 3699 // there has recently been an "empty" underrun: decrement the retry counter 3700 if (--(track->mRetryCount) > 0) { 3701 break; 3702 } 3703 // indicate to client process that the track was disabled because of underrun; 3704 // it will then automatically call start() when data is available 3705 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 3706 // remove from active list, but state remains ACTIVE [confusing but true] 3707 isActive = false; 3708 break; 3709 } 3710 // fall through 3711 case TrackBase::STOPPING_2: 3712 case TrackBase::PAUSED: 3713 case TrackBase::STOPPED: 3714 case TrackBase::FLUSHED: // flush() while active 3715 // Check for presentation complete if track is inactive 3716 // We have consumed all the buffers of this track. 3717 // This would be incomplete if we auto-paused on underrun 3718 { 3719 size_t audioHALFrames = 3720 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3721 size_t framesWritten = mBytesWritten / mFrameSize; 3722 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 3723 // track stays in active list until presentation is complete 3724 break; 3725 } 3726 } 3727 if (track->isStopping_2()) { 3728 track->mState = TrackBase::STOPPED; 3729 } 3730 if (track->isStopped()) { 3731 // Can't reset directly, as fast mixer is still polling this track 3732 // track->reset(); 3733 // So instead mark this track as needing to be reset after push with ack 3734 resetMask |= 1 << i; 3735 } 3736 isActive = false; 3737 break; 3738 case TrackBase::IDLE: 3739 default: 3740 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState); 3741 } 3742 3743 if (isActive) { 3744 // was it previously inactive? 3745 if (!(state->mTrackMask & (1 << j))) { 3746 ExtendedAudioBufferProvider *eabp = track; 3747 VolumeProvider *vp = track; 3748 fastTrack->mBufferProvider = eabp; 3749 fastTrack->mVolumeProvider = vp; 3750 fastTrack->mChannelMask = track->mChannelMask; 3751 fastTrack->mFormat = track->mFormat; 3752 fastTrack->mGeneration++; 3753 state->mTrackMask |= 1 << j; 3754 didModify = true; 3755 // no acknowledgement required for newly active tracks 3756 } 3757 // cache the combined master volume and stream type volume for fast mixer; this 3758 // lacks any synchronization or barrier so VolumeProvider may read a stale value 3759 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 3760 ++fastTracks; 3761 } else { 3762 // was it previously active? 3763 if (state->mTrackMask & (1 << j)) { 3764 fastTrack->mBufferProvider = NULL; 3765 fastTrack->mGeneration++; 3766 state->mTrackMask &= ~(1 << j); 3767 didModify = true; 3768 // If any fast tracks were removed, we must wait for acknowledgement 3769 // because we're about to decrement the last sp<> on those tracks. 3770 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3771 } else { 3772 LOG_ALWAYS_FATAL("fast track %d should have been active", j); 3773 } 3774 tracksToRemove->add(track); 3775 // Avoids a misleading display in dumpsys 3776 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 3777 } 3778 continue; 3779 } 3780 3781 { // local variable scope to avoid goto warning 3782 3783 audio_track_cblk_t* cblk = track->cblk(); 3784 3785 // The first time a track is added we wait 3786 // for all its buffers to be filled before processing it 3787 int name = track->name(); 3788 // make sure that we have enough frames to mix one full buffer. 3789 // enforce this condition only once to enable draining the buffer in case the client 3790 // app does not call stop() and relies on underrun to stop: 3791 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 3792 // during last round 3793 size_t desiredFrames; 3794 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3795 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate(); 3796 3797 desiredFrames = sourceFramesNeededWithTimestretch( 3798 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed); 3799 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed. 3800 // add frames already consumed but not yet released by the resampler 3801 // because mAudioTrackServerProxy->framesReady() will include these frames 3802 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 3803 3804 uint32_t minFrames = 1; 3805 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 3806 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 3807 minFrames = desiredFrames; 3808 } 3809 3810 size_t framesReady = track->framesReady(); 3811 if (ATRACE_ENABLED()) { 3812 // I wish we had formatted trace names 3813 char traceName[16]; 3814 strcpy(traceName, "nRdy"); 3815 int name = track->name(); 3816 if (AudioMixer::TRACK0 <= name && 3817 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) { 3818 name -= AudioMixer::TRACK0; 3819 traceName[4] = (name / 10) + '0'; 3820 traceName[5] = (name % 10) + '0'; 3821 } else { 3822 traceName[4] = '?'; 3823 traceName[5] = '?'; 3824 } 3825 traceName[6] = '\0'; 3826 ATRACE_INT(traceName, framesReady); 3827 } 3828 if ((framesReady >= minFrames) && track->isReady() && 3829 !track->isPaused() && !track->isTerminated()) 3830 { 3831 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 3832 3833 mixedTracks++; 3834 3835 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means 3836 // there is an effect chain connected to the track 3837 chain.clear(); 3838 if (track->mainBuffer() != mSinkBuffer && 3839 track->mainBuffer() != mMixerBuffer) { 3840 if (mEffectBufferEnabled) { 3841 mEffectBufferValid = true; // Later can set directly. 3842 } 3843 chain = getEffectChain_l(track->sessionId()); 3844 // Delegate volume control to effect in track effect chain if needed 3845 if (chain != 0) { 3846 tracksWithEffect++; 3847 } else { 3848 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 3849 "session %d", 3850 name, track->sessionId()); 3851 } 3852 } 3853 3854 3855 int param = AudioMixer::VOLUME; 3856 if (track->mFillingUpStatus == Track::FS_FILLED) { 3857 // no ramp for the first volume setting 3858 track->mFillingUpStatus = Track::FS_ACTIVE; 3859 if (track->mState == TrackBase::RESUMING) { 3860 track->mState = TrackBase::ACTIVE; 3861 param = AudioMixer::RAMP_VOLUME; 3862 } 3863 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3864 // FIXME should not make a decision based on mServer 3865 } else if (cblk->mServer != 0) { 3866 // If the track is stopped before the first frame was mixed, 3867 // do not apply ramp 3868 param = AudioMixer::RAMP_VOLUME; 3869 } 3870 3871 // compute volume for this track 3872 uint32_t vl, vr; // in U8.24 integer format 3873 float vlf, vrf, vaf; // in [0.0, 1.0] float format 3874 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 3875 vl = vr = 0; 3876 vlf = vrf = vaf = 0.; 3877 if (track->isPausing()) { 3878 track->setPaused(); 3879 } 3880 } else { 3881 3882 // read original volumes with volume control 3883 float typeVolume = mStreamTypes[track->streamType()].volume; 3884 float v = masterVolume * typeVolume; 3885 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3886 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 3887 vlf = float_from_gain(gain_minifloat_unpack_left(vlr)); 3888 vrf = float_from_gain(gain_minifloat_unpack_right(vlr)); 3889 // track volumes come from shared memory, so can't be trusted and must be clamped 3890 if (vlf > GAIN_FLOAT_UNITY) { 3891 ALOGV("Track left volume out of range: %.3g", vlf); 3892 vlf = GAIN_FLOAT_UNITY; 3893 } 3894 if (vrf > GAIN_FLOAT_UNITY) { 3895 ALOGV("Track right volume out of range: %.3g", vrf); 3896 vrf = GAIN_FLOAT_UNITY; 3897 } 3898 // now apply the master volume and stream type volume 3899 vlf *= v; 3900 vrf *= v; 3901 // assuming master volume and stream type volume each go up to 1.0, 3902 // then derive vl and vr as U8.24 versions for the effect chain 3903 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT; 3904 vl = (uint32_t) (scaleto8_24 * vlf); 3905 vr = (uint32_t) (scaleto8_24 * vrf); 3906 // vl and vr are now in U8.24 format 3907 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 3908 // send level comes from shared memory and so may be corrupt 3909 if (sendLevel > MAX_GAIN_INT) { 3910 ALOGV("Track send level out of range: %04X", sendLevel); 3911 sendLevel = MAX_GAIN_INT; 3912 } 3913 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel 3914 vaf = v * sendLevel * (1. / MAX_GAIN_INT); 3915 } 3916 3917 // Delegate volume control to effect in track effect chain if needed 3918 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3919 // Do not ramp volume if volume is controlled by effect 3920 param = AudioMixer::VOLUME; 3921 // Update remaining floating point volume levels 3922 vlf = (float)vl / (1 << 24); 3923 vrf = (float)vr / (1 << 24); 3924 track->mHasVolumeController = true; 3925 } else { 3926 // force no volume ramp when volume controller was just disabled or removed 3927 // from effect chain to avoid volume spike 3928 if (track->mHasVolumeController) { 3929 param = AudioMixer::VOLUME; 3930 } 3931 track->mHasVolumeController = false; 3932 } 3933 3934 // XXX: these things DON'T need to be done each time 3935 mAudioMixer->setBufferProvider(name, track); 3936 mAudioMixer->enable(name); 3937 3938 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf); 3939 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf); 3940 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf); 3941 mAudioMixer->setParameter( 3942 name, 3943 AudioMixer::TRACK, 3944 AudioMixer::FORMAT, (void *)track->format()); 3945 mAudioMixer->setParameter( 3946 name, 3947 AudioMixer::TRACK, 3948 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask()); 3949 mAudioMixer->setParameter( 3950 name, 3951 AudioMixer::TRACK, 3952 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask); 3953 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3954 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX; 3955 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3956 if (reqSampleRate == 0) { 3957 reqSampleRate = mSampleRate; 3958 } else if (reqSampleRate > maxSampleRate) { 3959 reqSampleRate = maxSampleRate; 3960 } 3961 mAudioMixer->setParameter( 3962 name, 3963 AudioMixer::RESAMPLE, 3964 AudioMixer::SAMPLE_RATE, 3965 (void *)(uintptr_t)reqSampleRate); 3966 3967 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate(); 3968 mAudioMixer->setParameter( 3969 name, 3970 AudioMixer::TIMESTRETCH, 3971 AudioMixer::PLAYBACK_RATE, 3972 &playbackRate); 3973 3974 /* 3975 * Select the appropriate output buffer for the track. 3976 * 3977 * Tracks with effects go into their own effects chain buffer 3978 * and from there into either mEffectBuffer or mSinkBuffer. 3979 * 3980 * Other tracks can use mMixerBuffer for higher precision 3981 * channel accumulation. If this buffer is enabled 3982 * (mMixerBufferEnabled true), then selected tracks will accumulate 3983 * into it. 3984 * 3985 */ 3986 if (mMixerBufferEnabled 3987 && (track->mainBuffer() == mSinkBuffer 3988 || track->mainBuffer() == mMixerBuffer)) { 3989 mAudioMixer->setParameter( 3990 name, 3991 AudioMixer::TRACK, 3992 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat); 3993 mAudioMixer->setParameter( 3994 name, 3995 AudioMixer::TRACK, 3996 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer); 3997 // TODO: override track->mainBuffer()? 3998 mMixerBufferValid = true; 3999 } else { 4000 mAudioMixer->setParameter( 4001 name, 4002 AudioMixer::TRACK, 4003 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT); 4004 mAudioMixer->setParameter( 4005 name, 4006 AudioMixer::TRACK, 4007 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 4008 } 4009 mAudioMixer->setParameter( 4010 name, 4011 AudioMixer::TRACK, 4012 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 4013 4014 // reset retry count 4015 track->mRetryCount = kMaxTrackRetries; 4016 4017 // If one track is ready, set the mixer ready if: 4018 // - the mixer was not ready during previous round OR 4019 // - no other track is not ready 4020 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 4021 mixerStatus != MIXER_TRACKS_ENABLED) { 4022 mixerStatus = MIXER_TRACKS_READY; 4023 } 4024 } else { 4025 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 4026 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 4027 } 4028 // clear effect chain input buffer if an active track underruns to avoid sending 4029 // previous audio buffer again to effects 4030 chain = getEffectChain_l(track->sessionId()); 4031 if (chain != 0) { 4032 chain->clearInputBuffer(); 4033 } 4034 4035 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 4036 if ((track->sharedBuffer() != 0) || track->isTerminated() || 4037 track->isStopped() || track->isPaused()) { 4038 // We have consumed all the buffers of this track. 4039 // Remove it from the list of active tracks. 4040 // TODO: use actual buffer filling status instead of latency when available from 4041 // audio HAL 4042 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 4043 size_t framesWritten = mBytesWritten / mFrameSize; 4044 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 4045 if (track->isStopped()) { 4046 track->reset(); 4047 } 4048 tracksToRemove->add(track); 4049 } 4050 } else { 4051 // No buffers for this track. Give it a few chances to 4052 // fill a buffer, then remove it from active list. 4053 if (--(track->mRetryCount) <= 0) { 4054 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 4055 tracksToRemove->add(track); 4056 // indicate to client process that the track was disabled because of underrun; 4057 // it will then automatically call start() when data is available 4058 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4059 // If one track is not ready, mark the mixer also not ready if: 4060 // - the mixer was ready during previous round OR 4061 // - no other track is ready 4062 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 4063 mixerStatus != MIXER_TRACKS_READY) { 4064 mixerStatus = MIXER_TRACKS_ENABLED; 4065 } 4066 } 4067 mAudioMixer->disable(name); 4068 } 4069 4070 } // local variable scope to avoid goto warning 4071track_is_ready: ; 4072 4073 } 4074 4075 // Push the new FastMixer state if necessary 4076 bool pauseAudioWatchdog = false; 4077 if (didModify) { 4078 state->mFastTracksGen++; 4079 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 4080 if (kUseFastMixer == FastMixer_Dynamic && 4081 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 4082 state->mCommand = FastMixerState::COLD_IDLE; 4083 state->mColdFutexAddr = &mFastMixerFutex; 4084 state->mColdGen++; 4085 mFastMixerFutex = 0; 4086 if (kUseFastMixer == FastMixer_Dynamic) { 4087 mNormalSink = mOutputSink; 4088 } 4089 // If we go into cold idle, need to wait for acknowledgement 4090 // so that fast mixer stops doing I/O. 4091 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 4092 pauseAudioWatchdog = true; 4093 } 4094 } 4095 if (sq != NULL) { 4096 sq->end(didModify); 4097 sq->push(block); 4098 } 4099#ifdef AUDIO_WATCHDOG 4100 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 4101 mAudioWatchdog->pause(); 4102 } 4103#endif 4104 4105 // Now perform the deferred reset on fast tracks that have stopped 4106 while (resetMask != 0) { 4107 size_t i = __builtin_ctz(resetMask); 4108 ALOG_ASSERT(i < count); 4109 resetMask &= ~(1 << i); 4110 sp<Track> t = mActiveTracks[i].promote(); 4111 if (t == 0) { 4112 continue; 4113 } 4114 Track* track = t.get(); 4115 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 4116 track->reset(); 4117 } 4118 4119 // remove all the tracks that need to be... 4120 removeTracks_l(*tracksToRemove); 4121 4122 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) { 4123 mEffectBufferValid = true; 4124 } 4125 4126 if (mEffectBufferValid) { 4127 // as long as there are effects we should clear the effects buffer, to avoid 4128 // passing a non-clean buffer to the effect chain 4129 memset(mEffectBuffer, 0, mEffectBufferSize); 4130 } 4131 // sink or mix buffer must be cleared if all tracks are connected to an 4132 // effect chain as in this case the mixer will not write to the sink or mix buffer 4133 // and track effects will accumulate into it 4134 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 4135 (mixedTracks == 0 && fastTracks > 0))) { 4136 // FIXME as a performance optimization, should remember previous zero status 4137 if (mMixerBufferValid) { 4138 memset(mMixerBuffer, 0, mMixerBufferSize); 4139 // TODO: In testing, mSinkBuffer below need not be cleared because 4140 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer 4141 // after mixing. 4142 // 4143 // To enforce this guarantee: 4144 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 4145 // (mixedTracks == 0 && fastTracks > 0)) 4146 // must imply MIXER_TRACKS_READY. 4147 // Later, we may clear buffers regardless, and skip much of this logic. 4148 } 4149 // FIXME as a performance optimization, should remember previous zero status 4150 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize); 4151 } 4152 4153 // if any fast tracks, then status is ready 4154 mMixerStatusIgnoringFastTracks = mixerStatus; 4155 if (fastTracks > 0) { 4156 mixerStatus = MIXER_TRACKS_READY; 4157 } 4158 return mixerStatus; 4159} 4160 4161// getTrackName_l() must be called with ThreadBase::mLock held 4162int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, 4163 audio_format_t format, int sessionId) 4164{ 4165 return mAudioMixer->getTrackName(channelMask, format, sessionId); 4166} 4167 4168// deleteTrackName_l() must be called with ThreadBase::mLock held 4169void AudioFlinger::MixerThread::deleteTrackName_l(int name) 4170{ 4171 ALOGV("remove track (%d) and delete from mixer", name); 4172 mAudioMixer->deleteTrackName(name); 4173} 4174 4175// checkForNewParameter_l() must be called with ThreadBase::mLock held 4176bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair, 4177 status_t& status) 4178{ 4179 bool reconfig = false; 4180 4181 status = NO_ERROR; 4182 4183 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 4184 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 4185 if (mFastMixer != 0) { 4186 FastMixerStateQueue *sq = mFastMixer->sq(); 4187 FastMixerState *state = sq->begin(); 4188 if (!(state->mCommand & FastMixerState::IDLE)) { 4189 previousCommand = state->mCommand; 4190 state->mCommand = FastMixerState::HOT_IDLE; 4191 sq->end(); 4192 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 4193 } else { 4194 sq->end(false /*didModify*/); 4195 } 4196 } 4197 4198 AudioParameter param = AudioParameter(keyValuePair); 4199 int value; 4200 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4201 reconfig = true; 4202 } 4203 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4204 if (!isValidPcmSinkFormat((audio_format_t) value)) { 4205 status = BAD_VALUE; 4206 } else { 4207 // no need to save value, since it's constant 4208 reconfig = true; 4209 } 4210 } 4211 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4212 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) { 4213 status = BAD_VALUE; 4214 } else { 4215 // no need to save value, since it's constant 4216 reconfig = true; 4217 } 4218 } 4219 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4220 // do not accept frame count changes if tracks are open as the track buffer 4221 // size depends on frame count and correct behavior would not be guaranteed 4222 // if frame count is changed after track creation 4223 if (!mTracks.isEmpty()) { 4224 status = INVALID_OPERATION; 4225 } else { 4226 reconfig = true; 4227 } 4228 } 4229 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4230#ifdef ADD_BATTERY_DATA 4231 // when changing the audio output device, call addBatteryData to notify 4232 // the change 4233 if (mOutDevice != value) { 4234 uint32_t params = 0; 4235 // check whether speaker is on 4236 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 4237 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 4238 } 4239 4240 audio_devices_t deviceWithoutSpeaker 4241 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 4242 // check if any other device (except speaker) is on 4243 if (value & deviceWithoutSpeaker) { 4244 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 4245 } 4246 4247 if (params != 0) { 4248 addBatteryData(params); 4249 } 4250 } 4251#endif 4252 4253 // forward device change to effects that have requested to be 4254 // aware of attached audio device. 4255 if (value != AUDIO_DEVICE_NONE) { 4256 mOutDevice = value; 4257 for (size_t i = 0; i < mEffectChains.size(); i++) { 4258 mEffectChains[i]->setDevice_l(mOutDevice); 4259 } 4260 } 4261 } 4262 4263 if (status == NO_ERROR) { 4264 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4265 keyValuePair.string()); 4266 if (!mStandby && status == INVALID_OPERATION) { 4267 mOutput->standby(); 4268 mStandby = true; 4269 mBytesWritten = 0; 4270 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4271 keyValuePair.string()); 4272 } 4273 if (status == NO_ERROR && reconfig) { 4274 readOutputParameters_l(); 4275 delete mAudioMixer; 4276 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 4277 for (size_t i = 0; i < mTracks.size() ; i++) { 4278 int name = getTrackName_l(mTracks[i]->mChannelMask, 4279 mTracks[i]->mFormat, mTracks[i]->mSessionId); 4280 if (name < 0) { 4281 break; 4282 } 4283 mTracks[i]->mName = name; 4284 } 4285 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 4286 } 4287 } 4288 4289 if (!(previousCommand & FastMixerState::IDLE)) { 4290 ALOG_ASSERT(mFastMixer != 0); 4291 FastMixerStateQueue *sq = mFastMixer->sq(); 4292 FastMixerState *state = sq->begin(); 4293 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 4294 state->mCommand = previousCommand; 4295 sq->end(); 4296 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 4297 } 4298 4299 return reconfig; 4300} 4301 4302 4303void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 4304{ 4305 const size_t SIZE = 256; 4306 char buffer[SIZE]; 4307 String8 result; 4308 4309 PlaybackThread::dumpInternals(fd, args); 4310 4311 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames()); 4312 4313 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 4314 const FastMixerDumpState copy(mFastMixerDumpState); 4315 copy.dump(fd); 4316 4317#ifdef STATE_QUEUE_DUMP 4318 // Similar for state queue 4319 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 4320 observerCopy.dump(fd); 4321 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 4322 mutatorCopy.dump(fd); 4323#endif 4324 4325#ifdef TEE_SINK 4326 // Write the tee output to a .wav file 4327 dumpTee(fd, mTeeSource, mId); 4328#endif 4329 4330#ifdef AUDIO_WATCHDOG 4331 if (mAudioWatchdog != 0) { 4332 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 4333 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 4334 wdCopy.dump(fd); 4335 } 4336#endif 4337} 4338 4339uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 4340{ 4341 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 4342} 4343 4344uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 4345{ 4346 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 4347} 4348 4349void AudioFlinger::MixerThread::cacheParameters_l() 4350{ 4351 PlaybackThread::cacheParameters_l(); 4352 4353 // FIXME: Relaxed timing because of a certain device that can't meet latency 4354 // Should be reduced to 2x after the vendor fixes the driver issue 4355 // increase threshold again due to low power audio mode. The way this warning 4356 // threshold is calculated and its usefulness should be reconsidered anyway. 4357 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 4358} 4359 4360// ---------------------------------------------------------------------------- 4361 4362AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4363 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady) 4364 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady) 4365 // mLeftVolFloat, mRightVolFloat 4366{ 4367} 4368 4369AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4370 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 4371 ThreadBase::type_t type, bool systemReady) 4372 : PlaybackThread(audioFlinger, output, id, device, type, systemReady) 4373 // mLeftVolFloat, mRightVolFloat 4374{ 4375} 4376 4377AudioFlinger::DirectOutputThread::~DirectOutputThread() 4378{ 4379} 4380 4381void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 4382{ 4383 audio_track_cblk_t* cblk = track->cblk(); 4384 float left, right; 4385 4386 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 4387 left = right = 0; 4388 } else { 4389 float typeVolume = mStreamTypes[track->streamType()].volume; 4390 float v = mMasterVolume * typeVolume; 4391 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 4392 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 4393 left = float_from_gain(gain_minifloat_unpack_left(vlr)); 4394 if (left > GAIN_FLOAT_UNITY) { 4395 left = GAIN_FLOAT_UNITY; 4396 } 4397 left *= v; 4398 right = float_from_gain(gain_minifloat_unpack_right(vlr)); 4399 if (right > GAIN_FLOAT_UNITY) { 4400 right = GAIN_FLOAT_UNITY; 4401 } 4402 right *= v; 4403 } 4404 4405 if (lastTrack) { 4406 if (left != mLeftVolFloat || right != mRightVolFloat) { 4407 mLeftVolFloat = left; 4408 mRightVolFloat = right; 4409 4410 // Convert volumes from float to 8.24 4411 uint32_t vl = (uint32_t)(left * (1 << 24)); 4412 uint32_t vr = (uint32_t)(right * (1 << 24)); 4413 4414 // Delegate volume control to effect in track effect chain if needed 4415 // only one effect chain can be present on DirectOutputThread, so if 4416 // there is one, the track is connected to it 4417 if (!mEffectChains.isEmpty()) { 4418 mEffectChains[0]->setVolume_l(&vl, &vr); 4419 left = (float)vl / (1 << 24); 4420 right = (float)vr / (1 << 24); 4421 } 4422 if (mOutput->stream->set_volume) { 4423 mOutput->stream->set_volume(mOutput->stream, left, right); 4424 } 4425 } 4426 } 4427} 4428 4429 4430AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 4431 Vector< sp<Track> > *tracksToRemove 4432) 4433{ 4434 size_t count = mActiveTracks.size(); 4435 mixer_state mixerStatus = MIXER_IDLE; 4436 bool doHwPause = false; 4437 bool doHwResume = false; 4438 bool flushPending = false; 4439 4440 // find out which tracks need to be processed 4441 for (size_t i = 0; i < count; i++) { 4442 sp<Track> t = mActiveTracks[i].promote(); 4443 // The track died recently 4444 if (t == 0) { 4445 continue; 4446 } 4447 4448 Track* const track = t.get(); 4449 audio_track_cblk_t* cblk = track->cblk(); 4450 // Only consider last track started for volume and mixer state control. 4451 // In theory an older track could underrun and restart after the new one starts 4452 // but as we only care about the transition phase between two tracks on a 4453 // direct output, it is not a problem to ignore the underrun case. 4454 sp<Track> l = mLatestActiveTrack.promote(); 4455 bool last = l.get() == track; 4456 4457 if (track->isPausing()) { 4458 track->setPaused(); 4459 if (mHwSupportsPause && last && !mHwPaused) { 4460 doHwPause = true; 4461 mHwPaused = true; 4462 } 4463 tracksToRemove->add(track); 4464 } else if (track->isFlushPending()) { 4465 track->flushAck(); 4466 if (last) { 4467 flushPending = true; 4468 } 4469 } else if (track->isResumePending()) { 4470 track->resumeAck(); 4471 if (last && mHwPaused) { 4472 doHwResume = true; 4473 mHwPaused = false; 4474 } 4475 } 4476 4477 // The first time a track is added we wait 4478 // for all its buffers to be filled before processing it. 4479 // Allow draining the buffer in case the client 4480 // app does not call stop() and relies on underrun to stop: 4481 // hence the test on (track->mRetryCount > 1). 4482 // If retryCount<=1 then track is about to underrun and be removed. 4483 uint32_t minFrames; 4484 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing() 4485 && (track->mRetryCount > 1)) { 4486 minFrames = mNormalFrameCount; 4487 } else { 4488 minFrames = 1; 4489 } 4490 4491 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() && 4492 !track->isStopping_2() && !track->isStopped()) 4493 { 4494 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 4495 4496 if (track->mFillingUpStatus == Track::FS_FILLED) { 4497 track->mFillingUpStatus = Track::FS_ACTIVE; 4498 // make sure processVolume_l() will apply new volume even if 0 4499 mLeftVolFloat = mRightVolFloat = -1.0; 4500 if (!mHwSupportsPause) { 4501 track->resumeAck(); 4502 } 4503 } 4504 4505 // compute volume for this track 4506 processVolume_l(track, last); 4507 if (last) { 4508 // reset retry count 4509 track->mRetryCount = kMaxTrackRetriesDirect; 4510 mActiveTrack = t; 4511 mixerStatus = MIXER_TRACKS_READY; 4512 if (mHwPaused) { 4513 doHwResume = true; 4514 mHwPaused = false; 4515 } 4516 } 4517 } else { 4518 // clear effect chain input buffer if the last active track started underruns 4519 // to avoid sending previous audio buffer again to effects 4520 if (!mEffectChains.isEmpty() && last) { 4521 mEffectChains[0]->clearInputBuffer(); 4522 } 4523 if (track->isStopping_1()) { 4524 track->mState = TrackBase::STOPPING_2; 4525 if (last && mHwPaused) { 4526 doHwResume = true; 4527 mHwPaused = false; 4528 } 4529 } 4530 if ((track->sharedBuffer() != 0) || track->isStopped() || 4531 track->isStopping_2() || track->isPaused()) { 4532 // We have consumed all the buffers of this track. 4533 // Remove it from the list of active tracks. 4534 size_t audioHALFrames; 4535 if (audio_is_linear_pcm(mFormat)) { 4536 audioHALFrames = (latency_l() * mSampleRate) / 1000; 4537 } else { 4538 audioHALFrames = 0; 4539 } 4540 4541 size_t framesWritten = mBytesWritten / mFrameSize; 4542 if (mStandby || !last || 4543 track->presentationComplete(framesWritten, audioHALFrames)) { 4544 if (track->isStopping_2()) { 4545 track->mState = TrackBase::STOPPED; 4546 } 4547 if (track->isStopped()) { 4548 track->reset(); 4549 } 4550 tracksToRemove->add(track); 4551 } 4552 } else { 4553 // No buffers for this track. Give it a few chances to 4554 // fill a buffer, then remove it from active list. 4555 // Only consider last track started for mixer state control 4556 if (--(track->mRetryCount) <= 0) { 4557 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 4558 tracksToRemove->add(track); 4559 // indicate to client process that the track was disabled because of underrun; 4560 // it will then automatically call start() when data is available 4561 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4562 } else if (last) { 4563 mixerStatus = MIXER_TRACKS_ENABLED; 4564 if (mHwSupportsPause && !mHwPaused && !mStandby) { 4565 doHwPause = true; 4566 mHwPaused = true; 4567 } 4568 } 4569 } 4570 } 4571 } 4572 4573 // if an active track did not command a flush, check for pending flush on stopped tracks 4574 if (!flushPending) { 4575 for (size_t i = 0; i < mTracks.size(); i++) { 4576 if (mTracks[i]->isFlushPending()) { 4577 mTracks[i]->flushAck(); 4578 flushPending = true; 4579 } 4580 } 4581 } 4582 4583 // make sure the pause/flush/resume sequence is executed in the right order. 4584 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 4585 // before flush and then resume HW. This can happen in case of pause/flush/resume 4586 // if resume is received before pause is executed. 4587 if (mHwSupportsPause && !mStandby && 4588 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) { 4589 mOutput->stream->pause(mOutput->stream); 4590 } 4591 if (flushPending) { 4592 flushHw_l(); 4593 } 4594 if (mHwSupportsPause && !mStandby && doHwResume) { 4595 mOutput->stream->resume(mOutput->stream); 4596 } 4597 // remove all the tracks that need to be... 4598 removeTracks_l(*tracksToRemove); 4599 4600 return mixerStatus; 4601} 4602 4603void AudioFlinger::DirectOutputThread::threadLoop_mix() 4604{ 4605 size_t frameCount = mFrameCount; 4606 int8_t *curBuf = (int8_t *)mSinkBuffer; 4607 // output audio to hardware 4608 while (frameCount) { 4609 AudioBufferProvider::Buffer buffer; 4610 buffer.frameCount = frameCount; 4611 status_t status = mActiveTrack->getNextBuffer(&buffer); 4612 if (status != NO_ERROR || buffer.raw == NULL) { 4613 memset(curBuf, 0, frameCount * mFrameSize); 4614 break; 4615 } 4616 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 4617 frameCount -= buffer.frameCount; 4618 curBuf += buffer.frameCount * mFrameSize; 4619 mActiveTrack->releaseBuffer(&buffer); 4620 } 4621 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer; 4622 mSleepTimeUs = 0; 4623 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 4624 mActiveTrack.clear(); 4625} 4626 4627void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 4628{ 4629 // do not write to HAL when paused 4630 if (mHwPaused || (usesHwAvSync() && mStandby)) { 4631 mSleepTimeUs = mIdleSleepTimeUs; 4632 return; 4633 } 4634 if (mSleepTimeUs == 0) { 4635 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4636 mSleepTimeUs = mActiveSleepTimeUs; 4637 } else { 4638 mSleepTimeUs = mIdleSleepTimeUs; 4639 } 4640 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 4641 memset(mSinkBuffer, 0, mFrameCount * mFrameSize); 4642 mSleepTimeUs = 0; 4643 } 4644} 4645 4646void AudioFlinger::DirectOutputThread::threadLoop_exit() 4647{ 4648 { 4649 Mutex::Autolock _l(mLock); 4650 bool flushPending = false; 4651 for (size_t i = 0; i < mTracks.size(); i++) { 4652 if (mTracks[i]->isFlushPending()) { 4653 mTracks[i]->flushAck(); 4654 flushPending = true; 4655 } 4656 } 4657 if (flushPending) { 4658 flushHw_l(); 4659 } 4660 } 4661 PlaybackThread::threadLoop_exit(); 4662} 4663 4664// must be called with thread mutex locked 4665bool AudioFlinger::DirectOutputThread::shouldStandby_l() 4666{ 4667 bool trackPaused = false; 4668 bool trackStopped = false; 4669 4670 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4671 // after a timeout and we will enter standby then. 4672 if (mTracks.size() > 0) { 4673 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4674 trackStopped = mTracks[mTracks.size() - 1]->isStopped() || 4675 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE; 4676 } 4677 4678 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped)); 4679} 4680 4681// getTrackName_l() must be called with ThreadBase::mLock held 4682int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 4683 audio_format_t format __unused, int sessionId __unused) 4684{ 4685 return 0; 4686} 4687 4688// deleteTrackName_l() must be called with ThreadBase::mLock held 4689void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 4690{ 4691} 4692 4693// checkForNewParameter_l() must be called with ThreadBase::mLock held 4694bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair, 4695 status_t& status) 4696{ 4697 bool reconfig = false; 4698 4699 status = NO_ERROR; 4700 4701 AudioParameter param = AudioParameter(keyValuePair); 4702 int value; 4703 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4704 // forward device change to effects that have requested to be 4705 // aware of attached audio device. 4706 if (value != AUDIO_DEVICE_NONE) { 4707 mOutDevice = value; 4708 for (size_t i = 0; i < mEffectChains.size(); i++) { 4709 mEffectChains[i]->setDevice_l(mOutDevice); 4710 } 4711 } 4712 } 4713 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4714 // do not accept frame count changes if tracks are open as the track buffer 4715 // size depends on frame count and correct behavior would not be garantied 4716 // if frame count is changed after track creation 4717 if (!mTracks.isEmpty()) { 4718 status = INVALID_OPERATION; 4719 } else { 4720 reconfig = true; 4721 } 4722 } 4723 if (status == NO_ERROR) { 4724 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4725 keyValuePair.string()); 4726 if (!mStandby && status == INVALID_OPERATION) { 4727 mOutput->standby(); 4728 mStandby = true; 4729 mBytesWritten = 0; 4730 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 4731 keyValuePair.string()); 4732 } 4733 if (status == NO_ERROR && reconfig) { 4734 readOutputParameters_l(); 4735 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 4736 } 4737 } 4738 4739 return reconfig; 4740} 4741 4742uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 4743{ 4744 uint32_t time; 4745 if (audio_is_linear_pcm(mFormat)) { 4746 time = PlaybackThread::activeSleepTimeUs(); 4747 } else { 4748 time = 10000; 4749 } 4750 return time; 4751} 4752 4753uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 4754{ 4755 uint32_t time; 4756 if (audio_is_linear_pcm(mFormat)) { 4757 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 4758 } else { 4759 time = 10000; 4760 } 4761 return time; 4762} 4763 4764uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 4765{ 4766 uint32_t time; 4767 if (audio_is_linear_pcm(mFormat)) { 4768 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 4769 } else { 4770 time = 10000; 4771 } 4772 return time; 4773} 4774 4775void AudioFlinger::DirectOutputThread::cacheParameters_l() 4776{ 4777 PlaybackThread::cacheParameters_l(); 4778 4779 // use shorter standby delay as on normal output to release 4780 // hardware resources as soon as possible 4781 // no delay on outputs with HW A/V sync 4782 if (usesHwAvSync()) { 4783 mStandbyDelayNs = 0; 4784 } else if ((mType == OFFLOAD) && !audio_is_linear_pcm(mFormat)) { 4785 mStandbyDelayNs = kOffloadStandbyDelayNs; 4786 } else { 4787 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2); 4788 } 4789} 4790 4791void AudioFlinger::DirectOutputThread::flushHw_l() 4792{ 4793 mOutput->flush(); 4794 mHwPaused = false; 4795} 4796 4797// ---------------------------------------------------------------------------- 4798 4799AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 4800 const wp<AudioFlinger::PlaybackThread>& playbackThread) 4801 : Thread(false /*canCallJava*/), 4802 mPlaybackThread(playbackThread), 4803 mWriteAckSequence(0), 4804 mDrainSequence(0) 4805{ 4806} 4807 4808AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 4809{ 4810} 4811 4812void AudioFlinger::AsyncCallbackThread::onFirstRef() 4813{ 4814 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 4815} 4816 4817bool AudioFlinger::AsyncCallbackThread::threadLoop() 4818{ 4819 while (!exitPending()) { 4820 uint32_t writeAckSequence; 4821 uint32_t drainSequence; 4822 4823 { 4824 Mutex::Autolock _l(mLock); 4825 while (!((mWriteAckSequence & 1) || 4826 (mDrainSequence & 1) || 4827 exitPending())) { 4828 mWaitWorkCV.wait(mLock); 4829 } 4830 4831 if (exitPending()) { 4832 break; 4833 } 4834 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 4835 mWriteAckSequence, mDrainSequence); 4836 writeAckSequence = mWriteAckSequence; 4837 mWriteAckSequence &= ~1; 4838 drainSequence = mDrainSequence; 4839 mDrainSequence &= ~1; 4840 } 4841 { 4842 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 4843 if (playbackThread != 0) { 4844 if (writeAckSequence & 1) { 4845 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 4846 } 4847 if (drainSequence & 1) { 4848 playbackThread->resetDraining(drainSequence >> 1); 4849 } 4850 } 4851 } 4852 } 4853 return false; 4854} 4855 4856void AudioFlinger::AsyncCallbackThread::exit() 4857{ 4858 ALOGV("AsyncCallbackThread::exit"); 4859 Mutex::Autolock _l(mLock); 4860 requestExit(); 4861 mWaitWorkCV.broadcast(); 4862} 4863 4864void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 4865{ 4866 Mutex::Autolock _l(mLock); 4867 // bit 0 is cleared 4868 mWriteAckSequence = sequence << 1; 4869} 4870 4871void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 4872{ 4873 Mutex::Autolock _l(mLock); 4874 // ignore unexpected callbacks 4875 if (mWriteAckSequence & 2) { 4876 mWriteAckSequence |= 1; 4877 mWaitWorkCV.signal(); 4878 } 4879} 4880 4881void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 4882{ 4883 Mutex::Autolock _l(mLock); 4884 // bit 0 is cleared 4885 mDrainSequence = sequence << 1; 4886} 4887 4888void AudioFlinger::AsyncCallbackThread::resetDraining() 4889{ 4890 Mutex::Autolock _l(mLock); 4891 // ignore unexpected callbacks 4892 if (mDrainSequence & 2) { 4893 mDrainSequence |= 1; 4894 mWaitWorkCV.signal(); 4895 } 4896} 4897 4898 4899// ---------------------------------------------------------------------------- 4900AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 4901 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady) 4902 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady), 4903 mPausedBytesRemaining(0) 4904{ 4905 //FIXME: mStandby should be set to true by ThreadBase constructor 4906 mStandby = true; 4907} 4908 4909void AudioFlinger::OffloadThread::threadLoop_exit() 4910{ 4911 if (mFlushPending || mHwPaused) { 4912 // If a flush is pending or track was paused, just discard buffered data 4913 flushHw_l(); 4914 } else { 4915 mMixerStatus = MIXER_DRAIN_ALL; 4916 threadLoop_drain(); 4917 } 4918 if (mUseAsyncWrite) { 4919 ALOG_ASSERT(mCallbackThread != 0); 4920 mCallbackThread->exit(); 4921 } 4922 PlaybackThread::threadLoop_exit(); 4923} 4924 4925AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 4926 Vector< sp<Track> > *tracksToRemove 4927) 4928{ 4929 size_t count = mActiveTracks.size(); 4930 4931 mixer_state mixerStatus = MIXER_IDLE; 4932 bool doHwPause = false; 4933 bool doHwResume = false; 4934 4935 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 4936 4937 // find out which tracks need to be processed 4938 for (size_t i = 0; i < count; i++) { 4939 sp<Track> t = mActiveTracks[i].promote(); 4940 // The track died recently 4941 if (t == 0) { 4942 continue; 4943 } 4944 Track* const track = t.get(); 4945 audio_track_cblk_t* cblk = track->cblk(); 4946 // Only consider last track started for volume and mixer state control. 4947 // In theory an older track could underrun and restart after the new one starts 4948 // but as we only care about the transition phase between two tracks on a 4949 // direct output, it is not a problem to ignore the underrun case. 4950 sp<Track> l = mLatestActiveTrack.promote(); 4951 bool last = l.get() == track; 4952 4953 if (track->isInvalid()) { 4954 ALOGW("An invalidated track shouldn't be in active list"); 4955 tracksToRemove->add(track); 4956 continue; 4957 } 4958 4959 if (track->mState == TrackBase::IDLE) { 4960 ALOGW("An idle track shouldn't be in active list"); 4961 continue; 4962 } 4963 4964 if (track->isPausing()) { 4965 track->setPaused(); 4966 if (last) { 4967 if (mHwSupportsPause && !mHwPaused) { 4968 doHwPause = true; 4969 mHwPaused = true; 4970 } 4971 // If we were part way through writing the mixbuffer to 4972 // the HAL we must save this until we resume 4973 // BUG - this will be wrong if a different track is made active, 4974 // in that case we want to discard the pending data in the 4975 // mixbuffer and tell the client to present it again when the 4976 // track is resumed 4977 mPausedWriteLength = mCurrentWriteLength; 4978 mPausedBytesRemaining = mBytesRemaining; 4979 mBytesRemaining = 0; // stop writing 4980 } 4981 tracksToRemove->add(track); 4982 } else if (track->isFlushPending()) { 4983 track->flushAck(); 4984 if (last) { 4985 mFlushPending = true; 4986 } 4987 } else if (track->isResumePending()){ 4988 track->resumeAck(); 4989 if (last) { 4990 if (mPausedBytesRemaining) { 4991 // Need to continue write that was interrupted 4992 mCurrentWriteLength = mPausedWriteLength; 4993 mBytesRemaining = mPausedBytesRemaining; 4994 mPausedBytesRemaining = 0; 4995 } 4996 if (mHwPaused) { 4997 doHwResume = true; 4998 mHwPaused = false; 4999 // threadLoop_mix() will handle the case that we need to 5000 // resume an interrupted write 5001 } 5002 // enable write to audio HAL 5003 mSleepTimeUs = 0; 5004 5005 // Do not handle new data in this iteration even if track->framesReady() 5006 mixerStatus = MIXER_TRACKS_ENABLED; 5007 } 5008 } else if (track->framesReady() && track->isReady() && 5009 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 5010 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 5011 if (track->mFillingUpStatus == Track::FS_FILLED) { 5012 track->mFillingUpStatus = Track::FS_ACTIVE; 5013 // make sure processVolume_l() will apply new volume even if 0 5014 mLeftVolFloat = mRightVolFloat = -1.0; 5015 } 5016 5017 if (last) { 5018 sp<Track> previousTrack = mPreviousTrack.promote(); 5019 if (previousTrack != 0) { 5020 if (track != previousTrack.get()) { 5021 // Flush any data still being written from last track 5022 mBytesRemaining = 0; 5023 if (mPausedBytesRemaining) { 5024 // Last track was paused so we also need to flush saved 5025 // mixbuffer state and invalidate track so that it will 5026 // re-submit that unwritten data when it is next resumed 5027 mPausedBytesRemaining = 0; 5028 // Invalidate is a bit drastic - would be more efficient 5029 // to have a flag to tell client that some of the 5030 // previously written data was lost 5031 previousTrack->invalidate(); 5032 } 5033 // flush data already sent to the DSP if changing audio session as audio 5034 // comes from a different source. Also invalidate previous track to force a 5035 // seek when resuming. 5036 if (previousTrack->sessionId() != track->sessionId()) { 5037 previousTrack->invalidate(); 5038 } 5039 } 5040 } 5041 mPreviousTrack = track; 5042 // reset retry count 5043 track->mRetryCount = kMaxTrackRetriesOffload; 5044 mActiveTrack = t; 5045 mixerStatus = MIXER_TRACKS_READY; 5046 } 5047 } else { 5048 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 5049 if (track->isStopping_1()) { 5050 // Hardware buffer can hold a large amount of audio so we must 5051 // wait for all current track's data to drain before we say 5052 // that the track is stopped. 5053 if (mBytesRemaining == 0) { 5054 // Only start draining when all data in mixbuffer 5055 // has been written 5056 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 5057 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 5058 // do not drain if no data was ever sent to HAL (mStandby == true) 5059 if (last && !mStandby) { 5060 // do not modify drain sequence if we are already draining. This happens 5061 // when resuming from pause after drain. 5062 if ((mDrainSequence & 1) == 0) { 5063 mSleepTimeUs = 0; 5064 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5065 mixerStatus = MIXER_DRAIN_TRACK; 5066 mDrainSequence += 2; 5067 } 5068 if (mHwPaused) { 5069 // It is possible to move from PAUSED to STOPPING_1 without 5070 // a resume so we must ensure hardware is running 5071 doHwResume = true; 5072 mHwPaused = false; 5073 } 5074 } 5075 } 5076 } else if (track->isStopping_2()) { 5077 // Drain has completed or we are in standby, signal presentation complete 5078 if (!(mDrainSequence & 1) || !last || mStandby) { 5079 track->mState = TrackBase::STOPPED; 5080 size_t audioHALFrames = 5081 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 5082 size_t framesWritten = 5083 mBytesWritten / mOutput->getFrameSize(); 5084 track->presentationComplete(framesWritten, audioHALFrames); 5085 track->reset(); 5086 tracksToRemove->add(track); 5087 } 5088 } else { 5089 // No buffers for this track. Give it a few chances to 5090 // fill a buffer, then remove it from active list. 5091 if (--(track->mRetryCount) <= 0) { 5092 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 5093 track->name()); 5094 tracksToRemove->add(track); 5095 // indicate to client process that the track was disabled because of underrun; 5096 // it will then automatically call start() when data is available 5097 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 5098 } else if (last){ 5099 mixerStatus = MIXER_TRACKS_ENABLED; 5100 } 5101 } 5102 } 5103 // compute volume for this track 5104 processVolume_l(track, last); 5105 } 5106 5107 // make sure the pause/flush/resume sequence is executed in the right order. 5108 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 5109 // before flush and then resume HW. This can happen in case of pause/flush/resume 5110 // if resume is received before pause is executed. 5111 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 5112 mOutput->stream->pause(mOutput->stream); 5113 } 5114 if (mFlushPending) { 5115 flushHw_l(); 5116 mFlushPending = false; 5117 } 5118 if (!mStandby && doHwResume) { 5119 mOutput->stream->resume(mOutput->stream); 5120 } 5121 5122 // remove all the tracks that need to be... 5123 removeTracks_l(*tracksToRemove); 5124 5125 return mixerStatus; 5126} 5127 5128// must be called with thread mutex locked 5129bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 5130{ 5131 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 5132 mWriteAckSequence, mDrainSequence); 5133 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 5134 return true; 5135 } 5136 return false; 5137} 5138 5139bool AudioFlinger::OffloadThread::waitingAsyncCallback() 5140{ 5141 Mutex::Autolock _l(mLock); 5142 return waitingAsyncCallback_l(); 5143} 5144 5145void AudioFlinger::OffloadThread::flushHw_l() 5146{ 5147 DirectOutputThread::flushHw_l(); 5148 // Flush anything still waiting in the mixbuffer 5149 mCurrentWriteLength = 0; 5150 mBytesRemaining = 0; 5151 mPausedWriteLength = 0; 5152 mPausedBytesRemaining = 0; 5153 5154 if (mUseAsyncWrite) { 5155 // discard any pending drain or write ack by incrementing sequence 5156 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 5157 mDrainSequence = (mDrainSequence + 2) & ~1; 5158 ALOG_ASSERT(mCallbackThread != 0); 5159 mCallbackThread->setWriteBlocked(mWriteAckSequence); 5160 mCallbackThread->setDraining(mDrainSequence); 5161 } 5162} 5163 5164void AudioFlinger::OffloadThread::onAddNewTrack_l() 5165{ 5166 sp<Track> previousTrack = mPreviousTrack.promote(); 5167 sp<Track> latestTrack = mLatestActiveTrack.promote(); 5168 5169 if (previousTrack != 0 && latestTrack != 0 && 5170 (previousTrack->sessionId() != latestTrack->sessionId())) { 5171 mFlushPending = true; 5172 } 5173 PlaybackThread::onAddNewTrack_l(); 5174} 5175 5176// ---------------------------------------------------------------------------- 5177 5178AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 5179 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady) 5180 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 5181 systemReady, DUPLICATING), 5182 mWaitTimeMs(UINT_MAX) 5183{ 5184 addOutputTrack(mainThread); 5185} 5186 5187AudioFlinger::DuplicatingThread::~DuplicatingThread() 5188{ 5189 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5190 mOutputTracks[i]->destroy(); 5191 } 5192} 5193 5194void AudioFlinger::DuplicatingThread::threadLoop_mix() 5195{ 5196 // mix buffers... 5197 if (outputsReady(outputTracks)) { 5198 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 5199 } else { 5200 if (mMixerBufferValid) { 5201 memset(mMixerBuffer, 0, mMixerBufferSize); 5202 } else { 5203 memset(mSinkBuffer, 0, mSinkBufferSize); 5204 } 5205 } 5206 mSleepTimeUs = 0; 5207 writeFrames = mNormalFrameCount; 5208 mCurrentWriteLength = mSinkBufferSize; 5209 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5210} 5211 5212void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 5213{ 5214 if (mSleepTimeUs == 0) { 5215 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5216 mSleepTimeUs = mActiveSleepTimeUs; 5217 } else { 5218 mSleepTimeUs = mIdleSleepTimeUs; 5219 } 5220 } else if (mBytesWritten != 0) { 5221 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5222 writeFrames = mNormalFrameCount; 5223 memset(mSinkBuffer, 0, mSinkBufferSize); 5224 } else { 5225 // flush remaining overflow buffers in output tracks 5226 writeFrames = 0; 5227 } 5228 mSleepTimeUs = 0; 5229 } 5230} 5231 5232ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 5233{ 5234 for (size_t i = 0; i < outputTracks.size(); i++) { 5235 outputTracks[i]->write(mSinkBuffer, writeFrames); 5236 } 5237 mStandby = false; 5238 return (ssize_t)mSinkBufferSize; 5239} 5240 5241void AudioFlinger::DuplicatingThread::threadLoop_standby() 5242{ 5243 // DuplicatingThread implements standby by stopping all tracks 5244 for (size_t i = 0; i < outputTracks.size(); i++) { 5245 outputTracks[i]->stop(); 5246 } 5247} 5248 5249void AudioFlinger::DuplicatingThread::saveOutputTracks() 5250{ 5251 outputTracks = mOutputTracks; 5252} 5253 5254void AudioFlinger::DuplicatingThread::clearOutputTracks() 5255{ 5256 outputTracks.clear(); 5257} 5258 5259void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 5260{ 5261 Mutex::Autolock _l(mLock); 5262 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass. 5263 // Adjust for thread->sampleRate() to determine minimum buffer frame count. 5264 // Then triple buffer because Threads do not run synchronously and may not be clock locked. 5265 const size_t frameCount = 5266 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate()); 5267 // TODO: Consider asynchronous sample rate conversion to handle clock disparity 5268 // from different OutputTracks and their associated MixerThreads (e.g. one may 5269 // nearly empty and the other may be dropping data). 5270 5271 sp<OutputTrack> outputTrack = new OutputTrack(thread, 5272 this, 5273 mSampleRate, 5274 mFormat, 5275 mChannelMask, 5276 frameCount, 5277 IPCThreadState::self()->getCallingUid()); 5278 if (outputTrack->cblk() != NULL) { 5279 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f); 5280 mOutputTracks.add(outputTrack); 5281 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread); 5282 updateWaitTime_l(); 5283 } 5284} 5285 5286void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 5287{ 5288 Mutex::Autolock _l(mLock); 5289 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5290 if (mOutputTracks[i]->thread() == thread) { 5291 mOutputTracks[i]->destroy(); 5292 mOutputTracks.removeAt(i); 5293 updateWaitTime_l(); 5294 if (thread->getOutput() == mOutput) { 5295 mOutput = NULL; 5296 } 5297 return; 5298 } 5299 } 5300 ALOGV("removeOutputTrack(): unknown thread: %p", thread); 5301} 5302 5303// caller must hold mLock 5304void AudioFlinger::DuplicatingThread::updateWaitTime_l() 5305{ 5306 mWaitTimeMs = UINT_MAX; 5307 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5308 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 5309 if (strong != 0) { 5310 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 5311 if (waitTimeMs < mWaitTimeMs) { 5312 mWaitTimeMs = waitTimeMs; 5313 } 5314 } 5315 } 5316} 5317 5318 5319bool AudioFlinger::DuplicatingThread::outputsReady( 5320 const SortedVector< sp<OutputTrack> > &outputTracks) 5321{ 5322 for (size_t i = 0; i < outputTracks.size(); i++) { 5323 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 5324 if (thread == 0) { 5325 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 5326 outputTracks[i].get()); 5327 return false; 5328 } 5329 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 5330 // see note at standby() declaration 5331 if (playbackThread->standby() && !playbackThread->isSuspended()) { 5332 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 5333 thread.get()); 5334 return false; 5335 } 5336 } 5337 return true; 5338} 5339 5340uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 5341{ 5342 return (mWaitTimeMs * 1000) / 2; 5343} 5344 5345void AudioFlinger::DuplicatingThread::cacheParameters_l() 5346{ 5347 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 5348 updateWaitTime_l(); 5349 5350 MixerThread::cacheParameters_l(); 5351} 5352 5353// ---------------------------------------------------------------------------- 5354// Record 5355// ---------------------------------------------------------------------------- 5356 5357AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 5358 AudioStreamIn *input, 5359 audio_io_handle_t id, 5360 audio_devices_t outDevice, 5361 audio_devices_t inDevice, 5362 bool systemReady 5363#ifdef TEE_SINK 5364 , const sp<NBAIO_Sink>& teeSink 5365#endif 5366 ) : 5367 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady), 5368 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL), 5369 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l() 5370 mRsmpInRear(0) 5371#ifdef TEE_SINK 5372 , mTeeSink(teeSink) 5373#endif 5374 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize, 5375 "RecordThreadRO", MemoryHeapBase::READ_ONLY)) 5376 // mFastCapture below 5377 , mFastCaptureFutex(0) 5378 // mInputSource 5379 // mPipeSink 5380 // mPipeSource 5381 , mPipeFramesP2(0) 5382 // mPipeMemory 5383 // mFastCaptureNBLogWriter 5384 , mFastTrackAvail(false) 5385{ 5386 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id); 5387 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 5388 5389 readInputParameters_l(); 5390 5391 // create an NBAIO source for the HAL input stream, and negotiate 5392 mInputSource = new AudioStreamInSource(input->stream); 5393 size_t numCounterOffers = 0; 5394 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 5395 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers); 5396 ALOG_ASSERT(index == 0); 5397 5398 // initialize fast capture depending on configuration 5399 bool initFastCapture; 5400 switch (kUseFastCapture) { 5401 case FastCapture_Never: 5402 initFastCapture = false; 5403 break; 5404 case FastCapture_Always: 5405 initFastCapture = true; 5406 break; 5407 case FastCapture_Static: 5408 uint32_t primaryOutputSampleRate; 5409 { 5410 AutoMutex _l(audioFlinger->mHardwareLock); 5411 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate; 5412 } 5413 initFastCapture = 5414 // either capture sample rate is same as (a reasonable) primary output sample rate 5415 ((isMusicRate(primaryOutputSampleRate) && 5416 (mSampleRate == primaryOutputSampleRate)) || 5417 // or primary output sample rate is unknown, and capture sample rate is reasonable 5418 ((primaryOutputSampleRate == 0) && 5419 isMusicRate(mSampleRate))) && 5420 // and the buffer size is < 12 ms 5421 (mFrameCount * 1000) / mSampleRate < 12; 5422 break; 5423 // case FastCapture_Dynamic: 5424 } 5425 5426 if (initFastCapture) { 5427 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from 5428 NBAIO_Format format = mInputSource->format(); 5429 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each 5430 size_t pipeSize = pipeFramesP2 * Format_frameSize(format); 5431 void *pipeBuffer; 5432 const sp<MemoryDealer> roHeap(readOnlyHeap()); 5433 sp<IMemory> pipeMemory; 5434 if ((roHeap == 0) || 5435 (pipeMemory = roHeap->allocate(pipeSize)) == 0 || 5436 (pipeBuffer = pipeMemory->pointer()) == NULL) { 5437 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize); 5438 goto failed; 5439 } 5440 // pipe will be shared directly with fast clients, so clear to avoid leaking old information 5441 memset(pipeBuffer, 0, pipeSize); 5442 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer); 5443 const NBAIO_Format offers[1] = {format}; 5444 size_t numCounterOffers = 0; 5445 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 5446 ALOG_ASSERT(index == 0); 5447 mPipeSink = pipe; 5448 PipeReader *pipeReader = new PipeReader(*pipe); 5449 numCounterOffers = 0; 5450 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 5451 ALOG_ASSERT(index == 0); 5452 mPipeSource = pipeReader; 5453 mPipeFramesP2 = pipeFramesP2; 5454 mPipeMemory = pipeMemory; 5455 5456 // create fast capture 5457 mFastCapture = new FastCapture(); 5458 FastCaptureStateQueue *sq = mFastCapture->sq(); 5459#ifdef STATE_QUEUE_DUMP 5460 // FIXME 5461#endif 5462 FastCaptureState *state = sq->begin(); 5463 state->mCblk = NULL; 5464 state->mInputSource = mInputSource.get(); 5465 state->mInputSourceGen++; 5466 state->mPipeSink = pipe; 5467 state->mPipeSinkGen++; 5468 state->mFrameCount = mFrameCount; 5469 state->mCommand = FastCaptureState::COLD_IDLE; 5470 // already done in constructor initialization list 5471 //mFastCaptureFutex = 0; 5472 state->mColdFutexAddr = &mFastCaptureFutex; 5473 state->mColdGen++; 5474 state->mDumpState = &mFastCaptureDumpState; 5475#ifdef TEE_SINK 5476 // FIXME 5477#endif 5478 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture"); 5479 state->mNBLogWriter = mFastCaptureNBLogWriter.get(); 5480 sq->end(); 5481 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5482 5483 // start the fast capture 5484 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO); 5485 pid_t tid = mFastCapture->getTid(); 5486 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 5487#ifdef AUDIO_WATCHDOG 5488 // FIXME 5489#endif 5490 5491 mFastTrackAvail = true; 5492 } 5493failed: ; 5494 5495 // FIXME mNormalSource 5496} 5497 5498AudioFlinger::RecordThread::~RecordThread() 5499{ 5500 if (mFastCapture != 0) { 5501 FastCaptureStateQueue *sq = mFastCapture->sq(); 5502 FastCaptureState *state = sq->begin(); 5503 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5504 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5505 if (old == -1) { 5506 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5507 } 5508 } 5509 state->mCommand = FastCaptureState::EXIT; 5510 sq->end(); 5511 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 5512 mFastCapture->join(); 5513 mFastCapture.clear(); 5514 } 5515 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter); 5516 mAudioFlinger->unregisterWriter(mNBLogWriter); 5517 free(mRsmpInBuffer); 5518} 5519 5520void AudioFlinger::RecordThread::onFirstRef() 5521{ 5522 run(mThreadName, PRIORITY_URGENT_AUDIO); 5523} 5524 5525bool AudioFlinger::RecordThread::threadLoop() 5526{ 5527 nsecs_t lastWarning = 0; 5528 5529 inputStandBy(); 5530 5531reacquire_wakelock: 5532 sp<RecordTrack> activeTrack; 5533 int activeTracksGen; 5534 { 5535 Mutex::Autolock _l(mLock); 5536 size_t size = mActiveTracks.size(); 5537 activeTracksGen = mActiveTracksGen; 5538 if (size > 0) { 5539 // FIXME an arbitrary choice 5540 activeTrack = mActiveTracks[0]; 5541 acquireWakeLock_l(activeTrack->uid()); 5542 if (size > 1) { 5543 SortedVector<int> tmp; 5544 for (size_t i = 0; i < size; i++) { 5545 tmp.add(mActiveTracks[i]->uid()); 5546 } 5547 updateWakeLockUids_l(tmp); 5548 } 5549 } else { 5550 acquireWakeLock_l(-1); 5551 } 5552 } 5553 5554 // used to request a deferred sleep, to be executed later while mutex is unlocked 5555 uint32_t sleepUs = 0; 5556 5557 // loop while there is work to do 5558 for (;;) { 5559 Vector< sp<EffectChain> > effectChains; 5560 5561 // sleep with mutex unlocked 5562 if (sleepUs > 0) { 5563 ATRACE_BEGIN("sleep"); 5564 usleep(sleepUs); 5565 ATRACE_END(); 5566 sleepUs = 0; 5567 } 5568 5569 // activeTracks accumulates a copy of a subset of mActiveTracks 5570 Vector< sp<RecordTrack> > activeTracks; 5571 5572 // reference to the (first and only) active fast track 5573 sp<RecordTrack> fastTrack; 5574 5575 // reference to a fast track which is about to be removed 5576 sp<RecordTrack> fastTrackToRemove; 5577 5578 { // scope for mLock 5579 Mutex::Autolock _l(mLock); 5580 5581 processConfigEvents_l(); 5582 5583 // check exitPending here because checkForNewParameters_l() and 5584 // checkForNewParameters_l() can temporarily release mLock 5585 if (exitPending()) { 5586 break; 5587 } 5588 5589 // if no active track(s), then standby and release wakelock 5590 size_t size = mActiveTracks.size(); 5591 if (size == 0) { 5592 standbyIfNotAlreadyInStandby(); 5593 // exitPending() can't become true here 5594 releaseWakeLock_l(); 5595 ALOGV("RecordThread: loop stopping"); 5596 // go to sleep 5597 mWaitWorkCV.wait(mLock); 5598 ALOGV("RecordThread: loop starting"); 5599 goto reacquire_wakelock; 5600 } 5601 5602 if (mActiveTracksGen != activeTracksGen) { 5603 activeTracksGen = mActiveTracksGen; 5604 SortedVector<int> tmp; 5605 for (size_t i = 0; i < size; i++) { 5606 tmp.add(mActiveTracks[i]->uid()); 5607 } 5608 updateWakeLockUids_l(tmp); 5609 } 5610 5611 bool doBroadcast = false; 5612 for (size_t i = 0; i < size; ) { 5613 5614 activeTrack = mActiveTracks[i]; 5615 if (activeTrack->isTerminated()) { 5616 if (activeTrack->isFastTrack()) { 5617 ALOG_ASSERT(fastTrackToRemove == 0); 5618 fastTrackToRemove = activeTrack; 5619 } 5620 removeTrack_l(activeTrack); 5621 mActiveTracks.remove(activeTrack); 5622 mActiveTracksGen++; 5623 size--; 5624 continue; 5625 } 5626 5627 TrackBase::track_state activeTrackState = activeTrack->mState; 5628 switch (activeTrackState) { 5629 5630 case TrackBase::PAUSING: 5631 mActiveTracks.remove(activeTrack); 5632 mActiveTracksGen++; 5633 doBroadcast = true; 5634 size--; 5635 continue; 5636 5637 case TrackBase::STARTING_1: 5638 sleepUs = 10000; 5639 i++; 5640 continue; 5641 5642 case TrackBase::STARTING_2: 5643 doBroadcast = true; 5644 mStandby = false; 5645 activeTrack->mState = TrackBase::ACTIVE; 5646 break; 5647 5648 case TrackBase::ACTIVE: 5649 break; 5650 5651 case TrackBase::IDLE: 5652 i++; 5653 continue; 5654 5655 default: 5656 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState); 5657 } 5658 5659 activeTracks.add(activeTrack); 5660 i++; 5661 5662 if (activeTrack->isFastTrack()) { 5663 ALOG_ASSERT(!mFastTrackAvail); 5664 ALOG_ASSERT(fastTrack == 0); 5665 fastTrack = activeTrack; 5666 } 5667 } 5668 if (doBroadcast) { 5669 mStartStopCond.broadcast(); 5670 } 5671 5672 // sleep if there are no active tracks to process 5673 if (activeTracks.size() == 0) { 5674 if (sleepUs == 0) { 5675 sleepUs = kRecordThreadSleepUs; 5676 } 5677 continue; 5678 } 5679 sleepUs = 0; 5680 5681 lockEffectChains_l(effectChains); 5682 } 5683 5684 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0 5685 5686 size_t size = effectChains.size(); 5687 for (size_t i = 0; i < size; i++) { 5688 // thread mutex is not locked, but effect chain is locked 5689 effectChains[i]->process_l(); 5690 } 5691 5692 // Push a new fast capture state if fast capture is not already running, or cblk change 5693 if (mFastCapture != 0) { 5694 FastCaptureStateQueue *sq = mFastCapture->sq(); 5695 FastCaptureState *state = sq->begin(); 5696 bool didModify = false; 5697 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED; 5698 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME && 5699 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) { 5700 if (state->mCommand == FastCaptureState::COLD_IDLE) { 5701 int32_t old = android_atomic_inc(&mFastCaptureFutex); 5702 if (old == -1) { 5703 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 5704 } 5705 } 5706 state->mCommand = FastCaptureState::READ_WRITE; 5707#if 0 // FIXME 5708 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 5709 FastThreadDumpState::kSamplingNforLowRamDevice : 5710 FastThreadDumpState::kSamplingN); 5711#endif 5712 didModify = true; 5713 } 5714 audio_track_cblk_t *cblkOld = state->mCblk; 5715 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL; 5716 if (cblkNew != cblkOld) { 5717 state->mCblk = cblkNew; 5718 // block until acked if removing a fast track 5719 if (cblkOld != NULL) { 5720 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED; 5721 } 5722 didModify = true; 5723 } 5724 sq->end(didModify); 5725 if (didModify) { 5726 sq->push(block); 5727#if 0 5728 if (kUseFastCapture == FastCapture_Dynamic) { 5729 mNormalSource = mPipeSource; 5730 } 5731#endif 5732 } 5733 } 5734 5735 // now run the fast track destructor with thread mutex unlocked 5736 fastTrackToRemove.clear(); 5737 5738 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one. 5739 // Only the client(s) that are too slow will overrun. But if even the fastest client is too 5740 // slow, then this RecordThread will overrun by not calling HAL read often enough. 5741 // If destination is non-contiguous, first read past the nominal end of buffer, then 5742 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 5743 5744 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1); 5745 ssize_t framesRead; 5746 5747 // If an NBAIO source is present, use it to read the normal capture's data 5748 if (mPipeSource != 0) { 5749 size_t framesToRead = mBufferSize / mFrameSize; 5750 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize, 5751 framesToRead, AudioBufferProvider::kInvalidPTS); 5752 if (framesRead == 0) { 5753 // since pipe is non-blocking, simulate blocking input 5754 sleepUs = (framesToRead * 1000000LL) / mSampleRate; 5755 } 5756 // otherwise use the HAL / AudioStreamIn directly 5757 } else { 5758 ssize_t bytesRead = mInput->stream->read(mInput->stream, 5759 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize); 5760 if (bytesRead < 0) { 5761 framesRead = bytesRead; 5762 } else { 5763 framesRead = bytesRead / mFrameSize; 5764 } 5765 } 5766 5767 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) { 5768 ALOGE("read failed: framesRead=%d", framesRead); 5769 // Force input into standby so that it tries to recover at next read attempt 5770 inputStandBy(); 5771 sleepUs = kRecordThreadSleepUs; 5772 } 5773 if (framesRead <= 0) { 5774 goto unlock; 5775 } 5776 ALOG_ASSERT(framesRead > 0); 5777 5778 if (mTeeSink != 0) { 5779 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead); 5780 } 5781 // If destination is non-contiguous, we now correct for reading past end of buffer. 5782 { 5783 size_t part1 = mRsmpInFramesP2 - rear; 5784 if ((size_t) framesRead > part1) { 5785 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize, 5786 (framesRead - part1) * mFrameSize); 5787 } 5788 } 5789 rear = mRsmpInRear += framesRead; 5790 5791 size = activeTracks.size(); 5792 // loop over each active track 5793 for (size_t i = 0; i < size; i++) { 5794 activeTrack = activeTracks[i]; 5795 5796 // skip fast tracks, as those are handled directly by FastCapture 5797 if (activeTrack->isFastTrack()) { 5798 continue; 5799 } 5800 5801 // TODO: This code probably should be moved to RecordTrack. 5802 // TODO: Update the activeTrack buffer converter in case of reconfigure. 5803 5804 enum { 5805 OVERRUN_UNKNOWN, 5806 OVERRUN_TRUE, 5807 OVERRUN_FALSE 5808 } overrun = OVERRUN_UNKNOWN; 5809 5810 // loop over getNextBuffer to handle circular sink 5811 for (;;) { 5812 5813 activeTrack->mSink.frameCount = ~0; 5814 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink); 5815 size_t framesOut = activeTrack->mSink.frameCount; 5816 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0)); 5817 5818 // check available frames and handle overrun conditions 5819 // if the record track isn't draining fast enough. 5820 bool hasOverrun; 5821 size_t framesIn; 5822 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun); 5823 if (hasOverrun) { 5824 overrun = OVERRUN_TRUE; 5825 } 5826 if (framesOut == 0 || framesIn == 0) { 5827 break; 5828 } 5829 5830 // Don't allow framesOut to be larger than what is possible with resampling 5831 // from framesIn. 5832 // This isn't strictly necessary but helps limit buffer resizing in 5833 // RecordBufferConverter. TODO: remove when no longer needed. 5834 framesOut = min(framesOut, 5835 destinationFramesPossible( 5836 framesIn, mSampleRate, activeTrack->mSampleRate)); 5837 // process frames from the RecordThread buffer provider to the RecordTrack buffer 5838 framesOut = activeTrack->mRecordBufferConverter->convert( 5839 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut); 5840 5841 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) { 5842 overrun = OVERRUN_FALSE; 5843 } 5844 5845 if (activeTrack->mFramesToDrop == 0) { 5846 if (framesOut > 0) { 5847 activeTrack->mSink.frameCount = framesOut; 5848 activeTrack->releaseBuffer(&activeTrack->mSink); 5849 } 5850 } else { 5851 // FIXME could do a partial drop of framesOut 5852 if (activeTrack->mFramesToDrop > 0) { 5853 activeTrack->mFramesToDrop -= framesOut; 5854 if (activeTrack->mFramesToDrop <= 0) { 5855 activeTrack->clearSyncStartEvent(); 5856 } 5857 } else { 5858 activeTrack->mFramesToDrop += framesOut; 5859 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 || 5860 activeTrack->mSyncStartEvent->isCancelled()) { 5861 ALOGW("Synced record %s, session %d, trigger session %d", 5862 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled", 5863 activeTrack->sessionId(), 5864 (activeTrack->mSyncStartEvent != 0) ? 5865 activeTrack->mSyncStartEvent->triggerSession() : 0); 5866 activeTrack->clearSyncStartEvent(); 5867 } 5868 } 5869 } 5870 5871 if (framesOut == 0) { 5872 break; 5873 } 5874 } 5875 5876 switch (overrun) { 5877 case OVERRUN_TRUE: 5878 // client isn't retrieving buffers fast enough 5879 if (!activeTrack->setOverflow()) { 5880 nsecs_t now = systemTime(); 5881 // FIXME should lastWarning per track? 5882 if ((now - lastWarning) > kWarningThrottleNs) { 5883 ALOGW("RecordThread: buffer overflow"); 5884 lastWarning = now; 5885 } 5886 } 5887 break; 5888 case OVERRUN_FALSE: 5889 activeTrack->clearOverflow(); 5890 break; 5891 case OVERRUN_UNKNOWN: 5892 break; 5893 } 5894 5895 } 5896 5897unlock: 5898 // enable changes in effect chain 5899 unlockEffectChains(effectChains); 5900 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 5901 } 5902 5903 standbyIfNotAlreadyInStandby(); 5904 5905 { 5906 Mutex::Autolock _l(mLock); 5907 for (size_t i = 0; i < mTracks.size(); i++) { 5908 sp<RecordTrack> track = mTracks[i]; 5909 track->invalidate(); 5910 } 5911 mActiveTracks.clear(); 5912 mActiveTracksGen++; 5913 mStartStopCond.broadcast(); 5914 } 5915 5916 releaseWakeLock(); 5917 5918 ALOGV("RecordThread %p exiting", this); 5919 return false; 5920} 5921 5922void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 5923{ 5924 if (!mStandby) { 5925 inputStandBy(); 5926 mStandby = true; 5927 } 5928} 5929 5930void AudioFlinger::RecordThread::inputStandBy() 5931{ 5932 // Idle the fast capture if it's currently running 5933 if (mFastCapture != 0) { 5934 FastCaptureStateQueue *sq = mFastCapture->sq(); 5935 FastCaptureState *state = sq->begin(); 5936 if (!(state->mCommand & FastCaptureState::IDLE)) { 5937 state->mCommand = FastCaptureState::COLD_IDLE; 5938 state->mColdFutexAddr = &mFastCaptureFutex; 5939 state->mColdGen++; 5940 mFastCaptureFutex = 0; 5941 sq->end(); 5942 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 5943 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED); 5944#if 0 5945 if (kUseFastCapture == FastCapture_Dynamic) { 5946 // FIXME 5947 } 5948#endif 5949#ifdef AUDIO_WATCHDOG 5950 // FIXME 5951#endif 5952 } else { 5953 sq->end(false /*didModify*/); 5954 } 5955 } 5956 mInput->stream->common.standby(&mInput->stream->common); 5957} 5958 5959// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held 5960sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 5961 const sp<AudioFlinger::Client>& client, 5962 uint32_t sampleRate, 5963 audio_format_t format, 5964 audio_channel_mask_t channelMask, 5965 size_t *pFrameCount, 5966 int sessionId, 5967 size_t *notificationFrames, 5968 int uid, 5969 IAudioFlinger::track_flags_t *flags, 5970 pid_t tid, 5971 status_t *status) 5972{ 5973 size_t frameCount = *pFrameCount; 5974 sp<RecordTrack> track; 5975 status_t lStatus; 5976 5977 // client expresses a preference for FAST, but we get the final say 5978 if (*flags & IAudioFlinger::TRACK_FAST) { 5979 if ( 5980 // we formerly checked for a callback handler (non-0 tid), 5981 // but that is no longer required for TRANSFER_OBTAIN mode 5982 // 5983 // frame count is not specified, or is exactly the pipe depth 5984 ((frameCount == 0) || (frameCount == mPipeFramesP2)) && 5985 // PCM data 5986 audio_is_linear_pcm(format) && 5987 // native format 5988 (format == mFormat) && 5989 // native channel mask 5990 (channelMask == mChannelMask) && 5991 // native hardware sample rate 5992 (sampleRate == mSampleRate) && 5993 // record thread has an associated fast capture 5994 hasFastCapture() && 5995 // there are sufficient fast track slots available 5996 mFastTrackAvail 5997 ) { 5998 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u", 5999 frameCount, mFrameCount); 6000 } else { 6001 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u " 6002 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 6003 "hasFastCapture=%d tid=%d mFastTrackAvail=%d", 6004 frameCount, mFrameCount, mPipeFramesP2, 6005 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate, 6006 hasFastCapture(), tid, mFastTrackAvail); 6007 *flags &= ~IAudioFlinger::TRACK_FAST; 6008 } 6009 } 6010 6011 // compute track buffer size in frames, and suggest the notification frame count 6012 if (*flags & IAudioFlinger::TRACK_FAST) { 6013 // fast track: frame count is exactly the pipe depth 6014 frameCount = mPipeFramesP2; 6015 // ignore requested notificationFrames, and always notify exactly once every HAL buffer 6016 *notificationFrames = mFrameCount; 6017 } else { 6018 // not fast track: max notification period is resampled equivalent of one HAL buffer time 6019 // or 20 ms if there is a fast capture 6020 // TODO This could be a roundupRatio inline, and const 6021 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount) 6022 * sampleRate + mSampleRate - 1) / mSampleRate; 6023 // minimum number of notification periods is at least kMinNotifications, 6024 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs) 6025 static const size_t kMinNotifications = 3; 6026 static const uint32_t kMinMs = 30; 6027 // TODO This could be a roundupRatio inline 6028 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000; 6029 // TODO This could be a roundupRatio inline 6030 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) / 6031 maxNotificationFrames; 6032 const size_t minFrameCount = maxNotificationFrames * 6033 max(kMinNotifications, minNotificationsByMs); 6034 frameCount = max(frameCount, minFrameCount); 6035 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) { 6036 *notificationFrames = maxNotificationFrames; 6037 } 6038 } 6039 *pFrameCount = frameCount; 6040 6041 lStatus = initCheck(); 6042 if (lStatus != NO_ERROR) { 6043 ALOGE("createRecordTrack_l() audio driver not initialized"); 6044 goto Exit; 6045 } 6046 6047 { // scope for mLock 6048 Mutex::Autolock _l(mLock); 6049 6050 track = new RecordTrack(this, client, sampleRate, 6051 format, channelMask, frameCount, NULL, sessionId, uid, 6052 *flags, TrackBase::TYPE_DEFAULT); 6053 6054 lStatus = track->initCheck(); 6055 if (lStatus != NO_ERROR) { 6056 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 6057 // track must be cleared from the caller as the caller has the AF lock 6058 goto Exit; 6059 } 6060 mTracks.add(track); 6061 6062 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6063 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6064 mAudioFlinger->btNrecIsOff(); 6065 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 6066 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 6067 6068 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 6069 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 6070 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 6071 // so ask activity manager to do this on our behalf 6072 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 6073 } 6074 } 6075 6076 lStatus = NO_ERROR; 6077 6078Exit: 6079 *status = lStatus; 6080 return track; 6081} 6082 6083status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 6084 AudioSystem::sync_event_t event, 6085 int triggerSession) 6086{ 6087 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 6088 sp<ThreadBase> strongMe = this; 6089 status_t status = NO_ERROR; 6090 6091 if (event == AudioSystem::SYNC_EVENT_NONE) { 6092 recordTrack->clearSyncStartEvent(); 6093 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 6094 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 6095 triggerSession, 6096 recordTrack->sessionId(), 6097 syncStartEventCallback, 6098 recordTrack); 6099 // Sync event can be cancelled by the trigger session if the track is not in a 6100 // compatible state in which case we start record immediately 6101 if (recordTrack->mSyncStartEvent->isCancelled()) { 6102 recordTrack->clearSyncStartEvent(); 6103 } else { 6104 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 6105 recordTrack->mFramesToDrop = - 6106 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000); 6107 } 6108 } 6109 6110 { 6111 // This section is a rendezvous between binder thread executing start() and RecordThread 6112 AutoMutex lock(mLock); 6113 if (mActiveTracks.indexOf(recordTrack) >= 0) { 6114 if (recordTrack->mState == TrackBase::PAUSING) { 6115 ALOGV("active record track PAUSING -> ACTIVE"); 6116 recordTrack->mState = TrackBase::ACTIVE; 6117 } else { 6118 ALOGV("active record track state %d", recordTrack->mState); 6119 } 6120 return status; 6121 } 6122 6123 // TODO consider other ways of handling this, such as changing the state to :STARTING and 6124 // adding the track to mActiveTracks after returning from AudioSystem::startInput(), 6125 // or using a separate command thread 6126 recordTrack->mState = TrackBase::STARTING_1; 6127 mActiveTracks.add(recordTrack); 6128 mActiveTracksGen++; 6129 status_t status = NO_ERROR; 6130 if (recordTrack->isExternalTrack()) { 6131 mLock.unlock(); 6132 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId()); 6133 mLock.lock(); 6134 // FIXME should verify that recordTrack is still in mActiveTracks 6135 if (status != NO_ERROR) { 6136 mActiveTracks.remove(recordTrack); 6137 mActiveTracksGen++; 6138 recordTrack->clearSyncStartEvent(); 6139 ALOGV("RecordThread::start error %d", status); 6140 return status; 6141 } 6142 } 6143 // Catch up with current buffer indices if thread is already running. 6144 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront 6145 // was initialized to some value closer to the thread's mRsmpInFront, then the track could 6146 // see previously buffered data before it called start(), but with greater risk of overrun. 6147 6148 recordTrack->mResamplerBufferProvider->reset(); 6149 // clear any converter state as new data will be discontinuous 6150 recordTrack->mRecordBufferConverter->reset(); 6151 recordTrack->mState = TrackBase::STARTING_2; 6152 // signal thread to start 6153 mWaitWorkCV.broadcast(); 6154 if (mActiveTracks.indexOf(recordTrack) < 0) { 6155 ALOGV("Record failed to start"); 6156 status = BAD_VALUE; 6157 goto startError; 6158 } 6159 return status; 6160 } 6161 6162startError: 6163 if (recordTrack->isExternalTrack()) { 6164 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId()); 6165 } 6166 recordTrack->clearSyncStartEvent(); 6167 // FIXME I wonder why we do not reset the state here? 6168 return status; 6169} 6170 6171void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 6172{ 6173 sp<SyncEvent> strongEvent = event.promote(); 6174 6175 if (strongEvent != 0) { 6176 sp<RefBase> ptr = strongEvent->cookie().promote(); 6177 if (ptr != 0) { 6178 RecordTrack *recordTrack = (RecordTrack *)ptr.get(); 6179 recordTrack->handleSyncStartEvent(strongEvent); 6180 } 6181 } 6182} 6183 6184bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 6185 ALOGV("RecordThread::stop"); 6186 AutoMutex _l(mLock); 6187 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 6188 return false; 6189 } 6190 // note that threadLoop may still be processing the track at this point [without lock] 6191 recordTrack->mState = TrackBase::PAUSING; 6192 // do not wait for mStartStopCond if exiting 6193 if (exitPending()) { 6194 return true; 6195 } 6196 // FIXME incorrect usage of wait: no explicit predicate or loop 6197 mStartStopCond.wait(mLock); 6198 // if we have been restarted, recordTrack is in mActiveTracks here 6199 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 6200 ALOGV("Record stopped OK"); 6201 return true; 6202 } 6203 return false; 6204} 6205 6206bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 6207{ 6208 return false; 6209} 6210 6211status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 6212{ 6213#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 6214 if (!isValidSyncEvent(event)) { 6215 return BAD_VALUE; 6216 } 6217 6218 int eventSession = event->triggerSession(); 6219 status_t ret = NAME_NOT_FOUND; 6220 6221 Mutex::Autolock _l(mLock); 6222 6223 for (size_t i = 0; i < mTracks.size(); i++) { 6224 sp<RecordTrack> track = mTracks[i]; 6225 if (eventSession == track->sessionId()) { 6226 (void) track->setSyncEvent(event); 6227 ret = NO_ERROR; 6228 } 6229 } 6230 return ret; 6231#else 6232 return BAD_VALUE; 6233#endif 6234} 6235 6236// destroyTrack_l() must be called with ThreadBase::mLock held 6237void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 6238{ 6239 track->terminate(); 6240 track->mState = TrackBase::STOPPED; 6241 // active tracks are removed by threadLoop() 6242 if (mActiveTracks.indexOf(track) < 0) { 6243 removeTrack_l(track); 6244 } 6245} 6246 6247void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 6248{ 6249 mTracks.remove(track); 6250 // need anything related to effects here? 6251 if (track->isFastTrack()) { 6252 ALOG_ASSERT(!mFastTrackAvail); 6253 mFastTrackAvail = true; 6254 } 6255} 6256 6257void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 6258{ 6259 dumpInternals(fd, args); 6260 dumpTracks(fd, args); 6261 dumpEffectChains(fd, args); 6262} 6263 6264void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 6265{ 6266 dprintf(fd, "\nInput thread %p:\n", this); 6267 6268 dumpBase(fd, args); 6269 6270 if (mActiveTracks.size() == 0) { 6271 dprintf(fd, " No active record clients\n"); 6272 } 6273 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no"); 6274 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no"); 6275 6276 // Make a non-atomic copy of fast capture dump state so it won't change underneath us 6277 const FastCaptureDumpState copy(mFastCaptureDumpState); 6278 copy.dump(fd); 6279} 6280 6281void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 6282{ 6283 const size_t SIZE = 256; 6284 char buffer[SIZE]; 6285 String8 result; 6286 6287 size_t numtracks = mTracks.size(); 6288 size_t numactive = mActiveTracks.size(); 6289 size_t numactiveseen = 0; 6290 dprintf(fd, " %d Tracks", numtracks); 6291 if (numtracks) { 6292 dprintf(fd, " of which %d are active\n", numactive); 6293 RecordTrack::appendDumpHeader(result); 6294 for (size_t i = 0; i < numtracks ; ++i) { 6295 sp<RecordTrack> track = mTracks[i]; 6296 if (track != 0) { 6297 bool active = mActiveTracks.indexOf(track) >= 0; 6298 if (active) { 6299 numactiveseen++; 6300 } 6301 track->dump(buffer, SIZE, active); 6302 result.append(buffer); 6303 } 6304 } 6305 } else { 6306 dprintf(fd, "\n"); 6307 } 6308 6309 if (numactiveseen != numactive) { 6310 snprintf(buffer, SIZE, " The following tracks are in the active list but" 6311 " not in the track list\n"); 6312 result.append(buffer); 6313 RecordTrack::appendDumpHeader(result); 6314 for (size_t i = 0; i < numactive; ++i) { 6315 sp<RecordTrack> track = mActiveTracks[i]; 6316 if (mTracks.indexOf(track) < 0) { 6317 track->dump(buffer, SIZE, true); 6318 result.append(buffer); 6319 } 6320 } 6321 6322 } 6323 write(fd, result.string(), result.size()); 6324} 6325 6326 6327void AudioFlinger::RecordThread::ResamplerBufferProvider::reset() 6328{ 6329 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6330 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6331 mRsmpInFront = recordThread->mRsmpInRear; 6332 mRsmpInUnrel = 0; 6333} 6334 6335void AudioFlinger::RecordThread::ResamplerBufferProvider::sync( 6336 size_t *framesAvailable, bool *hasOverrun) 6337{ 6338 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6339 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6340 const int32_t rear = recordThread->mRsmpInRear; 6341 const int32_t front = mRsmpInFront; 6342 const ssize_t filled = rear - front; 6343 6344 size_t framesIn; 6345 bool overrun = false; 6346 if (filled < 0) { 6347 // should not happen, but treat like a massive overrun and re-sync 6348 framesIn = 0; 6349 mRsmpInFront = rear; 6350 overrun = true; 6351 } else if ((size_t) filled <= recordThread->mRsmpInFrames) { 6352 framesIn = (size_t) filled; 6353 } else { 6354 // client is not keeping up with server, but give it latest data 6355 framesIn = recordThread->mRsmpInFrames; 6356 mRsmpInFront = /* front = */ rear - framesIn; 6357 overrun = true; 6358 } 6359 if (framesAvailable != NULL) { 6360 *framesAvailable = framesIn; 6361 } 6362 if (hasOverrun != NULL) { 6363 *hasOverrun = overrun; 6364 } 6365} 6366 6367// AudioBufferProvider interface 6368status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer( 6369 AudioBufferProvider::Buffer* buffer, int64_t pts __unused) 6370{ 6371 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6372 if (threadBase == 0) { 6373 buffer->frameCount = 0; 6374 buffer->raw = NULL; 6375 return NOT_ENOUGH_DATA; 6376 } 6377 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6378 int32_t rear = recordThread->mRsmpInRear; 6379 int32_t front = mRsmpInFront; 6380 ssize_t filled = rear - front; 6381 // FIXME should not be P2 (don't want to increase latency) 6382 // FIXME if client not keeping up, discard 6383 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames)); 6384 // 'filled' may be non-contiguous, so return only the first contiguous chunk 6385 front &= recordThread->mRsmpInFramesP2 - 1; 6386 size_t part1 = recordThread->mRsmpInFramesP2 - front; 6387 if (part1 > (size_t) filled) { 6388 part1 = filled; 6389 } 6390 size_t ask = buffer->frameCount; 6391 ALOG_ASSERT(ask > 0); 6392 if (part1 > ask) { 6393 part1 = ask; 6394 } 6395 if (part1 == 0) { 6396 // out of data is fine since the resampler will return a short-count. 6397 buffer->raw = NULL; 6398 buffer->frameCount = 0; 6399 mRsmpInUnrel = 0; 6400 return NOT_ENOUGH_DATA; 6401 } 6402 6403 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize; 6404 buffer->frameCount = part1; 6405 mRsmpInUnrel = part1; 6406 return NO_ERROR; 6407} 6408 6409// AudioBufferProvider interface 6410void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer( 6411 AudioBufferProvider::Buffer* buffer) 6412{ 6413 size_t stepCount = buffer->frameCount; 6414 if (stepCount == 0) { 6415 return; 6416 } 6417 ALOG_ASSERT(stepCount <= mRsmpInUnrel); 6418 mRsmpInUnrel -= stepCount; 6419 mRsmpInFront += stepCount; 6420 buffer->raw = NULL; 6421 buffer->frameCount = 0; 6422} 6423 6424AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter( 6425 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat, 6426 uint32_t srcSampleRate, 6427 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat, 6428 uint32_t dstSampleRate) : 6429 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars 6430 // mSrcFormat 6431 // mSrcSampleRate 6432 // mDstChannelMask 6433 // mDstFormat 6434 // mDstSampleRate 6435 // mSrcChannelCount 6436 // mDstChannelCount 6437 // mDstFrameSize 6438 mBuf(NULL), mBufFrames(0), mBufFrameSize(0), 6439 mResampler(NULL), 6440 mIsLegacyDownmix(false), 6441 mIsLegacyUpmix(false), 6442 mRequiresFloat(false), 6443 mInputConverterProvider(NULL) 6444{ 6445 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate, 6446 dstChannelMask, dstFormat, dstSampleRate); 6447} 6448 6449AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() { 6450 free(mBuf); 6451 delete mResampler; 6452 delete mInputConverterProvider; 6453} 6454 6455size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst, 6456 AudioBufferProvider *provider, size_t frames) 6457{ 6458 if (mInputConverterProvider != NULL) { 6459 mInputConverterProvider->setBufferProvider(provider); 6460 provider = mInputConverterProvider; 6461 } 6462 6463 if (mResampler == NULL) { 6464 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x", 6465 mSrcSampleRate, mSrcFormat, mDstFormat); 6466 6467 AudioBufferProvider::Buffer buffer; 6468 for (size_t i = frames; i > 0; ) { 6469 buffer.frameCount = i; 6470 status_t status = provider->getNextBuffer(&buffer, 0); 6471 if (status != OK || buffer.frameCount == 0) { 6472 frames -= i; // cannot fill request. 6473 break; 6474 } 6475 // format convert to destination buffer 6476 convertNoResampler(dst, buffer.raw, buffer.frameCount); 6477 6478 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize; 6479 i -= buffer.frameCount; 6480 provider->releaseBuffer(&buffer); 6481 } 6482 } else { 6483 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x", 6484 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat); 6485 6486 // reallocate buffer if needed 6487 if (mBufFrameSize != 0 && mBufFrames < frames) { 6488 free(mBuf); 6489 mBufFrames = frames; 6490 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize); 6491 } 6492 // resampler accumulates, but we only have one source track 6493 memset(mBuf, 0, frames * mBufFrameSize); 6494 frames = mResampler->resample((int32_t*)mBuf, frames, provider); 6495 // format convert to destination buffer 6496 convertResampler(dst, mBuf, frames); 6497 } 6498 return frames; 6499} 6500 6501status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters( 6502 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat, 6503 uint32_t srcSampleRate, 6504 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat, 6505 uint32_t dstSampleRate) 6506{ 6507 // quick evaluation if there is any change. 6508 if (mSrcFormat == srcFormat 6509 && mSrcChannelMask == srcChannelMask 6510 && mSrcSampleRate == srcSampleRate 6511 && mDstFormat == dstFormat 6512 && mDstChannelMask == dstChannelMask 6513 && mDstSampleRate == dstSampleRate) { 6514 return NO_ERROR; 6515 } 6516 6517 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x" 6518 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u", 6519 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate); 6520 const bool valid = 6521 audio_is_input_channel(srcChannelMask) 6522 && audio_is_input_channel(dstChannelMask) 6523 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat) 6524 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat) 6525 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) 6526 ; // no upsampling checks for now 6527 if (!valid) { 6528 return BAD_VALUE; 6529 } 6530 6531 mSrcFormat = srcFormat; 6532 mSrcChannelMask = srcChannelMask; 6533 mSrcSampleRate = srcSampleRate; 6534 mDstFormat = dstFormat; 6535 mDstChannelMask = dstChannelMask; 6536 mDstSampleRate = dstSampleRate; 6537 6538 // compute derived parameters 6539 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask); 6540 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask); 6541 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat); 6542 6543 // do we need to resample? 6544 delete mResampler; 6545 mResampler = NULL; 6546 if (mSrcSampleRate != mDstSampleRate) { 6547 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT, 6548 mSrcChannelCount, mDstSampleRate); 6549 mResampler->setSampleRate(mSrcSampleRate); 6550 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT); 6551 } 6552 6553 // are we running legacy channel conversion modes? 6554 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO 6555 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK) 6556 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO; 6557 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO 6558 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO 6559 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK); 6560 6561 // do we need to process in float? 6562 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix; 6563 6564 // do we need a staging buffer to convert for destination (we can still optimize this)? 6565 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity 6566 if (mResampler != NULL) { 6567 mBufFrameSize = max(mSrcChannelCount, FCC_2) 6568 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT); 6569 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) { 6570 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT); 6571 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) { 6572 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat); 6573 } else { 6574 mBufFrameSize = 0; 6575 } 6576 mBufFrames = 0; // force the buffer to be resized. 6577 6578 // do we need an input converter buffer provider to give us float? 6579 delete mInputConverterProvider; 6580 mInputConverterProvider = NULL; 6581 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) { 6582 mInputConverterProvider = new ReformatBufferProvider( 6583 audio_channel_count_from_in_mask(mSrcChannelMask), 6584 mSrcFormat, 6585 AUDIO_FORMAT_PCM_FLOAT, 6586 256 /* provider buffer frame count */); 6587 } 6588 6589 // do we need a remixer to do channel mask conversion 6590 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) { 6591 (void) memcpy_by_index_array_initialization_from_channel_mask( 6592 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask); 6593 } 6594 return NO_ERROR; 6595} 6596 6597void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler( 6598 void *dst, const void *src, size_t frames) 6599{ 6600 // src is native type unless there is legacy upmix or downmix, whereupon it is float. 6601 if (mBufFrameSize != 0 && mBufFrames < frames) { 6602 free(mBuf); 6603 mBufFrames = frames; 6604 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize); 6605 } 6606 // do we need to do legacy upmix and downmix? 6607 if (mIsLegacyUpmix || mIsLegacyDownmix) { 6608 void *dstBuf = mBuf != NULL ? mBuf : dst; 6609 if (mIsLegacyUpmix) { 6610 upmix_to_stereo_float_from_mono_float((float *)dstBuf, 6611 (const float *)src, frames); 6612 } else /*mIsLegacyDownmix */ { 6613 downmix_to_mono_float_from_stereo_float((float *)dstBuf, 6614 (const float *)src, frames); 6615 } 6616 if (mBuf != NULL) { 6617 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT, 6618 frames * mDstChannelCount); 6619 } 6620 return; 6621 } 6622 // do we need to do channel mask conversion? 6623 if (mSrcChannelMask != mDstChannelMask) { 6624 void *dstBuf = mBuf != NULL ? mBuf : dst; 6625 memcpy_by_index_array(dstBuf, mDstChannelCount, 6626 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames); 6627 if (dstBuf == dst) { 6628 return; // format is the same 6629 } 6630 } 6631 // convert to destination buffer 6632 const void *convertBuf = mBuf != NULL ? mBuf : src; 6633 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat, 6634 frames * mDstChannelCount); 6635} 6636 6637void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler( 6638 void *dst, /*not-a-const*/ void *src, size_t frames) 6639{ 6640 // src buffer format is ALWAYS float when entering this routine 6641 if (mIsLegacyUpmix) { 6642 ; // mono to stereo already handled by resampler 6643 } else if (mIsLegacyDownmix 6644 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) { 6645 // the resampler outputs stereo for mono input channel (a feature?) 6646 // must convert to mono 6647 downmix_to_mono_float_from_stereo_float((float *)src, 6648 (const float *)src, frames); 6649 } else if (mSrcChannelMask != mDstChannelMask) { 6650 // convert to mono channel again for channel mask conversion (could be skipped 6651 // with further optimization). 6652 if (mSrcChannelCount == 1) { 6653 downmix_to_mono_float_from_stereo_float((float *)src, 6654 (const float *)src, frames); 6655 } 6656 // convert to destination format (in place, OK as float is larger than other types) 6657 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) { 6658 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT, 6659 frames * mSrcChannelCount); 6660 } 6661 // channel convert and save to dst 6662 memcpy_by_index_array(dst, mDstChannelCount, 6663 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames); 6664 return; 6665 } 6666 // convert to destination format and save to dst 6667 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT, 6668 frames * mDstChannelCount); 6669} 6670 6671bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair, 6672 status_t& status) 6673{ 6674 bool reconfig = false; 6675 6676 status = NO_ERROR; 6677 6678 audio_format_t reqFormat = mFormat; 6679 uint32_t samplingRate = mSampleRate; 6680 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount); 6681 // possible that we are > 2 channels, use channel index mask 6682 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) { 6683 audio_channel_mask_for_index_assignment_from_count(mChannelCount); 6684 } 6685 6686 AudioParameter param = AudioParameter(keyValuePair); 6687 int value; 6688 // TODO Investigate when this code runs. Check with audio policy when a sample rate and 6689 // channel count change can be requested. Do we mandate the first client defines the 6690 // HAL sampling rate and channel count or do we allow changes on the fly? 6691 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 6692 samplingRate = value; 6693 reconfig = true; 6694 } 6695 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 6696 if (!audio_is_linear_pcm((audio_format_t) value)) { 6697 status = BAD_VALUE; 6698 } else { 6699 reqFormat = (audio_format_t) value; 6700 reconfig = true; 6701 } 6702 } 6703 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 6704 audio_channel_mask_t mask = (audio_channel_mask_t) value; 6705 if (!audio_is_input_channel(mask) || 6706 audio_channel_count_from_in_mask(mask) > FCC_8) { 6707 status = BAD_VALUE; 6708 } else { 6709 channelMask = mask; 6710 reconfig = true; 6711 } 6712 } 6713 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 6714 // do not accept frame count changes if tracks are open as the track buffer 6715 // size depends on frame count and correct behavior would not be guaranteed 6716 // if frame count is changed after track creation 6717 if (mActiveTracks.size() > 0) { 6718 status = INVALID_OPERATION; 6719 } else { 6720 reconfig = true; 6721 } 6722 } 6723 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 6724 // forward device change to effects that have requested to be 6725 // aware of attached audio device. 6726 for (size_t i = 0; i < mEffectChains.size(); i++) { 6727 mEffectChains[i]->setDevice_l(value); 6728 } 6729 6730 // store input device and output device but do not forward output device to audio HAL. 6731 // Note that status is ignored by the caller for output device 6732 // (see AudioFlinger::setParameters() 6733 if (audio_is_output_devices(value)) { 6734 mOutDevice = value; 6735 status = BAD_VALUE; 6736 } else { 6737 mInDevice = value; 6738 // disable AEC and NS if the device is a BT SCO headset supporting those 6739 // pre processings 6740 if (mTracks.size() > 0) { 6741 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6742 mAudioFlinger->btNrecIsOff(); 6743 for (size_t i = 0; i < mTracks.size(); i++) { 6744 sp<RecordTrack> track = mTracks[i]; 6745 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6746 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6747 } 6748 } 6749 } 6750 } 6751 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 6752 mAudioSource != (audio_source_t)value) { 6753 // forward device change to effects that have requested to be 6754 // aware of attached audio device. 6755 for (size_t i = 0; i < mEffectChains.size(); i++) { 6756 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 6757 } 6758 mAudioSource = (audio_source_t)value; 6759 } 6760 6761 if (status == NO_ERROR) { 6762 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6763 keyValuePair.string()); 6764 if (status == INVALID_OPERATION) { 6765 inputStandBy(); 6766 status = mInput->stream->common.set_parameters(&mInput->stream->common, 6767 keyValuePair.string()); 6768 } 6769 if (reconfig) { 6770 if (status == BAD_VALUE && 6771 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) && 6772 audio_is_linear_pcm(reqFormat) && 6773 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 6774 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) && 6775 audio_channel_count_from_in_mask( 6776 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) { 6777 status = NO_ERROR; 6778 } 6779 if (status == NO_ERROR) { 6780 readInputParameters_l(); 6781 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 6782 } 6783 } 6784 } 6785 6786 return reconfig; 6787} 6788 6789String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 6790{ 6791 Mutex::Autolock _l(mLock); 6792 if (initCheck() != NO_ERROR) { 6793 return String8(); 6794 } 6795 6796 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 6797 const String8 out_s8(s); 6798 free(s); 6799 return out_s8; 6800} 6801 6802void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) { 6803 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 6804 6805 desc->mIoHandle = mId; 6806 6807 switch (event) { 6808 case AUDIO_INPUT_OPENED: 6809 case AUDIO_INPUT_CONFIG_CHANGED: 6810 desc->mPatch = mPatch; 6811 desc->mChannelMask = mChannelMask; 6812 desc->mSamplingRate = mSampleRate; 6813 desc->mFormat = mFormat; 6814 desc->mFrameCount = mFrameCount; 6815 desc->mLatency = 0; 6816 break; 6817 6818 case AUDIO_INPUT_CLOSED: 6819 default: 6820 break; 6821 } 6822 mAudioFlinger->ioConfigChanged(event, desc); 6823} 6824 6825void AudioFlinger::RecordThread::readInputParameters_l() 6826{ 6827 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 6828 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 6829 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 6830 if (mChannelCount > FCC_8) { 6831 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8); 6832 } 6833 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common); 6834 mFormat = mHALFormat; 6835 if (!audio_is_linear_pcm(mFormat)) { 6836 ALOGE("HAL format %#x is not linear pcm", mFormat); 6837 } 6838 mFrameSize = audio_stream_in_frame_size(mInput->stream); 6839 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 6840 mFrameCount = mBufferSize / mFrameSize; 6841 // This is the formula for calculating the temporary buffer size. 6842 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to 6843 // 1 full output buffer, regardless of the alignment of the available input. 6844 // The value is somewhat arbitrary, and could probably be even larger. 6845 // A larger value should allow more old data to be read after a track calls start(), 6846 // without increasing latency. 6847 // 6848 // Note this is independent of the maximum downsampling ratio permitted for capture. 6849 mRsmpInFrames = mFrameCount * 7; 6850 mRsmpInFramesP2 = roundup(mRsmpInFrames); 6851 free(mRsmpInBuffer); 6852 6853 // TODO optimize audio capture buffer sizes ... 6854 // Here we calculate the size of the sliding buffer used as a source 6855 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7). 6856 // For current HAL frame counts, this is usually 2048 = 40 ms. It would 6857 // be better to have it derived from the pipe depth in the long term. 6858 // The current value is higher than necessary. However it should not add to latency. 6859 6860 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 6861 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize); 6862 6863 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints. 6864 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks? 6865} 6866 6867uint32_t AudioFlinger::RecordThread::getInputFramesLost() 6868{ 6869 Mutex::Autolock _l(mLock); 6870 if (initCheck() != NO_ERROR) { 6871 return 0; 6872 } 6873 6874 return mInput->stream->get_input_frames_lost(mInput->stream); 6875} 6876 6877uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 6878{ 6879 Mutex::Autolock _l(mLock); 6880 uint32_t result = 0; 6881 if (getEffectChain_l(sessionId) != 0) { 6882 result = EFFECT_SESSION; 6883 } 6884 6885 for (size_t i = 0; i < mTracks.size(); ++i) { 6886 if (sessionId == mTracks[i]->sessionId()) { 6887 result |= TRACK_SESSION; 6888 break; 6889 } 6890 } 6891 6892 return result; 6893} 6894 6895KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 6896{ 6897 KeyedVector<int, bool> ids; 6898 Mutex::Autolock _l(mLock); 6899 for (size_t j = 0; j < mTracks.size(); ++j) { 6900 sp<RecordThread::RecordTrack> track = mTracks[j]; 6901 int sessionId = track->sessionId(); 6902 if (ids.indexOfKey(sessionId) < 0) { 6903 ids.add(sessionId, true); 6904 } 6905 } 6906 return ids; 6907} 6908 6909AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 6910{ 6911 Mutex::Autolock _l(mLock); 6912 AudioStreamIn *input = mInput; 6913 mInput = NULL; 6914 return input; 6915} 6916 6917// this method must always be called either with ThreadBase mLock held or inside the thread loop 6918audio_stream_t* AudioFlinger::RecordThread::stream() const 6919{ 6920 if (mInput == NULL) { 6921 return NULL; 6922 } 6923 return &mInput->stream->common; 6924} 6925 6926status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 6927{ 6928 // only one chain per input thread 6929 if (mEffectChains.size() != 0) { 6930 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this); 6931 return INVALID_OPERATION; 6932 } 6933 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 6934 chain->setThread(this); 6935 chain->setInBuffer(NULL); 6936 chain->setOutBuffer(NULL); 6937 6938 checkSuspendOnAddEffectChain_l(chain); 6939 6940 // make sure enabled pre processing effects state is communicated to the HAL as we 6941 // just moved them to a new input stream. 6942 chain->syncHalEffectsState(); 6943 6944 mEffectChains.add(chain); 6945 6946 return NO_ERROR; 6947} 6948 6949size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 6950{ 6951 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 6952 ALOGW_IF(mEffectChains.size() != 1, 6953 "removeEffectChain_l() %p invalid chain size %d on thread %p", 6954 chain.get(), mEffectChains.size(), this); 6955 if (mEffectChains.size() == 1) { 6956 mEffectChains.removeAt(0); 6957 } 6958 return 0; 6959} 6960 6961status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch, 6962 audio_patch_handle_t *handle) 6963{ 6964 status_t status = NO_ERROR; 6965 6966 // store new device and send to effects 6967 mInDevice = patch->sources[0].ext.device.type; 6968 mPatch = *patch; 6969 for (size_t i = 0; i < mEffectChains.size(); i++) { 6970 mEffectChains[i]->setDevice_l(mInDevice); 6971 } 6972 6973 // disable AEC and NS if the device is a BT SCO headset supporting those 6974 // pre processings 6975 if (mTracks.size() > 0) { 6976 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6977 mAudioFlinger->btNrecIsOff(); 6978 for (size_t i = 0; i < mTracks.size(); i++) { 6979 sp<RecordTrack> track = mTracks[i]; 6980 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 6981 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 6982 } 6983 } 6984 6985 // store new source and send to effects 6986 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 6987 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 6988 for (size_t i = 0; i < mEffectChains.size(); i++) { 6989 mEffectChains[i]->setAudioSource_l(mAudioSource); 6990 } 6991 } 6992 6993 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 6994 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 6995 status = hwDevice->create_audio_patch(hwDevice, 6996 patch->num_sources, 6997 patch->sources, 6998 patch->num_sinks, 6999 patch->sinks, 7000 handle); 7001 } else { 7002 char *address; 7003 if (strcmp(patch->sources[0].ext.device.address, "") != 0) { 7004 address = audio_device_address_to_parameter( 7005 patch->sources[0].ext.device.type, 7006 patch->sources[0].ext.device.address); 7007 } else { 7008 address = (char *)calloc(1, 1); 7009 } 7010 AudioParameter param = AudioParameter(String8(address)); 7011 free(address); 7012 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 7013 (int)patch->sources[0].ext.device.type); 7014 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE), 7015 (int)patch->sinks[0].ext.mix.usecase.source); 7016 status = mInput->stream->common.set_parameters(&mInput->stream->common, 7017 param.toString().string()); 7018 *handle = AUDIO_PATCH_HANDLE_NONE; 7019 } 7020 7021 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7022 7023 return status; 7024} 7025 7026status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 7027{ 7028 status_t status = NO_ERROR; 7029 7030 mInDevice = AUDIO_DEVICE_NONE; 7031 7032 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) { 7033 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice(); 7034 status = hwDevice->release_audio_patch(hwDevice, handle); 7035 } else { 7036 AudioParameter param; 7037 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0); 7038 status = mInput->stream->common.set_parameters(&mInput->stream->common, 7039 param.toString().string()); 7040 } 7041 return status; 7042} 7043 7044void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record) 7045{ 7046 Mutex::Autolock _l(mLock); 7047 mTracks.add(record); 7048} 7049 7050void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record) 7051{ 7052 Mutex::Autolock _l(mLock); 7053 destroyTrack_l(record); 7054} 7055 7056void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config) 7057{ 7058 ThreadBase::getAudioPortConfig(config); 7059 config->role = AUDIO_PORT_ROLE_SINK; 7060 config->ext.mix.hw_module = mInput->audioHwDev->handle(); 7061 config->ext.mix.usecase.source = mAudioSource; 7062} 7063 7064} // namespace android 7065