blob: 9c8fd1f172218ebb6208c297ede086334f4a3a69 [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
2708 if (mNormalSink != 0) {
2709 status = mNormalSink->getNextWriteTimestamp(&pts);
2710 } else {
2711 status = mOutputSink->getNextWriteTimestamp(&pts);
2712 }
2713
2714 if (status != NO_ERROR) {
2715 pts = AudioBufferProvider::kInvalidPTS;
2716 }
2717
2718 // mix buffers...
2719 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002721 // increase sleep time progressively when application underrun condition clears.
2722 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2723 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2724 // such that we would underrun the audio HAL.
2725 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2726 sleepTimeShift--;
2727 }
2728 sleepTime = 0;
2729 standbyTime = systemTime() + standbyDelay;
2730 //TODO: delay standby when effects have a tail
2731}
2732
2733void AudioFlinger::MixerThread::threadLoop_sleepTime()
2734{
2735 // If no tracks are ready, sleep once for the duration of an output
2736 // buffer size, then write 0s to the output
2737 if (sleepTime == 0) {
2738 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2739 sleepTime = activeSleepTime >> sleepTimeShift;
2740 if (sleepTime < kMinThreadSleepTimeUs) {
2741 sleepTime = kMinThreadSleepTimeUs;
2742 }
2743 // reduce sleep time in case of consecutive application underruns to avoid
2744 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2745 // duration we would end up writing less data than needed by the audio HAL if
2746 // the condition persists.
2747 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2748 sleepTimeShift++;
2749 }
2750 } else {
2751 sleepTime = idleSleepTime;
2752 }
2753 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2754 memset (mMixBuffer, 0, mixBufferSize);
2755 sleepTime = 0;
2756 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2757 "anticipated start");
2758 }
2759 // TODO add standby time extension fct of effect tail
2760}
2761
2762// prepareTracks_l() must be called with ThreadBase::mLock held
2763AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2764 Vector< sp<Track> > *tracksToRemove)
2765{
2766
2767 mixer_state mixerStatus = MIXER_IDLE;
2768 // find out which tracks need to be processed
2769 size_t count = mActiveTracks.size();
2770 size_t mixedTracks = 0;
2771 size_t tracksWithEffect = 0;
2772 // counts only _active_ fast tracks
2773 size_t fastTracks = 0;
2774 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2775
2776 float masterVolume = mMasterVolume;
2777 bool masterMute = mMasterMute;
2778
2779 if (masterMute) {
2780 masterVolume = 0;
2781 }
2782 // Delegate master volume control to effect in output mix effect chain if needed
2783 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2784 if (chain != 0) {
2785 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2786 chain->setVolume_l(&v, &v);
2787 masterVolume = (float)((v + (1 << 23)) >> 24);
2788 chain.clear();
2789 }
2790
2791 // prepare a new state to push
2792 FastMixerStateQueue *sq = NULL;
2793 FastMixerState *state = NULL;
2794 bool didModify = false;
2795 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2796 if (mFastMixer != NULL) {
2797 sq = mFastMixer->sq();
2798 state = sq->begin();
2799 }
2800
2801 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002802 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002803 if (t == 0) {
2804 continue;
2805 }
2806
2807 // this const just means the local variable doesn't change
2808 Track* const track = t.get();
2809
2810 // process fast tracks
2811 if (track->isFastTrack()) {
2812
2813 // It's theoretically possible (though unlikely) for a fast track to be created
2814 // and then removed within the same normal mix cycle. This is not a problem, as
2815 // the track never becomes active so it's fast mixer slot is never touched.
2816 // The converse, of removing an (active) track and then creating a new track
2817 // at the identical fast mixer slot within the same normal mix cycle,
2818 // is impossible because the slot isn't marked available until the end of each cycle.
2819 int j = track->mFastIndex;
2820 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2821 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2822 FastTrack *fastTrack = &state->mFastTracks[j];
2823
2824 // Determine whether the track is currently in underrun condition,
2825 // and whether it had a recent underrun.
2826 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2827 FastTrackUnderruns underruns = ftDump->mUnderruns;
2828 uint32_t recentFull = (underruns.mBitFields.mFull -
2829 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2830 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2831 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2832 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2833 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2834 uint32_t recentUnderruns = recentPartial + recentEmpty;
2835 track->mObservedUnderruns = underruns;
2836 // don't count underruns that occur while stopping or pausing
2837 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002838 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2839 recentUnderruns > 0) {
2840 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2841 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002842 }
2843
2844 // This is similar to the state machine for normal tracks,
2845 // with a few modifications for fast tracks.
2846 bool isActive = true;
2847 switch (track->mState) {
2848 case TrackBase::STOPPING_1:
2849 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002851 track->mState = TrackBase::STOPPING_2;
2852 }
2853 break;
2854 case TrackBase::PAUSING:
2855 // ramp down is not yet implemented
2856 track->setPaused();
2857 break;
2858 case TrackBase::RESUMING:
2859 // ramp up is not yet implemented
2860 track->mState = TrackBase::ACTIVE;
2861 break;
2862 case TrackBase::ACTIVE:
2863 if (recentFull > 0 || recentPartial > 0) {
2864 // track has provided at least some frames recently: reset retry count
2865 track->mRetryCount = kMaxTrackRetries;
2866 }
2867 if (recentUnderruns == 0) {
2868 // no recent underruns: stay active
2869 break;
2870 }
2871 // there has recently been an underrun of some kind
2872 if (track->sharedBuffer() == 0) {
2873 // were any of the recent underruns "empty" (no frames available)?
2874 if (recentEmpty == 0) {
2875 // no, then ignore the partial underruns as they are allowed indefinitely
2876 break;
2877 }
2878 // there has recently been an "empty" underrun: decrement the retry counter
2879 if (--(track->mRetryCount) > 0) {
2880 break;
2881 }
2882 // indicate to client process that the track was disabled because of underrun;
2883 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002884 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002885 // remove from active list, but state remains ACTIVE [confusing but true]
2886 isActive = false;
2887 break;
2888 }
2889 // fall through
2890 case TrackBase::STOPPING_2:
2891 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002892 case TrackBase::STOPPED:
2893 case TrackBase::FLUSHED: // flush() while active
2894 // Check for presentation complete if track is inactive
2895 // We have consumed all the buffers of this track.
2896 // This would be incomplete if we auto-paused on underrun
2897 {
2898 size_t audioHALFrames =
2899 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2900 size_t framesWritten = mBytesWritten / mFrameSize;
2901 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2902 // track stays in active list until presentation is complete
2903 break;
2904 }
2905 }
2906 if (track->isStopping_2()) {
2907 track->mState = TrackBase::STOPPED;
2908 }
2909 if (track->isStopped()) {
2910 // Can't reset directly, as fast mixer is still polling this track
2911 // track->reset();
2912 // So instead mark this track as needing to be reset after push with ack
2913 resetMask |= 1 << i;
2914 }
2915 isActive = false;
2916 break;
2917 case TrackBase::IDLE:
2918 default:
2919 LOG_FATAL("unexpected track state %d", track->mState);
2920 }
2921
2922 if (isActive) {
2923 // was it previously inactive?
2924 if (!(state->mTrackMask & (1 << j))) {
2925 ExtendedAudioBufferProvider *eabp = track;
2926 VolumeProvider *vp = track;
2927 fastTrack->mBufferProvider = eabp;
2928 fastTrack->mVolumeProvider = vp;
2929 fastTrack->mSampleRate = track->mSampleRate;
2930 fastTrack->mChannelMask = track->mChannelMask;
2931 fastTrack->mGeneration++;
2932 state->mTrackMask |= 1 << j;
2933 didModify = true;
2934 // no acknowledgement required for newly active tracks
2935 }
2936 // cache the combined master volume and stream type volume for fast mixer; this
2937 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002938 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002939 ++fastTracks;
2940 } else {
2941 // was it previously active?
2942 if (state->mTrackMask & (1 << j)) {
2943 fastTrack->mBufferProvider = NULL;
2944 fastTrack->mGeneration++;
2945 state->mTrackMask &= ~(1 << j);
2946 didModify = true;
2947 // If any fast tracks were removed, we must wait for acknowledgement
2948 // because we're about to decrement the last sp<> on those tracks.
2949 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2950 } else {
2951 LOG_FATAL("fast track %d should have been active", j);
2952 }
2953 tracksToRemove->add(track);
2954 // Avoids a misleading display in dumpsys
2955 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2956 }
2957 continue;
2958 }
2959
2960 { // local variable scope to avoid goto warning
2961
2962 audio_track_cblk_t* cblk = track->cblk();
2963
2964 // The first time a track is added we wait
2965 // for all its buffers to be filled before processing it
2966 int name = track->name();
2967 // make sure that we have enough frames to mix one full buffer.
2968 // enforce this condition only once to enable draining the buffer in case the client
2969 // app does not call stop() and relies on underrun to stop:
2970 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2971 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002972 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002973 uint32_t sr = track->sampleRate();
2974 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002975 desiredFrames = mNormalFrameCount;
2976 } else {
2977 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002978 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002979 // add frames already consumed but not yet released by the resampler
2980 // because cblk->framesReady() will include these frames
2981 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2982 // the minimum track buffer size is normally twice the number of frames necessary
2983 // to fill one buffer and the resampler should not leave more than one buffer worth
2984 // of unreleased frames after each pass, but just in case...
2985 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2986 }
Eric Laurent81784c32012-11-19 14:55:58 -08002987 uint32_t minFrames = 1;
2988 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2989 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002990 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002991 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002992 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2993 size_t framesReady;
2994 if (track->sharedBuffer() == 0) {
2995 framesReady = track->framesReady();
2996 } else if (track->isStopped()) {
2997 framesReady = 0;
2998 } else {
2999 framesReady = 1;
3000 }
3001 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003002 !track->isPaused() && !track->isTerminated())
3003 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003004 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003005
3006 mixedTracks++;
3007
3008 // track->mainBuffer() != mMixBuffer means there is an effect chain
3009 // connected to the track
3010 chain.clear();
3011 if (track->mainBuffer() != mMixBuffer) {
3012 chain = getEffectChain_l(track->sessionId());
3013 // Delegate volume control to effect in track effect chain if needed
3014 if (chain != 0) {
3015 tracksWithEffect++;
3016 } else {
3017 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3018 "session %d",
3019 name, track->sessionId());
3020 }
3021 }
3022
3023
3024 int param = AudioMixer::VOLUME;
3025 if (track->mFillingUpStatus == Track::FS_FILLED) {
3026 // no ramp for the first volume setting
3027 track->mFillingUpStatus = Track::FS_ACTIVE;
3028 if (track->mState == TrackBase::RESUMING) {
3029 track->mState = TrackBase::ACTIVE;
3030 param = AudioMixer::RAMP_VOLUME;
3031 }
3032 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003033 // FIXME should not make a decision based on mServer
3034 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003035 // If the track is stopped before the first frame was mixed,
3036 // do not apply ramp
3037 param = AudioMixer::RAMP_VOLUME;
3038 }
3039
3040 // compute volume for this track
3041 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003042 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003043 vl = vr = va = 0;
3044 if (track->isPausing()) {
3045 track->setPaused();
3046 }
3047 } else {
3048
3049 // read original volumes with volume control
3050 float typeVolume = mStreamTypes[track->streamType()].volume;
3051 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003052 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003053 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003054 vl = vlr & 0xFFFF;
3055 vr = vlr >> 16;
3056 // track volumes come from shared memory, so can't be trusted and must be clamped
3057 if (vl > MAX_GAIN_INT) {
3058 ALOGV("Track left volume out of range: %04X", vl);
3059 vl = MAX_GAIN_INT;
3060 }
3061 if (vr > MAX_GAIN_INT) {
3062 ALOGV("Track right volume out of range: %04X", vr);
3063 vr = MAX_GAIN_INT;
3064 }
3065 // now apply the master volume and stream type volume
3066 vl = (uint32_t)(v * vl) << 12;
3067 vr = (uint32_t)(v * vr) << 12;
3068 // assuming master volume and stream type volume each go up to 1.0,
3069 // vl and vr are now in 8.24 format
3070
Glenn Kastene3aa6592012-12-04 12:22:46 -08003071 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003072 // send level comes from shared memory and so may be corrupt
3073 if (sendLevel > MAX_GAIN_INT) {
3074 ALOGV("Track send level out of range: %04X", sendLevel);
3075 sendLevel = MAX_GAIN_INT;
3076 }
3077 va = (uint32_t)(v * sendLevel);
3078 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003079
Eric Laurent81784c32012-11-19 14:55:58 -08003080 // Delegate volume control to effect in track effect chain if needed
3081 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3082 // Do not ramp volume if volume is controlled by effect
3083 param = AudioMixer::VOLUME;
3084 track->mHasVolumeController = true;
3085 } else {
3086 // force no volume ramp when volume controller was just disabled or removed
3087 // from effect chain to avoid volume spike
3088 if (track->mHasVolumeController) {
3089 param = AudioMixer::VOLUME;
3090 }
3091 track->mHasVolumeController = false;
3092 }
3093
3094 // Convert volumes from 8.24 to 4.12 format
3095 // This additional clamping is needed in case chain->setVolume_l() overshot
3096 vl = (vl + (1 << 11)) >> 12;
3097 if (vl > MAX_GAIN_INT) {
3098 vl = MAX_GAIN_INT;
3099 }
3100 vr = (vr + (1 << 11)) >> 12;
3101 if (vr > MAX_GAIN_INT) {
3102 vr = MAX_GAIN_INT;
3103 }
3104
3105 if (va > MAX_GAIN_INT) {
3106 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3107 }
3108
3109 // XXX: these things DON'T need to be done each time
3110 mAudioMixer->setBufferProvider(name, track);
3111 mAudioMixer->enable(name);
3112
3113 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3114 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3115 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3116 mAudioMixer->setParameter(
3117 name,
3118 AudioMixer::TRACK,
3119 AudioMixer::FORMAT, (void *)track->format());
3120 mAudioMixer->setParameter(
3121 name,
3122 AudioMixer::TRACK,
3123 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003124 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3125 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003126 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003127 if (reqSampleRate == 0) {
3128 reqSampleRate = mSampleRate;
3129 } else if (reqSampleRate > maxSampleRate) {
3130 reqSampleRate = maxSampleRate;
3131 }
Eric Laurent81784c32012-11-19 14:55:58 -08003132 mAudioMixer->setParameter(
3133 name,
3134 AudioMixer::RESAMPLE,
3135 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003136 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003137 mAudioMixer->setParameter(
3138 name,
3139 AudioMixer::TRACK,
3140 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3141 mAudioMixer->setParameter(
3142 name,
3143 AudioMixer::TRACK,
3144 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3145
3146 // reset retry count
3147 track->mRetryCount = kMaxTrackRetries;
3148
3149 // If one track is ready, set the mixer ready if:
3150 // - the mixer was not ready during previous round OR
3151 // - no other track is not ready
3152 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3153 mixerStatus != MIXER_TRACKS_ENABLED) {
3154 mixerStatus = MIXER_TRACKS_READY;
3155 }
3156 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003157 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003158 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003159 }
Eric Laurent81784c32012-11-19 14:55:58 -08003160 // clear effect chain input buffer if an active track underruns to avoid sending
3161 // previous audio buffer again to effects
3162 chain = getEffectChain_l(track->sessionId());
3163 if (chain != 0) {
3164 chain->clearInputBuffer();
3165 }
3166
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003167 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003168 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3169 track->isStopped() || track->isPaused()) {
3170 // We have consumed all the buffers of this track.
3171 // Remove it from the list of active tracks.
3172 // TODO: use actual buffer filling status instead of latency when available from
3173 // audio HAL
3174 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3175 size_t framesWritten = mBytesWritten / mFrameSize;
3176 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3177 if (track->isStopped()) {
3178 track->reset();
3179 }
3180 tracksToRemove->add(track);
3181 }
3182 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003183 // No buffers for this track. Give it a few chances to
3184 // fill a buffer, then remove it from active list.
3185 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003186 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003187 tracksToRemove->add(track);
3188 // indicate to client process that the track was disabled because of underrun;
3189 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003190 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003191 // If one track is not ready, mark the mixer also not ready if:
3192 // - the mixer was ready during previous round OR
3193 // - no other track is ready
3194 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3195 mixerStatus != MIXER_TRACKS_READY) {
3196 mixerStatus = MIXER_TRACKS_ENABLED;
3197 }
3198 }
3199 mAudioMixer->disable(name);
3200 }
3201
3202 } // local variable scope to avoid goto warning
3203track_is_ready: ;
3204
3205 }
3206
3207 // Push the new FastMixer state if necessary
3208 bool pauseAudioWatchdog = false;
3209 if (didModify) {
3210 state->mFastTracksGen++;
3211 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3212 if (kUseFastMixer == FastMixer_Dynamic &&
3213 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3214 state->mCommand = FastMixerState::COLD_IDLE;
3215 state->mColdFutexAddr = &mFastMixerFutex;
3216 state->mColdGen++;
3217 mFastMixerFutex = 0;
3218 if (kUseFastMixer == FastMixer_Dynamic) {
3219 mNormalSink = mOutputSink;
3220 }
3221 // If we go into cold idle, need to wait for acknowledgement
3222 // so that fast mixer stops doing I/O.
3223 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3224 pauseAudioWatchdog = true;
3225 }
Eric Laurent81784c32012-11-19 14:55:58 -08003226 }
3227 if (sq != NULL) {
3228 sq->end(didModify);
3229 sq->push(block);
3230 }
3231#ifdef AUDIO_WATCHDOG
3232 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3233 mAudioWatchdog->pause();
3234 }
3235#endif
3236
3237 // Now perform the deferred reset on fast tracks that have stopped
3238 while (resetMask != 0) {
3239 size_t i = __builtin_ctz(resetMask);
3240 ALOG_ASSERT(i < count);
3241 resetMask &= ~(1 << i);
3242 sp<Track> t = mActiveTracks[i].promote();
3243 if (t == 0) {
3244 continue;
3245 }
3246 Track* track = t.get();
3247 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3248 track->reset();
3249 }
3250
3251 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003253
3254 // mix buffer must be cleared if all tracks are connected to an
3255 // effect chain as in this case the mixer will not write to
3256 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003257 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3258 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003259 // FIXME as a performance optimization, should remember previous zero status
3260 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3261 }
3262
3263 // if any fast tracks, then status is ready
3264 mMixerStatusIgnoringFastTracks = mixerStatus;
3265 if (fastTracks > 0) {
3266 mixerStatus = MIXER_TRACKS_READY;
3267 }
3268 return mixerStatus;
3269}
3270
3271// getTrackName_l() must be called with ThreadBase::mLock held
3272int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3273{
3274 return mAudioMixer->getTrackName(channelMask, sessionId);
3275}
3276
3277// deleteTrackName_l() must be called with ThreadBase::mLock held
3278void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3279{
3280 ALOGV("remove track (%d) and delete from mixer", name);
3281 mAudioMixer->deleteTrackName(name);
3282}
3283
3284// checkForNewParameters_l() must be called with ThreadBase::mLock held
3285bool AudioFlinger::MixerThread::checkForNewParameters_l()
3286{
3287 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3288 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3289 bool reconfig = false;
3290
3291 while (!mNewParameters.isEmpty()) {
3292
3293 if (mFastMixer != NULL) {
3294 FastMixerStateQueue *sq = mFastMixer->sq();
3295 FastMixerState *state = sq->begin();
3296 if (!(state->mCommand & FastMixerState::IDLE)) {
3297 previousCommand = state->mCommand;
3298 state->mCommand = FastMixerState::HOT_IDLE;
3299 sq->end();
3300 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3301 } else {
3302 sq->end(false /*didModify*/);
3303 }
3304 }
3305
3306 status_t status = NO_ERROR;
3307 String8 keyValuePair = mNewParameters[0];
3308 AudioParameter param = AudioParameter(keyValuePair);
3309 int value;
3310
3311 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3312 reconfig = true;
3313 }
3314 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3315 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3316 status = BAD_VALUE;
3317 } else {
3318 reconfig = true;
3319 }
3320 }
3321 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003322 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003323 status = BAD_VALUE;
3324 } else {
3325 reconfig = true;
3326 }
3327 }
3328 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3329 // do not accept frame count changes if tracks are open as the track buffer
3330 // size depends on frame count and correct behavior would not be guaranteed
3331 // if frame count is changed after track creation
3332 if (!mTracks.isEmpty()) {
3333 status = INVALID_OPERATION;
3334 } else {
3335 reconfig = true;
3336 }
3337 }
3338 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3339#ifdef ADD_BATTERY_DATA
3340 // when changing the audio output device, call addBatteryData to notify
3341 // the change
3342 if (mOutDevice != value) {
3343 uint32_t params = 0;
3344 // check whether speaker is on
3345 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3346 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3347 }
3348
3349 audio_devices_t deviceWithoutSpeaker
3350 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3351 // check if any other device (except speaker) is on
3352 if (value & deviceWithoutSpeaker ) {
3353 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3354 }
3355
3356 if (params != 0) {
3357 addBatteryData(params);
3358 }
3359 }
3360#endif
3361
3362 // forward device change to effects that have requested to be
3363 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003364 if (value != AUDIO_DEVICE_NONE) {
3365 mOutDevice = value;
3366 for (size_t i = 0; i < mEffectChains.size(); i++) {
3367 mEffectChains[i]->setDevice_l(mOutDevice);
3368 }
Eric Laurent81784c32012-11-19 14:55:58 -08003369 }
3370 }
3371
3372 if (status == NO_ERROR) {
3373 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3374 keyValuePair.string());
3375 if (!mStandby && status == INVALID_OPERATION) {
3376 mOutput->stream->common.standby(&mOutput->stream->common);
3377 mStandby = true;
3378 mBytesWritten = 0;
3379 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3380 keyValuePair.string());
3381 }
3382 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003383 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003384 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003385 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3386 for (size_t i = 0; i < mTracks.size() ; i++) {
3387 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3388 if (name < 0) {
3389 break;
3390 }
3391 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003392 }
3393 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3394 }
3395 }
3396
3397 mNewParameters.removeAt(0);
3398
3399 mParamStatus = status;
3400 mParamCond.signal();
3401 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3402 // already timed out waiting for the status and will never signal the condition.
3403 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3404 }
3405
3406 if (!(previousCommand & FastMixerState::IDLE)) {
3407 ALOG_ASSERT(mFastMixer != NULL);
3408 FastMixerStateQueue *sq = mFastMixer->sq();
3409 FastMixerState *state = sq->begin();
3410 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3411 state->mCommand = previousCommand;
3412 sq->end();
3413 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3414 }
3415
3416 return reconfig;
3417}
3418
3419
3420void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3421{
3422 const size_t SIZE = 256;
3423 char buffer[SIZE];
3424 String8 result;
3425
3426 PlaybackThread::dumpInternals(fd, args);
3427
3428 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3429 result.append(buffer);
3430 write(fd, result.string(), result.size());
3431
3432 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003433 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003434 copy.dump(fd);
3435
3436#ifdef STATE_QUEUE_DUMP
3437 // Similar for state queue
3438 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3439 observerCopy.dump(fd);
3440 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3441 mutatorCopy.dump(fd);
3442#endif
3443
Glenn Kasten46909e72013-02-26 09:20:22 -08003444#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003445 // Write the tee output to a .wav file
3446 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003447#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003448
3449#ifdef AUDIO_WATCHDOG
3450 if (mAudioWatchdog != 0) {
3451 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3452 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3453 wdCopy.dump(fd);
3454 }
3455#endif
3456}
3457
3458uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3459{
3460 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3461}
3462
3463uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3464{
3465 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3466}
3467
3468void AudioFlinger::MixerThread::cacheParameters_l()
3469{
3470 PlaybackThread::cacheParameters_l();
3471
3472 // FIXME: Relaxed timing because of a certain device that can't meet latency
3473 // Should be reduced to 2x after the vendor fixes the driver issue
3474 // increase threshold again due to low power audio mode. The way this warning
3475 // threshold is calculated and its usefulness should be reconsidered anyway.
3476 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3477}
3478
3479// ----------------------------------------------------------------------------
3480
3481AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3482 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3483 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3484 // mLeftVolFloat, mRightVolFloat
3485{
3486}
3487
Eric Laurentbfb1b832013-01-07 09:53:42 -08003488AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3489 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3490 ThreadBase::type_t type)
3491 : PlaybackThread(audioFlinger, output, id, device, type)
3492 // mLeftVolFloat, mRightVolFloat
3493{
3494}
3495
Eric Laurent81784c32012-11-19 14:55:58 -08003496AudioFlinger::DirectOutputThread::~DirectOutputThread()
3497{
3498}
3499
Eric Laurentbfb1b832013-01-07 09:53:42 -08003500void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3501{
3502 audio_track_cblk_t* cblk = track->cblk();
3503 float left, right;
3504
3505 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3506 left = right = 0;
3507 } else {
3508 float typeVolume = mStreamTypes[track->streamType()].volume;
3509 float v = mMasterVolume * typeVolume;
3510 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3511 uint32_t vlr = proxy->getVolumeLR();
3512 float v_clamped = v * (vlr & 0xFFFF);
3513 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3514 left = v_clamped/MAX_GAIN;
3515 v_clamped = v * (vlr >> 16);
3516 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3517 right = v_clamped/MAX_GAIN;
3518 }
3519
3520 if (lastTrack) {
3521 if (left != mLeftVolFloat || right != mRightVolFloat) {
3522 mLeftVolFloat = left;
3523 mRightVolFloat = right;
3524
3525 // Convert volumes from float to 8.24
3526 uint32_t vl = (uint32_t)(left * (1 << 24));
3527 uint32_t vr = (uint32_t)(right * (1 << 24));
3528
3529 // Delegate volume control to effect in track effect chain if needed
3530 // only one effect chain can be present on DirectOutputThread, so if
3531 // there is one, the track is connected to it
3532 if (!mEffectChains.isEmpty()) {
3533 mEffectChains[0]->setVolume_l(&vl, &vr);
3534 left = (float)vl / (1 << 24);
3535 right = (float)vr / (1 << 24);
3536 }
3537 if (mOutput->stream->set_volume) {
3538 mOutput->stream->set_volume(mOutput->stream, left, right);
3539 }
3540 }
3541 }
3542}
3543
3544
Eric Laurent81784c32012-11-19 14:55:58 -08003545AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3546 Vector< sp<Track> > *tracksToRemove
3547)
3548{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003549 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003550 mixer_state mixerStatus = MIXER_IDLE;
3551
3552 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003553 for (size_t i = 0; i < count; i++) {
3554 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003555 // The track died recently
3556 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003557 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003558 }
3559
3560 Track* const track = t.get();
3561 audio_track_cblk_t* cblk = track->cblk();
3562
3563 // The first time a track is added we wait
3564 // for all its buffers to be filled before processing it
3565 uint32_t minFrames;
3566 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3567 minFrames = mNormalFrameCount;
3568 } else {
3569 minFrames = 1;
3570 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 // Only consider last track started for volume and mixer state control.
3572 // This is the last entry in mActiveTracks unless a track underruns.
3573 // As we only care about the transition phase between two tracks on a
3574 // direct output, it is not a problem to ignore the underrun case.
3575 bool last = (i == (count - 1));
3576
Eric Laurent81784c32012-11-19 14:55:58 -08003577 if ((track->framesReady() >= minFrames) && track->isReady() &&
3578 !track->isPaused() && !track->isTerminated())
3579 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003580 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003581
3582 if (track->mFillingUpStatus == Track::FS_FILLED) {
3583 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003584 // make sure processVolume_l() will apply new volume even if 0
3585 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003586 if (track->mState == TrackBase::RESUMING) {
3587 track->mState = TrackBase::ACTIVE;
3588 }
3589 }
3590
3591 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592 processVolume_l(track, last);
3593 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003594 // reset retry count
3595 track->mRetryCount = kMaxTrackRetriesDirect;
3596 mActiveTrack = t;
3597 mixerStatus = MIXER_TRACKS_READY;
3598 }
Eric Laurent81784c32012-11-19 14:55:58 -08003599 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003600 // clear effect chain input buffer if the last active track started underruns
3601 // to avoid sending previous audio buffer again to effects
3602 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003603 mEffectChains[0]->clearInputBuffer();
3604 }
3605
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003606 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003607 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3608 track->isStopped() || track->isPaused()) {
3609 // We have consumed all the buffers of this track.
3610 // Remove it from the list of active tracks.
3611 // TODO: implement behavior for compressed audio
3612 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3613 size_t framesWritten = mBytesWritten / mFrameSize;
3614 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3615 if (track->isStopped()) {
3616 track->reset();
3617 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003618 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003619 }
3620 } else {
3621 // No buffers for this track. Give it a few chances to
3622 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003623 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003624 if (--(track->mRetryCount) <= 0) {
3625 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003626 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003627 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003628 mixerStatus = MIXER_TRACKS_ENABLED;
3629 }
3630 }
3631 }
3632 }
3633
Eric Laurent81784c32012-11-19 14:55:58 -08003634 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003635 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003636
3637 return mixerStatus;
3638}
3639
3640void AudioFlinger::DirectOutputThread::threadLoop_mix()
3641{
Eric Laurent81784c32012-11-19 14:55:58 -08003642 size_t frameCount = mFrameCount;
3643 int8_t *curBuf = (int8_t *)mMixBuffer;
3644 // output audio to hardware
3645 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003646 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003647 buffer.frameCount = frameCount;
3648 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003649 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003650 memset(curBuf, 0, frameCount * mFrameSize);
3651 break;
3652 }
3653 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3654 frameCount -= buffer.frameCount;
3655 curBuf += buffer.frameCount * mFrameSize;
3656 mActiveTrack->releaseBuffer(&buffer);
3657 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003658 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003659 sleepTime = 0;
3660 standbyTime = systemTime() + standbyDelay;
3661 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003662}
3663
3664void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3665{
3666 if (sleepTime == 0) {
3667 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3668 sleepTime = activeSleepTime;
3669 } else {
3670 sleepTime = idleSleepTime;
3671 }
3672 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3673 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3674 sleepTime = 0;
3675 }
3676}
3677
3678// getTrackName_l() must be called with ThreadBase::mLock held
3679int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3680 int sessionId)
3681{
3682 return 0;
3683}
3684
3685// deleteTrackName_l() must be called with ThreadBase::mLock held
3686void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3687{
3688}
3689
3690// checkForNewParameters_l() must be called with ThreadBase::mLock held
3691bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3692{
3693 bool reconfig = false;
3694
3695 while (!mNewParameters.isEmpty()) {
3696 status_t status = NO_ERROR;
3697 String8 keyValuePair = mNewParameters[0];
3698 AudioParameter param = AudioParameter(keyValuePair);
3699 int value;
3700
3701 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3702 // do not accept frame count changes if tracks are open as the track buffer
3703 // size depends on frame count and correct behavior would not be garantied
3704 // if frame count is changed after track creation
3705 if (!mTracks.isEmpty()) {
3706 status = INVALID_OPERATION;
3707 } else {
3708 reconfig = true;
3709 }
3710 }
3711 if (status == NO_ERROR) {
3712 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3713 keyValuePair.string());
3714 if (!mStandby && status == INVALID_OPERATION) {
3715 mOutput->stream->common.standby(&mOutput->stream->common);
3716 mStandby = true;
3717 mBytesWritten = 0;
3718 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3719 keyValuePair.string());
3720 }
3721 if (status == NO_ERROR && reconfig) {
3722 readOutputParameters();
3723 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3724 }
3725 }
3726
3727 mNewParameters.removeAt(0);
3728
3729 mParamStatus = status;
3730 mParamCond.signal();
3731 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3732 // already timed out waiting for the status and will never signal the condition.
3733 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3734 }
3735 return reconfig;
3736}
3737
3738uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3739{
3740 uint32_t time;
3741 if (audio_is_linear_pcm(mFormat)) {
3742 time = PlaybackThread::activeSleepTimeUs();
3743 } else {
3744 time = 10000;
3745 }
3746 return time;
3747}
3748
3749uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3750{
3751 uint32_t time;
3752 if (audio_is_linear_pcm(mFormat)) {
3753 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3754 } else {
3755 time = 10000;
3756 }
3757 return time;
3758}
3759
3760uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3761{
3762 uint32_t time;
3763 if (audio_is_linear_pcm(mFormat)) {
3764 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3765 } else {
3766 time = 10000;
3767 }
3768 return time;
3769}
3770
3771void AudioFlinger::DirectOutputThread::cacheParameters_l()
3772{
3773 PlaybackThread::cacheParameters_l();
3774
3775 // use shorter standby delay as on normal output to release
3776 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003777 if (audio_is_linear_pcm(mFormat)) {
3778 standbyDelay = microseconds(activeSleepTime*2);
3779 } else {
3780 standbyDelay = kOffloadStandbyDelayNs;
3781 }
Eric Laurent81784c32012-11-19 14:55:58 -08003782}
3783
3784// ----------------------------------------------------------------------------
3785
Eric Laurentbfb1b832013-01-07 09:53:42 -08003786AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003787 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003788 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003789 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003790 mWriteAckSequence(0),
3791 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003792{
3793}
3794
3795AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3796{
3797}
3798
3799void AudioFlinger::AsyncCallbackThread::onFirstRef()
3800{
3801 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3802}
3803
3804bool AudioFlinger::AsyncCallbackThread::threadLoop()
3805{
3806 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003807 uint32_t writeAckSequence;
3808 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809
3810 {
3811 Mutex::Autolock _l(mLock);
3812 mWaitWorkCV.wait(mLock);
3813 if (exitPending()) {
3814 break;
3815 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003816 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3817 mWriteAckSequence, mDrainSequence);
3818 writeAckSequence = mWriteAckSequence;
3819 mWriteAckSequence &= ~1;
3820 drainSequence = mDrainSequence;
3821 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003822 }
3823 {
Eric Laurent4de95592013-09-26 15:28:21 -07003824 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3825 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003826 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003827 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003828 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003829 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003830 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831 }
3832 }
3833 }
3834 }
3835 return false;
3836}
3837
3838void AudioFlinger::AsyncCallbackThread::exit()
3839{
3840 ALOGV("AsyncCallbackThread::exit");
3841 Mutex::Autolock _l(mLock);
3842 requestExit();
3843 mWaitWorkCV.broadcast();
3844}
3845
Eric Laurent3b4529e2013-09-05 18:09:19 -07003846void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847{
3848 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003849 // bit 0 is cleared
3850 mWriteAckSequence = sequence << 1;
3851}
3852
3853void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3854{
3855 Mutex::Autolock _l(mLock);
3856 // ignore unexpected callbacks
3857 if (mWriteAckSequence & 2) {
3858 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 mWaitWorkCV.signal();
3860 }
3861}
3862
Eric Laurent3b4529e2013-09-05 18:09:19 -07003863void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864{
3865 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003866 // bit 0 is cleared
3867 mDrainSequence = sequence << 1;
3868}
3869
3870void AudioFlinger::AsyncCallbackThread::resetDraining()
3871{
3872 Mutex::Autolock _l(mLock);
3873 // ignore unexpected callbacks
3874 if (mDrainSequence & 2) {
3875 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003876 mWaitWorkCV.signal();
3877 }
3878}
3879
3880
3881// ----------------------------------------------------------------------------
3882AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3883 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3884 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3885 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003886 mFlushPending(false),
Eric Laurent6a51d7e2013-10-17 18:59:26 -07003887 mPausedBytesRemaining(0),
3888 mPreviousTrack(NULL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003889{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003890}
3891
Eric Laurentbfb1b832013-01-07 09:53:42 -08003892void AudioFlinger::OffloadThread::threadLoop_exit()
3893{
3894 if (mFlushPending || mHwPaused) {
3895 // If a flush is pending or track was paused, just discard buffered data
3896 flushHw_l();
3897 } else {
3898 mMixerStatus = MIXER_DRAIN_ALL;
3899 threadLoop_drain();
3900 }
3901 mCallbackThread->exit();
3902 PlaybackThread::threadLoop_exit();
3903}
3904
3905AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3906 Vector< sp<Track> > *tracksToRemove
3907)
3908{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909 size_t count = mActiveTracks.size();
3910
3911 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003912 bool doHwPause = false;
3913 bool doHwResume = false;
3914
Eric Laurentede6c3b2013-09-19 14:37:46 -07003915 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3916
Eric Laurentbfb1b832013-01-07 09:53:42 -08003917 // find out which tracks need to be processed
3918 for (size_t i = 0; i < count; i++) {
3919 sp<Track> t = mActiveTracks[i].promote();
3920 // The track died recently
3921 if (t == 0) {
3922 continue;
3923 }
3924 Track* const track = t.get();
3925 audio_track_cblk_t* cblk = track->cblk();
3926 if (mPreviousTrack != NULL) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07003927 if (t.get() != mPreviousTrack) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928 // Flush any data still being written from last track
3929 mBytesRemaining = 0;
3930 if (mPausedBytesRemaining) {
3931 // Last track was paused so we also need to flush saved
3932 // mixbuffer state and invalidate track so that it will
3933 // re-submit that unwritten data when it is next resumed
3934 mPausedBytesRemaining = 0;
3935 // Invalidate is a bit drastic - would be more efficient
3936 // to have a flag to tell client that some of the
3937 // previously written data was lost
3938 mPreviousTrack->invalidate();
3939 }
3940 }
3941 }
Eric Laurent6a51d7e2013-10-17 18:59:26 -07003942 mPreviousTrack = t.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943 bool last = (i == (count - 1));
3944 if (track->isPausing()) {
3945 track->setPaused();
3946 if (last) {
3947 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003948 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003949 mHwPaused = true;
3950 }
3951 // If we were part way through writing the mixbuffer to
3952 // the HAL we must save this until we resume
3953 // BUG - this will be wrong if a different track is made active,
3954 // in that case we want to discard the pending data in the
3955 // mixbuffer and tell the client to present it again when the
3956 // track is resumed
3957 mPausedWriteLength = mCurrentWriteLength;
3958 mPausedBytesRemaining = mBytesRemaining;
3959 mBytesRemaining = 0; // stop writing
3960 }
3961 tracksToRemove->add(track);
3962 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07003963 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003964 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965 if (track->mFillingUpStatus == Track::FS_FILLED) {
3966 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003967 // make sure processVolume_l() will apply new volume even if 0
3968 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003969 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003970 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003971 if (last) {
3972 if (mPausedBytesRemaining) {
3973 // Need to continue write that was interrupted
3974 mCurrentWriteLength = mPausedWriteLength;
3975 mBytesRemaining = mPausedBytesRemaining;
3976 mPausedBytesRemaining = 0;
3977 }
3978 if (mHwPaused) {
3979 doHwResume = true;
3980 mHwPaused = false;
3981 // threadLoop_mix() will handle the case that we need to
3982 // resume an interrupted write
3983 }
3984 // enable write to audio HAL
3985 sleepTime = 0;
3986 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003987 }
3988 }
3989
3990 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003991 // reset retry count
3992 track->mRetryCount = kMaxTrackRetriesOffload;
3993 mActiveTrack = t;
3994 mixerStatus = MIXER_TRACKS_READY;
3995 }
3996 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003997 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003998 if (track->isStopping_1()) {
3999 // Hardware buffer can hold a large amount of audio so we must
4000 // wait for all current track's data to drain before we say
4001 // that the track is stopped.
4002 if (mBytesRemaining == 0) {
4003 // Only start draining when all data in mixbuffer
4004 // has been written
4005 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4006 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004007 // do not drain if no data was ever sent to HAL (mStandby == true)
4008 if (last && !mStandby) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07004009 sleepTime = 0;
4010 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004011 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07004012 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004013 if (mHwPaused) {
4014 // It is possible to move from PAUSED to STOPPING_1 without
4015 // a resume so we must ensure hardware is running
4016 mOutput->stream->resume(mOutput->stream);
4017 mHwPaused = false;
4018 }
4019 }
4020 }
4021 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004022 // Drain has completed or we are in standby, signal presentation complete
4023 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004024 track->mState = TrackBase::STOPPED;
4025 size_t audioHALFrames =
4026 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4027 size_t framesWritten =
4028 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4029 track->presentationComplete(framesWritten, audioHALFrames);
4030 track->reset();
4031 tracksToRemove->add(track);
4032 }
4033 } else {
4034 // No buffers for this track. Give it a few chances to
4035 // fill a buffer, then remove it from active list.
4036 if (--(track->mRetryCount) <= 0) {
4037 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4038 track->name());
4039 tracksToRemove->add(track);
4040 } else if (last){
4041 mixerStatus = MIXER_TRACKS_ENABLED;
4042 }
4043 }
4044 }
4045 // compute volume for this track
4046 processVolume_l(track, last);
4047 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004048
Eric Laurentea0fade2013-10-04 16:23:48 -07004049 // make sure the pause/flush/resume sequence is executed in the right order.
4050 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4051 // before flush and then resume HW. This can happen in case of pause/flush/resume
4052 // if resume is received before pause is executed.
4053 if (doHwPause || (mFlushPending && !mHwPaused && (count != 0))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004054 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004055 if (!doHwPause) {
4056 doHwResume = true;
4057 }
Eric Laurent972a1732013-09-04 09:42:59 -07004058 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004059 if (mFlushPending) {
4060 flushHw_l();
4061 mFlushPending = false;
4062 }
Eric Laurent972a1732013-09-04 09:42:59 -07004063 if (doHwResume) {
4064 mOutput->stream->resume(mOutput->stream);
4065 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004066
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067 // remove all the tracks that need to be...
4068 removeTracks_l(*tracksToRemove);
4069
4070 return mixerStatus;
4071}
4072
4073void AudioFlinger::OffloadThread::flushOutput_l()
4074{
4075 mFlushPending = true;
4076}
4077
4078// must be called with thread mutex locked
4079bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4080{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004081 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4082 mWriteAckSequence, mDrainSequence);
4083 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 return true;
4085 }
4086 return false;
4087}
4088
4089// must be called with thread mutex locked
4090bool AudioFlinger::OffloadThread::shouldStandby_l()
4091{
4092 bool TrackPaused = false;
4093
4094 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4095 // after a timeout and we will enter standby then.
4096 if (mTracks.size() > 0) {
4097 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4098 }
4099
4100 return !mStandby && !TrackPaused;
4101}
4102
4103
4104bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4105{
4106 Mutex::Autolock _l(mLock);
4107 return waitingAsyncCallback_l();
4108}
4109
4110void AudioFlinger::OffloadThread::flushHw_l()
4111{
4112 mOutput->stream->flush(mOutput->stream);
4113 // Flush anything still waiting in the mixbuffer
4114 mCurrentWriteLength = 0;
4115 mBytesRemaining = 0;
4116 mPausedWriteLength = 0;
4117 mPausedBytesRemaining = 0;
4118 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004119 // discard any pending drain or write ack by incrementing sequence
4120 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4121 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004122 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004123 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4124 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125 }
4126}
4127
4128// ----------------------------------------------------------------------------
4129
Eric Laurent81784c32012-11-19 14:55:58 -08004130AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4131 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4132 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4133 DUPLICATING),
4134 mWaitTimeMs(UINT_MAX)
4135{
4136 addOutputTrack(mainThread);
4137}
4138
4139AudioFlinger::DuplicatingThread::~DuplicatingThread()
4140{
4141 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4142 mOutputTracks[i]->destroy();
4143 }
4144}
4145
4146void AudioFlinger::DuplicatingThread::threadLoop_mix()
4147{
4148 // mix buffers...
4149 if (outputsReady(outputTracks)) {
4150 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4151 } else {
4152 memset(mMixBuffer, 0, mixBufferSize);
4153 }
4154 sleepTime = 0;
4155 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004157 standbyTime = systemTime() + standbyDelay;
4158}
4159
4160void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4161{
4162 if (sleepTime == 0) {
4163 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4164 sleepTime = activeSleepTime;
4165 } else {
4166 sleepTime = idleSleepTime;
4167 }
4168 } else if (mBytesWritten != 0) {
4169 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4170 writeFrames = mNormalFrameCount;
4171 memset(mMixBuffer, 0, mixBufferSize);
4172 } else {
4173 // flush remaining overflow buffers in output tracks
4174 writeFrames = 0;
4175 }
4176 sleepTime = 0;
4177 }
4178}
4179
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004181{
4182 for (size_t i = 0; i < outputTracks.size(); i++) {
4183 outputTracks[i]->write(mMixBuffer, writeFrames);
4184 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004185 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004186}
4187
4188void AudioFlinger::DuplicatingThread::threadLoop_standby()
4189{
4190 // DuplicatingThread implements standby by stopping all tracks
4191 for (size_t i = 0; i < outputTracks.size(); i++) {
4192 outputTracks[i]->stop();
4193 }
4194}
4195
4196void AudioFlinger::DuplicatingThread::saveOutputTracks()
4197{
4198 outputTracks = mOutputTracks;
4199}
4200
4201void AudioFlinger::DuplicatingThread::clearOutputTracks()
4202{
4203 outputTracks.clear();
4204}
4205
4206void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4207{
4208 Mutex::Autolock _l(mLock);
4209 // FIXME explain this formula
4210 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4211 OutputTrack *outputTrack = new OutputTrack(thread,
4212 this,
4213 mSampleRate,
4214 mFormat,
4215 mChannelMask,
4216 frameCount);
4217 if (outputTrack->cblk() != NULL) {
4218 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4219 mOutputTracks.add(outputTrack);
4220 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4221 updateWaitTime_l();
4222 }
4223}
4224
4225void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4226{
4227 Mutex::Autolock _l(mLock);
4228 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4229 if (mOutputTracks[i]->thread() == thread) {
4230 mOutputTracks[i]->destroy();
4231 mOutputTracks.removeAt(i);
4232 updateWaitTime_l();
4233 return;
4234 }
4235 }
4236 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4237}
4238
4239// caller must hold mLock
4240void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4241{
4242 mWaitTimeMs = UINT_MAX;
4243 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4244 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4245 if (strong != 0) {
4246 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4247 if (waitTimeMs < mWaitTimeMs) {
4248 mWaitTimeMs = waitTimeMs;
4249 }
4250 }
4251 }
4252}
4253
4254
4255bool AudioFlinger::DuplicatingThread::outputsReady(
4256 const SortedVector< sp<OutputTrack> > &outputTracks)
4257{
4258 for (size_t i = 0; i < outputTracks.size(); i++) {
4259 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4260 if (thread == 0) {
4261 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4262 outputTracks[i].get());
4263 return false;
4264 }
4265 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4266 // see note at standby() declaration
4267 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4268 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4269 thread.get());
4270 return false;
4271 }
4272 }
4273 return true;
4274}
4275
4276uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4277{
4278 return (mWaitTimeMs * 1000) / 2;
4279}
4280
4281void AudioFlinger::DuplicatingThread::cacheParameters_l()
4282{
4283 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4284 updateWaitTime_l();
4285
4286 MixerThread::cacheParameters_l();
4287}
4288
4289// ----------------------------------------------------------------------------
4290// Record
4291// ----------------------------------------------------------------------------
4292
4293AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4294 AudioStreamIn *input,
4295 uint32_t sampleRate,
4296 audio_channel_mask_t channelMask,
4297 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004298 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004299 audio_devices_t inDevice
4300#ifdef TEE_SINK
4301 , const sp<NBAIO_Sink>& teeSink
4302#endif
4303 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004304 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004305 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004306 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004307 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004308 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004309 // mBytesRead is only meaningful while active, and so is cleared in start()
4310 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004311#ifdef TEE_SINK
4312 , mTeeSink(teeSink)
4313#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004314{
4315 snprintf(mName, kNameLength, "AudioIn_%X", id);
4316
4317 readInputParameters();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004318 mClientUid = IPCThreadState::self()->getCallingUid();
Eric Laurent81784c32012-11-19 14:55:58 -08004319}
4320
4321
4322AudioFlinger::RecordThread::~RecordThread()
4323{
4324 delete[] mRsmpInBuffer;
4325 delete mResampler;
4326 delete[] mRsmpOutBuffer;
4327}
4328
4329void AudioFlinger::RecordThread::onFirstRef()
4330{
4331 run(mName, PRIORITY_URGENT_AUDIO);
4332}
4333
4334status_t AudioFlinger::RecordThread::readyToRun()
4335{
4336 status_t status = initCheck();
4337 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4338 return status;
4339}
4340
4341bool AudioFlinger::RecordThread::threadLoop()
4342{
4343 AudioBufferProvider::Buffer buffer;
4344 sp<RecordTrack> activeTrack;
4345 Vector< sp<EffectChain> > effectChains;
4346
4347 nsecs_t lastWarning = 0;
4348
4349 inputStandBy();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004350 acquireWakeLock(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004351
4352 // used to verify we've read at least once before evaluating how many bytes were read
4353 bool readOnce = false;
4354
4355 // start recording
4356 while (!exitPending()) {
4357
4358 processConfigEvents();
4359
4360 { // scope for mLock
4361 Mutex::Autolock _l(mLock);
4362 checkForNewParameters_l();
4363 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4364 standby();
4365
4366 if (exitPending()) {
4367 break;
4368 }
4369
4370 releaseWakeLock_l();
4371 ALOGV("RecordThread: loop stopping");
4372 // go to sleep
4373 mWaitWorkCV.wait(mLock);
4374 ALOGV("RecordThread: loop starting");
Marco Nelissene14a5d62013-10-03 08:51:24 -07004375 acquireWakeLock_l(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004376 continue;
4377 }
4378 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004379 if (mActiveTrack->isTerminated()) {
4380 removeTrack_l(mActiveTrack);
4381 mActiveTrack.clear();
4382 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004383 standby();
4384 mActiveTrack.clear();
4385 mStartStopCond.broadcast();
4386 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4387 if (mReqChannelCount != mActiveTrack->channelCount()) {
4388 mActiveTrack.clear();
4389 mStartStopCond.broadcast();
4390 } else if (readOnce) {
4391 // record start succeeds only if first read from audio input
4392 // succeeds
4393 if (mBytesRead >= 0) {
4394 mActiveTrack->mState = TrackBase::ACTIVE;
4395 } else {
4396 mActiveTrack.clear();
4397 }
4398 mStartStopCond.broadcast();
4399 }
4400 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004401 }
4402 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004403
Eric Laurent81784c32012-11-19 14:55:58 -08004404 lockEffectChains_l(effectChains);
4405 }
4406
4407 if (mActiveTrack != 0) {
4408 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4409 mActiveTrack->mState != TrackBase::RESUMING) {
4410 unlockEffectChains(effectChains);
4411 usleep(kRecordThreadSleepUs);
4412 continue;
4413 }
4414 for (size_t i = 0; i < effectChains.size(); i ++) {
4415 effectChains[i]->process_l();
4416 }
4417
4418 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004419 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004420 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004421 readOnce = true;
4422 size_t framesOut = buffer.frameCount;
4423 if (mResampler == NULL) {
4424 // no resampling
4425 while (framesOut) {
4426 size_t framesIn = mFrameCount - mRsmpInIndex;
4427 if (framesIn) {
4428 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4429 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4430 mActiveTrack->mFrameSize;
4431 if (framesIn > framesOut)
4432 framesIn = framesOut;
4433 mRsmpInIndex += framesIn;
4434 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004435 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004436 memcpy(dst, src, framesIn * mFrameSize);
4437 } else {
4438 if (mChannelCount == 1) {
4439 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4440 (int16_t *)src, framesIn);
4441 } else {
4442 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4443 (int16_t *)src, framesIn);
4444 }
4445 }
4446 }
4447 if (framesOut && mFrameCount == mRsmpInIndex) {
4448 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004449 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004450 readInto = buffer.raw;
4451 framesOut = 0;
4452 } else {
4453 readInto = mRsmpInBuffer;
4454 mRsmpInIndex = 0;
4455 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004456 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004457 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004458 if (mBytesRead <= 0) {
4459 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4460 {
4461 ALOGE("Error reading audio input");
4462 // Force input into standby so that it tries to
4463 // recover at next read attempt
4464 inputStandBy();
4465 usleep(kRecordThreadSleepUs);
4466 }
4467 mRsmpInIndex = mFrameCount;
4468 framesOut = 0;
4469 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004470 }
4471#ifdef TEE_SINK
4472 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004473 (void) mTeeSink->write(readInto,
4474 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4475 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004476#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004477 }
4478 }
4479 } else {
4480 // resampling
4481
Glenn Kasten34af0262013-07-30 11:52:39 -07004482 // resampler accumulates, but we only have one source track
4483 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004484 // alter output frame count as if we were expecting stereo samples
4485 if (mChannelCount == 1 && mReqChannelCount == 1) {
4486 framesOut >>= 1;
4487 }
4488 mResampler->resample(mRsmpOutBuffer, framesOut,
4489 this /* AudioBufferProvider* */);
4490 // ditherAndClamp() works as long as all buffers returned by
4491 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4492 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004493 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004494 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4495 // the resampler always outputs stereo samples:
4496 // do post stereo to mono conversion
4497 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4498 framesOut);
4499 } else {
4500 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4501 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004502 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004503
4504 }
4505 if (mFramestoDrop == 0) {
4506 mActiveTrack->releaseBuffer(&buffer);
4507 } else {
4508 if (mFramestoDrop > 0) {
4509 mFramestoDrop -= buffer.frameCount;
4510 if (mFramestoDrop <= 0) {
4511 clearSyncStartEvent();
4512 }
4513 } else {
4514 mFramestoDrop += buffer.frameCount;
4515 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4516 mSyncStartEvent->isCancelled()) {
4517 ALOGW("Synced record %s, session %d, trigger session %d",
4518 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4519 mActiveTrack->sessionId(),
4520 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4521 clearSyncStartEvent();
4522 }
4523 }
4524 }
4525 mActiveTrack->clearOverflow();
4526 }
4527 // client isn't retrieving buffers fast enough
4528 else {
4529 if (!mActiveTrack->setOverflow()) {
4530 nsecs_t now = systemTime();
4531 if ((now - lastWarning) > kWarningThrottleNs) {
4532 ALOGW("RecordThread: buffer overflow");
4533 lastWarning = now;
4534 }
4535 }
4536 // Release the processor for a while before asking for a new buffer.
4537 // This will give the application more chance to read from the buffer and
4538 // clear the overflow.
4539 usleep(kRecordThreadSleepUs);
4540 }
4541 }
4542 // enable changes in effect chain
4543 unlockEffectChains(effectChains);
4544 effectChains.clear();
4545 }
4546
4547 standby();
4548
4549 {
4550 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004551 for (size_t i = 0; i < mTracks.size(); i++) {
4552 sp<RecordTrack> track = mTracks[i];
4553 track->invalidate();
4554 }
Eric Laurent81784c32012-11-19 14:55:58 -08004555 mActiveTrack.clear();
4556 mStartStopCond.broadcast();
4557 }
4558
4559 releaseWakeLock();
4560
4561 ALOGV("RecordThread %p exiting", this);
4562 return false;
4563}
4564
4565void AudioFlinger::RecordThread::standby()
4566{
4567 if (!mStandby) {
4568 inputStandBy();
4569 mStandby = true;
4570 }
4571}
4572
4573void AudioFlinger::RecordThread::inputStandBy()
4574{
4575 mInput->stream->common.standby(&mInput->stream->common);
4576}
4577
4578sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4579 const sp<AudioFlinger::Client>& client,
4580 uint32_t sampleRate,
4581 audio_format_t format,
4582 audio_channel_mask_t channelMask,
4583 size_t frameCount,
4584 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004585 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004586 pid_t tid,
4587 status_t *status)
4588{
4589 sp<RecordTrack> track;
4590 status_t lStatus;
4591
4592 lStatus = initCheck();
4593 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004594 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004595 goto Exit;
4596 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004597 // client expresses a preference for FAST, but we get the final say
4598 if (*flags & IAudioFlinger::TRACK_FAST) {
4599 if (
4600 // use case: callback handler and frame count is default or at least as large as HAL
4601 (
4602 (tid != -1) &&
4603 ((frameCount == 0) ||
4604 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4605 ) &&
4606 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4607 // mono or stereo
4608 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4609 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4610 // hardware sample rate
4611 (sampleRate == mSampleRate) &&
4612 // record thread has an associated fast recorder
4613 hasFastRecorder()
4614 // FIXME test that RecordThread for this fast track has a capable output HAL
4615 // FIXME add a permission test also?
4616 ) {
4617 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4618 if (frameCount == 0) {
4619 frameCount = mFrameCount * kFastTrackMultiplier;
4620 }
4621 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4622 frameCount, mFrameCount);
4623 } else {
4624 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4625 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4626 "hasFastRecorder=%d tid=%d",
4627 frameCount, mFrameCount, format,
4628 audio_is_linear_pcm(format),
4629 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4630 *flags &= ~IAudioFlinger::TRACK_FAST;
4631 // For compatibility with AudioRecord calculation, buffer depth is forced
4632 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4633 // This is probably too conservative, but legacy application code may depend on it.
4634 // If you change this calculation, also review the start threshold which is related.
4635 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4636 size_t mNormalFrameCount = 2048; // FIXME
4637 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4638 if (minBufCount < 2) {
4639 minBufCount = 2;
4640 }
4641 size_t minFrameCount = mNormalFrameCount * minBufCount;
4642 if (frameCount < minFrameCount) {
4643 frameCount = minFrameCount;
4644 }
4645 }
4646 }
4647
Eric Laurent81784c32012-11-19 14:55:58 -08004648 // FIXME use flags and tid similar to createTrack_l()
4649
4650 { // scope for mLock
4651 Mutex::Autolock _l(mLock);
4652
4653 track = new RecordTrack(this, client, sampleRate,
4654 format, channelMask, frameCount, sessionId);
4655
4656 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004657 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004658 lStatus = NO_MEMORY;
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004659 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004660 goto Exit;
4661 }
4662 mTracks.add(track);
4663
4664 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4665 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4666 mAudioFlinger->btNrecIsOff();
4667 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4668 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004669
4670 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4671 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4672 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4673 // so ask activity manager to do this on our behalf
4674 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4675 }
Eric Laurent81784c32012-11-19 14:55:58 -08004676 }
4677 lStatus = NO_ERROR;
4678
4679Exit:
4680 if (status) {
4681 *status = lStatus;
4682 }
4683 return track;
4684}
4685
4686status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4687 AudioSystem::sync_event_t event,
4688 int triggerSession)
4689{
4690 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4691 sp<ThreadBase> strongMe = this;
4692 status_t status = NO_ERROR;
4693
4694 if (event == AudioSystem::SYNC_EVENT_NONE) {
4695 clearSyncStartEvent();
4696 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4697 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4698 triggerSession,
4699 recordTrack->sessionId(),
4700 syncStartEventCallback,
4701 this);
4702 // Sync event can be cancelled by the trigger session if the track is not in a
4703 // compatible state in which case we start record immediately
4704 if (mSyncStartEvent->isCancelled()) {
4705 clearSyncStartEvent();
4706 } else {
4707 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4708 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4709 }
4710 }
4711
4712 {
4713 AutoMutex lock(mLock);
4714 if (mActiveTrack != 0) {
4715 if (recordTrack != mActiveTrack.get()) {
4716 status = -EBUSY;
4717 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4718 mActiveTrack->mState = TrackBase::ACTIVE;
4719 }
4720 return status;
4721 }
4722
4723 recordTrack->mState = TrackBase::IDLE;
4724 mActiveTrack = recordTrack;
4725 mLock.unlock();
4726 status_t status = AudioSystem::startInput(mId);
4727 mLock.lock();
4728 if (status != NO_ERROR) {
4729 mActiveTrack.clear();
4730 clearSyncStartEvent();
4731 return status;
4732 }
4733 mRsmpInIndex = mFrameCount;
4734 mBytesRead = 0;
4735 if (mResampler != NULL) {
4736 mResampler->reset();
4737 }
4738 mActiveTrack->mState = TrackBase::RESUMING;
4739 // signal thread to start
4740 ALOGV("Signal record thread");
4741 mWaitWorkCV.broadcast();
4742 // do not wait for mStartStopCond if exiting
4743 if (exitPending()) {
4744 mActiveTrack.clear();
4745 status = INVALID_OPERATION;
4746 goto startError;
4747 }
4748 mStartStopCond.wait(mLock);
4749 if (mActiveTrack == 0) {
4750 ALOGV("Record failed to start");
4751 status = BAD_VALUE;
4752 goto startError;
4753 }
4754 ALOGV("Record started OK");
4755 return status;
4756 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004757
Eric Laurent81784c32012-11-19 14:55:58 -08004758startError:
4759 AudioSystem::stopInput(mId);
4760 clearSyncStartEvent();
4761 return status;
4762}
4763
4764void AudioFlinger::RecordThread::clearSyncStartEvent()
4765{
4766 if (mSyncStartEvent != 0) {
4767 mSyncStartEvent->cancel();
4768 }
4769 mSyncStartEvent.clear();
4770 mFramestoDrop = 0;
4771}
4772
4773void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4774{
4775 sp<SyncEvent> strongEvent = event.promote();
4776
4777 if (strongEvent != 0) {
4778 RecordThread *me = (RecordThread *)strongEvent->cookie();
4779 me->handleSyncStartEvent(strongEvent);
4780 }
4781}
4782
4783void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4784{
4785 if (event == mSyncStartEvent) {
4786 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4787 // from audio HAL
4788 mFramestoDrop = mFrameCount * 2;
4789 }
4790}
4791
Glenn Kastena8356f62013-07-25 14:37:52 -07004792bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004793 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004794 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004795 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4796 return false;
4797 }
4798 recordTrack->mState = TrackBase::PAUSING;
4799 // do not wait for mStartStopCond if exiting
4800 if (exitPending()) {
4801 return true;
4802 }
4803 mStartStopCond.wait(mLock);
4804 // if we have been restarted, recordTrack == mActiveTrack.get() here
4805 if (exitPending() || recordTrack != mActiveTrack.get()) {
4806 ALOGV("Record stopped OK");
4807 return true;
4808 }
4809 return false;
4810}
4811
4812bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4813{
4814 return false;
4815}
4816
4817status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4818{
4819#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4820 if (!isValidSyncEvent(event)) {
4821 return BAD_VALUE;
4822 }
4823
4824 int eventSession = event->triggerSession();
4825 status_t ret = NAME_NOT_FOUND;
4826
4827 Mutex::Autolock _l(mLock);
4828
4829 for (size_t i = 0; i < mTracks.size(); i++) {
4830 sp<RecordTrack> track = mTracks[i];
4831 if (eventSession == track->sessionId()) {
4832 (void) track->setSyncEvent(event);
4833 ret = NO_ERROR;
4834 }
4835 }
4836 return ret;
4837#else
4838 return BAD_VALUE;
4839#endif
4840}
4841
4842// destroyTrack_l() must be called with ThreadBase::mLock held
4843void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4844{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845 track->terminate();
4846 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004847 // active tracks are removed by threadLoop()
4848 if (mActiveTrack != track) {
4849 removeTrack_l(track);
4850 }
4851}
4852
4853void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4854{
4855 mTracks.remove(track);
4856 // need anything related to effects here?
4857}
4858
4859void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4860{
4861 dumpInternals(fd, args);
4862 dumpTracks(fd, args);
4863 dumpEffectChains(fd, args);
4864}
4865
4866void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4867{
4868 const size_t SIZE = 256;
4869 char buffer[SIZE];
4870 String8 result;
4871
4872 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4873 result.append(buffer);
4874
4875 if (mActiveTrack != 0) {
4876 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4877 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004878 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004879 result.append(buffer);
4880 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4881 result.append(buffer);
4882 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4883 result.append(buffer);
4884 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4885 result.append(buffer);
4886 } else {
4887 result.append("No active record client\n");
4888 }
4889
4890 write(fd, result.string(), result.size());
4891
4892 dumpBase(fd, args);
4893}
4894
4895void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4896{
4897 const size_t SIZE = 256;
4898 char buffer[SIZE];
4899 String8 result;
4900
4901 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4902 result.append(buffer);
4903 RecordTrack::appendDumpHeader(result);
4904 for (size_t i = 0; i < mTracks.size(); ++i) {
4905 sp<RecordTrack> track = mTracks[i];
4906 if (track != 0) {
4907 track->dump(buffer, SIZE);
4908 result.append(buffer);
4909 }
4910 }
4911
4912 if (mActiveTrack != 0) {
4913 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4914 result.append(buffer);
4915 RecordTrack::appendDumpHeader(result);
4916 mActiveTrack->dump(buffer, SIZE);
4917 result.append(buffer);
4918
4919 }
4920 write(fd, result.string(), result.size());
4921}
4922
4923// AudioBufferProvider interface
4924status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4925{
4926 size_t framesReq = buffer->frameCount;
4927 size_t framesReady = mFrameCount - mRsmpInIndex;
4928 int channelCount;
4929
4930 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004931 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004932 if (mBytesRead <= 0) {
4933 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4934 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4935 // Force input into standby so that it tries to
4936 // recover at next read attempt
4937 inputStandBy();
4938 usleep(kRecordThreadSleepUs);
4939 }
4940 buffer->raw = NULL;
4941 buffer->frameCount = 0;
4942 return NOT_ENOUGH_DATA;
4943 }
4944 mRsmpInIndex = 0;
4945 framesReady = mFrameCount;
4946 }
4947
4948 if (framesReq > framesReady) {
4949 framesReq = framesReady;
4950 }
4951
4952 if (mChannelCount == 1 && mReqChannelCount == 2) {
4953 channelCount = 1;
4954 } else {
4955 channelCount = 2;
4956 }
4957 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4958 buffer->frameCount = framesReq;
4959 return NO_ERROR;
4960}
4961
4962// AudioBufferProvider interface
4963void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4964{
4965 mRsmpInIndex += buffer->frameCount;
4966 buffer->frameCount = 0;
4967}
4968
4969bool AudioFlinger::RecordThread::checkForNewParameters_l()
4970{
4971 bool reconfig = false;
4972
4973 while (!mNewParameters.isEmpty()) {
4974 status_t status = NO_ERROR;
4975 String8 keyValuePair = mNewParameters[0];
4976 AudioParameter param = AudioParameter(keyValuePair);
4977 int value;
4978 audio_format_t reqFormat = mFormat;
4979 uint32_t reqSamplingRate = mReqSampleRate;
4980 uint32_t reqChannelCount = mReqChannelCount;
4981
4982 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4983 reqSamplingRate = value;
4984 reconfig = true;
4985 }
4986 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004987 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4988 status = BAD_VALUE;
4989 } else {
4990 reqFormat = (audio_format_t) value;
4991 reconfig = true;
4992 }
Eric Laurent81784c32012-11-19 14:55:58 -08004993 }
4994 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4995 reqChannelCount = popcount(value);
4996 reconfig = true;
4997 }
4998 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4999 // do not accept frame count changes if tracks are open as the track buffer
5000 // size depends on frame count and correct behavior would not be guaranteed
5001 // if frame count is changed after track creation
5002 if (mActiveTrack != 0) {
5003 status = INVALID_OPERATION;
5004 } else {
5005 reconfig = true;
5006 }
5007 }
5008 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5009 // forward device change to effects that have requested to be
5010 // aware of attached audio device.
5011 for (size_t i = 0; i < mEffectChains.size(); i++) {
5012 mEffectChains[i]->setDevice_l(value);
5013 }
5014
5015 // store input device and output device but do not forward output device to audio HAL.
5016 // Note that status is ignored by the caller for output device
5017 // (see AudioFlinger::setParameters()
5018 if (audio_is_output_devices(value)) {
5019 mOutDevice = value;
5020 status = BAD_VALUE;
5021 } else {
5022 mInDevice = value;
5023 // disable AEC and NS if the device is a BT SCO headset supporting those
5024 // pre processings
5025 if (mTracks.size() > 0) {
5026 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5027 mAudioFlinger->btNrecIsOff();
5028 for (size_t i = 0; i < mTracks.size(); i++) {
5029 sp<RecordTrack> track = mTracks[i];
5030 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5031 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5032 }
5033 }
5034 }
5035 }
5036 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5037 mAudioSource != (audio_source_t)value) {
5038 // forward device change to effects that have requested to be
5039 // aware of attached audio device.
5040 for (size_t i = 0; i < mEffectChains.size(); i++) {
5041 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5042 }
5043 mAudioSource = (audio_source_t)value;
5044 }
5045 if (status == NO_ERROR) {
5046 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5047 keyValuePair.string());
5048 if (status == INVALID_OPERATION) {
5049 inputStandBy();
5050 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5051 keyValuePair.string());
5052 }
5053 if (reconfig) {
5054 if (status == BAD_VALUE &&
5055 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5056 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005057 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005058 <= (2 * reqSamplingRate)) &&
5059 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5060 <= FCC_2 &&
5061 (reqChannelCount <= FCC_2)) {
5062 status = NO_ERROR;
5063 }
5064 if (status == NO_ERROR) {
5065 readInputParameters();
5066 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5067 }
5068 }
5069 }
5070
5071 mNewParameters.removeAt(0);
5072
5073 mParamStatus = status;
5074 mParamCond.signal();
5075 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5076 // already timed out waiting for the status and will never signal the condition.
5077 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5078 }
5079 return reconfig;
5080}
5081
5082String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5083{
Eric Laurent81784c32012-11-19 14:55:58 -08005084 Mutex::Autolock _l(mLock);
5085 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005086 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005087 }
5088
Glenn Kastend8ea6992013-07-16 14:17:15 -07005089 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5090 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005091 free(s);
5092 return out_s8;
5093}
5094
5095void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5096 AudioSystem::OutputDescriptor desc;
5097 void *param2 = NULL;
5098
5099 switch (event) {
5100 case AudioSystem::INPUT_OPENED:
5101 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005102 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005103 desc.samplingRate = mSampleRate;
5104 desc.format = mFormat;
5105 desc.frameCount = mFrameCount;
5106 desc.latency = 0;
5107 param2 = &desc;
5108 break;
5109
5110 case AudioSystem::INPUT_CLOSED:
5111 default:
5112 break;
5113 }
5114 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5115}
5116
5117void AudioFlinger::RecordThread::readInputParameters()
5118{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005119 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005120 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005121 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005122 mRsmpOutBuffer = NULL;
5123 delete mResampler;
5124 mResampler = NULL;
5125
5126 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5127 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005128 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005129 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005130 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5131 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5132 }
Eric Laurent81784c32012-11-19 14:55:58 -08005133 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005134 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5135 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005136 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5137
5138 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5139 {
5140 int channelCount;
5141 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5142 // stereo to mono post process as the resampler always outputs stereo.
5143 if (mChannelCount == 1 && mReqChannelCount == 2) {
5144 channelCount = 1;
5145 } else {
5146 channelCount = 2;
5147 }
5148 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5149 mResampler->setSampleRate(mSampleRate);
5150 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005151 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005152
5153 // optmization: if mono to mono, alter input frame count as if we were inputing
5154 // stereo samples
5155 if (mChannelCount == 1 && mReqChannelCount == 1) {
5156 mFrameCount >>= 1;
5157 }
5158
5159 }
5160 mRsmpInIndex = mFrameCount;
5161}
5162
5163unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5164{
5165 Mutex::Autolock _l(mLock);
5166 if (initCheck() != NO_ERROR) {
5167 return 0;
5168 }
5169
5170 return mInput->stream->get_input_frames_lost(mInput->stream);
5171}
5172
5173uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5174{
5175 Mutex::Autolock _l(mLock);
5176 uint32_t result = 0;
5177 if (getEffectChain_l(sessionId) != 0) {
5178 result = EFFECT_SESSION;
5179 }
5180
5181 for (size_t i = 0; i < mTracks.size(); ++i) {
5182 if (sessionId == mTracks[i]->sessionId()) {
5183 result |= TRACK_SESSION;
5184 break;
5185 }
5186 }
5187
5188 return result;
5189}
5190
5191KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5192{
5193 KeyedVector<int, bool> ids;
5194 Mutex::Autolock _l(mLock);
5195 for (size_t j = 0; j < mTracks.size(); ++j) {
5196 sp<RecordThread::RecordTrack> track = mTracks[j];
5197 int sessionId = track->sessionId();
5198 if (ids.indexOfKey(sessionId) < 0) {
5199 ids.add(sessionId, true);
5200 }
5201 }
5202 return ids;
5203}
5204
5205AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5206{
5207 Mutex::Autolock _l(mLock);
5208 AudioStreamIn *input = mInput;
5209 mInput = NULL;
5210 return input;
5211}
5212
5213// this method must always be called either with ThreadBase mLock held or inside the thread loop
5214audio_stream_t* AudioFlinger::RecordThread::stream() const
5215{
5216 if (mInput == NULL) {
5217 return NULL;
5218 }
5219 return &mInput->stream->common;
5220}
5221
5222status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5223{
5224 // only one chain per input thread
5225 if (mEffectChains.size() != 0) {
5226 return INVALID_OPERATION;
5227 }
5228 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5229
5230 chain->setInBuffer(NULL);
5231 chain->setOutBuffer(NULL);
5232
5233 checkSuspendOnAddEffectChain_l(chain);
5234
5235 mEffectChains.add(chain);
5236
5237 return NO_ERROR;
5238}
5239
5240size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5241{
5242 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5243 ALOGW_IF(mEffectChains.size() != 1,
5244 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5245 chain.get(), mEffectChains.size(), this);
5246 if (mEffectChains.size() == 1) {
5247 mEffectChains.removeAt(0);
5248 }
5249 return 0;
5250}
5251
5252}; // namespace android