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