Threads.cpp revision c527a7c2b1bfd26e8f3086e1b653d56e521379d9
161277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver/* 261277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** 361277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** Copyright 2012, The Android Open Source Project 461277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** 561277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** Licensed under the Apache License, Version 2.0 (the "License"); 661277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** you may not use this file except in compliance with the License. 761277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** You may obtain a copy of the License at 861277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** 961277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** http://www.apache.org/licenses/LICENSE-2.0 1061277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** 1161277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** Unless required by applicable law or agreed to in writing, software 1261277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** distributed under the License is distributed on an "AS IS" BASIS, 1361277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1461277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** See the License for the specific language governing permissions and 1561277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver** limitations under the License. 1661277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver*/ 1761277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 1861277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 1961277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#define LOG_TAG "AudioFlinger" 2061277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver//#define LOG_NDEBUG 0 2161277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#define ATRACE_TAG ATRACE_TAG_AUDIO 2261277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 2361277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include "Configuration.h" 2461277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <math.h> 2561277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <fcntl.h> 2661277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <sys/stat.h> 2761277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <cutils/properties.h> 2861277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/AudioParameter.h> 2961277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <utils/Log.h> 3061277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <utils/Trace.h> 3161277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 3261277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <private/media/AudioTrackShared.h> 3361277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <hardware/audio.h> 3461277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <audio_effects/effect_ns.h> 3561277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <audio_effects/effect_aec.h> 3661277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <audio_utils/primitives.h> 3761277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 3861277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver// NBAIO implementations 3961277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/nbaio/AudioStreamOutSink.h> 4061277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/nbaio/MonoPipe.h> 4161277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/nbaio/MonoPipeReader.h> 4261277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/nbaio/Pipe.h> 4361277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/nbaio/PipeReader.h> 4461277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/nbaio/SourceAudioBufferProvider.h> 4561277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 4661277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <powermanager/PowerManager.h> 4761277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 4861277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <common_time/cc_helper.h> 4961277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <common_time/local_clock.h> 5061277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 5161277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include "AudioFlinger.h" 5261277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include "AudioMixer.h" 5361277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include "FastMixer.h" 5461277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include "ServiceUtilities.h" 5561277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include "SchedulingPolicyService.h" 5661277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver 5761277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#ifdef ADD_BATTERY_DATA 5861277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/IMediaPlayerService.h> 5961277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#include <media/IMediaDeathNotifier.h> 6061277b50b39015efe38c9cc5c79b31f6dd35c1f6Ben Gruver#endif 61 62#ifdef DEBUG_CPU_USAGE 63#include <cpustats/CentralTendencyStatistics.h> 64#include <cpustats/ThreadCpuUsage.h> 65#endif 66 67// ---------------------------------------------------------------------------- 68 69// Note: the following macro is used for extremely verbose logging message. In 70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 71// 0; but one side effect of this is to turn all LOGV's as well. Some messages 72// are so verbose that we want to suppress them even when we have ALOG_ASSERT 73// turned on. Do not uncomment the #def below unless you really know what you 74// are doing and want to see all of the extremely verbose messages. 75//#define VERY_VERY_VERBOSE_LOGGING 76#ifdef VERY_VERY_VERBOSE_LOGGING 77#define ALOGVV ALOGV 78#else 79#define ALOGVV(a...) do { } while(0) 80#endif 81 82namespace android { 83 84// retry counts for buffer fill timeout 85// 50 * ~20msecs = 1 second 86static const int8_t kMaxTrackRetries = 50; 87static const int8_t kMaxTrackStartupRetries = 50; 88// allow less retry attempts on direct output thread. 89// direct outputs can be a scarce resource in audio hardware and should 90// be released as quickly as possible. 91static const int8_t kMaxTrackRetriesDirect = 2; 92 93// don't warn about blocked writes or record buffer overflows more often than this 94static const nsecs_t kWarningThrottleNs = seconds(5); 95 96// RecordThread loop sleep time upon application overrun or audio HAL read error 97static const int kRecordThreadSleepUs = 5000; 98 99// maximum time to wait for setParameters to complete 100static const nsecs_t kSetParametersTimeoutNs = seconds(2); 101 102// minimum sleep time for the mixer thread loop when tracks are active but in underrun 103static const uint32_t kMinThreadSleepTimeUs = 5000; 104// maximum divider applied to the active sleep time in the mixer thread loop 105static const uint32_t kMaxThreadSleepTimeShift = 2; 106 107// minimum normal mix buffer size, expressed in milliseconds rather than frames 108static const uint32_t kMinNormalMixBufferSizeMs = 20; 109// maximum normal mix buffer size 110static const uint32_t kMaxNormalMixBufferSizeMs = 24; 111 112// Whether to use fast mixer 113static const enum { 114 FastMixer_Never, // never initialize or use: for debugging only 115 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 116 // normal mixer multiplier is 1 117 FastMixer_Static, // initialize if needed, then use all the time if initialized, 118 // multiplier is calculated based on min & max normal mixer buffer size 119 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 120 // multiplier is calculated based on min & max normal mixer buffer size 121 // FIXME for FastMixer_Dynamic: 122 // Supporting this option will require fixing HALs that can't handle large writes. 123 // For example, one HAL implementation returns an error from a large write, 124 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 125 // We could either fix the HAL implementations, or provide a wrapper that breaks 126 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 127} kUseFastMixer = FastMixer_Static; 128 129// Priorities for requestPriority 130static const int kPriorityAudioApp = 2; 131static const int kPriorityFastMixer = 3; 132 133// IAudioFlinger::createTrack() reports back to client the total size of shared memory area 134// for the track. The client then sub-divides this into smaller buffers for its use. 135// Currently the client uses double-buffering by default, but doesn't tell us about that. 136// So for now we just assume that client is double-buffered. 137// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or 138// N-buffering, so AudioFlinger could allocate the right amount of memory. 139// See the client's minBufCount and mNotificationFramesAct calculations for details. 140static const int kFastTrackMultiplier = 1; 141 142// ---------------------------------------------------------------------------- 143 144#ifdef ADD_BATTERY_DATA 145// To collect the amplifier usage 146static void addBatteryData(uint32_t params) { 147 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 148 if (service == NULL) { 149 // it already logged 150 return; 151 } 152 153 service->addBatteryData(params); 154} 155#endif 156 157 158// ---------------------------------------------------------------------------- 159// CPU Stats 160// ---------------------------------------------------------------------------- 161 162class CpuStats { 163public: 164 CpuStats(); 165 void sample(const String8 &title); 166#ifdef DEBUG_CPU_USAGE 167private: 168 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 169 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 170 171 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 172 173 int mCpuNum; // thread's current CPU number 174 int mCpukHz; // frequency of thread's current CPU in kHz 175#endif 176}; 177 178CpuStats::CpuStats() 179#ifdef DEBUG_CPU_USAGE 180 : mCpuNum(-1), mCpukHz(-1) 181#endif 182{ 183} 184 185void CpuStats::sample(const String8 &title) { 186#ifdef DEBUG_CPU_USAGE 187 // get current thread's delta CPU time in wall clock ns 188 double wcNs; 189 bool valid = mCpuUsage.sampleAndEnable(wcNs); 190 191 // record sample for wall clock statistics 192 if (valid) { 193 mWcStats.sample(wcNs); 194 } 195 196 // get the current CPU number 197 int cpuNum = sched_getcpu(); 198 199 // get the current CPU frequency in kHz 200 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 201 202 // check if either CPU number or frequency changed 203 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 204 mCpuNum = cpuNum; 205 mCpukHz = cpukHz; 206 // ignore sample for purposes of cycles 207 valid = false; 208 } 209 210 // if no change in CPU number or frequency, then record sample for cycle statistics 211 if (valid && mCpukHz > 0) { 212 double cycles = wcNs * cpukHz * 0.000001; 213 mHzStats.sample(cycles); 214 } 215 216 unsigned n = mWcStats.n(); 217 // mCpuUsage.elapsed() is expensive, so don't call it every loop 218 if ((n & 127) == 1) { 219 long long elapsed = mCpuUsage.elapsed(); 220 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 221 double perLoop = elapsed / (double) n; 222 double perLoop100 = perLoop * 0.01; 223 double perLoop1k = perLoop * 0.001; 224 double mean = mWcStats.mean(); 225 double stddev = mWcStats.stddev(); 226 double minimum = mWcStats.minimum(); 227 double maximum = mWcStats.maximum(); 228 double meanCycles = mHzStats.mean(); 229 double stddevCycles = mHzStats.stddev(); 230 double minCycles = mHzStats.minimum(); 231 double maxCycles = mHzStats.maximum(); 232 mCpuUsage.resetElapsed(); 233 mWcStats.reset(); 234 mHzStats.reset(); 235 ALOGD("CPU usage for %s over past %.1f secs\n" 236 " (%u mixer loops at %.1f mean ms per loop):\n" 237 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 238 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 239 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 240 title.string(), 241 elapsed * .000000001, n, perLoop * .000001, 242 mean * .001, 243 stddev * .001, 244 minimum * .001, 245 maximum * .001, 246 mean / perLoop100, 247 stddev / perLoop100, 248 minimum / perLoop100, 249 maximum / perLoop100, 250 meanCycles / perLoop1k, 251 stddevCycles / perLoop1k, 252 minCycles / perLoop1k, 253 maxCycles / perLoop1k); 254 255 } 256 } 257#endif 258}; 259 260// ---------------------------------------------------------------------------- 261// ThreadBase 262// ---------------------------------------------------------------------------- 263 264AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 265 audio_devices_t outDevice, audio_devices_t inDevice, type_t type) 266 : Thread(false /*canCallJava*/), 267 mType(type), 268 mAudioFlinger(audioFlinger), 269 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize 270 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters() 271 mParamStatus(NO_ERROR), 272 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 273 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 274 // mName will be set by concrete (non-virtual) subclass 275 mDeathRecipient(new PMDeathRecipient(this)) 276{ 277} 278 279AudioFlinger::ThreadBase::~ThreadBase() 280{ 281 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns 282 for (size_t i = 0; i < mConfigEvents.size(); i++) { 283 delete mConfigEvents[i]; 284 } 285 mConfigEvents.clear(); 286 287 mParamCond.broadcast(); 288 // do not lock the mutex in destructor 289 releaseWakeLock_l(); 290 if (mPowerManager != 0) { 291 sp<IBinder> binder = mPowerManager->asBinder(); 292 binder->unlinkToDeath(mDeathRecipient); 293 } 294} 295 296status_t AudioFlinger::ThreadBase::readyToRun() 297{ 298 status_t status = initCheck(); 299 if (status == NO_ERROR) { 300 ALOGI("AudioFlinger's thread %p ready to run", this); 301 } else { 302 ALOGE("No working audio driver found."); 303 } 304 return status; 305} 306 307void AudioFlinger::ThreadBase::exit() 308{ 309 ALOGV("ThreadBase::exit"); 310 // do any cleanup required for exit to succeed 311 preExit(); 312 { 313 // This lock prevents the following race in thread (uniprocessor for illustration): 314 // if (!exitPending()) { 315 // // context switch from here to exit() 316 // // exit() calls requestExit(), what exitPending() observes 317 // // exit() calls signal(), which is dropped since no waiters 318 // // context switch back from exit() to here 319 // mWaitWorkCV.wait(...); 320 // // now thread is hung 321 // } 322 AutoMutex lock(mLock); 323 requestExit(); 324 mWaitWorkCV.broadcast(); 325 } 326 // When Thread::requestExitAndWait is made virtual and this method is renamed to 327 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 328 requestExitAndWait(); 329} 330 331status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 332{ 333 status_t status; 334 335 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 336 Mutex::Autolock _l(mLock); 337 338 mNewParameters.add(keyValuePairs); 339 mWaitWorkCV.signal(); 340 // wait condition with timeout in case the thread loop has exited 341 // before the request could be processed 342 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { 343 status = mParamStatus; 344 mWaitWorkCV.signal(); 345 } else { 346 status = TIMED_OUT; 347 } 348 return status; 349} 350 351void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param) 352{ 353 Mutex::Autolock _l(mLock); 354 sendIoConfigEvent_l(event, param); 355} 356 357// sendIoConfigEvent_l() must be called with ThreadBase::mLock held 358void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param) 359{ 360 IoConfigEvent *ioEvent = new IoConfigEvent(event, param); 361 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent)); 362 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, 363 param); 364 mWaitWorkCV.signal(); 365} 366 367// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 368void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio) 369{ 370 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio); 371 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent)); 372 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d", 373 mConfigEvents.size(), pid, tid, prio); 374 mWaitWorkCV.signal(); 375} 376 377void AudioFlinger::ThreadBase::processConfigEvents() 378{ 379 mLock.lock(); 380 while (!mConfigEvents.isEmpty()) { 381 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); 382 ConfigEvent *event = mConfigEvents[0]; 383 mConfigEvents.removeAt(0); 384 // release mLock before locking AudioFlinger mLock: lock order is always 385 // AudioFlinger then ThreadBase to avoid cross deadlock 386 mLock.unlock(); 387 switch (event->type()) { 388 case CFG_EVENT_PRIO: { 389 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event); 390 // FIXME Need to understand why this has be done asynchronously 391 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(), 392 true /*asynchronous*/); 393 if (err != 0) { 394 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 395 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err); 396 } 397 } break; 398 case CFG_EVENT_IO: { 399 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event); 400 mAudioFlinger->mLock.lock(); 401 audioConfigChanged_l(ioEvent->event(), ioEvent->param()); 402 mAudioFlinger->mLock.unlock(); 403 } break; 404 default: 405 ALOGE("processConfigEvents() unknown event type %d", event->type()); 406 break; 407 } 408 delete event; 409 mLock.lock(); 410 } 411 mLock.unlock(); 412} 413 414void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) 415{ 416 const size_t SIZE = 256; 417 char buffer[SIZE]; 418 String8 result; 419 420 bool locked = AudioFlinger::dumpTryLock(mLock); 421 if (!locked) { 422 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); 423 write(fd, buffer, strlen(buffer)); 424 } 425 426 snprintf(buffer, SIZE, "io handle: %d\n", mId); 427 result.append(buffer); 428 snprintf(buffer, SIZE, "TID: %d\n", getTid()); 429 result.append(buffer); 430 snprintf(buffer, SIZE, "standby: %d\n", mStandby); 431 result.append(buffer); 432 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate); 433 result.append(buffer); 434 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount); 435 result.append(buffer); 436 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize); 437 result.append(buffer); 438 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount); 439 result.append(buffer); 440 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); 441 result.append(buffer); 442 snprintf(buffer, SIZE, "Format: %d\n", mFormat); 443 result.append(buffer); 444 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); 445 result.append(buffer); 446 447 snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); 448 result.append(buffer); 449 result.append(" Index Command"); 450 for (size_t i = 0; i < mNewParameters.size(); ++i) { 451 snprintf(buffer, SIZE, "\n %02d ", i); 452 result.append(buffer); 453 result.append(mNewParameters[i]); 454 } 455 456 snprintf(buffer, SIZE, "\n\nPending config events: \n"); 457 result.append(buffer); 458 for (size_t i = 0; i < mConfigEvents.size(); i++) { 459 mConfigEvents[i]->dump(buffer, SIZE); 460 result.append(buffer); 461 } 462 result.append("\n"); 463 464 write(fd, result.string(), result.size()); 465 466 if (locked) { 467 mLock.unlock(); 468 } 469} 470 471void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 472{ 473 const size_t SIZE = 256; 474 char buffer[SIZE]; 475 String8 result; 476 477 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); 478 write(fd, buffer, strlen(buffer)); 479 480 for (size_t i = 0; i < mEffectChains.size(); ++i) { 481 sp<EffectChain> chain = mEffectChains[i]; 482 if (chain != 0) { 483 chain->dump(fd, args); 484 } 485 } 486} 487 488void AudioFlinger::ThreadBase::acquireWakeLock() 489{ 490 Mutex::Autolock _l(mLock); 491 acquireWakeLock_l(); 492} 493 494void AudioFlinger::ThreadBase::acquireWakeLock_l() 495{ 496 if (mPowerManager == 0) { 497 // use checkService() to avoid blocking if power service is not up yet 498 sp<IBinder> binder = 499 defaultServiceManager()->checkService(String16("power")); 500 if (binder == 0) { 501 ALOGW("Thread %s cannot connect to the power manager service", mName); 502 } else { 503 mPowerManager = interface_cast<IPowerManager>(binder); 504 binder->linkToDeath(mDeathRecipient); 505 } 506 } 507 if (mPowerManager != 0) { 508 sp<IBinder> binder = new BBinder(); 509 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 510 binder, 511 String16(mName), 512 String16("media")); 513 if (status == NO_ERROR) { 514 mWakeLockToken = binder; 515 } 516 ALOGV("acquireWakeLock_l() %s status %d", mName, status); 517 } 518} 519 520void AudioFlinger::ThreadBase::releaseWakeLock() 521{ 522 Mutex::Autolock _l(mLock); 523 releaseWakeLock_l(); 524} 525 526void AudioFlinger::ThreadBase::releaseWakeLock_l() 527{ 528 if (mWakeLockToken != 0) { 529 ALOGV("releaseWakeLock_l() %s", mName); 530 if (mPowerManager != 0) { 531 mPowerManager->releaseWakeLock(mWakeLockToken, 0); 532 } 533 mWakeLockToken.clear(); 534 } 535} 536 537void AudioFlinger::ThreadBase::clearPowerManager() 538{ 539 Mutex::Autolock _l(mLock); 540 releaseWakeLock_l(); 541 mPowerManager.clear(); 542} 543 544void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) 545{ 546 sp<ThreadBase> thread = mThread.promote(); 547 if (thread != 0) { 548 thread->clearPowerManager(); 549 } 550 ALOGW("power manager service died !!!"); 551} 552 553void AudioFlinger::ThreadBase::setEffectSuspended( 554 const effect_uuid_t *type, bool suspend, int sessionId) 555{ 556 Mutex::Autolock _l(mLock); 557 setEffectSuspended_l(type, suspend, sessionId); 558} 559 560void AudioFlinger::ThreadBase::setEffectSuspended_l( 561 const effect_uuid_t *type, bool suspend, int sessionId) 562{ 563 sp<EffectChain> chain = getEffectChain_l(sessionId); 564 if (chain != 0) { 565 if (type != NULL) { 566 chain->setEffectSuspended_l(type, suspend); 567 } else { 568 chain->setEffectSuspendedAll_l(suspend); 569 } 570 } 571 572 updateSuspendedSessions_l(type, suspend, sessionId); 573} 574 575void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 576{ 577 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 578 if (index < 0) { 579 return; 580 } 581 582 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 583 mSuspendedSessions.valueAt(index); 584 585 for (size_t i = 0; i < sessionEffects.size(); i++) { 586 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i); 587 for (int j = 0; j < desc->mRefCount; j++) { 588 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 589 chain->setEffectSuspendedAll_l(true); 590 } else { 591 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 592 desc->mType.timeLow); 593 chain->setEffectSuspended_l(&desc->mType, true); 594 } 595 } 596 } 597} 598 599void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 600 bool suspend, 601 int sessionId) 602{ 603 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 604 605 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 606 607 if (suspend) { 608 if (index >= 0) { 609 sessionEffects = mSuspendedSessions.valueAt(index); 610 } else { 611 mSuspendedSessions.add(sessionId, sessionEffects); 612 } 613 } else { 614 if (index < 0) { 615 return; 616 } 617 sessionEffects = mSuspendedSessions.valueAt(index); 618 } 619 620 621 int key = EffectChain::kKeyForSuspendAll; 622 if (type != NULL) { 623 key = type->timeLow; 624 } 625 index = sessionEffects.indexOfKey(key); 626 627 sp<SuspendedSessionDesc> desc; 628 if (suspend) { 629 if (index >= 0) { 630 desc = sessionEffects.valueAt(index); 631 } else { 632 desc = new SuspendedSessionDesc(); 633 if (type != NULL) { 634 desc->mType = *type; 635 } 636 sessionEffects.add(key, desc); 637 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 638 } 639 desc->mRefCount++; 640 } else { 641 if (index < 0) { 642 return; 643 } 644 desc = sessionEffects.valueAt(index); 645 if (--desc->mRefCount == 0) { 646 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 647 sessionEffects.removeItemsAt(index); 648 if (sessionEffects.isEmpty()) { 649 ALOGV("updateSuspendedSessions_l() restore removing session %d", 650 sessionId); 651 mSuspendedSessions.removeItem(sessionId); 652 } 653 } 654 } 655 if (!sessionEffects.isEmpty()) { 656 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 657 } 658} 659 660void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 661 bool enabled, 662 int sessionId) 663{ 664 Mutex::Autolock _l(mLock); 665 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 666} 667 668void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 669 bool enabled, 670 int sessionId) 671{ 672 if (mType != RECORD) { 673 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 674 // another session. This gives the priority to well behaved effect control panels 675 // and applications not using global effects. 676 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 677 // global effects 678 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 679 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 680 } 681 } 682 683 sp<EffectChain> chain = getEffectChain_l(sessionId); 684 if (chain != 0) { 685 chain->checkSuspendOnEffectEnabled(effect, enabled); 686 } 687} 688 689// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held 690sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 691 const sp<AudioFlinger::Client>& client, 692 const sp<IEffectClient>& effectClient, 693 int32_t priority, 694 int sessionId, 695 effect_descriptor_t *desc, 696 int *enabled, 697 status_t *status) 698{ 699 sp<EffectModule> effect; 700 sp<EffectHandle> handle; 701 status_t lStatus; 702 sp<EffectChain> chain; 703 bool chainCreated = false; 704 bool effectCreated = false; 705 bool effectRegistered = false; 706 707 lStatus = initCheck(); 708 if (lStatus != NO_ERROR) { 709 ALOGW("createEffect_l() Audio driver not initialized."); 710 goto Exit; 711 } 712 713 // Do not allow effects with session ID 0 on direct output or duplicating threads 714 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format 715 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { 716 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", 717 desc->name, sessionId); 718 lStatus = BAD_VALUE; 719 goto Exit; 720 } 721 // Only Pre processor effects are allowed on input threads and only on input threads 722 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 723 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 724 desc->name, desc->flags, mType); 725 lStatus = BAD_VALUE; 726 goto Exit; 727 } 728 729 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 730 731 { // scope for mLock 732 Mutex::Autolock _l(mLock); 733 734 // check for existing effect chain with the requested audio session 735 chain = getEffectChain_l(sessionId); 736 if (chain == 0) { 737 // create a new chain for this session 738 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 739 chain = new EffectChain(this, sessionId); 740 addEffectChain_l(chain); 741 chain->setStrategy(getStrategyForSession_l(sessionId)); 742 chainCreated = true; 743 } else { 744 effect = chain->getEffectFromDesc_l(desc); 745 } 746 747 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 748 749 if (effect == 0) { 750 int id = mAudioFlinger->nextUniqueId(); 751 // Check CPU and memory usage 752 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 753 if (lStatus != NO_ERROR) { 754 goto Exit; 755 } 756 effectRegistered = true; 757 // create a new effect module if none present in the chain 758 effect = new EffectModule(this, chain, desc, id, sessionId); 759 lStatus = effect->status(); 760 if (lStatus != NO_ERROR) { 761 goto Exit; 762 } 763 lStatus = chain->addEffect_l(effect); 764 if (lStatus != NO_ERROR) { 765 goto Exit; 766 } 767 effectCreated = true; 768 769 effect->setDevice(mOutDevice); 770 effect->setDevice(mInDevice); 771 effect->setMode(mAudioFlinger->getMode()); 772 effect->setAudioSource(mAudioSource); 773 } 774 // create effect handle and connect it to effect module 775 handle = new EffectHandle(effect, client, effectClient, priority); 776 lStatus = effect->addHandle(handle.get()); 777 if (enabled != NULL) { 778 *enabled = (int)effect->isEnabled(); 779 } 780 } 781 782Exit: 783 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 784 Mutex::Autolock _l(mLock); 785 if (effectCreated) { 786 chain->removeEffect_l(effect); 787 } 788 if (effectRegistered) { 789 AudioSystem::unregisterEffect(effect->id()); 790 } 791 if (chainCreated) { 792 removeEffectChain_l(chain); 793 } 794 handle.clear(); 795 } 796 797 *status = lStatus; 798 return handle; 799} 800 801sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId) 802{ 803 Mutex::Autolock _l(mLock); 804 return getEffect_l(sessionId, effectId); 805} 806 807sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 808{ 809 sp<EffectChain> chain = getEffectChain_l(sessionId); 810 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 811} 812 813// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 814// PlaybackThread::mLock held 815status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 816{ 817 // check for existing effect chain with the requested audio session 818 int sessionId = effect->sessionId(); 819 sp<EffectChain> chain = getEffectChain_l(sessionId); 820 bool chainCreated = false; 821 822 if (chain == 0) { 823 // create a new chain for this session 824 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 825 chain = new EffectChain(this, sessionId); 826 addEffectChain_l(chain); 827 chain->setStrategy(getStrategyForSession_l(sessionId)); 828 chainCreated = true; 829 } 830 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 831 832 if (chain->getEffectFromId_l(effect->id()) != 0) { 833 ALOGW("addEffect_l() %p effect %s already present in chain %p", 834 this, effect->desc().name, chain.get()); 835 return BAD_VALUE; 836 } 837 838 status_t status = chain->addEffect_l(effect); 839 if (status != NO_ERROR) { 840 if (chainCreated) { 841 removeEffectChain_l(chain); 842 } 843 return status; 844 } 845 846 effect->setDevice(mOutDevice); 847 effect->setDevice(mInDevice); 848 effect->setMode(mAudioFlinger->getMode()); 849 effect->setAudioSource(mAudioSource); 850 return NO_ERROR; 851} 852 853void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 854 855 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 856 effect_descriptor_t desc = effect->desc(); 857 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 858 detachAuxEffect_l(effect->id()); 859 } 860 861 sp<EffectChain> chain = effect->chain().promote(); 862 if (chain != 0) { 863 // remove effect chain if removing last effect 864 if (chain->removeEffect_l(effect) == 0) { 865 removeEffectChain_l(chain); 866 } 867 } else { 868 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 869 } 870} 871 872void AudioFlinger::ThreadBase::lockEffectChains_l( 873 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 874{ 875 effectChains = mEffectChains; 876 for (size_t i = 0; i < mEffectChains.size(); i++) { 877 mEffectChains[i]->lock(); 878 } 879} 880 881void AudioFlinger::ThreadBase::unlockEffectChains( 882 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 883{ 884 for (size_t i = 0; i < effectChains.size(); i++) { 885 effectChains[i]->unlock(); 886 } 887} 888 889sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 890{ 891 Mutex::Autolock _l(mLock); 892 return getEffectChain_l(sessionId); 893} 894 895sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const 896{ 897 size_t size = mEffectChains.size(); 898 for (size_t i = 0; i < size; i++) { 899 if (mEffectChains[i]->sessionId() == sessionId) { 900 return mEffectChains[i]; 901 } 902 } 903 return 0; 904} 905 906void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 907{ 908 Mutex::Autolock _l(mLock); 909 size_t size = mEffectChains.size(); 910 for (size_t i = 0; i < size; i++) { 911 mEffectChains[i]->setMode_l(mode); 912 } 913} 914 915void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 916 EffectHandle *handle, 917 bool unpinIfLast) { 918 919 Mutex::Autolock _l(mLock); 920 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 921 // delete the effect module if removing last handle on it 922 if (effect->removeHandle(handle) == 0) { 923 if (!effect->isPinned() || unpinIfLast) { 924 removeEffect_l(effect); 925 AudioSystem::unregisterEffect(effect->id()); 926 } 927 } 928} 929 930// ---------------------------------------------------------------------------- 931// Playback 932// ---------------------------------------------------------------------------- 933 934AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 935 AudioStreamOut* output, 936 audio_io_handle_t id, 937 audio_devices_t device, 938 type_t type) 939 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type), 940 mNormalFrameCount(0), mMixBuffer(NULL), 941 mSuspended(0), mBytesWritten(0), 942 // mStreamTypes[] initialized in constructor body 943 mOutput(output), 944 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 945 mMixerStatus(MIXER_IDLE), 946 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 947 standbyDelay(AudioFlinger::mStandbyTimeInNsecs), 948 mBytesRemaining(0), 949 mCurrentWriteLength(0), 950 mUseAsyncWrite(false), 951 mWriteBlocked(false), 952 mDraining(false), 953 mScreenState(AudioFlinger::mScreenState), 954 // index 0 is reserved for normal mixer's submix 955 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1) 956{ 957 snprintf(mName, kNameLength, "AudioOut_%X", id); 958 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 959 960 // Assumes constructor is called by AudioFlinger with it's mLock held, but 961 // it would be safer to explicitly pass initial masterVolume/masterMute as 962 // parameter. 963 // 964 // If the HAL we are using has support for master volume or master mute, 965 // then do not attenuate or mute during mixing (just leave the volume at 1.0 966 // and the mute set to false). 967 mMasterVolume = audioFlinger->masterVolume_l(); 968 mMasterMute = audioFlinger->masterMute_l(); 969 if (mOutput && mOutput->audioHwDev) { 970 if (mOutput->audioHwDev->canSetMasterVolume()) { 971 mMasterVolume = 1.0; 972 } 973 974 if (mOutput->audioHwDev->canSetMasterMute()) { 975 mMasterMute = false; 976 } 977 } 978 979 readOutputParameters(); 980 981 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 982 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile 983 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; 984 stream = (audio_stream_type_t) (stream + 1)) { 985 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 986 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 987 } 988 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, 989 // because mAudioFlinger doesn't have one to copy from 990} 991 992AudioFlinger::PlaybackThread::~PlaybackThread() 993{ 994 mAudioFlinger->unregisterWriter(mNBLogWriter); 995 delete[] mMixBuffer; 996} 997 998void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 999{ 1000 dumpInternals(fd, args); 1001 dumpTracks(fd, args); 1002 dumpEffectChains(fd, args); 1003} 1004 1005void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) 1006{ 1007 const size_t SIZE = 256; 1008 char buffer[SIZE]; 1009 String8 result; 1010 1011 result.appendFormat("Output thread %p stream volumes in dB:\n ", this); 1012 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1013 const stream_type_t *st = &mStreamTypes[i]; 1014 if (i > 0) { 1015 result.appendFormat(", "); 1016 } 1017 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1018 if (st->mute) { 1019 result.append("M"); 1020 } 1021 } 1022 result.append("\n"); 1023 write(fd, result.string(), result.length()); 1024 result.clear(); 1025 1026 snprintf(buffer, SIZE, "Output thread %p tracks\n", this); 1027 result.append(buffer); 1028 Track::appendDumpHeader(result); 1029 for (size_t i = 0; i < mTracks.size(); ++i) { 1030 sp<Track> track = mTracks[i]; 1031 if (track != 0) { 1032 track->dump(buffer, SIZE); 1033 result.append(buffer); 1034 } 1035 } 1036 1037 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); 1038 result.append(buffer); 1039 Track::appendDumpHeader(result); 1040 for (size_t i = 0; i < mActiveTracks.size(); ++i) { 1041 sp<Track> track = mActiveTracks[i].promote(); 1042 if (track != 0) { 1043 track->dump(buffer, SIZE); 1044 result.append(buffer); 1045 } 1046 } 1047 write(fd, result.string(), result.size()); 1048 1049 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1050 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1051 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n", 1052 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1053} 1054 1055void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1056{ 1057 const size_t SIZE = 256; 1058 char buffer[SIZE]; 1059 String8 result; 1060 1061 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); 1062 result.append(buffer); 1063 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount); 1064 result.append(buffer); 1065 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", 1066 ns2ms(systemTime() - mLastWriteTime)); 1067 result.append(buffer); 1068 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); 1069 result.append(buffer); 1070 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); 1071 result.append(buffer); 1072 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); 1073 result.append(buffer); 1074 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); 1075 result.append(buffer); 1076 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); 1077 result.append(buffer); 1078 write(fd, result.string(), result.size()); 1079 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask); 1080 1081 dumpBase(fd, args); 1082} 1083 1084// Thread virtuals 1085 1086void AudioFlinger::PlaybackThread::onFirstRef() 1087{ 1088 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1089} 1090 1091// ThreadBase virtuals 1092void AudioFlinger::PlaybackThread::preExit() 1093{ 1094 ALOGV(" preExit()"); 1095 // FIXME this is using hard-coded strings but in the future, this functionality will be 1096 // converted to use audio HAL extensions required to support tunneling 1097 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1"); 1098} 1099 1100// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1101sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1102 const sp<AudioFlinger::Client>& client, 1103 audio_stream_type_t streamType, 1104 uint32_t sampleRate, 1105 audio_format_t format, 1106 audio_channel_mask_t channelMask, 1107 size_t frameCount, 1108 const sp<IMemory>& sharedBuffer, 1109 int sessionId, 1110 IAudioFlinger::track_flags_t *flags, 1111 pid_t tid, 1112 status_t *status) 1113{ 1114 sp<Track> track; 1115 status_t lStatus; 1116 1117 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0; 1118 1119 // client expresses a preference for FAST, but we get the final say 1120 if (*flags & IAudioFlinger::TRACK_FAST) { 1121 if ( 1122 // not timed 1123 (!isTimed) && 1124 // either of these use cases: 1125 ( 1126 // use case 1: shared buffer with any frame count 1127 ( 1128 (sharedBuffer != 0) 1129 ) || 1130 // use case 2: callback handler and frame count is default or at least as large as HAL 1131 ( 1132 (tid != -1) && 1133 ((frameCount == 0) || 1134 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 1135 ) 1136 ) && 1137 // PCM data 1138 audio_is_linear_pcm(format) && 1139 // mono or stereo 1140 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 1141 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 1142#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE 1143 // hardware sample rate 1144 (sampleRate == mSampleRate) && 1145#endif 1146 // normal mixer has an associated fast mixer 1147 hasFastMixer() && 1148 // there are sufficient fast track slots available 1149 (mFastTrackAvailMask != 0) 1150 // FIXME test that MixerThread for this fast track has a capable output HAL 1151 // FIXME add a permission test also? 1152 ) { 1153 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count 1154 if (frameCount == 0) { 1155 frameCount = mFrameCount * kFastTrackMultiplier; 1156 } 1157 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 1158 frameCount, mFrameCount); 1159 } else { 1160 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " 1161 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 1162 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1163 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, 1164 audio_is_linear_pcm(format), 1165 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1166 *flags &= ~IAudioFlinger::TRACK_FAST; 1167 // For compatibility with AudioTrack calculation, buffer depth is forced 1168 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1169 // This is probably too conservative, but legacy application code may depend on it. 1170 // If you change this calculation, also review the start threshold which is related. 1171 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); 1172 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1173 if (minBufCount < 2) { 1174 minBufCount = 2; 1175 } 1176 size_t minFrameCount = mNormalFrameCount * minBufCount; 1177 if (frameCount < minFrameCount) { 1178 frameCount = minFrameCount; 1179 } 1180 } 1181 } 1182 1183 if (mType == DIRECT) { 1184 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { 1185 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1186 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x " 1187 "for output %p with format %d", 1188 sampleRate, format, channelMask, mOutput, mFormat); 1189 lStatus = BAD_VALUE; 1190 goto Exit; 1191 } 1192 } 1193 } else if (mType == OFFLOAD) { 1194 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1195 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \"" 1196 "for output %p with format %d", 1197 sampleRate, format, channelMask, mOutput, mFormat); 1198 lStatus = BAD_VALUE; 1199 goto Exit; 1200 } 1201 } else { 1202 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) { 1203 ALOGE("createTrack_l() Bad parameter: format %d \"" 1204 "for output %p with format %d", 1205 format, mOutput, mFormat); 1206 lStatus = BAD_VALUE; 1207 goto Exit; 1208 } 1209 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 1210 if (sampleRate > mSampleRate*2) { 1211 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1212 lStatus = BAD_VALUE; 1213 goto Exit; 1214 } 1215 } 1216 1217 lStatus = initCheck(); 1218 if (lStatus != NO_ERROR) { 1219 ALOGE("Audio driver not initialized."); 1220 goto Exit; 1221 } 1222 1223 { // scope for mLock 1224 Mutex::Autolock _l(mLock); 1225 1226 // all tracks in same audio session must share the same routing strategy otherwise 1227 // conflicts will happen when tracks are moved from one output to another by audio policy 1228 // manager 1229 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1230 for (size_t i = 0; i < mTracks.size(); ++i) { 1231 sp<Track> t = mTracks[i]; 1232 if (t != 0 && !t->isOutputTrack()) { 1233 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1234 if (sessionId == t->sessionId() && strategy != actual) { 1235 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1236 strategy, actual); 1237 lStatus = BAD_VALUE; 1238 goto Exit; 1239 } 1240 } 1241 } 1242 1243 if (!isTimed) { 1244 track = new Track(this, client, streamType, sampleRate, format, 1245 channelMask, frameCount, sharedBuffer, sessionId, *flags); 1246 } else { 1247 track = TimedTrack::create(this, client, streamType, sampleRate, format, 1248 channelMask, frameCount, sharedBuffer, sessionId); 1249 } 1250 1251 // new Track always returns non-NULL, 1252 // but TimedTrack::create() is a factory that could fail by returning NULL 1253 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; 1254 if (lStatus != NO_ERROR) { 1255 track.clear(); 1256 goto Exit; 1257 } 1258 1259 mTracks.add(track); 1260 1261 sp<EffectChain> chain = getEffectChain_l(sessionId); 1262 if (chain != 0) { 1263 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1264 track->setMainBuffer(chain->inBuffer()); 1265 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 1266 chain->incTrackCnt(); 1267 } 1268 1269 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 1270 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1271 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 1272 // so ask activity manager to do this on our behalf 1273 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 1274 } 1275 } 1276 1277 lStatus = NO_ERROR; 1278 1279Exit: 1280 *status = lStatus; 1281 return track; 1282} 1283 1284uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 1285{ 1286 return latency; 1287} 1288 1289uint32_t AudioFlinger::PlaybackThread::latency() const 1290{ 1291 Mutex::Autolock _l(mLock); 1292 return latency_l(); 1293} 1294uint32_t AudioFlinger::PlaybackThread::latency_l() const 1295{ 1296 if (initCheck() == NO_ERROR) { 1297 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream)); 1298 } else { 1299 return 0; 1300 } 1301} 1302 1303void AudioFlinger::PlaybackThread::setMasterVolume(float value) 1304{ 1305 Mutex::Autolock _l(mLock); 1306 // Don't apply master volume in SW if our HAL can do it for us. 1307 if (mOutput && mOutput->audioHwDev && 1308 mOutput->audioHwDev->canSetMasterVolume()) { 1309 mMasterVolume = 1.0; 1310 } else { 1311 mMasterVolume = value; 1312 } 1313} 1314 1315void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1316{ 1317 Mutex::Autolock _l(mLock); 1318 // Don't apply master mute in SW if our HAL can do it for us. 1319 if (mOutput && mOutput->audioHwDev && 1320 mOutput->audioHwDev->canSetMasterMute()) { 1321 mMasterMute = false; 1322 } else { 1323 mMasterMute = muted; 1324 } 1325} 1326 1327void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1328{ 1329 Mutex::Autolock _l(mLock); 1330 mStreamTypes[stream].volume = value; 1331 signal_l(); 1332} 1333 1334void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1335{ 1336 Mutex::Autolock _l(mLock); 1337 mStreamTypes[stream].mute = muted; 1338 signal_l(); 1339} 1340 1341float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1342{ 1343 Mutex::Autolock _l(mLock); 1344 return mStreamTypes[stream].volume; 1345} 1346 1347// addTrack_l() must be called with ThreadBase::mLock held 1348status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1349{ 1350 status_t status = ALREADY_EXISTS; 1351 1352 // set retry count for buffer fill 1353 track->mRetryCount = kMaxTrackStartupRetries; 1354 if (mActiveTracks.indexOf(track) < 0) { 1355 // the track is newly added, make sure it fills up all its 1356 // buffers before playing. This is to ensure the client will 1357 // effectively get the latency it requested. 1358 if (!track->isOutputTrack()) { 1359 TrackBase::track_state state = track->mState; 1360 mLock.unlock(); 1361 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId()); 1362 mLock.lock(); 1363 // abort track was stopped/paused while we released the lock 1364 if (state != track->mState) { 1365 if (status == NO_ERROR) { 1366 mLock.unlock(); 1367 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1368 mLock.lock(); 1369 } 1370 return INVALID_OPERATION; 1371 } 1372 // abort if start is rejected by audio policy manager 1373 if (status != NO_ERROR) { 1374 return PERMISSION_DENIED; 1375 } 1376#ifdef ADD_BATTERY_DATA 1377 // to track the speaker usage 1378 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 1379#endif 1380 } 1381 1382 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; 1383 track->mResetDone = false; 1384 track->mPresentationCompleteFrames = 0; 1385 mActiveTracks.add(track); 1386 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1387 if (chain != 0) { 1388 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 1389 track->sessionId()); 1390 chain->incActiveTrackCnt(); 1391 } 1392 1393 status = NO_ERROR; 1394 } 1395 1396 ALOGV("mWaitWorkCV.broadcast"); 1397 mWaitWorkCV.broadcast(); 1398 1399 return status; 1400} 1401 1402bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 1403{ 1404 track->terminate(); 1405 // active tracks are removed by threadLoop() 1406 bool trackActive = (mActiveTracks.indexOf(track) >= 0); 1407 track->mState = TrackBase::STOPPED; 1408 if (!trackActive) { 1409 removeTrack_l(track); 1410 } else if (track->isFastTrack() || track->isOffloaded()) { 1411 track->mState = TrackBase::STOPPING_1; 1412 } 1413 1414 return trackActive; 1415} 1416 1417void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 1418{ 1419 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 1420 mTracks.remove(track); 1421 deleteTrackName_l(track->name()); 1422 // redundant as track is about to be destroyed, for dumpsys only 1423 track->mName = -1; 1424 if (track->isFastTrack()) { 1425 int index = track->mFastIndex; 1426 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks); 1427 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 1428 mFastTrackAvailMask |= 1 << index; 1429 // redundant as track is about to be destroyed, for dumpsys only 1430 track->mFastIndex = -1; 1431 } 1432 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1433 if (chain != 0) { 1434 chain->decTrackCnt(); 1435 } 1436} 1437 1438void AudioFlinger::PlaybackThread::signal_l() 1439{ 1440 // Thread could be blocked waiting for async 1441 // so signal it to handle state changes immediately 1442 // If threadLoop is currently unlocked a signal of mWaitWorkCV will 1443 // be lost so we also flag to prevent it blocking on mWaitWorkCV 1444 mSignalPending = true; 1445 mWaitWorkCV.signal(); 1446} 1447 1448String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 1449{ 1450 Mutex::Autolock _l(mLock); 1451 if (initCheck() != NO_ERROR) { 1452 return String8(); 1453 } 1454 1455 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); 1456 const String8 out_s8(s); 1457 free(s); 1458 return out_s8; 1459} 1460 1461// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1462void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { 1463 AudioSystem::OutputDescriptor desc; 1464 void *param2 = NULL; 1465 1466 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, 1467 param); 1468 1469 switch (event) { 1470 case AudioSystem::OUTPUT_OPENED: 1471 case AudioSystem::OUTPUT_CONFIG_CHANGED: 1472 desc.channelMask = mChannelMask; 1473 desc.samplingRate = mSampleRate; 1474 desc.format = mFormat; 1475 desc.frameCount = mNormalFrameCount; // FIXME see 1476 // AudioFlinger::frameCount(audio_io_handle_t) 1477 desc.latency = latency(); 1478 param2 = &desc; 1479 break; 1480 1481 case AudioSystem::STREAM_CONFIG_CHANGED: 1482 param2 = ¶m; 1483 case AudioSystem::OUTPUT_CLOSED: 1484 default: 1485 break; 1486 } 1487 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 1488} 1489 1490void AudioFlinger::PlaybackThread::writeCallback() 1491{ 1492 ALOG_ASSERT(mCallbackThread != 0); 1493 mCallbackThread->setWriteBlocked(false); 1494} 1495 1496void AudioFlinger::PlaybackThread::drainCallback() 1497{ 1498 ALOG_ASSERT(mCallbackThread != 0); 1499 mCallbackThread->setDraining(false); 1500} 1501 1502void AudioFlinger::PlaybackThread::setWriteBlocked(bool value) 1503{ 1504 Mutex::Autolock _l(mLock); 1505 mWriteBlocked = value; 1506 if (!value) { 1507 mWaitWorkCV.signal(); 1508 } 1509} 1510 1511void AudioFlinger::PlaybackThread::setDraining(bool value) 1512{ 1513 Mutex::Autolock _l(mLock); 1514 mDraining = value; 1515 if (!value) { 1516 mWaitWorkCV.signal(); 1517 } 1518} 1519 1520// static 1521int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event, 1522 void *param, 1523 void *cookie) 1524{ 1525 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie; 1526 ALOGV("asyncCallback() event %d", event); 1527 switch (event) { 1528 case STREAM_CBK_EVENT_WRITE_READY: 1529 me->writeCallback(); 1530 break; 1531 case STREAM_CBK_EVENT_DRAIN_READY: 1532 me->drainCallback(); 1533 break; 1534 default: 1535 ALOGW("asyncCallback() unknown event %d", event); 1536 break; 1537 } 1538 return 0; 1539} 1540 1541void AudioFlinger::PlaybackThread::readOutputParameters() 1542{ 1543 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL 1544 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); 1545 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); 1546 if (!audio_is_output_channel(mChannelMask)) { 1547 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask); 1548 } 1549 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) { 1550 LOG_FATAL("HAL channel mask %#x not supported for mixed output; " 1551 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask); 1552 } 1553 mChannelCount = popcount(mChannelMask); 1554 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); 1555 if (!audio_is_valid_format(mFormat)) { 1556 LOG_FATAL("HAL format %d not valid for output", mFormat); 1557 } 1558 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) { 1559 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT", 1560 mFormat); 1561 } 1562 mFrameSize = audio_stream_frame_size(&mOutput->stream->common); 1563 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common); 1564 mFrameCount = mBufferSize / mFrameSize; 1565 if (mFrameCount & 15) { 1566 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames", 1567 mFrameCount); 1568 } 1569 1570 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) && 1571 (mOutput->stream->set_callback != NULL)) { 1572 if (mOutput->stream->set_callback(mOutput->stream, 1573 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) { 1574 mUseAsyncWrite = true; 1575 } 1576 } 1577 1578 // Calculate size of normal mix buffer relative to the HAL output buffer size 1579 double multiplier = 1.0; 1580 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 1581 kUseFastMixer == FastMixer_Dynamic)) { 1582 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000; 1583 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000; 1584 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 1585 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 1586 maxNormalFrameCount = maxNormalFrameCount & ~15; 1587 if (maxNormalFrameCount < minNormalFrameCount) { 1588 maxNormalFrameCount = minNormalFrameCount; 1589 } 1590 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 1591 if (multiplier <= 1.0) { 1592 multiplier = 1.0; 1593 } else if (multiplier <= 2.0) { 1594 if (2 * mFrameCount <= maxNormalFrameCount) { 1595 multiplier = 2.0; 1596 } else { 1597 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 1598 } 1599 } else { 1600 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL 1601 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast 1602 // track, but we sometimes have to do this to satisfy the maximum frame count 1603 // constraint) 1604 // FIXME this rounding up should not be done if no HAL SRC 1605 uint32_t truncMult = (uint32_t) multiplier; 1606 if ((truncMult & 1)) { 1607 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { 1608 ++truncMult; 1609 } 1610 } 1611 multiplier = (double) truncMult; 1612 } 1613 } 1614 mNormalFrameCount = multiplier * mFrameCount; 1615 // round up to nearest 16 frames to satisfy AudioMixer 1616 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 1617 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, 1618 mNormalFrameCount); 1619 1620 delete[] mMixBuffer; 1621 size_t normalBufferSize = mNormalFrameCount * mFrameSize; 1622 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1) 1623 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1]; 1624 memset(mMixBuffer, 0, normalBufferSize); 1625 1626 // force reconfiguration of effect chains and engines to take new buffer size and audio 1627 // parameters into account 1628 // Note that mLock is not held when readOutputParameters() is called from the constructor 1629 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 1630 // matter. 1631 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 1632 Vector< sp<EffectChain> > effectChains = mEffectChains; 1633 for (size_t i = 0; i < effectChains.size(); i ++) { 1634 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 1635 } 1636} 1637 1638 1639status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames) 1640{ 1641 if (halFrames == NULL || dspFrames == NULL) { 1642 return BAD_VALUE; 1643 } 1644 Mutex::Autolock _l(mLock); 1645 if (initCheck() != NO_ERROR) { 1646 return INVALID_OPERATION; 1647 } 1648 size_t framesWritten = mBytesWritten / mFrameSize; 1649 *halFrames = framesWritten; 1650 1651 if (isSuspended()) { 1652 // return an estimation of rendered frames when the output is suspended 1653 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 1654 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; 1655 return NO_ERROR; 1656 } else { 1657 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 1658 } 1659} 1660 1661uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 1662{ 1663 Mutex::Autolock _l(mLock); 1664 uint32_t result = 0; 1665 if (getEffectChain_l(sessionId) != 0) { 1666 result = EFFECT_SESSION; 1667 } 1668 1669 for (size_t i = 0; i < mTracks.size(); ++i) { 1670 sp<Track> track = mTracks[i]; 1671 if (sessionId == track->sessionId() && !track->isInvalid()) { 1672 result |= TRACK_SESSION; 1673 break; 1674 } 1675 } 1676 1677 return result; 1678} 1679 1680uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 1681{ 1682 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 1683 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 1684 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1685 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1686 } 1687 for (size_t i = 0; i < mTracks.size(); i++) { 1688 sp<Track> track = mTracks[i]; 1689 if (sessionId == track->sessionId() && !track->isInvalid()) { 1690 return AudioSystem::getStrategyForStream(track->streamType()); 1691 } 1692 } 1693 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1694} 1695 1696 1697AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 1698{ 1699 Mutex::Autolock _l(mLock); 1700 return mOutput; 1701} 1702 1703AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 1704{ 1705 Mutex::Autolock _l(mLock); 1706 AudioStreamOut *output = mOutput; 1707 mOutput = NULL; 1708 // FIXME FastMixer might also have a raw ptr to mOutputSink; 1709 // must push a NULL and wait for ack 1710 mOutputSink.clear(); 1711 mPipeSink.clear(); 1712 mNormalSink.clear(); 1713 return output; 1714} 1715 1716// this method must always be called either with ThreadBase mLock held or inside the thread loop 1717audio_stream_t* AudioFlinger::PlaybackThread::stream() const 1718{ 1719 if (mOutput == NULL) { 1720 return NULL; 1721 } 1722 return &mOutput->stream->common; 1723} 1724 1725uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 1726{ 1727 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 1728} 1729 1730status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 1731{ 1732 if (!isValidSyncEvent(event)) { 1733 return BAD_VALUE; 1734 } 1735 1736 Mutex::Autolock _l(mLock); 1737 1738 for (size_t i = 0; i < mTracks.size(); ++i) { 1739 sp<Track> track = mTracks[i]; 1740 if (event->triggerSession() == track->sessionId()) { 1741 (void) track->setSyncEvent(event); 1742 return NO_ERROR; 1743 } 1744 } 1745 1746 return NAME_NOT_FOUND; 1747} 1748 1749bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 1750{ 1751 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 1752} 1753 1754void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 1755 const Vector< sp<Track> >& tracksToRemove) 1756{ 1757 size_t count = tracksToRemove.size(); 1758 if (count > 0) { 1759 for (size_t i = 0 ; i < count ; i++) { 1760 const sp<Track>& track = tracksToRemove.itemAt(i); 1761 if (!track->isOutputTrack()) { 1762 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1763#ifdef ADD_BATTERY_DATA 1764 // to track the speaker usage 1765 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 1766#endif 1767 if (track->isTerminated()) { 1768 AudioSystem::releaseOutput(mId); 1769 } 1770 } 1771 } 1772 } 1773} 1774 1775void AudioFlinger::PlaybackThread::checkSilentMode_l() 1776{ 1777 if (!mMasterMute) { 1778 char value[PROPERTY_VALUE_MAX]; 1779 if (property_get("ro.audio.silent", value, "0") > 0) { 1780 char *endptr; 1781 unsigned long ul = strtoul(value, &endptr, 0); 1782 if (*endptr == '\0' && ul != 0) { 1783 ALOGD("Silence is golden"); 1784 // The setprop command will not allow a property to be changed after 1785 // the first time it is set, so we don't have to worry about un-muting. 1786 setMasterMute_l(true); 1787 } 1788 } 1789 } 1790} 1791 1792// shared by MIXER and DIRECT, overridden by DUPLICATING 1793ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 1794{ 1795 // FIXME rewrite to reduce number of system calls 1796 mLastWriteTime = systemTime(); 1797 mInWrite = true; 1798 ssize_t bytesWritten; 1799 1800 // If an NBAIO sink is present, use it to write the normal mixer's submix 1801 if (mNormalSink != 0) { 1802#define mBitShift 2 // FIXME 1803 size_t count = mBytesRemaining >> mBitShift; 1804 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1; 1805 ATRACE_BEGIN("write"); 1806 // update the setpoint when AudioFlinger::mScreenState changes 1807 uint32_t screenState = AudioFlinger::mScreenState; 1808 if (screenState != mScreenState) { 1809 mScreenState = screenState; 1810 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 1811 if (pipe != NULL) { 1812 pipe->setAvgFrames((mScreenState & 1) ? 1813 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 1814 } 1815 } 1816 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count); 1817 ATRACE_END(); 1818 if (framesWritten > 0) { 1819 bytesWritten = framesWritten << mBitShift; 1820 } else { 1821 bytesWritten = framesWritten; 1822 } 1823 // otherwise use the HAL / AudioStreamOut directly 1824 } else { 1825 // Direct output and offload threads 1826 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t); 1827 if (mUseAsyncWrite) { 1828 mWriteBlocked = true; 1829 ALOG_ASSERT(mCallbackThread != 0); 1830 mCallbackThread->setWriteBlocked(true); 1831 } 1832 bytesWritten = mOutput->stream->write(mOutput->stream, 1833 mMixBuffer + offset, mBytesRemaining); 1834 if (mUseAsyncWrite && 1835 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 1836 // do not wait for async callback in case of error of full write 1837 mWriteBlocked = false; 1838 ALOG_ASSERT(mCallbackThread != 0); 1839 mCallbackThread->setWriteBlocked(false); 1840 } 1841 } 1842 1843 mNumWrites++; 1844 mInWrite = false; 1845 1846 return bytesWritten; 1847} 1848 1849void AudioFlinger::PlaybackThread::threadLoop_drain() 1850{ 1851 if (mOutput->stream->drain) { 1852 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 1853 if (mUseAsyncWrite) { 1854 mDraining = true; 1855 ALOG_ASSERT(mCallbackThread != 0); 1856 mCallbackThread->setDraining(true); 1857 } 1858 mOutput->stream->drain(mOutput->stream, 1859 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY 1860 : AUDIO_DRAIN_ALL); 1861 } 1862} 1863 1864void AudioFlinger::PlaybackThread::threadLoop_exit() 1865{ 1866 // Default implementation has nothing to do 1867} 1868 1869/* 1870The derived values that are cached: 1871 - mixBufferSize from frame count * frame size 1872 - activeSleepTime from activeSleepTimeUs() 1873 - idleSleepTime from idleSleepTimeUs() 1874 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 1875 - maxPeriod from frame count and sample rate (MIXER only) 1876 1877The parameters that affect these derived values are: 1878 - frame count 1879 - frame size 1880 - sample rate 1881 - device type: A2DP or not 1882 - device latency 1883 - format: PCM or not 1884 - active sleep time 1885 - idle sleep time 1886*/ 1887 1888void AudioFlinger::PlaybackThread::cacheParameters_l() 1889{ 1890 mixBufferSize = mNormalFrameCount * mFrameSize; 1891 activeSleepTime = activeSleepTimeUs(); 1892 idleSleepTime = idleSleepTimeUs(); 1893} 1894 1895void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 1896{ 1897 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 1898 this, streamType, mTracks.size()); 1899 Mutex::Autolock _l(mLock); 1900 1901 size_t size = mTracks.size(); 1902 for (size_t i = 0; i < size; i++) { 1903 sp<Track> t = mTracks[i]; 1904 if (t->streamType() == streamType) { 1905 t->invalidate(); 1906 } 1907 } 1908} 1909 1910status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 1911{ 1912 int session = chain->sessionId(); 1913 int16_t *buffer = mMixBuffer; 1914 bool ownsBuffer = false; 1915 1916 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 1917 if (session > 0) { 1918 // Only one effect chain can be present in direct output thread and it uses 1919 // the mix buffer as input 1920 if (mType != DIRECT) { 1921 size_t numSamples = mNormalFrameCount * mChannelCount; 1922 buffer = new int16_t[numSamples]; 1923 memset(buffer, 0, numSamples * sizeof(int16_t)); 1924 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 1925 ownsBuffer = true; 1926 } 1927 1928 // Attach all tracks with same session ID to this chain. 1929 for (size_t i = 0; i < mTracks.size(); ++i) { 1930 sp<Track> track = mTracks[i]; 1931 if (session == track->sessionId()) { 1932 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 1933 buffer); 1934 track->setMainBuffer(buffer); 1935 chain->incTrackCnt(); 1936 } 1937 } 1938 1939 // indicate all active tracks in the chain 1940 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 1941 sp<Track> track = mActiveTracks[i].promote(); 1942 if (track == 0) { 1943 continue; 1944 } 1945 if (session == track->sessionId()) { 1946 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 1947 chain->incActiveTrackCnt(); 1948 } 1949 } 1950 } 1951 1952 chain->setInBuffer(buffer, ownsBuffer); 1953 chain->setOutBuffer(mMixBuffer); 1954 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 1955 // chains list in order to be processed last as it contains output stage effects 1956 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 1957 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 1958 // after track specific effects and before output stage 1959 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 1960 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 1961 // Effect chain for other sessions are inserted at beginning of effect 1962 // chains list to be processed before output mix effects. Relative order between other 1963 // sessions is not important 1964 size_t size = mEffectChains.size(); 1965 size_t i = 0; 1966 for (i = 0; i < size; i++) { 1967 if (mEffectChains[i]->sessionId() < session) { 1968 break; 1969 } 1970 } 1971 mEffectChains.insertAt(chain, i); 1972 checkSuspendOnAddEffectChain_l(chain); 1973 1974 return NO_ERROR; 1975} 1976 1977size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 1978{ 1979 int session = chain->sessionId(); 1980 1981 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 1982 1983 for (size_t i = 0; i < mEffectChains.size(); i++) { 1984 if (chain == mEffectChains[i]) { 1985 mEffectChains.removeAt(i); 1986 // detach all active tracks from the chain 1987 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 1988 sp<Track> track = mActiveTracks[i].promote(); 1989 if (track == 0) { 1990 continue; 1991 } 1992 if (session == track->sessionId()) { 1993 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 1994 chain.get(), session); 1995 chain->decActiveTrackCnt(); 1996 } 1997 } 1998 1999 // detach all tracks with same session ID from this chain 2000 for (size_t i = 0; i < mTracks.size(); ++i) { 2001 sp<Track> track = mTracks[i]; 2002 if (session == track->sessionId()) { 2003 track->setMainBuffer(mMixBuffer); 2004 chain->decTrackCnt(); 2005 } 2006 } 2007 break; 2008 } 2009 } 2010 return mEffectChains.size(); 2011} 2012 2013status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2015{ 2016 Mutex::Autolock _l(mLock); 2017 return attachAuxEffect_l(track, EffectId); 2018} 2019 2020status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2021 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2022{ 2023 status_t status = NO_ERROR; 2024 2025 if (EffectId == 0) { 2026 track->setAuxBuffer(0, NULL); 2027 } else { 2028 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2029 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2030 if (effect != 0) { 2031 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2032 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2033 } else { 2034 status = INVALID_OPERATION; 2035 } 2036 } else { 2037 status = BAD_VALUE; 2038 } 2039 } 2040 return status; 2041} 2042 2043void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2044{ 2045 for (size_t i = 0; i < mTracks.size(); ++i) { 2046 sp<Track> track = mTracks[i]; 2047 if (track->auxEffectId() == effectId) { 2048 attachAuxEffect_l(track, 0); 2049 } 2050 } 2051} 2052 2053bool AudioFlinger::PlaybackThread::threadLoop() 2054{ 2055 Vector< sp<Track> > tracksToRemove; 2056 2057 standbyTime = systemTime(); 2058 2059 // MIXER 2060 nsecs_t lastWarning = 0; 2061 2062 // DUPLICATING 2063 // FIXME could this be made local to while loop? 2064 writeFrames = 0; 2065 2066 cacheParameters_l(); 2067 sleepTime = idleSleepTime; 2068 2069 if (mType == MIXER) { 2070 sleepTimeShift = 0; 2071 } 2072 2073 CpuStats cpuStats; 2074 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2075 2076 acquireWakeLock(); 2077 2078 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2079 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2080 // and then that string will be logged at the next convenient opportunity. 2081 const char *logString = NULL; 2082 2083 while (!exitPending()) 2084 { 2085 cpuStats.sample(myName); 2086 2087 Vector< sp<EffectChain> > effectChains; 2088 2089 processConfigEvents(); 2090 2091 { // scope for mLock 2092 2093 Mutex::Autolock _l(mLock); 2094 2095 if (logString != NULL) { 2096 mNBLogWriter->logTimestamp(); 2097 mNBLogWriter->log(logString); 2098 logString = NULL; 2099 } 2100 2101 if (checkForNewParameters_l()) { 2102 cacheParameters_l(); 2103 } 2104 2105 saveOutputTracks(); 2106 2107 if (mSignalPending) { 2108 // A signal was raised while we were unlocked 2109 mSignalPending = false; 2110 } else if (waitingAsyncCallback_l()) { 2111 if (exitPending()) { 2112 break; 2113 } 2114 releaseWakeLock_l(); 2115 ALOGV("wait async completion"); 2116 mWaitWorkCV.wait(mLock); 2117 ALOGV("async completion/wake"); 2118 acquireWakeLock_l(); 2119 if (exitPending()) { 2120 break; 2121 } 2122 if (!mActiveTracks.size() && (systemTime() > standbyTime)) { 2123 continue; 2124 } 2125 sleepTime = 0; 2126 } else if ((!mActiveTracks.size() && systemTime() > standbyTime) || 2127 isSuspended()) { 2128 // put audio hardware into standby after short delay 2129 if (shouldStandby_l()) { 2130 2131 threadLoop_standby(); 2132 2133 mStandby = true; 2134 } 2135 2136 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2137 // we're about to wait, flush the binder command buffer 2138 IPCThreadState::self()->flushCommands(); 2139 2140 clearOutputTracks(); 2141 2142 if (exitPending()) { 2143 break; 2144 } 2145 2146 releaseWakeLock_l(); 2147 // wait until we have something to do... 2148 ALOGV("%s going to sleep", myName.string()); 2149 mWaitWorkCV.wait(mLock); 2150 ALOGV("%s waking up", myName.string()); 2151 acquireWakeLock_l(); 2152 2153 mMixerStatus = MIXER_IDLE; 2154 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2155 mBytesWritten = 0; 2156 mBytesRemaining = 0; 2157 checkSilentMode_l(); 2158 2159 standbyTime = systemTime() + standbyDelay; 2160 sleepTime = idleSleepTime; 2161 if (mType == MIXER) { 2162 sleepTimeShift = 0; 2163 } 2164 2165 continue; 2166 } 2167 } 2168 2169 // mMixerStatusIgnoringFastTracks is also updated internally 2170 mMixerStatus = prepareTracks_l(&tracksToRemove); 2171 2172 // prevent any changes in effect chain list and in each effect chain 2173 // during mixing and effect process as the audio buffers could be deleted 2174 // or modified if an effect is created or deleted 2175 lockEffectChains_l(effectChains); 2176 } 2177 2178 if (mBytesRemaining == 0) { 2179 mCurrentWriteLength = 0; 2180 if (mMixerStatus == MIXER_TRACKS_READY) { 2181 // threadLoop_mix() sets mCurrentWriteLength 2182 threadLoop_mix(); 2183 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 2184 && (mMixerStatus != MIXER_DRAIN_ALL)) { 2185 // threadLoop_sleepTime sets sleepTime to 0 if data 2186 // must be written to HAL 2187 threadLoop_sleepTime(); 2188 if (sleepTime == 0) { 2189 mCurrentWriteLength = mixBufferSize; 2190 } 2191 } 2192 mBytesRemaining = mCurrentWriteLength; 2193 if (isSuspended()) { 2194 sleepTime = suspendSleepTimeUs(); 2195 // simulate write to HAL when suspended 2196 mBytesWritten += mixBufferSize; 2197 mBytesRemaining = 0; 2198 } 2199 2200 // only process effects if we're going to write 2201 if (sleepTime == 0) { 2202 for (size_t i = 0; i < effectChains.size(); i ++) { 2203 effectChains[i]->process_l(); 2204 } 2205 } 2206 } 2207 2208 // enable changes in effect chain 2209 unlockEffectChains(effectChains); 2210 2211 if (!waitingAsyncCallback()) { 2212 // sleepTime == 0 means we must write to audio hardware 2213 if (sleepTime == 0) { 2214 if (mBytesRemaining) { 2215 ssize_t ret = threadLoop_write(); 2216 if (ret < 0) { 2217 mBytesRemaining = 0; 2218 } else { 2219 mBytesWritten += ret; 2220 mBytesRemaining -= ret; 2221 } 2222 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 2223 (mMixerStatus == MIXER_DRAIN_ALL)) { 2224 threadLoop_drain(); 2225 } 2226if (mType == MIXER) { 2227 // write blocked detection 2228 nsecs_t now = systemTime(); 2229 nsecs_t delta = now - mLastWriteTime; 2230 if (!mStandby && delta > maxPeriod) { 2231 mNumDelayedWrites++; 2232 if ((now - lastWarning) > kWarningThrottleNs) { 2233 ATRACE_NAME("underrun"); 2234 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2235 ns2ms(delta), mNumDelayedWrites, this); 2236 lastWarning = now; 2237 } 2238 } 2239} 2240 2241 mStandby = false; 2242 } else { 2243 usleep(sleepTime); 2244 } 2245 } 2246 2247 // Finally let go of removed track(s), without the lock held 2248 // since we can't guarantee the destructors won't acquire that 2249 // same lock. This will also mutate and push a new fast mixer state. 2250 threadLoop_removeTracks(tracksToRemove); 2251 tracksToRemove.clear(); 2252 2253 // FIXME I don't understand the need for this here; 2254 // it was in the original code but maybe the 2255 // assignment in saveOutputTracks() makes this unnecessary? 2256 clearOutputTracks(); 2257 2258 // Effect chains will be actually deleted here if they were removed from 2259 // mEffectChains list during mixing or effects processing 2260 effectChains.clear(); 2261 2262 // FIXME Note that the above .clear() is no longer necessary since effectChains 2263 // is now local to this block, but will keep it for now (at least until merge done). 2264 } 2265 2266 threadLoop_exit(); 2267 2268 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ... 2269 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) { 2270 // put output stream into standby mode 2271 if (!mStandby) { 2272 mOutput->stream->common.standby(&mOutput->stream->common); 2273 } 2274 } 2275 2276 releaseWakeLock(); 2277 2278 ALOGV("Thread %p type %d exiting", this, mType); 2279 return false; 2280} 2281 2282// removeTracks_l() must be called with ThreadBase::mLock held 2283void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 2284{ 2285 size_t count = tracksToRemove.size(); 2286 if (count > 0) { 2287 for (size_t i=0 ; i<count ; i++) { 2288 const sp<Track>& track = tracksToRemove.itemAt(i); 2289 mActiveTracks.remove(track); 2290 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 2291 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2292 if (chain != 0) { 2293 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 2294 track->sessionId()); 2295 chain->decActiveTrackCnt(); 2296 } 2297 if (track->isTerminated()) { 2298 removeTrack_l(track); 2299 } 2300 } 2301 } 2302 2303} 2304 2305// ---------------------------------------------------------------------------- 2306 2307AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2308 audio_io_handle_t id, audio_devices_t device, type_t type) 2309 : PlaybackThread(audioFlinger, output, id, device, type), 2310 // mAudioMixer below 2311 // mFastMixer below 2312 mFastMixerFutex(0) 2313 // mOutputSink below 2314 // mPipeSink below 2315 // mNormalSink below 2316{ 2317 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2318 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 2319 "mFrameCount=%d, mNormalFrameCount=%d", 2320 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2321 mNormalFrameCount); 2322 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2323 2324 // FIXME - Current mixer implementation only supports stereo output 2325 if (mChannelCount != FCC_2) { 2326 ALOGE("Invalid audio hardware channel count %d", mChannelCount); 2327 } 2328 2329 // create an NBAIO sink for the HAL output stream, and negotiate 2330 mOutputSink = new AudioStreamOutSink(output->stream); 2331 size_t numCounterOffers = 0; 2332 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2333 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2334 ALOG_ASSERT(index == 0); 2335 2336 // initialize fast mixer depending on configuration 2337 bool initFastMixer; 2338 switch (kUseFastMixer) { 2339 case FastMixer_Never: 2340 initFastMixer = false; 2341 break; 2342 case FastMixer_Always: 2343 initFastMixer = true; 2344 break; 2345 case FastMixer_Static: 2346 case FastMixer_Dynamic: 2347 initFastMixer = mFrameCount < mNormalFrameCount; 2348 break; 2349 } 2350 if (initFastMixer) { 2351 2352 // create a MonoPipe to connect our submix to FastMixer 2353 NBAIO_Format format = mOutputSink->format(); 2354 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2355 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2356 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2357 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2358 const NBAIO_Format offers[1] = {format}; 2359 size_t numCounterOffers = 0; 2360 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2361 ALOG_ASSERT(index == 0); 2362 monoPipe->setAvgFrames((mScreenState & 1) ? 2363 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2364 mPipeSink = monoPipe; 2365 2366#ifdef TEE_SINK 2367 if (mTeeSinkOutputEnabled) { 2368 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2369 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format); 2370 numCounterOffers = 0; 2371 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2372 ALOG_ASSERT(index == 0); 2373 mTeeSink = teeSink; 2374 PipeReader *teeSource = new PipeReader(*teeSink); 2375 numCounterOffers = 0; 2376 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2377 ALOG_ASSERT(index == 0); 2378 mTeeSource = teeSource; 2379 } 2380#endif 2381 2382 // create fast mixer and configure it initially with just one fast track for our submix 2383 mFastMixer = new FastMixer(); 2384 FastMixerStateQueue *sq = mFastMixer->sq(); 2385#ifdef STATE_QUEUE_DUMP 2386 sq->setObserverDump(&mStateQueueObserverDump); 2387 sq->setMutatorDump(&mStateQueueMutatorDump); 2388#endif 2389 FastMixerState *state = sq->begin(); 2390 FastTrack *fastTrack = &state->mFastTracks[0]; 2391 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2392 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2393 fastTrack->mVolumeProvider = NULL; 2394 fastTrack->mGeneration++; 2395 state->mFastTracksGen++; 2396 state->mTrackMask = 1; 2397 // fast mixer will use the HAL output sink 2398 state->mOutputSink = mOutputSink.get(); 2399 state->mOutputSinkGen++; 2400 state->mFrameCount = mFrameCount; 2401 state->mCommand = FastMixerState::COLD_IDLE; 2402 // already done in constructor initialization list 2403 //mFastMixerFutex = 0; 2404 state->mColdFutexAddr = &mFastMixerFutex; 2405 state->mColdGen++; 2406 state->mDumpState = &mFastMixerDumpState; 2407#ifdef TEE_SINK 2408 state->mTeeSink = mTeeSink.get(); 2409#endif 2410 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 2411 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 2412 sq->end(); 2413 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2414 2415 // start the fast mixer 2416 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2417 pid_t tid = mFastMixer->getTid(); 2418 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2419 if (err != 0) { 2420 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2421 kPriorityFastMixer, getpid_cached, tid, err); 2422 } 2423 2424#ifdef AUDIO_WATCHDOG 2425 // create and start the watchdog 2426 mAudioWatchdog = new AudioWatchdog(); 2427 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2428 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2429 tid = mAudioWatchdog->getTid(); 2430 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2431 if (err != 0) { 2432 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2433 kPriorityFastMixer, getpid_cached, tid, err); 2434 } 2435#endif 2436 2437 } else { 2438 mFastMixer = NULL; 2439 } 2440 2441 switch (kUseFastMixer) { 2442 case FastMixer_Never: 2443 case FastMixer_Dynamic: 2444 mNormalSink = mOutputSink; 2445 break; 2446 case FastMixer_Always: 2447 mNormalSink = mPipeSink; 2448 break; 2449 case FastMixer_Static: 2450 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2451 break; 2452 } 2453} 2454 2455AudioFlinger::MixerThread::~MixerThread() 2456{ 2457 if (mFastMixer != NULL) { 2458 FastMixerStateQueue *sq = mFastMixer->sq(); 2459 FastMixerState *state = sq->begin(); 2460 if (state->mCommand == FastMixerState::COLD_IDLE) { 2461 int32_t old = android_atomic_inc(&mFastMixerFutex); 2462 if (old == -1) { 2463 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2464 } 2465 } 2466 state->mCommand = FastMixerState::EXIT; 2467 sq->end(); 2468 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2469 mFastMixer->join(); 2470 // Though the fast mixer thread has exited, it's state queue is still valid. 2471 // We'll use that extract the final state which contains one remaining fast track 2472 // corresponding to our sub-mix. 2473 state = sq->begin(); 2474 ALOG_ASSERT(state->mTrackMask == 1); 2475 FastTrack *fastTrack = &state->mFastTracks[0]; 2476 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2477 delete fastTrack->mBufferProvider; 2478 sq->end(false /*didModify*/); 2479 delete mFastMixer; 2480#ifdef AUDIO_WATCHDOG 2481 if (mAudioWatchdog != 0) { 2482 mAudioWatchdog->requestExit(); 2483 mAudioWatchdog->requestExitAndWait(); 2484 mAudioWatchdog.clear(); 2485 } 2486#endif 2487 } 2488 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 2489 delete mAudioMixer; 2490} 2491 2492 2493uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 2494{ 2495 if (mFastMixer != NULL) { 2496 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2497 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 2498 } 2499 return latency; 2500} 2501 2502 2503void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2504{ 2505 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2506} 2507 2508ssize_t AudioFlinger::MixerThread::threadLoop_write() 2509{ 2510 // FIXME we should only do one push per cycle; confirm this is true 2511 // Start the fast mixer if it's not already running 2512 if (mFastMixer != NULL) { 2513 FastMixerStateQueue *sq = mFastMixer->sq(); 2514 FastMixerState *state = sq->begin(); 2515 if (state->mCommand != FastMixerState::MIX_WRITE && 2516 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2517 if (state->mCommand == FastMixerState::COLD_IDLE) { 2518 int32_t old = android_atomic_inc(&mFastMixerFutex); 2519 if (old == -1) { 2520 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2521 } 2522#ifdef AUDIO_WATCHDOG 2523 if (mAudioWatchdog != 0) { 2524 mAudioWatchdog->resume(); 2525 } 2526#endif 2527 } 2528 state->mCommand = FastMixerState::MIX_WRITE; 2529 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 2530 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 2531 sq->end(); 2532 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2533 if (kUseFastMixer == FastMixer_Dynamic) { 2534 mNormalSink = mPipeSink; 2535 } 2536 } else { 2537 sq->end(false /*didModify*/); 2538 } 2539 } 2540 return PlaybackThread::threadLoop_write(); 2541} 2542 2543void AudioFlinger::MixerThread::threadLoop_standby() 2544{ 2545 // Idle the fast mixer if it's currently running 2546 if (mFastMixer != NULL) { 2547 FastMixerStateQueue *sq = mFastMixer->sq(); 2548 FastMixerState *state = sq->begin(); 2549 if (!(state->mCommand & FastMixerState::IDLE)) { 2550 state->mCommand = FastMixerState::COLD_IDLE; 2551 state->mColdFutexAddr = &mFastMixerFutex; 2552 state->mColdGen++; 2553 mFastMixerFutex = 0; 2554 sq->end(); 2555 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2556 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2557 if (kUseFastMixer == FastMixer_Dynamic) { 2558 mNormalSink = mOutputSink; 2559 } 2560#ifdef AUDIO_WATCHDOG 2561 if (mAudioWatchdog != 0) { 2562 mAudioWatchdog->pause(); 2563 } 2564#endif 2565 } else { 2566 sq->end(false /*didModify*/); 2567 } 2568 } 2569 PlaybackThread::threadLoop_standby(); 2570} 2571 2572// Empty implementation for standard mixer 2573// Overridden for offloaded playback 2574void AudioFlinger::PlaybackThread::flushOutput_l() 2575{ 2576} 2577 2578bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 2579{ 2580 return false; 2581} 2582 2583bool AudioFlinger::PlaybackThread::shouldStandby_l() 2584{ 2585 return !mStandby; 2586} 2587 2588bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 2589{ 2590 Mutex::Autolock _l(mLock); 2591 return waitingAsyncCallback_l(); 2592} 2593 2594// shared by MIXER and DIRECT, overridden by DUPLICATING 2595void AudioFlinger::PlaybackThread::threadLoop_standby() 2596{ 2597 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 2598 mOutput->stream->common.standby(&mOutput->stream->common); 2599 if (mUseAsyncWrite != 0) { 2600 mWriteBlocked = false; 2601 mDraining = false; 2602 ALOG_ASSERT(mCallbackThread != 0); 2603 mCallbackThread->setWriteBlocked(false); 2604 mCallbackThread->setDraining(false); 2605 } 2606} 2607 2608void AudioFlinger::MixerThread::threadLoop_mix() 2609{ 2610 // obtain the presentation timestamp of the next output buffer 2611 int64_t pts; 2612 status_t status = INVALID_OPERATION; 2613 2614 if (mNormalSink != 0) { 2615 status = mNormalSink->getNextWriteTimestamp(&pts); 2616 } else { 2617 status = mOutputSink->getNextWriteTimestamp(&pts); 2618 } 2619 2620 if (status != NO_ERROR) { 2621 pts = AudioBufferProvider::kInvalidPTS; 2622 } 2623 2624 // mix buffers... 2625 mAudioMixer->process(pts); 2626 mCurrentWriteLength = mixBufferSize; 2627 // increase sleep time progressively when application underrun condition clears. 2628 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2629 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2630 // such that we would underrun the audio HAL. 2631 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2632 sleepTimeShift--; 2633 } 2634 sleepTime = 0; 2635 standbyTime = systemTime() + standbyDelay; 2636 //TODO: delay standby when effects have a tail 2637} 2638 2639void AudioFlinger::MixerThread::threadLoop_sleepTime() 2640{ 2641 // If no tracks are ready, sleep once for the duration of an output 2642 // buffer size, then write 0s to the output 2643 if (sleepTime == 0) { 2644 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2645 sleepTime = activeSleepTime >> sleepTimeShift; 2646 if (sleepTime < kMinThreadSleepTimeUs) { 2647 sleepTime = kMinThreadSleepTimeUs; 2648 } 2649 // reduce sleep time in case of consecutive application underruns to avoid 2650 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2651 // duration we would end up writing less data than needed by the audio HAL if 2652 // the condition persists. 2653 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2654 sleepTimeShift++; 2655 } 2656 } else { 2657 sleepTime = idleSleepTime; 2658 } 2659 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2660 memset(mMixBuffer, 0, mixBufferSize); 2661 sleepTime = 0; 2662 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 2663 "anticipated start"); 2664 } 2665 // TODO add standby time extension fct of effect tail 2666} 2667 2668// prepareTracks_l() must be called with ThreadBase::mLock held 2669AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2670 Vector< sp<Track> > *tracksToRemove) 2671{ 2672 2673 mixer_state mixerStatus = MIXER_IDLE; 2674 // find out which tracks need to be processed 2675 size_t count = mActiveTracks.size(); 2676 size_t mixedTracks = 0; 2677 size_t tracksWithEffect = 0; 2678 // counts only _active_ fast tracks 2679 size_t fastTracks = 0; 2680 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2681 2682 float masterVolume = mMasterVolume; 2683 bool masterMute = mMasterMute; 2684 2685 if (masterMute) { 2686 masterVolume = 0; 2687 } 2688 // Delegate master volume control to effect in output mix effect chain if needed 2689 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2690 if (chain != 0) { 2691 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2692 chain->setVolume_l(&v, &v); 2693 masterVolume = (float)((v + (1 << 23)) >> 24); 2694 chain.clear(); 2695 } 2696 2697 // prepare a new state to push 2698 FastMixerStateQueue *sq = NULL; 2699 FastMixerState *state = NULL; 2700 bool didModify = false; 2701 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2702 if (mFastMixer != NULL) { 2703 sq = mFastMixer->sq(); 2704 state = sq->begin(); 2705 } 2706 2707 for (size_t i=0 ; i<count ; i++) { 2708 const sp<Track> t = mActiveTracks[i].promote(); 2709 if (t == 0) { 2710 continue; 2711 } 2712 2713 // this const just means the local variable doesn't change 2714 Track* const track = t.get(); 2715 2716 // process fast tracks 2717 if (track->isFastTrack()) { 2718 2719 // It's theoretically possible (though unlikely) for a fast track to be created 2720 // and then removed within the same normal mix cycle. This is not a problem, as 2721 // the track never becomes active so it's fast mixer slot is never touched. 2722 // The converse, of removing an (active) track and then creating a new track 2723 // at the identical fast mixer slot within the same normal mix cycle, 2724 // is impossible because the slot isn't marked available until the end of each cycle. 2725 int j = track->mFastIndex; 2726 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2727 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2728 FastTrack *fastTrack = &state->mFastTracks[j]; 2729 2730 // Determine whether the track is currently in underrun condition, 2731 // and whether it had a recent underrun. 2732 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2733 FastTrackUnderruns underruns = ftDump->mUnderruns; 2734 uint32_t recentFull = (underruns.mBitFields.mFull - 2735 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2736 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2737 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2738 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2739 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2740 uint32_t recentUnderruns = recentPartial + recentEmpty; 2741 track->mObservedUnderruns = underruns; 2742 // don't count underruns that occur while stopping or pausing 2743 // or stopped which can occur when flush() is called while active 2744 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 2745 recentUnderruns > 0) { 2746 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 2747 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 2748 } 2749 2750 // This is similar to the state machine for normal tracks, 2751 // with a few modifications for fast tracks. 2752 bool isActive = true; 2753 switch (track->mState) { 2754 case TrackBase::STOPPING_1: 2755 // track stays active in STOPPING_1 state until first underrun 2756 if (recentUnderruns > 0 || track->isTerminated()) { 2757 track->mState = TrackBase::STOPPING_2; 2758 } 2759 break; 2760 case TrackBase::PAUSING: 2761 // ramp down is not yet implemented 2762 track->setPaused(); 2763 break; 2764 case TrackBase::RESUMING: 2765 // ramp up is not yet implemented 2766 track->mState = TrackBase::ACTIVE; 2767 break; 2768 case TrackBase::ACTIVE: 2769 if (recentFull > 0 || recentPartial > 0) { 2770 // track has provided at least some frames recently: reset retry count 2771 track->mRetryCount = kMaxTrackRetries; 2772 } 2773 if (recentUnderruns == 0) { 2774 // no recent underruns: stay active 2775 break; 2776 } 2777 // there has recently been an underrun of some kind 2778 if (track->sharedBuffer() == 0) { 2779 // were any of the recent underruns "empty" (no frames available)? 2780 if (recentEmpty == 0) { 2781 // no, then ignore the partial underruns as they are allowed indefinitely 2782 break; 2783 } 2784 // there has recently been an "empty" underrun: decrement the retry counter 2785 if (--(track->mRetryCount) > 0) { 2786 break; 2787 } 2788 // indicate to client process that the track was disabled because of underrun; 2789 // it will then automatically call start() when data is available 2790 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 2791 // remove from active list, but state remains ACTIVE [confusing but true] 2792 isActive = false; 2793 break; 2794 } 2795 // fall through 2796 case TrackBase::STOPPING_2: 2797 case TrackBase::PAUSED: 2798 case TrackBase::STOPPED: 2799 case TrackBase::FLUSHED: // flush() while active 2800 // Check for presentation complete if track is inactive 2801 // We have consumed all the buffers of this track. 2802 // This would be incomplete if we auto-paused on underrun 2803 { 2804 size_t audioHALFrames = 2805 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 2806 size_t framesWritten = mBytesWritten / mFrameSize; 2807 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 2808 // track stays in active list until presentation is complete 2809 break; 2810 } 2811 } 2812 if (track->isStopping_2()) { 2813 track->mState = TrackBase::STOPPED; 2814 } 2815 if (track->isStopped()) { 2816 // Can't reset directly, as fast mixer is still polling this track 2817 // track->reset(); 2818 // So instead mark this track as needing to be reset after push with ack 2819 resetMask |= 1 << i; 2820 } 2821 isActive = false; 2822 break; 2823 case TrackBase::IDLE: 2824 default: 2825 LOG_FATAL("unexpected track state %d", track->mState); 2826 } 2827 2828 if (isActive) { 2829 // was it previously inactive? 2830 if (!(state->mTrackMask & (1 << j))) { 2831 ExtendedAudioBufferProvider *eabp = track; 2832 VolumeProvider *vp = track; 2833 fastTrack->mBufferProvider = eabp; 2834 fastTrack->mVolumeProvider = vp; 2835 fastTrack->mSampleRate = track->mSampleRate; 2836 fastTrack->mChannelMask = track->mChannelMask; 2837 fastTrack->mGeneration++; 2838 state->mTrackMask |= 1 << j; 2839 didModify = true; 2840 // no acknowledgement required for newly active tracks 2841 } 2842 // cache the combined master volume and stream type volume for fast mixer; this 2843 // lacks any synchronization or barrier so VolumeProvider may read a stale value 2844 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 2845 ++fastTracks; 2846 } else { 2847 // was it previously active? 2848 if (state->mTrackMask & (1 << j)) { 2849 fastTrack->mBufferProvider = NULL; 2850 fastTrack->mGeneration++; 2851 state->mTrackMask &= ~(1 << j); 2852 didModify = true; 2853 // If any fast tracks were removed, we must wait for acknowledgement 2854 // because we're about to decrement the last sp<> on those tracks. 2855 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 2856 } else { 2857 LOG_FATAL("fast track %d should have been active", j); 2858 } 2859 tracksToRemove->add(track); 2860 // Avoids a misleading display in dumpsys 2861 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 2862 } 2863 continue; 2864 } 2865 2866 { // local variable scope to avoid goto warning 2867 2868 audio_track_cblk_t* cblk = track->cblk(); 2869 2870 // The first time a track is added we wait 2871 // for all its buffers to be filled before processing it 2872 int name = track->name(); 2873 // make sure that we have enough frames to mix one full buffer. 2874 // enforce this condition only once to enable draining the buffer in case the client 2875 // app does not call stop() and relies on underrun to stop: 2876 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 2877 // during last round 2878 size_t desiredFrames; 2879 uint32_t sr = track->sampleRate(); 2880 if (sr == mSampleRate) { 2881 desiredFrames = mNormalFrameCount; 2882 } else { 2883 // +1 for rounding and +1 for additional sample needed for interpolation 2884 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1; 2885 // add frames already consumed but not yet released by the resampler 2886 // because mAudioTrackServerProxy->framesReady() will include these frames 2887 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 2888 // the minimum track buffer size is normally twice the number of frames necessary 2889 // to fill one buffer and the resampler should not leave more than one buffer worth 2890 // of unreleased frames after each pass, but just in case... 2891 ALOG_ASSERT(desiredFrames <= cblk->frameCount_); 2892 } 2893 uint32_t minFrames = 1; 2894 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 2895 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 2896 minFrames = desiredFrames; 2897 } 2898 // It's not safe to call framesReady() for a static buffer track, so assume it's ready 2899 size_t framesReady; 2900 if (track->sharedBuffer() == 0) { 2901 framesReady = track->framesReady(); 2902 } else if (track->isStopped()) { 2903 framesReady = 0; 2904 } else { 2905 framesReady = 1; 2906 } 2907 if ((framesReady >= minFrames) && track->isReady() && 2908 !track->isPaused() && !track->isTerminated()) 2909 { 2910 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 2911 2912 mixedTracks++; 2913 2914 // track->mainBuffer() != mMixBuffer means there is an effect chain 2915 // connected to the track 2916 chain.clear(); 2917 if (track->mainBuffer() != mMixBuffer) { 2918 chain = getEffectChain_l(track->sessionId()); 2919 // Delegate volume control to effect in track effect chain if needed 2920 if (chain != 0) { 2921 tracksWithEffect++; 2922 } else { 2923 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 2924 "session %d", 2925 name, track->sessionId()); 2926 } 2927 } 2928 2929 2930 int param = AudioMixer::VOLUME; 2931 if (track->mFillingUpStatus == Track::FS_FILLED) { 2932 // no ramp for the first volume setting 2933 track->mFillingUpStatus = Track::FS_ACTIVE; 2934 if (track->mState == TrackBase::RESUMING) { 2935 track->mState = TrackBase::ACTIVE; 2936 param = AudioMixer::RAMP_VOLUME; 2937 } 2938 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 2939 // FIXME should not make a decision based on mServer 2940 } else if (cblk->mServer != 0) { 2941 // If the track is stopped before the first frame was mixed, 2942 // do not apply ramp 2943 param = AudioMixer::RAMP_VOLUME; 2944 } 2945 2946 // compute volume for this track 2947 uint32_t vl, vr, va; 2948 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 2949 vl = vr = va = 0; 2950 if (track->isPausing()) { 2951 track->setPaused(); 2952 } 2953 } else { 2954 2955 // read original volumes with volume control 2956 float typeVolume = mStreamTypes[track->streamType()].volume; 2957 float v = masterVolume * typeVolume; 2958 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 2959 uint32_t vlr = proxy->getVolumeLR(); 2960 vl = vlr & 0xFFFF; 2961 vr = vlr >> 16; 2962 // track volumes come from shared memory, so can't be trusted and must be clamped 2963 if (vl > MAX_GAIN_INT) { 2964 ALOGV("Track left volume out of range: %04X", vl); 2965 vl = MAX_GAIN_INT; 2966 } 2967 if (vr > MAX_GAIN_INT) { 2968 ALOGV("Track right volume out of range: %04X", vr); 2969 vr = MAX_GAIN_INT; 2970 } 2971 // now apply the master volume and stream type volume 2972 vl = (uint32_t)(v * vl) << 12; 2973 vr = (uint32_t)(v * vr) << 12; 2974 // assuming master volume and stream type volume each go up to 1.0, 2975 // vl and vr are now in 8.24 format 2976 2977 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 2978 // send level comes from shared memory and so may be corrupt 2979 if (sendLevel > MAX_GAIN_INT) { 2980 ALOGV("Track send level out of range: %04X", sendLevel); 2981 sendLevel = MAX_GAIN_INT; 2982 } 2983 va = (uint32_t)(v * sendLevel); 2984 } 2985 2986 // Delegate volume control to effect in track effect chain if needed 2987 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 2988 // Do not ramp volume if volume is controlled by effect 2989 param = AudioMixer::VOLUME; 2990 track->mHasVolumeController = true; 2991 } else { 2992 // force no volume ramp when volume controller was just disabled or removed 2993 // from effect chain to avoid volume spike 2994 if (track->mHasVolumeController) { 2995 param = AudioMixer::VOLUME; 2996 } 2997 track->mHasVolumeController = false; 2998 } 2999 3000 // Convert volumes from 8.24 to 4.12 format 3001 // This additional clamping is needed in case chain->setVolume_l() overshot 3002 vl = (vl + (1 << 11)) >> 12; 3003 if (vl > MAX_GAIN_INT) { 3004 vl = MAX_GAIN_INT; 3005 } 3006 vr = (vr + (1 << 11)) >> 12; 3007 if (vr > MAX_GAIN_INT) { 3008 vr = MAX_GAIN_INT; 3009 } 3010 3011 if (va > MAX_GAIN_INT) { 3012 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3013 } 3014 3015 // XXX: these things DON'T need to be done each time 3016 mAudioMixer->setBufferProvider(name, track); 3017 mAudioMixer->enable(name); 3018 3019 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3020 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3021 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3022 mAudioMixer->setParameter( 3023 name, 3024 AudioMixer::TRACK, 3025 AudioMixer::FORMAT, (void *)track->format()); 3026 mAudioMixer->setParameter( 3027 name, 3028 AudioMixer::TRACK, 3029 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3030 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3031 uint32_t maxSampleRate = mSampleRate * 2; 3032 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3033 if (reqSampleRate == 0) { 3034 reqSampleRate = mSampleRate; 3035 } else if (reqSampleRate > maxSampleRate) { 3036 reqSampleRate = maxSampleRate; 3037 } 3038 mAudioMixer->setParameter( 3039 name, 3040 AudioMixer::RESAMPLE, 3041 AudioMixer::SAMPLE_RATE, 3042 (void *)reqSampleRate); 3043 mAudioMixer->setParameter( 3044 name, 3045 AudioMixer::TRACK, 3046 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3047 mAudioMixer->setParameter( 3048 name, 3049 AudioMixer::TRACK, 3050 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3051 3052 // reset retry count 3053 track->mRetryCount = kMaxTrackRetries; 3054 3055 // If one track is ready, set the mixer ready if: 3056 // - the mixer was not ready during previous round OR 3057 // - no other track is not ready 3058 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3059 mixerStatus != MIXER_TRACKS_ENABLED) { 3060 mixerStatus = MIXER_TRACKS_READY; 3061 } 3062 } else { 3063 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 3064 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 3065 } 3066 // clear effect chain input buffer if an active track underruns to avoid sending 3067 // previous audio buffer again to effects 3068 chain = getEffectChain_l(track->sessionId()); 3069 if (chain != 0) { 3070 chain->clearInputBuffer(); 3071 } 3072 3073 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 3074 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3075 track->isStopped() || track->isPaused()) { 3076 // We have consumed all the buffers of this track. 3077 // Remove it from the list of active tracks. 3078 // TODO: use actual buffer filling status instead of latency when available from 3079 // audio HAL 3080 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3081 size_t framesWritten = mBytesWritten / mFrameSize; 3082 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3083 if (track->isStopped()) { 3084 track->reset(); 3085 } 3086 tracksToRemove->add(track); 3087 } 3088 } else { 3089 // No buffers for this track. Give it a few chances to 3090 // fill a buffer, then remove it from active list. 3091 if (--(track->mRetryCount) <= 0) { 3092 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3093 tracksToRemove->add(track); 3094 // indicate to client process that the track was disabled because of underrun; 3095 // it will then automatically call start() when data is available 3096 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3097 // If one track is not ready, mark the mixer also not ready if: 3098 // - the mixer was ready during previous round OR 3099 // - no other track is ready 3100 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3101 mixerStatus != MIXER_TRACKS_READY) { 3102 mixerStatus = MIXER_TRACKS_ENABLED; 3103 } 3104 } 3105 mAudioMixer->disable(name); 3106 } 3107 3108 } // local variable scope to avoid goto warning 3109track_is_ready: ; 3110 3111 } 3112 3113 // Push the new FastMixer state if necessary 3114 bool pauseAudioWatchdog = false; 3115 if (didModify) { 3116 state->mFastTracksGen++; 3117 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3118 if (kUseFastMixer == FastMixer_Dynamic && 3119 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3120 state->mCommand = FastMixerState::COLD_IDLE; 3121 state->mColdFutexAddr = &mFastMixerFutex; 3122 state->mColdGen++; 3123 mFastMixerFutex = 0; 3124 if (kUseFastMixer == FastMixer_Dynamic) { 3125 mNormalSink = mOutputSink; 3126 } 3127 // If we go into cold idle, need to wait for acknowledgement 3128 // so that fast mixer stops doing I/O. 3129 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3130 pauseAudioWatchdog = true; 3131 } 3132 } 3133 if (sq != NULL) { 3134 sq->end(didModify); 3135 sq->push(block); 3136 } 3137#ifdef AUDIO_WATCHDOG 3138 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3139 mAudioWatchdog->pause(); 3140 } 3141#endif 3142 3143 // Now perform the deferred reset on fast tracks that have stopped 3144 while (resetMask != 0) { 3145 size_t i = __builtin_ctz(resetMask); 3146 ALOG_ASSERT(i < count); 3147 resetMask &= ~(1 << i); 3148 sp<Track> t = mActiveTracks[i].promote(); 3149 if (t == 0) { 3150 continue; 3151 } 3152 Track* track = t.get(); 3153 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3154 track->reset(); 3155 } 3156 3157 // remove all the tracks that need to be... 3158 removeTracks_l(*tracksToRemove); 3159 3160 // mix buffer must be cleared if all tracks are connected to an 3161 // effect chain as in this case the mixer will not write to 3162 // mix buffer and track effects will accumulate into it 3163 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3164 (mixedTracks == 0 && fastTracks > 0))) { 3165 // FIXME as a performance optimization, should remember previous zero status 3166 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3167 } 3168 3169 // if any fast tracks, then status is ready 3170 mMixerStatusIgnoringFastTracks = mixerStatus; 3171 if (fastTracks > 0) { 3172 mixerStatus = MIXER_TRACKS_READY; 3173 } 3174 return mixerStatus; 3175} 3176 3177// getTrackName_l() must be called with ThreadBase::mLock held 3178int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) 3179{ 3180 return mAudioMixer->getTrackName(channelMask, sessionId); 3181} 3182 3183// deleteTrackName_l() must be called with ThreadBase::mLock held 3184void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3185{ 3186 ALOGV("remove track (%d) and delete from mixer", name); 3187 mAudioMixer->deleteTrackName(name); 3188} 3189 3190// checkForNewParameters_l() must be called with ThreadBase::mLock held 3191bool AudioFlinger::MixerThread::checkForNewParameters_l() 3192{ 3193 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3194 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3195 bool reconfig = false; 3196 3197 while (!mNewParameters.isEmpty()) { 3198 3199 if (mFastMixer != NULL) { 3200 FastMixerStateQueue *sq = mFastMixer->sq(); 3201 FastMixerState *state = sq->begin(); 3202 if (!(state->mCommand & FastMixerState::IDLE)) { 3203 previousCommand = state->mCommand; 3204 state->mCommand = FastMixerState::HOT_IDLE; 3205 sq->end(); 3206 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3207 } else { 3208 sq->end(false /*didModify*/); 3209 } 3210 } 3211 3212 status_t status = NO_ERROR; 3213 String8 keyValuePair = mNewParameters[0]; 3214 AudioParameter param = AudioParameter(keyValuePair); 3215 int value; 3216 3217 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3218 reconfig = true; 3219 } 3220 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3221 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3222 status = BAD_VALUE; 3223 } else { 3224 // no need to save value, since it's constant 3225 reconfig = true; 3226 } 3227 } 3228 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3229 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) { 3230 status = BAD_VALUE; 3231 } else { 3232 // no need to save value, since it's constant 3233 reconfig = true; 3234 } 3235 } 3236 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3237 // do not accept frame count changes if tracks are open as the track buffer 3238 // size depends on frame count and correct behavior would not be guaranteed 3239 // if frame count is changed after track creation 3240 if (!mTracks.isEmpty()) { 3241 status = INVALID_OPERATION; 3242 } else { 3243 reconfig = true; 3244 } 3245 } 3246 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3247#ifdef ADD_BATTERY_DATA 3248 // when changing the audio output device, call addBatteryData to notify 3249 // the change 3250 if (mOutDevice != value) { 3251 uint32_t params = 0; 3252 // check whether speaker is on 3253 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3254 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3255 } 3256 3257 audio_devices_t deviceWithoutSpeaker 3258 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3259 // check if any other device (except speaker) is on 3260 if (value & deviceWithoutSpeaker ) { 3261 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3262 } 3263 3264 if (params != 0) { 3265 addBatteryData(params); 3266 } 3267 } 3268#endif 3269 3270 // forward device change to effects that have requested to be 3271 // aware of attached audio device. 3272 if (value != AUDIO_DEVICE_NONE) { 3273 mOutDevice = value; 3274 for (size_t i = 0; i < mEffectChains.size(); i++) { 3275 mEffectChains[i]->setDevice_l(mOutDevice); 3276 } 3277 } 3278 } 3279 3280 if (status == NO_ERROR) { 3281 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3282 keyValuePair.string()); 3283 if (!mStandby && status == INVALID_OPERATION) { 3284 mOutput->stream->common.standby(&mOutput->stream->common); 3285 mStandby = true; 3286 mBytesWritten = 0; 3287 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3288 keyValuePair.string()); 3289 } 3290 if (status == NO_ERROR && reconfig) { 3291 readOutputParameters(); 3292 delete mAudioMixer; 3293 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3294 for (size_t i = 0; i < mTracks.size() ; i++) { 3295 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); 3296 if (name < 0) { 3297 break; 3298 } 3299 mTracks[i]->mName = name; 3300 } 3301 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3302 } 3303 } 3304 3305 mNewParameters.removeAt(0); 3306 3307 mParamStatus = status; 3308 mParamCond.signal(); 3309 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3310 // already timed out waiting for the status and will never signal the condition. 3311 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3312 } 3313 3314 if (!(previousCommand & FastMixerState::IDLE)) { 3315 ALOG_ASSERT(mFastMixer != NULL); 3316 FastMixerStateQueue *sq = mFastMixer->sq(); 3317 FastMixerState *state = sq->begin(); 3318 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3319 state->mCommand = previousCommand; 3320 sq->end(); 3321 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3322 } 3323 3324 return reconfig; 3325} 3326 3327 3328void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3329{ 3330 const size_t SIZE = 256; 3331 char buffer[SIZE]; 3332 String8 result; 3333 3334 PlaybackThread::dumpInternals(fd, args); 3335 3336 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 3337 result.append(buffer); 3338 write(fd, result.string(), result.size()); 3339 3340 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3341 const FastMixerDumpState copy(mFastMixerDumpState); 3342 copy.dump(fd); 3343 3344#ifdef STATE_QUEUE_DUMP 3345 // Similar for state queue 3346 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3347 observerCopy.dump(fd); 3348 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3349 mutatorCopy.dump(fd); 3350#endif 3351 3352#ifdef TEE_SINK 3353 // Write the tee output to a .wav file 3354 dumpTee(fd, mTeeSource, mId); 3355#endif 3356 3357#ifdef AUDIO_WATCHDOG 3358 if (mAudioWatchdog != 0) { 3359 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3360 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3361 wdCopy.dump(fd); 3362 } 3363#endif 3364} 3365 3366uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3367{ 3368 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3369} 3370 3371uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3372{ 3373 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3374} 3375 3376void AudioFlinger::MixerThread::cacheParameters_l() 3377{ 3378 PlaybackThread::cacheParameters_l(); 3379 3380 // FIXME: Relaxed timing because of a certain device that can't meet latency 3381 // Should be reduced to 2x after the vendor fixes the driver issue 3382 // increase threshold again due to low power audio mode. The way this warning 3383 // threshold is calculated and its usefulness should be reconsidered anyway. 3384 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3385} 3386 3387// ---------------------------------------------------------------------------- 3388 3389AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3390 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3391 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3392 // mLeftVolFloat, mRightVolFloat 3393{ 3394} 3395 3396AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3397 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 3398 ThreadBase::type_t type) 3399 : PlaybackThread(audioFlinger, output, id, device, type) 3400 // mLeftVolFloat, mRightVolFloat 3401{ 3402} 3403 3404AudioFlinger::DirectOutputThread::~DirectOutputThread() 3405{ 3406} 3407 3408void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 3409{ 3410 audio_track_cblk_t* cblk = track->cblk(); 3411 float left, right; 3412 3413 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 3414 left = right = 0; 3415 } else { 3416 float typeVolume = mStreamTypes[track->streamType()].volume; 3417 float v = mMasterVolume * typeVolume; 3418 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3419 uint32_t vlr = proxy->getVolumeLR(); 3420 float v_clamped = v * (vlr & 0xFFFF); 3421 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3422 left = v_clamped/MAX_GAIN; 3423 v_clamped = v * (vlr >> 16); 3424 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3425 right = v_clamped/MAX_GAIN; 3426 } 3427 3428 if (lastTrack) { 3429 if (left != mLeftVolFloat || right != mRightVolFloat) { 3430 mLeftVolFloat = left; 3431 mRightVolFloat = right; 3432 3433 // Convert volumes from float to 8.24 3434 uint32_t vl = (uint32_t)(left * (1 << 24)); 3435 uint32_t vr = (uint32_t)(right * (1 << 24)); 3436 3437 // Delegate volume control to effect in track effect chain if needed 3438 // only one effect chain can be present on DirectOutputThread, so if 3439 // there is one, the track is connected to it 3440 if (!mEffectChains.isEmpty()) { 3441 mEffectChains[0]->setVolume_l(&vl, &vr); 3442 left = (float)vl / (1 << 24); 3443 right = (float)vr / (1 << 24); 3444 } 3445 if (mOutput->stream->set_volume) { 3446 mOutput->stream->set_volume(mOutput->stream, left, right); 3447 } 3448 } 3449 } 3450} 3451 3452 3453AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3454 Vector< sp<Track> > *tracksToRemove 3455) 3456{ 3457 size_t count = mActiveTracks.size(); 3458 mixer_state mixerStatus = MIXER_IDLE; 3459 3460 // find out which tracks need to be processed 3461 for (size_t i = 0; i < count; i++) { 3462 sp<Track> t = mActiveTracks[i].promote(); 3463 // The track died recently 3464 if (t == 0) { 3465 continue; 3466 } 3467 3468 Track* const track = t.get(); 3469 audio_track_cblk_t* cblk = track->cblk(); 3470 3471 // The first time a track is added we wait 3472 // for all its buffers to be filled before processing it 3473 uint32_t minFrames; 3474 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3475 minFrames = mNormalFrameCount; 3476 } else { 3477 minFrames = 1; 3478 } 3479 // Only consider last track started for volume and mixer state control. 3480 // This is the last entry in mActiveTracks unless a track underruns. 3481 // As we only care about the transition phase between two tracks on a 3482 // direct output, it is not a problem to ignore the underrun case. 3483 bool last = (i == (count - 1)); 3484 3485 if ((track->framesReady() >= minFrames) && track->isReady() && 3486 !track->isPaused() && !track->isTerminated()) 3487 { 3488 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 3489 3490 if (track->mFillingUpStatus == Track::FS_FILLED) { 3491 track->mFillingUpStatus = Track::FS_ACTIVE; 3492 mLeftVolFloat = mRightVolFloat = 0; 3493 if (track->mState == TrackBase::RESUMING) { 3494 track->mState = TrackBase::ACTIVE; 3495 } 3496 } 3497 3498 // compute volume for this track 3499 processVolume_l(track, last); 3500 if (last) { 3501 // reset retry count 3502 track->mRetryCount = kMaxTrackRetriesDirect; 3503 mActiveTrack = t; 3504 mixerStatus = MIXER_TRACKS_READY; 3505 } 3506 } else { 3507 // clear effect chain input buffer if the last active track started underruns 3508 // to avoid sending previous audio buffer again to effects 3509 if (!mEffectChains.isEmpty() && (i == (count -1))) { 3510 mEffectChains[0]->clearInputBuffer(); 3511 } 3512 3513 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3514 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3515 track->isStopped() || track->isPaused()) { 3516 // We have consumed all the buffers of this track. 3517 // Remove it from the list of active tracks. 3518 // TODO: implement behavior for compressed audio 3519 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3520 size_t framesWritten = mBytesWritten / mFrameSize; 3521 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3522 if (track->isStopped()) { 3523 track->reset(); 3524 } 3525 tracksToRemove->add(track); 3526 } 3527 } else { 3528 // No buffers for this track. Give it a few chances to 3529 // fill a buffer, then remove it from active list. 3530 // Only consider last track started for mixer state control 3531 if (--(track->mRetryCount) <= 0) { 3532 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3533 tracksToRemove->add(track); 3534 } else if (last) { 3535 mixerStatus = MIXER_TRACKS_ENABLED; 3536 } 3537 } 3538 } 3539 } 3540 3541 // remove all the tracks that need to be... 3542 removeTracks_l(*tracksToRemove); 3543 3544 return mixerStatus; 3545} 3546 3547void AudioFlinger::DirectOutputThread::threadLoop_mix() 3548{ 3549 size_t frameCount = mFrameCount; 3550 int8_t *curBuf = (int8_t *)mMixBuffer; 3551 // output audio to hardware 3552 while (frameCount) { 3553 AudioBufferProvider::Buffer buffer; 3554 buffer.frameCount = frameCount; 3555 mActiveTrack->getNextBuffer(&buffer); 3556 if (buffer.raw == NULL) { 3557 memset(curBuf, 0, frameCount * mFrameSize); 3558 break; 3559 } 3560 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3561 frameCount -= buffer.frameCount; 3562 curBuf += buffer.frameCount * mFrameSize; 3563 mActiveTrack->releaseBuffer(&buffer); 3564 } 3565 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer; 3566 sleepTime = 0; 3567 standbyTime = systemTime() + standbyDelay; 3568 mActiveTrack.clear(); 3569} 3570 3571void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3572{ 3573 if (sleepTime == 0) { 3574 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3575 sleepTime = activeSleepTime; 3576 } else { 3577 sleepTime = idleSleepTime; 3578 } 3579 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3580 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3581 sleepTime = 0; 3582 } 3583} 3584 3585// getTrackName_l() must be called with ThreadBase::mLock held 3586int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask, 3587 int sessionId) 3588{ 3589 return 0; 3590} 3591 3592// deleteTrackName_l() must be called with ThreadBase::mLock held 3593void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 3594{ 3595} 3596 3597// checkForNewParameters_l() must be called with ThreadBase::mLock held 3598bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3599{ 3600 bool reconfig = false; 3601 3602 while (!mNewParameters.isEmpty()) { 3603 status_t status = NO_ERROR; 3604 String8 keyValuePair = mNewParameters[0]; 3605 AudioParameter param = AudioParameter(keyValuePair); 3606 int value; 3607 3608 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3609 // do not accept frame count changes if tracks are open as the track buffer 3610 // size depends on frame count and correct behavior would not be garantied 3611 // if frame count is changed after track creation 3612 if (!mTracks.isEmpty()) { 3613 status = INVALID_OPERATION; 3614 } else { 3615 reconfig = true; 3616 } 3617 } 3618 if (status == NO_ERROR) { 3619 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3620 keyValuePair.string()); 3621 if (!mStandby && status == INVALID_OPERATION) { 3622 mOutput->stream->common.standby(&mOutput->stream->common); 3623 mStandby = true; 3624 mBytesWritten = 0; 3625 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3626 keyValuePair.string()); 3627 } 3628 if (status == NO_ERROR && reconfig) { 3629 readOutputParameters(); 3630 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3631 } 3632 } 3633 3634 mNewParameters.removeAt(0); 3635 3636 mParamStatus = status; 3637 mParamCond.signal(); 3638 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3639 // already timed out waiting for the status and will never signal the condition. 3640 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3641 } 3642 return reconfig; 3643} 3644 3645uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3646{ 3647 uint32_t time; 3648 if (audio_is_linear_pcm(mFormat)) { 3649 time = PlaybackThread::activeSleepTimeUs(); 3650 } else { 3651 time = 10000; 3652 } 3653 return time; 3654} 3655 3656uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3657{ 3658 uint32_t time; 3659 if (audio_is_linear_pcm(mFormat)) { 3660 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3661 } else { 3662 time = 10000; 3663 } 3664 return time; 3665} 3666 3667uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3668{ 3669 uint32_t time; 3670 if (audio_is_linear_pcm(mFormat)) { 3671 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3672 } else { 3673 time = 10000; 3674 } 3675 return time; 3676} 3677 3678void AudioFlinger::DirectOutputThread::cacheParameters_l() 3679{ 3680 PlaybackThread::cacheParameters_l(); 3681 3682 // use shorter standby delay as on normal output to release 3683 // hardware resources as soon as possible 3684 standbyDelay = microseconds(activeSleepTime*2); 3685} 3686 3687// ---------------------------------------------------------------------------- 3688 3689AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 3690 const sp<AudioFlinger::OffloadThread>& offloadThread) 3691 : Thread(false /*canCallJava*/), 3692 mOffloadThread(offloadThread), 3693 mWriteBlocked(false), 3694 mDraining(false) 3695{ 3696} 3697 3698AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 3699{ 3700} 3701 3702void AudioFlinger::AsyncCallbackThread::onFirstRef() 3703{ 3704 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 3705} 3706 3707bool AudioFlinger::AsyncCallbackThread::threadLoop() 3708{ 3709 while (!exitPending()) { 3710 bool writeBlocked; 3711 bool draining; 3712 3713 { 3714 Mutex::Autolock _l(mLock); 3715 mWaitWorkCV.wait(mLock); 3716 if (exitPending()) { 3717 break; 3718 } 3719 writeBlocked = mWriteBlocked; 3720 draining = mDraining; 3721 ALOGV("AsyncCallbackThread mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining); 3722 } 3723 { 3724 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote(); 3725 if (offloadThread != 0) { 3726 if (writeBlocked == false) { 3727 offloadThread->setWriteBlocked(false); 3728 } 3729 if (draining == false) { 3730 offloadThread->setDraining(false); 3731 } 3732 } 3733 } 3734 } 3735 return false; 3736} 3737 3738void AudioFlinger::AsyncCallbackThread::exit() 3739{ 3740 ALOGV("AsyncCallbackThread::exit"); 3741 Mutex::Autolock _l(mLock); 3742 requestExit(); 3743 mWaitWorkCV.broadcast(); 3744} 3745 3746void AudioFlinger::AsyncCallbackThread::setWriteBlocked(bool value) 3747{ 3748 Mutex::Autolock _l(mLock); 3749 mWriteBlocked = value; 3750 if (!value) { 3751 mWaitWorkCV.signal(); 3752 } 3753} 3754 3755void AudioFlinger::AsyncCallbackThread::setDraining(bool value) 3756{ 3757 Mutex::Autolock _l(mLock); 3758 mDraining = value; 3759 if (!value) { 3760 mWaitWorkCV.signal(); 3761 } 3762} 3763 3764 3765// ---------------------------------------------------------------------------- 3766AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 3767 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 3768 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 3769 mHwPaused(false), 3770 mPausedBytesRemaining(0) 3771{ 3772 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 3773} 3774 3775AudioFlinger::OffloadThread::~OffloadThread() 3776{ 3777 mPreviousTrack.clear(); 3778} 3779 3780void AudioFlinger::OffloadThread::threadLoop_exit() 3781{ 3782 if (mFlushPending || mHwPaused) { 3783 // If a flush is pending or track was paused, just discard buffered data 3784 flushHw_l(); 3785 } else { 3786 mMixerStatus = MIXER_DRAIN_ALL; 3787 threadLoop_drain(); 3788 } 3789 mCallbackThread->exit(); 3790 PlaybackThread::threadLoop_exit(); 3791} 3792 3793AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 3794 Vector< sp<Track> > *tracksToRemove 3795) 3796{ 3797 ALOGV("OffloadThread::prepareTracks_l"); 3798 size_t count = mActiveTracks.size(); 3799 3800 mixer_state mixerStatus = MIXER_IDLE; 3801 if (mFlushPending) { 3802 flushHw_l(); 3803 mFlushPending = false; 3804 } 3805 // find out which tracks need to be processed 3806 for (size_t i = 0; i < count; i++) { 3807 sp<Track> t = mActiveTracks[i].promote(); 3808 // The track died recently 3809 if (t == 0) { 3810 continue; 3811 } 3812 Track* const track = t.get(); 3813 audio_track_cblk_t* cblk = track->cblk(); 3814 if (mPreviousTrack != NULL) { 3815 if (t != mPreviousTrack) { 3816 // Flush any data still being written from last track 3817 mBytesRemaining = 0; 3818 if (mPausedBytesRemaining) { 3819 // Last track was paused so we also need to flush saved 3820 // mixbuffer state and invalidate track so that it will 3821 // re-submit that unwritten data when it is next resumed 3822 mPausedBytesRemaining = 0; 3823 // Invalidate is a bit drastic - would be more efficient 3824 // to have a flag to tell client that some of the 3825 // previously written data was lost 3826 mPreviousTrack->invalidate(); 3827 } 3828 } 3829 } 3830 mPreviousTrack = t; 3831 bool last = (i == (count - 1)); 3832 if (track->isPausing()) { 3833 track->setPaused(); 3834 if (last) { 3835 if (!mHwPaused) { 3836 mOutput->stream->pause(mOutput->stream); 3837 mHwPaused = true; 3838 } 3839 // If we were part way through writing the mixbuffer to 3840 // the HAL we must save this until we resume 3841 // BUG - this will be wrong if a different track is made active, 3842 // in that case we want to discard the pending data in the 3843 // mixbuffer and tell the client to present it again when the 3844 // track is resumed 3845 mPausedWriteLength = mCurrentWriteLength; 3846 mPausedBytesRemaining = mBytesRemaining; 3847 mBytesRemaining = 0; // stop writing 3848 } 3849 tracksToRemove->add(track); 3850 } else if (track->framesReady() && track->isReady() && 3851 !track->isPaused() && !track->isTerminated()) { 3852 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 3853 if (track->mFillingUpStatus == Track::FS_FILLED) { 3854 track->mFillingUpStatus = Track::FS_ACTIVE; 3855 mLeftVolFloat = mRightVolFloat = 0; 3856 if (track->mState == TrackBase::RESUMING) { 3857 if (mPausedBytesRemaining) { 3858 // Need to continue write that was interrupted 3859 mCurrentWriteLength = mPausedWriteLength; 3860 mBytesRemaining = mPausedBytesRemaining; 3861 mPausedBytesRemaining = 0; 3862 } 3863 track->mState = TrackBase::ACTIVE; 3864 } 3865 } 3866 3867 if (last) { 3868 if (mHwPaused) { 3869 mOutput->stream->resume(mOutput->stream); 3870 mHwPaused = false; 3871 // threadLoop_mix() will handle the case that we need to 3872 // resume an interrupted write 3873 } 3874 // reset retry count 3875 track->mRetryCount = kMaxTrackRetriesOffload; 3876 mActiveTrack = t; 3877 mixerStatus = MIXER_TRACKS_READY; 3878 } 3879 } else { 3880 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3881 if (track->isStopping_1()) { 3882 // Hardware buffer can hold a large amount of audio so we must 3883 // wait for all current track's data to drain before we say 3884 // that the track is stopped. 3885 if (mBytesRemaining == 0) { 3886 // Only start draining when all data in mixbuffer 3887 // has been written 3888 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 3889 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 3890 sleepTime = 0; 3891 standbyTime = systemTime() + standbyDelay; 3892 if (last) { 3893 mixerStatus = MIXER_DRAIN_TRACK; 3894 if (mHwPaused) { 3895 // It is possible to move from PAUSED to STOPPING_1 without 3896 // a resume so we must ensure hardware is running 3897 mOutput->stream->resume(mOutput->stream); 3898 mHwPaused = false; 3899 } 3900 } 3901 } 3902 } else if (track->isStopping_2()) { 3903 // Drain has completed, signal presentation complete 3904 if (!mDraining || !last) { 3905 track->mState = TrackBase::STOPPED; 3906 size_t audioHALFrames = 3907 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3908 size_t framesWritten = 3909 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 3910 track->presentationComplete(framesWritten, audioHALFrames); 3911 track->reset(); 3912 tracksToRemove->add(track); 3913 } 3914 } else { 3915 // No buffers for this track. Give it a few chances to 3916 // fill a buffer, then remove it from active list. 3917 if (--(track->mRetryCount) <= 0) { 3918 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 3919 track->name()); 3920 tracksToRemove->add(track); 3921 } else if (last){ 3922 mixerStatus = MIXER_TRACKS_ENABLED; 3923 } 3924 } 3925 } 3926 // compute volume for this track 3927 processVolume_l(track, last); 3928 } 3929 // remove all the tracks that need to be... 3930 removeTracks_l(*tracksToRemove); 3931 3932 return mixerStatus; 3933} 3934 3935void AudioFlinger::OffloadThread::flushOutput_l() 3936{ 3937 mFlushPending = true; 3938} 3939 3940// must be called with thread mutex locked 3941bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 3942{ 3943 ALOGV("waitingAsyncCallback_l mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining); 3944 if (mUseAsyncWrite && (mWriteBlocked || mDraining)) { 3945 return true; 3946 } 3947 return false; 3948} 3949 3950// must be called with thread mutex locked 3951bool AudioFlinger::OffloadThread::shouldStandby_l() 3952{ 3953 bool TrackPaused = false; 3954 3955 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 3956 // after a timeout and we will enter standby then. 3957 if (mTracks.size() > 0) { 3958 TrackPaused = mTracks[mTracks.size() - 1]->isPaused(); 3959 } 3960 3961 return !mStandby && !TrackPaused; 3962} 3963 3964 3965bool AudioFlinger::OffloadThread::waitingAsyncCallback() 3966{ 3967 Mutex::Autolock _l(mLock); 3968 return waitingAsyncCallback_l(); 3969} 3970 3971void AudioFlinger::OffloadThread::flushHw_l() 3972{ 3973 mOutput->stream->flush(mOutput->stream); 3974 // Flush anything still waiting in the mixbuffer 3975 mCurrentWriteLength = 0; 3976 mBytesRemaining = 0; 3977 mPausedWriteLength = 0; 3978 mPausedBytesRemaining = 0; 3979 if (mUseAsyncWrite) { 3980 mWriteBlocked = false; 3981 mDraining = false; 3982 ALOG_ASSERT(mCallbackThread != 0); 3983 mCallbackThread->setWriteBlocked(false); 3984 mCallbackThread->setDraining(false); 3985 } 3986} 3987 3988// ---------------------------------------------------------------------------- 3989 3990AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 3991 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 3992 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 3993 DUPLICATING), 3994 mWaitTimeMs(UINT_MAX) 3995{ 3996 addOutputTrack(mainThread); 3997} 3998 3999AudioFlinger::DuplicatingThread::~DuplicatingThread() 4000{ 4001 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4002 mOutputTracks[i]->destroy(); 4003 } 4004} 4005 4006void AudioFlinger::DuplicatingThread::threadLoop_mix() 4007{ 4008 // mix buffers... 4009 if (outputsReady(outputTracks)) { 4010 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4011 } else { 4012 memset(mMixBuffer, 0, mixBufferSize); 4013 } 4014 sleepTime = 0; 4015 writeFrames = mNormalFrameCount; 4016 mCurrentWriteLength = mixBufferSize; 4017 standbyTime = systemTime() + standbyDelay; 4018} 4019 4020void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4021{ 4022 if (sleepTime == 0) { 4023 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4024 sleepTime = activeSleepTime; 4025 } else { 4026 sleepTime = idleSleepTime; 4027 } 4028 } else if (mBytesWritten != 0) { 4029 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4030 writeFrames = mNormalFrameCount; 4031 memset(mMixBuffer, 0, mixBufferSize); 4032 } else { 4033 // flush remaining overflow buffers in output tracks 4034 writeFrames = 0; 4035 } 4036 sleepTime = 0; 4037 } 4038} 4039 4040ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4041{ 4042 for (size_t i = 0; i < outputTracks.size(); i++) { 4043 outputTracks[i]->write(mMixBuffer, writeFrames); 4044 } 4045 return (ssize_t)mixBufferSize; 4046} 4047 4048void AudioFlinger::DuplicatingThread::threadLoop_standby() 4049{ 4050 // DuplicatingThread implements standby by stopping all tracks 4051 for (size_t i = 0; i < outputTracks.size(); i++) { 4052 outputTracks[i]->stop(); 4053 } 4054} 4055 4056void AudioFlinger::DuplicatingThread::saveOutputTracks() 4057{ 4058 outputTracks = mOutputTracks; 4059} 4060 4061void AudioFlinger::DuplicatingThread::clearOutputTracks() 4062{ 4063 outputTracks.clear(); 4064} 4065 4066void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4067{ 4068 Mutex::Autolock _l(mLock); 4069 // FIXME explain this formula 4070 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4071 OutputTrack *outputTrack = new OutputTrack(thread, 4072 this, 4073 mSampleRate, 4074 mFormat, 4075 mChannelMask, 4076 frameCount); 4077 if (outputTrack->cblk() != NULL) { 4078 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4079 mOutputTracks.add(outputTrack); 4080 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4081 updateWaitTime_l(); 4082 } 4083} 4084 4085void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4086{ 4087 Mutex::Autolock _l(mLock); 4088 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4089 if (mOutputTracks[i]->thread() == thread) { 4090 mOutputTracks[i]->destroy(); 4091 mOutputTracks.removeAt(i); 4092 updateWaitTime_l(); 4093 return; 4094 } 4095 } 4096 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4097} 4098 4099// caller must hold mLock 4100void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4101{ 4102 mWaitTimeMs = UINT_MAX; 4103 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4104 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4105 if (strong != 0) { 4106 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4107 if (waitTimeMs < mWaitTimeMs) { 4108 mWaitTimeMs = waitTimeMs; 4109 } 4110 } 4111 } 4112} 4113 4114 4115bool AudioFlinger::DuplicatingThread::outputsReady( 4116 const SortedVector< sp<OutputTrack> > &outputTracks) 4117{ 4118 for (size_t i = 0; i < outputTracks.size(); i++) { 4119 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4120 if (thread == 0) { 4121 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4122 outputTracks[i].get()); 4123 return false; 4124 } 4125 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4126 // see note at standby() declaration 4127 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4128 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4129 thread.get()); 4130 return false; 4131 } 4132 } 4133 return true; 4134} 4135 4136uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4137{ 4138 return (mWaitTimeMs * 1000) / 2; 4139} 4140 4141void AudioFlinger::DuplicatingThread::cacheParameters_l() 4142{ 4143 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4144 updateWaitTime_l(); 4145 4146 MixerThread::cacheParameters_l(); 4147} 4148 4149// ---------------------------------------------------------------------------- 4150// Record 4151// ---------------------------------------------------------------------------- 4152 4153AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4154 AudioStreamIn *input, 4155 uint32_t sampleRate, 4156 audio_channel_mask_t channelMask, 4157 audio_io_handle_t id, 4158 audio_devices_t outDevice, 4159 audio_devices_t inDevice 4160#ifdef TEE_SINK 4161 , const sp<NBAIO_Sink>& teeSink 4162#endif 4163 ) : 4164 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4165 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4166 // mRsmpInIndex set by readInputParameters() 4167 mReqChannelCount(popcount(channelMask)), 4168 mReqSampleRate(sampleRate) 4169 // mBytesRead is only meaningful while active, and so is cleared in start() 4170 // (but might be better to also clear here for dump?) 4171#ifdef TEE_SINK 4172 , mTeeSink(teeSink) 4173#endif 4174{ 4175 snprintf(mName, kNameLength, "AudioIn_%X", id); 4176 4177 readInputParameters(); 4178 4179} 4180 4181 4182AudioFlinger::RecordThread::~RecordThread() 4183{ 4184 delete[] mRsmpInBuffer; 4185 delete mResampler; 4186 delete[] mRsmpOutBuffer; 4187} 4188 4189void AudioFlinger::RecordThread::onFirstRef() 4190{ 4191 run(mName, PRIORITY_URGENT_AUDIO); 4192} 4193 4194bool AudioFlinger::RecordThread::threadLoop() 4195{ 4196 AudioBufferProvider::Buffer buffer; 4197 sp<RecordTrack> activeTrack; 4198 4199 nsecs_t lastWarning = 0; 4200 4201 inputStandBy(); 4202 acquireWakeLock(); 4203 4204 // used to verify we've read at least once before evaluating how many bytes were read 4205 bool readOnce = false; 4206 4207 // start recording 4208 // FIXME Race here: exitPending could become true immediately after testing. 4209 // It is only set to true while mLock held, but we don't hold mLock yet. 4210 // Probably a benign race, but it would be safer to check exitPending with mLock held. 4211 while (!exitPending()) { 4212 4213 processConfigEvents(); 4214 4215 Vector< sp<EffectChain> > effectChains; 4216 { // scope for mLock 4217 Mutex::Autolock _l(mLock); 4218 checkForNewParameters_l(); 4219 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 4220 standby(); 4221 4222 if (exitPending()) { 4223 break; 4224 } 4225 4226 releaseWakeLock_l(); 4227 ALOGV("RecordThread: loop stopping"); 4228 // go to sleep 4229 mWaitWorkCV.wait(mLock); 4230 ALOGV("RecordThread: loop starting"); 4231 acquireWakeLock_l(); 4232 continue; 4233 } 4234 if (mActiveTrack != 0) { 4235 if (mActiveTrack->isTerminated()) { 4236 removeTrack_l(mActiveTrack); 4237 mActiveTrack.clear(); 4238 } else { 4239 switch (mActiveTrack->mState) { 4240 case TrackBase::PAUSING: 4241 standby(); 4242 mActiveTrack.clear(); 4243 mStartStopCond.broadcast(); 4244 break; 4245 4246 case TrackBase::RESUMING: 4247 if (mReqChannelCount != mActiveTrack->channelCount()) { 4248 mActiveTrack.clear(); 4249 mStartStopCond.broadcast(); 4250 } else if (readOnce) { 4251 // record start succeeds only if first read from audio input 4252 // succeeds 4253 if (mBytesRead >= 0) { 4254 mActiveTrack->mState = TrackBase::ACTIVE; 4255 } else { 4256 mActiveTrack.clear(); 4257 } 4258 mStartStopCond.broadcast(); 4259 } 4260 mStandby = false; 4261 break; 4262 4263 case TrackBase::ACTIVE: 4264 break; 4265 4266 case TrackBase::IDLE: 4267 break; 4268 4269 default: 4270 LOG_FATAL("Unexpected mActiveTrack->mState %d", mActiveTrack->mState); 4271 } 4272 4273 } 4274 } 4275 lockEffectChains_l(effectChains); 4276 } 4277 4278 // thread mutex is now unlocked 4279 // FIXME RecordThread::start assigns to mActiveTrack under lock, but we read without lock 4280 if (mActiveTrack != 0) { 4281 // FIXME RecordThread::stop assigns to mState under lock, but we read without lock 4282 if (mActiveTrack->mState != TrackBase::ACTIVE && 4283 mActiveTrack->mState != TrackBase::RESUMING) { 4284 unlockEffectChains(effectChains); 4285 usleep(kRecordThreadSleepUs); 4286 continue; 4287 } 4288 for (size_t i = 0; i < effectChains.size(); i ++) { 4289 // thread mutex is not locked, but effect chain is locked 4290 effectChains[i]->process_l(); 4291 } 4292 4293 buffer.frameCount = mFrameCount; 4294 status_t status = mActiveTrack->getNextBuffer(&buffer); 4295 if (status == NO_ERROR) { 4296 readOnce = true; 4297 size_t framesOut = buffer.frameCount; 4298 if (mResampler == NULL) { 4299 // no resampling 4300 while (framesOut) { 4301 size_t framesIn = mFrameCount - mRsmpInIndex; 4302 if (framesIn > 0) { 4303 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4304 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * 4305 mActiveTrack->mFrameSize; 4306 if (framesIn > framesOut) { 4307 framesIn = framesOut; 4308 } 4309 mRsmpInIndex += framesIn; 4310 framesOut -= framesIn; 4311 if (mChannelCount == mReqChannelCount) { 4312 memcpy(dst, src, framesIn * mFrameSize); 4313 } else { 4314 if (mChannelCount == 1) { 4315 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, 4316 (int16_t *)src, framesIn); 4317 } else { 4318 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, 4319 (int16_t *)src, framesIn); 4320 } 4321 } 4322 } 4323 if (framesOut > 0 && mFrameCount == mRsmpInIndex) { 4324 void *readInto; 4325 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) { 4326 readInto = buffer.raw; 4327 framesOut = 0; 4328 } else { 4329 readInto = mRsmpInBuffer; 4330 mRsmpInIndex = 0; 4331 } 4332 mBytesRead = mInput->stream->read(mInput->stream, readInto, 4333 mBufferSize); 4334 if (mBytesRead <= 0) { 4335 // FIXME read mState without lock 4336 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) 4337 { 4338 ALOGE("Error reading audio input"); 4339 // Force input into standby so that it tries to 4340 // recover at next read attempt 4341 inputStandBy(); 4342 // FIXME sleep with effect chains locked 4343 usleep(kRecordThreadSleepUs); 4344 } 4345 mRsmpInIndex = mFrameCount; 4346 framesOut = 0; 4347 buffer.frameCount = 0; 4348 } 4349#ifdef TEE_SINK 4350 else if (mTeeSink != 0) { 4351 (void) mTeeSink->write(readInto, 4352 mBytesRead >> Format_frameBitShift(mTeeSink->format())); 4353 } 4354#endif 4355 } 4356 } 4357 } else { 4358 // resampling 4359 4360 // resampler accumulates, but we only have one source track 4361 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 4362 // alter output frame count as if we were expecting stereo samples 4363 if (mChannelCount == 1 && mReqChannelCount == 1) { 4364 framesOut >>= 1; 4365 } 4366 mResampler->resample(mRsmpOutBuffer, framesOut, 4367 this /* AudioBufferProvider* */); 4368 // ditherAndClamp() works as long as all buffers returned by 4369 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true. 4370 if (mChannelCount == 2 && mReqChannelCount == 1) { 4371 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t 4372 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4373 // the resampler always outputs stereo samples: 4374 // do post stereo to mono conversion 4375 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, 4376 framesOut); 4377 } else { 4378 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4379 } 4380 // now done with mRsmpOutBuffer 4381 4382 } 4383 if (mFramestoDrop == 0) { 4384 mActiveTrack->releaseBuffer(&buffer); 4385 } else { 4386 if (mFramestoDrop > 0) { 4387 mFramestoDrop -= buffer.frameCount; 4388 if (mFramestoDrop <= 0) { 4389 clearSyncStartEvent(); 4390 } 4391 } else { 4392 mFramestoDrop += buffer.frameCount; 4393 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 4394 mSyncStartEvent->isCancelled()) { 4395 ALOGW("Synced record %s, session %d, trigger session %d", 4396 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 4397 mActiveTrack->sessionId(), 4398 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 4399 clearSyncStartEvent(); 4400 } 4401 } 4402 } 4403 mActiveTrack->clearOverflow(); 4404 } 4405 // client isn't retrieving buffers fast enough 4406 else { 4407 if (!mActiveTrack->setOverflow()) { 4408 nsecs_t now = systemTime(); 4409 if ((now - lastWarning) > kWarningThrottleNs) { 4410 ALOGW("RecordThread: buffer overflow"); 4411 lastWarning = now; 4412 } 4413 } 4414 // Release the processor for a while before asking for a new buffer. 4415 // This will give the application more chance to read from the buffer and 4416 // clear the overflow. 4417 // FIXME sleep with effect chains locked 4418 usleep(kRecordThreadSleepUs); 4419 } 4420 } 4421 // enable changes in effect chain 4422 unlockEffectChains(effectChains); 4423 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 4424 } 4425 4426 standby(); 4427 4428 { 4429 Mutex::Autolock _l(mLock); 4430 mActiveTrack.clear(); 4431 mStartStopCond.broadcast(); 4432 } 4433 4434 releaseWakeLock(); 4435 4436 ALOGV("RecordThread %p exiting", this); 4437 return false; 4438} 4439 4440void AudioFlinger::RecordThread::standby() 4441{ 4442 if (!mStandby) { 4443 inputStandBy(); 4444 mStandby = true; 4445 } 4446} 4447 4448void AudioFlinger::RecordThread::inputStandBy() 4449{ 4450 mInput->stream->common.standby(&mInput->stream->common); 4451} 4452 4453sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4454 const sp<AudioFlinger::Client>& client, 4455 uint32_t sampleRate, 4456 audio_format_t format, 4457 audio_channel_mask_t channelMask, 4458 size_t frameCount, 4459 int sessionId, 4460 IAudioFlinger::track_flags_t *flags, 4461 pid_t tid, 4462 status_t *status) 4463{ 4464 sp<RecordTrack> track; 4465 status_t lStatus; 4466 4467 lStatus = initCheck(); 4468 if (lStatus != NO_ERROR) { 4469 ALOGE("Audio driver not initialized."); 4470 goto Exit; 4471 } 4472 4473 // client expresses a preference for FAST, but we get the final say 4474 if (*flags & IAudioFlinger::TRACK_FAST) { 4475 if ( 4476 // use case: callback handler and frame count is default or at least as large as HAL 4477 ( 4478 (tid != -1) && 4479 ((frameCount == 0) || 4480 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 4481 ) && 4482 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format) 4483 // mono or stereo 4484 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 4485 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 4486 // hardware sample rate 4487 (sampleRate == mSampleRate) && 4488 // record thread has an associated fast recorder 4489 hasFastRecorder() 4490 // FIXME test that RecordThread for this fast track has a capable output HAL 4491 // FIXME add a permission test also? 4492 ) { 4493 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count 4494 if (frameCount == 0) { 4495 frameCount = mFrameCount * kFastTrackMultiplier; 4496 } 4497 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 4498 frameCount, mFrameCount); 4499 } else { 4500 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d " 4501 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 4502 "hasFastRecorder=%d tid=%d", 4503 frameCount, mFrameCount, format, 4504 audio_is_linear_pcm(format), 4505 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid); 4506 *flags &= ~IAudioFlinger::TRACK_FAST; 4507 // For compatibility with AudioRecord calculation, buffer depth is forced 4508 // to be at least 2 x the record thread frame count and cover audio hardware latency. 4509 // This is probably too conservative, but legacy application code may depend on it. 4510 // If you change this calculation, also review the start threshold which is related. 4511 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream); 4512 size_t mNormalFrameCount = 2048; // FIXME 4513 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 4514 if (minBufCount < 2) { 4515 minBufCount = 2; 4516 } 4517 size_t minFrameCount = mNormalFrameCount * minBufCount; 4518 if (frameCount < minFrameCount) { 4519 frameCount = minFrameCount; 4520 } 4521 } 4522 } 4523 4524 // FIXME use flags and tid similar to createTrack_l() 4525 4526 { // scope for mLock 4527 Mutex::Autolock _l(mLock); 4528 4529 track = new RecordTrack(this, client, sampleRate, 4530 format, channelMask, frameCount, sessionId); 4531 4532 lStatus = track->initCheck(); 4533 if (lStatus != NO_ERROR) { 4534 track.clear(); 4535 goto Exit; 4536 } 4537 mTracks.add(track); 4538 4539 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4540 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4541 mAudioFlinger->btNrecIsOff(); 4542 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4543 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4544 4545 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 4546 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 4547 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 4548 // so ask activity manager to do this on our behalf 4549 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 4550 } 4551 } 4552 lStatus = NO_ERROR; 4553 4554Exit: 4555 *status = lStatus; 4556 return track; 4557} 4558 4559status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 4560 AudioSystem::sync_event_t event, 4561 int triggerSession) 4562{ 4563 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 4564 sp<ThreadBase> strongMe = this; 4565 status_t status = NO_ERROR; 4566 4567 if (event == AudioSystem::SYNC_EVENT_NONE) { 4568 clearSyncStartEvent(); 4569 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 4570 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 4571 triggerSession, 4572 recordTrack->sessionId(), 4573 syncStartEventCallback, 4574 this); 4575 // Sync event can be cancelled by the trigger session if the track is not in a 4576 // compatible state in which case we start record immediately 4577 if (mSyncStartEvent->isCancelled()) { 4578 clearSyncStartEvent(); 4579 } else { 4580 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 4581 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 4582 } 4583 } 4584 4585 { 4586 // This section is a rendezvous between binder thread executing start() and RecordThread 4587 AutoMutex lock(mLock); 4588 if (mActiveTrack != 0) { 4589 if (recordTrack != mActiveTrack.get()) { 4590 status = -EBUSY; 4591 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4592 mActiveTrack->mState = TrackBase::ACTIVE; 4593 } 4594 return status; 4595 } 4596 4597 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate 4598 recordTrack->mState = TrackBase::IDLE; 4599 mActiveTrack = recordTrack; 4600 mLock.unlock(); 4601 status_t status = AudioSystem::startInput(mId); 4602 mLock.lock(); 4603 // FIXME should verify that mActiveTrack is still == recordTrack 4604 if (status != NO_ERROR) { 4605 mActiveTrack.clear(); 4606 clearSyncStartEvent(); 4607 return status; 4608 } 4609 mRsmpInIndex = mFrameCount; 4610 mBytesRead = 0; 4611 if (mResampler != NULL) { 4612 mResampler->reset(); 4613 } 4614 // FIXME hijacking a playback track state name which was intended for start after pause; 4615 // here 'STARTING_2' would be more accurate 4616 mActiveTrack->mState = TrackBase::RESUMING; 4617 // signal thread to start 4618 ALOGV("Signal record thread"); 4619 mWaitWorkCV.broadcast(); 4620 // do not wait for mStartStopCond if exiting 4621 if (exitPending()) { 4622 mActiveTrack.clear(); 4623 status = INVALID_OPERATION; 4624 goto startError; 4625 } 4626 // FIXME incorrect usage of wait: no explicit predicate or loop 4627 mStartStopCond.wait(mLock); 4628 if (mActiveTrack == 0) { 4629 ALOGV("Record failed to start"); 4630 status = BAD_VALUE; 4631 goto startError; 4632 } 4633 ALOGV("Record started OK"); 4634 return status; 4635 } 4636 4637startError: 4638 AudioSystem::stopInput(mId); 4639 clearSyncStartEvent(); 4640 return status; 4641} 4642 4643void AudioFlinger::RecordThread::clearSyncStartEvent() 4644{ 4645 if (mSyncStartEvent != 0) { 4646 mSyncStartEvent->cancel(); 4647 } 4648 mSyncStartEvent.clear(); 4649 mFramestoDrop = 0; 4650} 4651 4652void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 4653{ 4654 sp<SyncEvent> strongEvent = event.promote(); 4655 4656 if (strongEvent != 0) { 4657 RecordThread *me = (RecordThread *)strongEvent->cookie(); 4658 me->handleSyncStartEvent(strongEvent); 4659 } 4660} 4661 4662void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 4663{ 4664 if (event == mSyncStartEvent) { 4665 // TODO: use actual buffer filling status instead of 2 buffers when info is available 4666 // from audio HAL 4667 mFramestoDrop = mFrameCount * 2; 4668 } 4669} 4670 4671bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 4672 ALOGV("RecordThread::stop"); 4673 AutoMutex _l(mLock); 4674 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) { 4675 return false; 4676 } 4677 // note that threadLoop may still be processing the track at this point [without lock] 4678 recordTrack->mState = TrackBase::PAUSING; 4679 // do not wait for mStartStopCond if exiting 4680 if (exitPending()) { 4681 return true; 4682 } 4683 // FIXME incorrect usage of wait: no explicit predicate or loop 4684 mStartStopCond.wait(mLock); 4685 // if we have been restarted, recordTrack == mActiveTrack.get() here 4686 if (exitPending() || recordTrack != mActiveTrack.get()) { 4687 ALOGV("Record stopped OK"); 4688 return true; 4689 } 4690 return false; 4691} 4692 4693bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const 4694{ 4695 return false; 4696} 4697 4698status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) 4699{ 4700#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 4701 if (!isValidSyncEvent(event)) { 4702 return BAD_VALUE; 4703 } 4704 4705 int eventSession = event->triggerSession(); 4706 status_t ret = NAME_NOT_FOUND; 4707 4708 Mutex::Autolock _l(mLock); 4709 4710 for (size_t i = 0; i < mTracks.size(); i++) { 4711 sp<RecordTrack> track = mTracks[i]; 4712 if (eventSession == track->sessionId()) { 4713 (void) track->setSyncEvent(event); 4714 ret = NO_ERROR; 4715 } 4716 } 4717 return ret; 4718#else 4719 return BAD_VALUE; 4720#endif 4721} 4722 4723// destroyTrack_l() must be called with ThreadBase::mLock held 4724void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 4725{ 4726 track->terminate(); 4727 track->mState = TrackBase::STOPPED; 4728 // active tracks are removed by threadLoop() 4729 if (mActiveTrack != track) { 4730 removeTrack_l(track); 4731 } 4732} 4733 4734void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 4735{ 4736 mTracks.remove(track); 4737 // need anything related to effects here? 4738} 4739 4740void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 4741{ 4742 dumpInternals(fd, args); 4743 dumpTracks(fd, args); 4744 dumpEffectChains(fd, args); 4745} 4746 4747void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 4748{ 4749 const size_t SIZE = 256; 4750 char buffer[SIZE]; 4751 String8 result; 4752 4753 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 4754 result.append(buffer); 4755 4756 if (mActiveTrack != 0) { 4757 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 4758 result.append(buffer); 4759 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize); 4760 result.append(buffer); 4761 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 4762 result.append(buffer); 4763 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount); 4764 result.append(buffer); 4765 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate); 4766 result.append(buffer); 4767 } else { 4768 result.append("No active record client\n"); 4769 } 4770 4771 write(fd, result.string(), result.size()); 4772 4773 dumpBase(fd, args); 4774} 4775 4776void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args) 4777{ 4778 const size_t SIZE = 256; 4779 char buffer[SIZE]; 4780 String8 result; 4781 4782 snprintf(buffer, SIZE, "Input thread %p tracks\n", this); 4783 result.append(buffer); 4784 RecordTrack::appendDumpHeader(result); 4785 for (size_t i = 0; i < mTracks.size(); ++i) { 4786 sp<RecordTrack> track = mTracks[i]; 4787 if (track != 0) { 4788 track->dump(buffer, SIZE); 4789 result.append(buffer); 4790 } 4791 } 4792 4793 if (mActiveTrack != 0) { 4794 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this); 4795 result.append(buffer); 4796 RecordTrack::appendDumpHeader(result); 4797 mActiveTrack->dump(buffer, SIZE); 4798 result.append(buffer); 4799 4800 } 4801 write(fd, result.string(), result.size()); 4802} 4803 4804// AudioBufferProvider interface 4805status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 4806{ 4807 size_t framesReq = buffer->frameCount; 4808 size_t framesReady = mFrameCount - mRsmpInIndex; 4809 int channelCount; 4810 4811 if (framesReady == 0) { 4812 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize); 4813 if (mBytesRead <= 0) { 4814 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) { 4815 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 4816 // Force input into standby so that it tries to 4817 // recover at next read attempt 4818 inputStandBy(); 4819 usleep(kRecordThreadSleepUs); 4820 } 4821 buffer->raw = NULL; 4822 buffer->frameCount = 0; 4823 return NOT_ENOUGH_DATA; 4824 } 4825 mRsmpInIndex = 0; 4826 framesReady = mFrameCount; 4827 } 4828 4829 if (framesReq > framesReady) { 4830 framesReq = framesReady; 4831 } 4832 4833 if (mChannelCount == 1 && mReqChannelCount == 2) { 4834 channelCount = 1; 4835 } else { 4836 channelCount = 2; 4837 } 4838 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 4839 buffer->frameCount = framesReq; 4840 return NO_ERROR; 4841} 4842 4843// AudioBufferProvider interface 4844void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4845{ 4846 mRsmpInIndex += buffer->frameCount; 4847 buffer->frameCount = 0; 4848} 4849 4850bool AudioFlinger::RecordThread::checkForNewParameters_l() 4851{ 4852 bool reconfig = false; 4853 4854 while (!mNewParameters.isEmpty()) { 4855 status_t status = NO_ERROR; 4856 String8 keyValuePair = mNewParameters[0]; 4857 AudioParameter param = AudioParameter(keyValuePair); 4858 int value; 4859 audio_format_t reqFormat = mFormat; 4860 uint32_t reqSamplingRate = mReqSampleRate; 4861 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount); 4862 4863 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4864 reqSamplingRate = value; 4865 reconfig = true; 4866 } 4867 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4868 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 4869 status = BAD_VALUE; 4870 } else { 4871 reqFormat = (audio_format_t) value; 4872 reconfig = true; 4873 } 4874 } 4875 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4876 audio_channel_mask_t mask = (audio_channel_mask_t) value; 4877 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) { 4878 status = BAD_VALUE; 4879 } else { 4880 reqChannelMask = mask; 4881 reconfig = true; 4882 } 4883 } 4884 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4885 // do not accept frame count changes if tracks are open as the track buffer 4886 // size depends on frame count and correct behavior would not be guaranteed 4887 // if frame count is changed after track creation 4888 if (mActiveTrack != 0) { 4889 status = INVALID_OPERATION; 4890 } else { 4891 reconfig = true; 4892 } 4893 } 4894 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4895 // forward device change to effects that have requested to be 4896 // aware of attached audio device. 4897 for (size_t i = 0; i < mEffectChains.size(); i++) { 4898 mEffectChains[i]->setDevice_l(value); 4899 } 4900 4901 // store input device and output device but do not forward output device to audio HAL. 4902 // Note that status is ignored by the caller for output device 4903 // (see AudioFlinger::setParameters() 4904 if (audio_is_output_devices(value)) { 4905 mOutDevice = value; 4906 status = BAD_VALUE; 4907 } else { 4908 mInDevice = value; 4909 // disable AEC and NS if the device is a BT SCO headset supporting those 4910 // pre processings 4911 if (mTracks.size() > 0) { 4912 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4913 mAudioFlinger->btNrecIsOff(); 4914 for (size_t i = 0; i < mTracks.size(); i++) { 4915 sp<RecordTrack> track = mTracks[i]; 4916 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 4917 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 4918 } 4919 } 4920 } 4921 } 4922 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 4923 mAudioSource != (audio_source_t)value) { 4924 // forward device change to effects that have requested to be 4925 // aware of attached audio device. 4926 for (size_t i = 0; i < mEffectChains.size(); i++) { 4927 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 4928 } 4929 mAudioSource = (audio_source_t)value; 4930 } 4931 4932 if (status == NO_ERROR) { 4933 status = mInput->stream->common.set_parameters(&mInput->stream->common, 4934 keyValuePair.string()); 4935 if (status == INVALID_OPERATION) { 4936 inputStandBy(); 4937 status = mInput->stream->common.set_parameters(&mInput->stream->common, 4938 keyValuePair.string()); 4939 } 4940 if (reconfig) { 4941 if (status == BAD_VALUE && 4942 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 4943 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 4944 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 4945 <= (2 * reqSamplingRate)) && 4946 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) 4947 <= FCC_2 && 4948 (reqChannelMask == AUDIO_CHANNEL_IN_MONO || 4949 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) { 4950 status = NO_ERROR; 4951 } 4952 if (status == NO_ERROR) { 4953 readInputParameters(); 4954 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 4955 } 4956 } 4957 } 4958 4959 mNewParameters.removeAt(0); 4960 4961 mParamStatus = status; 4962 mParamCond.signal(); 4963 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 4964 // already timed out waiting for the status and will never signal the condition. 4965 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 4966 } 4967 return reconfig; 4968} 4969 4970String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 4971{ 4972 Mutex::Autolock _l(mLock); 4973 if (initCheck() != NO_ERROR) { 4974 return String8(); 4975 } 4976 4977 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 4978 const String8 out_s8(s); 4979 free(s); 4980 return out_s8; 4981} 4982 4983void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 4984 AudioSystem::OutputDescriptor desc; 4985 void *param2 = NULL; 4986 4987 switch (event) { 4988 case AudioSystem::INPUT_OPENED: 4989 case AudioSystem::INPUT_CONFIG_CHANGED: 4990 desc.channelMask = mChannelMask; 4991 desc.samplingRate = mSampleRate; 4992 desc.format = mFormat; 4993 desc.frameCount = mFrameCount; 4994 desc.latency = 0; 4995 param2 = &desc; 4996 break; 4997 4998 case AudioSystem::INPUT_CLOSED: 4999 default: 5000 break; 5001 } 5002 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 5003} 5004 5005void AudioFlinger::RecordThread::readInputParameters() 5006{ 5007 delete[] mRsmpInBuffer; 5008 // mRsmpInBuffer is always assigned a new[] below 5009 delete[] mRsmpOutBuffer; 5010 mRsmpOutBuffer = NULL; 5011 delete mResampler; 5012 mResampler = NULL; 5013 5014 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 5015 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 5016 mChannelCount = popcount(mChannelMask); 5017 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 5018 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 5019 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 5020 } 5021 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 5022 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 5023 mFrameCount = mBufferSize / mFrameSize; 5024 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 5025 5026 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) { 5027 int channelCount; 5028 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid 5029 // stereo to mono post process as the resampler always outputs stereo. 5030 if (mChannelCount == 1 && mReqChannelCount == 2) { 5031 channelCount = 1; 5032 } else { 5033 channelCount = 2; 5034 } 5035 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 5036 mResampler->setSampleRate(mSampleRate); 5037 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 5038 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2]; 5039 5040 // optmization: if mono to mono, alter input frame count as if we were inputing 5041 // stereo samples 5042 if (mChannelCount == 1 && mReqChannelCount == 1) { 5043 mFrameCount >>= 1; 5044 } 5045 5046 } 5047 mRsmpInIndex = mFrameCount; 5048} 5049 5050unsigned int AudioFlinger::RecordThread::getInputFramesLost() 5051{ 5052 Mutex::Autolock _l(mLock); 5053 if (initCheck() != NO_ERROR) { 5054 return 0; 5055 } 5056 5057 return mInput->stream->get_input_frames_lost(mInput->stream); 5058} 5059 5060uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 5061{ 5062 Mutex::Autolock _l(mLock); 5063 uint32_t result = 0; 5064 if (getEffectChain_l(sessionId) != 0) { 5065 result = EFFECT_SESSION; 5066 } 5067 5068 for (size_t i = 0; i < mTracks.size(); ++i) { 5069 if (sessionId == mTracks[i]->sessionId()) { 5070 result |= TRACK_SESSION; 5071 break; 5072 } 5073 } 5074 5075 return result; 5076} 5077 5078KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 5079{ 5080 KeyedVector<int, bool> ids; 5081 Mutex::Autolock _l(mLock); 5082 for (size_t j = 0; j < mTracks.size(); ++j) { 5083 sp<RecordThread::RecordTrack> track = mTracks[j]; 5084 int sessionId = track->sessionId(); 5085 if (ids.indexOfKey(sessionId) < 0) { 5086 ids.add(sessionId, true); 5087 } 5088 } 5089 return ids; 5090} 5091 5092AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 5093{ 5094 Mutex::Autolock _l(mLock); 5095 AudioStreamIn *input = mInput; 5096 mInput = NULL; 5097 return input; 5098} 5099 5100// this method must always be called either with ThreadBase mLock held or inside the thread loop 5101audio_stream_t* AudioFlinger::RecordThread::stream() const 5102{ 5103 if (mInput == NULL) { 5104 return NULL; 5105 } 5106 return &mInput->stream->common; 5107} 5108 5109status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 5110{ 5111 // only one chain per input thread 5112 if (mEffectChains.size() != 0) { 5113 return INVALID_OPERATION; 5114 } 5115 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 5116 5117 chain->setInBuffer(NULL); 5118 chain->setOutBuffer(NULL); 5119 5120 checkSuspendOnAddEffectChain_l(chain); 5121 5122 mEffectChains.add(chain); 5123 5124 return NO_ERROR; 5125} 5126 5127size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 5128{ 5129 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 5130 ALOGW_IF(mEffectChains.size() != 1, 5131 "removeEffectChain_l() %p invalid chain size %d on thread %p", 5132 chain.get(), mEffectChains.size(), this); 5133 if (mEffectChains.size() == 1) { 5134 mEffectChains.removeAt(0); 5135 } 5136 return 0; 5137} 5138 5139}; // namespace android 5140