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