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