blob: 943a70ef0c3fee4868d67849ceea3bc7fe1dcb9c [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
Marco Nelissene14a5d62013-10-03 08:51:24 -0700485void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800486{
487 if (mPowerManager == 0) {
488 // use checkService() to avoid blocking if power service is not up yet
489 sp<IBinder> binder =
490 defaultServiceManager()->checkService(String16("power"));
491 if (binder == 0) {
492 ALOGW("Thread %s cannot connect to the power manager service", mName);
493 } else {
494 mPowerManager = interface_cast<IPowerManager>(binder);
495 binder->linkToDeath(mDeathRecipient);
496 }
497 }
498 if (mPowerManager != 0) {
499 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700500 status_t status;
501 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700502 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700503 binder,
504 String16(mName),
505 String16("media"),
506 uid);
507 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700508 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700509 binder,
510 String16(mName),
511 String16("media"));
512 }
Eric Laurent81784c32012-11-19 14:55:58 -0800513 if (status == NO_ERROR) {
514 mWakeLockToken = binder;
515 }
516 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
517 }
518}
519
520void AudioFlinger::ThreadBase::releaseWakeLock()
521{
522 Mutex::Autolock _l(mLock);
523 releaseWakeLock_l();
524}
525
526void AudioFlinger::ThreadBase::releaseWakeLock_l()
527{
528 if (mWakeLockToken != 0) {
529 ALOGV("releaseWakeLock_l() %s", mName);
530 if (mPowerManager != 0) {
531 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
532 }
533 mWakeLockToken.clear();
534 }
535}
536
537void AudioFlinger::ThreadBase::clearPowerManager()
538{
539 Mutex::Autolock _l(mLock);
540 releaseWakeLock_l();
541 mPowerManager.clear();
542}
543
544void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
545{
546 sp<ThreadBase> thread = mThread.promote();
547 if (thread != 0) {
548 thread->clearPowerManager();
549 }
550 ALOGW("power manager service died !!!");
551}
552
553void AudioFlinger::ThreadBase::setEffectSuspended(
554 const effect_uuid_t *type, bool suspend, int sessionId)
555{
556 Mutex::Autolock _l(mLock);
557 setEffectSuspended_l(type, suspend, sessionId);
558}
559
560void AudioFlinger::ThreadBase::setEffectSuspended_l(
561 const effect_uuid_t *type, bool suspend, int sessionId)
562{
563 sp<EffectChain> chain = getEffectChain_l(sessionId);
564 if (chain != 0) {
565 if (type != NULL) {
566 chain->setEffectSuspended_l(type, suspend);
567 } else {
568 chain->setEffectSuspendedAll_l(suspend);
569 }
570 }
571
572 updateSuspendedSessions_l(type, suspend, sessionId);
573}
574
575void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
576{
577 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
578 if (index < 0) {
579 return;
580 }
581
582 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
583 mSuspendedSessions.valueAt(index);
584
585 for (size_t i = 0; i < sessionEffects.size(); i++) {
586 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
587 for (int j = 0; j < desc->mRefCount; j++) {
588 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
589 chain->setEffectSuspendedAll_l(true);
590 } else {
591 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
592 desc->mType.timeLow);
593 chain->setEffectSuspended_l(&desc->mType, true);
594 }
595 }
596 }
597}
598
599void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
600 bool suspend,
601 int sessionId)
602{
603 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
604
605 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
606
607 if (suspend) {
608 if (index >= 0) {
609 sessionEffects = mSuspendedSessions.valueAt(index);
610 } else {
611 mSuspendedSessions.add(sessionId, sessionEffects);
612 }
613 } else {
614 if (index < 0) {
615 return;
616 }
617 sessionEffects = mSuspendedSessions.valueAt(index);
618 }
619
620
621 int key = EffectChain::kKeyForSuspendAll;
622 if (type != NULL) {
623 key = type->timeLow;
624 }
625 index = sessionEffects.indexOfKey(key);
626
627 sp<SuspendedSessionDesc> desc;
628 if (suspend) {
629 if (index >= 0) {
630 desc = sessionEffects.valueAt(index);
631 } else {
632 desc = new SuspendedSessionDesc();
633 if (type != NULL) {
634 desc->mType = *type;
635 }
636 sessionEffects.add(key, desc);
637 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
638 }
639 desc->mRefCount++;
640 } else {
641 if (index < 0) {
642 return;
643 }
644 desc = sessionEffects.valueAt(index);
645 if (--desc->mRefCount == 0) {
646 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
647 sessionEffects.removeItemsAt(index);
648 if (sessionEffects.isEmpty()) {
649 ALOGV("updateSuspendedSessions_l() restore removing session %d",
650 sessionId);
651 mSuspendedSessions.removeItem(sessionId);
652 }
653 }
654 }
655 if (!sessionEffects.isEmpty()) {
656 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
657 }
658}
659
660void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
661 bool enabled,
662 int sessionId)
663{
664 Mutex::Autolock _l(mLock);
665 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
666}
667
668void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
669 bool enabled,
670 int sessionId)
671{
672 if (mType != RECORD) {
673 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
674 // another session. This gives the priority to well behaved effect control panels
675 // and applications not using global effects.
676 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
677 // global effects
678 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
679 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
680 }
681 }
682
683 sp<EffectChain> chain = getEffectChain_l(sessionId);
684 if (chain != 0) {
685 chain->checkSuspendOnEffectEnabled(effect, enabled);
686 }
687}
688
689// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
690sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
691 const sp<AudioFlinger::Client>& client,
692 const sp<IEffectClient>& effectClient,
693 int32_t priority,
694 int sessionId,
695 effect_descriptor_t *desc,
696 int *enabled,
697 status_t *status
698 )
699{
700 sp<EffectModule> effect;
701 sp<EffectHandle> handle;
702 status_t lStatus;
703 sp<EffectChain> chain;
704 bool chainCreated = false;
705 bool effectCreated = false;
706 bool effectRegistered = false;
707
708 lStatus = initCheck();
709 if (lStatus != NO_ERROR) {
710 ALOGW("createEffect_l() Audio driver not initialized.");
711 goto Exit;
712 }
713
Eric Laurent5baf2af2013-09-12 17:37:00 -0700714 // Allow global effects only on offloaded and mixer threads
715 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
716 switch (mType) {
717 case MIXER:
718 case OFFLOAD:
719 break;
720 case DIRECT:
721 case DUPLICATING:
722 case RECORD:
723 default:
724 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
725 lStatus = BAD_VALUE;
726 goto Exit;
727 }
Eric Laurent81784c32012-11-19 14:55:58 -0800728 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700729
Eric Laurent81784c32012-11-19 14:55:58 -0800730 // Only Pre processor effects are allowed on input threads and only on input threads
731 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
732 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
733 desc->name, desc->flags, mType);
734 lStatus = BAD_VALUE;
735 goto Exit;
736 }
737
738 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
739
740 { // scope for mLock
741 Mutex::Autolock _l(mLock);
742
743 // check for existing effect chain with the requested audio session
744 chain = getEffectChain_l(sessionId);
745 if (chain == 0) {
746 // create a new chain for this session
747 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
748 chain = new EffectChain(this, sessionId);
749 addEffectChain_l(chain);
750 chain->setStrategy(getStrategyForSession_l(sessionId));
751 chainCreated = true;
752 } else {
753 effect = chain->getEffectFromDesc_l(desc);
754 }
755
756 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
757
758 if (effect == 0) {
759 int id = mAudioFlinger->nextUniqueId();
760 // Check CPU and memory usage
761 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
762 if (lStatus != NO_ERROR) {
763 goto Exit;
764 }
765 effectRegistered = true;
766 // create a new effect module if none present in the chain
767 effect = new EffectModule(this, chain, desc, id, sessionId);
768 lStatus = effect->status();
769 if (lStatus != NO_ERROR) {
770 goto Exit;
771 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700772 effect->setOffloaded(mType == OFFLOAD, mId);
773
Eric Laurent81784c32012-11-19 14:55:58 -0800774 lStatus = chain->addEffect_l(effect);
775 if (lStatus != NO_ERROR) {
776 goto Exit;
777 }
778 effectCreated = true;
779
780 effect->setDevice(mOutDevice);
781 effect->setDevice(mInDevice);
782 effect->setMode(mAudioFlinger->getMode());
783 effect->setAudioSource(mAudioSource);
784 }
785 // create effect handle and connect it to effect module
786 handle = new EffectHandle(effect, client, effectClient, priority);
787 lStatus = effect->addHandle(handle.get());
788 if (enabled != NULL) {
789 *enabled = (int)effect->isEnabled();
790 }
791 }
792
793Exit:
794 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
795 Mutex::Autolock _l(mLock);
796 if (effectCreated) {
797 chain->removeEffect_l(effect);
798 }
799 if (effectRegistered) {
800 AudioSystem::unregisterEffect(effect->id());
801 }
802 if (chainCreated) {
803 removeEffectChain_l(chain);
804 }
805 handle.clear();
806 }
807
808 if (status != NULL) {
809 *status = lStatus;
810 }
811 return handle;
812}
813
814sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
815{
816 Mutex::Autolock _l(mLock);
817 return getEffect_l(sessionId, effectId);
818}
819
820sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
821{
822 sp<EffectChain> chain = getEffectChain_l(sessionId);
823 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
824}
825
826// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
827// PlaybackThread::mLock held
828status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
829{
830 // check for existing effect chain with the requested audio session
831 int sessionId = effect->sessionId();
832 sp<EffectChain> chain = getEffectChain_l(sessionId);
833 bool chainCreated = false;
834
Eric Laurent5baf2af2013-09-12 17:37:00 -0700835 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
836 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
837 this, effect->desc().name, effect->desc().flags);
838
Eric Laurent81784c32012-11-19 14:55:58 -0800839 if (chain == 0) {
840 // create a new chain for this session
841 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
842 chain = new EffectChain(this, sessionId);
843 addEffectChain_l(chain);
844 chain->setStrategy(getStrategyForSession_l(sessionId));
845 chainCreated = true;
846 }
847 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
848
849 if (chain->getEffectFromId_l(effect->id()) != 0) {
850 ALOGW("addEffect_l() %p effect %s already present in chain %p",
851 this, effect->desc().name, chain.get());
852 return BAD_VALUE;
853 }
854
Eric Laurent5baf2af2013-09-12 17:37:00 -0700855 effect->setOffloaded(mType == OFFLOAD, mId);
856
Eric Laurent81784c32012-11-19 14:55:58 -0800857 status_t status = chain->addEffect_l(effect);
858 if (status != NO_ERROR) {
859 if (chainCreated) {
860 removeEffectChain_l(chain);
861 }
862 return status;
863 }
864
865 effect->setDevice(mOutDevice);
866 effect->setDevice(mInDevice);
867 effect->setMode(mAudioFlinger->getMode());
868 effect->setAudioSource(mAudioSource);
869 return NO_ERROR;
870}
871
872void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
873
874 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
875 effect_descriptor_t desc = effect->desc();
876 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
877 detachAuxEffect_l(effect->id());
878 }
879
880 sp<EffectChain> chain = effect->chain().promote();
881 if (chain != 0) {
882 // remove effect chain if removing last effect
883 if (chain->removeEffect_l(effect) == 0) {
884 removeEffectChain_l(chain);
885 }
886 } else {
887 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
888 }
889}
890
891void AudioFlinger::ThreadBase::lockEffectChains_l(
892 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
893{
894 effectChains = mEffectChains;
895 for (size_t i = 0; i < mEffectChains.size(); i++) {
896 mEffectChains[i]->lock();
897 }
898}
899
900void AudioFlinger::ThreadBase::unlockEffectChains(
901 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
902{
903 for (size_t i = 0; i < effectChains.size(); i++) {
904 effectChains[i]->unlock();
905 }
906}
907
908sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
909{
910 Mutex::Autolock _l(mLock);
911 return getEffectChain_l(sessionId);
912}
913
914sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
915{
916 size_t size = mEffectChains.size();
917 for (size_t i = 0; i < size; i++) {
918 if (mEffectChains[i]->sessionId() == sessionId) {
919 return mEffectChains[i];
920 }
921 }
922 return 0;
923}
924
925void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
926{
927 Mutex::Autolock _l(mLock);
928 size_t size = mEffectChains.size();
929 for (size_t i = 0; i < size; i++) {
930 mEffectChains[i]->setMode_l(mode);
931 }
932}
933
934void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
935 EffectHandle *handle,
936 bool unpinIfLast) {
937
938 Mutex::Autolock _l(mLock);
939 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
940 // delete the effect module if removing last handle on it
941 if (effect->removeHandle(handle) == 0) {
942 if (!effect->isPinned() || unpinIfLast) {
943 removeEffect_l(effect);
944 AudioSystem::unregisterEffect(effect->id());
945 }
946 }
947}
948
949// ----------------------------------------------------------------------------
950// Playback
951// ----------------------------------------------------------------------------
952
953AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
954 AudioStreamOut* output,
955 audio_io_handle_t id,
956 audio_devices_t device,
957 type_t type)
958 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700959 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800960 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800961 // mStreamTypes[] initialized in constructor body
962 mOutput(output),
963 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
964 mMixerStatus(MIXER_IDLE),
965 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
966 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800967 mBytesRemaining(0),
968 mCurrentWriteLength(0),
969 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -0700970 mWriteAckSequence(0),
971 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -0700972 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -0800973 mScreenState(AudioFlinger::mScreenState),
974 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700975 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
976 // mLatchD, mLatchQ,
977 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800978{
979 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800980 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -0800981
982 // Assumes constructor is called by AudioFlinger with it's mLock held, but
983 // it would be safer to explicitly pass initial masterVolume/masterMute as
984 // parameter.
985 //
986 // If the HAL we are using has support for master volume or master mute,
987 // then do not attenuate or mute during mixing (just leave the volume at 1.0
988 // and the mute set to false).
989 mMasterVolume = audioFlinger->masterVolume_l();
990 mMasterMute = audioFlinger->masterMute_l();
991 if (mOutput && mOutput->audioHwDev) {
992 if (mOutput->audioHwDev->canSetMasterVolume()) {
993 mMasterVolume = 1.0;
994 }
995
996 if (mOutput->audioHwDev->canSetMasterMute()) {
997 mMasterMute = false;
998 }
999 }
1000
1001 readOutputParameters();
1002
1003 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1004 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1005 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1006 stream = (audio_stream_type_t) (stream + 1)) {
1007 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1008 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1009 }
1010 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1011 // because mAudioFlinger doesn't have one to copy from
1012}
1013
1014AudioFlinger::PlaybackThread::~PlaybackThread()
1015{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001016 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001017 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001018}
1019
1020void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1021{
1022 dumpInternals(fd, args);
1023 dumpTracks(fd, args);
1024 dumpEffectChains(fd, args);
1025}
1026
1027void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1028{
1029 const size_t SIZE = 256;
1030 char buffer[SIZE];
1031 String8 result;
1032
1033 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1034 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1035 const stream_type_t *st = &mStreamTypes[i];
1036 if (i > 0) {
1037 result.appendFormat(", ");
1038 }
1039 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1040 if (st->mute) {
1041 result.append("M");
1042 }
1043 }
1044 result.append("\n");
1045 write(fd, result.string(), result.length());
1046 result.clear();
1047
1048 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1049 result.append(buffer);
1050 Track::appendDumpHeader(result);
1051 for (size_t i = 0; i < mTracks.size(); ++i) {
1052 sp<Track> track = mTracks[i];
1053 if (track != 0) {
1054 track->dump(buffer, SIZE);
1055 result.append(buffer);
1056 }
1057 }
1058
1059 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1060 result.append(buffer);
1061 Track::appendDumpHeader(result);
1062 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1063 sp<Track> track = mActiveTracks[i].promote();
1064 if (track != 0) {
1065 track->dump(buffer, SIZE);
1066 result.append(buffer);
1067 }
1068 }
1069 write(fd, result.string(), result.size());
1070
1071 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1072 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1073 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1074 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1075}
1076
1077void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1078{
1079 const size_t SIZE = 256;
1080 char buffer[SIZE];
1081 String8 result;
1082
1083 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1084 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001085 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1086 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001087 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1088 ns2ms(systemTime() - mLastWriteTime));
1089 result.append(buffer);
1090 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1091 result.append(buffer);
1092 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1093 result.append(buffer);
1094 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1095 result.append(buffer);
1096 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1097 result.append(buffer);
1098 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1099 result.append(buffer);
1100 write(fd, result.string(), result.size());
1101 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1102
1103 dumpBase(fd, args);
1104}
1105
1106// Thread virtuals
1107status_t AudioFlinger::PlaybackThread::readyToRun()
1108{
1109 status_t status = initCheck();
1110 if (status == NO_ERROR) {
1111 ALOGI("AudioFlinger's thread %p ready to run", this);
1112 } else {
1113 ALOGE("No working audio driver found.");
1114 }
1115 return status;
1116}
1117
1118void AudioFlinger::PlaybackThread::onFirstRef()
1119{
1120 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1121}
1122
1123// ThreadBase virtuals
1124void AudioFlinger::PlaybackThread::preExit()
1125{
1126 ALOGV(" preExit()");
1127 // FIXME this is using hard-coded strings but in the future, this functionality will be
1128 // converted to use audio HAL extensions required to support tunneling
1129 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1130}
1131
1132// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1133sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1134 const sp<AudioFlinger::Client>& client,
1135 audio_stream_type_t streamType,
1136 uint32_t sampleRate,
1137 audio_format_t format,
1138 audio_channel_mask_t channelMask,
1139 size_t frameCount,
1140 const sp<IMemory>& sharedBuffer,
1141 int sessionId,
1142 IAudioFlinger::track_flags_t *flags,
1143 pid_t tid,
1144 status_t *status)
1145{
1146 sp<Track> track;
1147 status_t lStatus;
1148
1149 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1150
1151 // client expresses a preference for FAST, but we get the final say
1152 if (*flags & IAudioFlinger::TRACK_FAST) {
1153 if (
1154 // not timed
1155 (!isTimed) &&
1156 // either of these use cases:
1157 (
1158 // use case 1: shared buffer with any frame count
1159 (
1160 (sharedBuffer != 0)
1161 ) ||
1162 // use case 2: callback handler and frame count is default or at least as large as HAL
1163 (
1164 (tid != -1) &&
1165 ((frameCount == 0) ||
1166 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1167 )
1168 ) &&
1169 // PCM data
1170 audio_is_linear_pcm(format) &&
1171 // mono or stereo
1172 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1173 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1174#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1175 // hardware sample rate
1176 (sampleRate == mSampleRate) &&
1177#endif
1178 // normal mixer has an associated fast mixer
1179 hasFastMixer() &&
1180 // there are sufficient fast track slots available
1181 (mFastTrackAvailMask != 0)
1182 // FIXME test that MixerThread for this fast track has a capable output HAL
1183 // FIXME add a permission test also?
1184 ) {
1185 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1186 if (frameCount == 0) {
1187 frameCount = mFrameCount * kFastTrackMultiplier;
1188 }
1189 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1190 frameCount, mFrameCount);
1191 } else {
1192 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1193 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1194 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1195 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1196 audio_is_linear_pcm(format),
1197 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1198 *flags &= ~IAudioFlinger::TRACK_FAST;
1199 // For compatibility with AudioTrack calculation, buffer depth is forced
1200 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1201 // This is probably too conservative, but legacy application code may depend on it.
1202 // If you change this calculation, also review the start threshold which is related.
1203 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1204 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1205 if (minBufCount < 2) {
1206 minBufCount = 2;
1207 }
1208 size_t minFrameCount = mNormalFrameCount * minBufCount;
1209 if (frameCount < minFrameCount) {
1210 frameCount = minFrameCount;
1211 }
1212 }
1213 }
1214
1215 if (mType == DIRECT) {
1216 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1217 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1218 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1219 "for output %p with format %d",
1220 sampleRate, format, channelMask, mOutput, mFormat);
1221 lStatus = BAD_VALUE;
1222 goto Exit;
1223 }
1224 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001225 } else if (mType == OFFLOAD) {
1226 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1227 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1228 "for output %p with format %d",
1229 sampleRate, format, channelMask, mOutput, mFormat);
1230 lStatus = BAD_VALUE;
1231 goto Exit;
1232 }
Eric Laurent81784c32012-11-19 14:55:58 -08001233 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001234 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1235 ALOGE("createTrack_l() Bad parameter: format %d \""
1236 "for output %p with format %d",
1237 format, mOutput, mFormat);
1238 lStatus = BAD_VALUE;
1239 goto Exit;
1240 }
Eric Laurent81784c32012-11-19 14:55:58 -08001241 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1242 if (sampleRate > mSampleRate*2) {
1243 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1244 lStatus = BAD_VALUE;
1245 goto Exit;
1246 }
1247 }
1248
1249 lStatus = initCheck();
1250 if (lStatus != NO_ERROR) {
1251 ALOGE("Audio driver not initialized.");
1252 goto Exit;
1253 }
1254
1255 { // scope for mLock
1256 Mutex::Autolock _l(mLock);
1257
1258 // all tracks in same audio session must share the same routing strategy otherwise
1259 // conflicts will happen when tracks are moved from one output to another by audio policy
1260 // manager
1261 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1262 for (size_t i = 0; i < mTracks.size(); ++i) {
1263 sp<Track> t = mTracks[i];
1264 if (t != 0 && !t->isOutputTrack()) {
1265 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1266 if (sessionId == t->sessionId() && strategy != actual) {
1267 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1268 strategy, actual);
1269 lStatus = BAD_VALUE;
1270 goto Exit;
1271 }
1272 }
1273 }
1274
1275 if (!isTimed) {
1276 track = new Track(this, client, streamType, sampleRate, format,
1277 channelMask, frameCount, sharedBuffer, sessionId, *flags);
1278 } else {
1279 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1280 channelMask, frameCount, sharedBuffer, sessionId);
1281 }
1282 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1283 lStatus = NO_MEMORY;
1284 goto Exit;
1285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001286
Eric Laurent81784c32012-11-19 14:55:58 -08001287 mTracks.add(track);
1288
1289 sp<EffectChain> chain = getEffectChain_l(sessionId);
1290 if (chain != 0) {
1291 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1292 track->setMainBuffer(chain->inBuffer());
1293 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1294 chain->incTrackCnt();
1295 }
1296
1297 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1298 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1299 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1300 // so ask activity manager to do this on our behalf
1301 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1302 }
1303 }
1304
1305 lStatus = NO_ERROR;
1306
1307Exit:
1308 if (status) {
1309 *status = lStatus;
1310 }
1311 return track;
1312}
1313
1314uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1315{
1316 return latency;
1317}
1318
1319uint32_t AudioFlinger::PlaybackThread::latency() const
1320{
1321 Mutex::Autolock _l(mLock);
1322 return latency_l();
1323}
1324uint32_t AudioFlinger::PlaybackThread::latency_l() const
1325{
1326 if (initCheck() == NO_ERROR) {
1327 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1328 } else {
1329 return 0;
1330 }
1331}
1332
1333void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1334{
1335 Mutex::Autolock _l(mLock);
1336 // Don't apply master volume in SW if our HAL can do it for us.
1337 if (mOutput && mOutput->audioHwDev &&
1338 mOutput->audioHwDev->canSetMasterVolume()) {
1339 mMasterVolume = 1.0;
1340 } else {
1341 mMasterVolume = value;
1342 }
1343}
1344
1345void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1346{
1347 Mutex::Autolock _l(mLock);
1348 // Don't apply master mute in SW if our HAL can do it for us.
1349 if (mOutput && mOutput->audioHwDev &&
1350 mOutput->audioHwDev->canSetMasterMute()) {
1351 mMasterMute = false;
1352 } else {
1353 mMasterMute = muted;
1354 }
1355}
1356
1357void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1358{
1359 Mutex::Autolock _l(mLock);
1360 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001361 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001362}
1363
1364void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1365{
1366 Mutex::Autolock _l(mLock);
1367 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001368 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001369}
1370
1371float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1372{
1373 Mutex::Autolock _l(mLock);
1374 return mStreamTypes[stream].volume;
1375}
1376
1377// addTrack_l() must be called with ThreadBase::mLock held
1378status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1379{
1380 status_t status = ALREADY_EXISTS;
1381
1382 // set retry count for buffer fill
1383 track->mRetryCount = kMaxTrackStartupRetries;
1384 if (mActiveTracks.indexOf(track) < 0) {
1385 // the track is newly added, make sure it fills up all its
1386 // buffers before playing. This is to ensure the client will
1387 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001388 if (!track->isOutputTrack()) {
1389 TrackBase::track_state state = track->mState;
1390 mLock.unlock();
1391 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1392 mLock.lock();
1393 // abort track was stopped/paused while we released the lock
1394 if (state != track->mState) {
1395 if (status == NO_ERROR) {
1396 mLock.unlock();
1397 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1398 mLock.lock();
1399 }
1400 return INVALID_OPERATION;
1401 }
1402 // abort if start is rejected by audio policy manager
1403 if (status != NO_ERROR) {
1404 return PERMISSION_DENIED;
1405 }
1406#ifdef ADD_BATTERY_DATA
1407 // to track the speaker usage
1408 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1409#endif
1410 }
1411
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001412 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001413 track->mResetDone = false;
1414 track->mPresentationCompleteFrames = 0;
1415 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07001416 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1417 if (chain != 0) {
1418 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1419 track->sessionId());
1420 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001421 }
1422
1423 status = NO_ERROR;
1424 }
1425
Eric Laurentede6c3b2013-09-19 14:37:46 -07001426 ALOGV("signal playback thread");
1427 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001428
1429 return status;
1430}
1431
Eric Laurentbfb1b832013-01-07 09:53:42 -08001432bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001433{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001434 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001435 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001436 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1437 track->mState = TrackBase::STOPPED;
1438 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001439 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001440 } else if (track->isFastTrack() || track->isOffloaded()) {
1441 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001442 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001443
1444 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001445}
1446
1447void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1448{
1449 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1450 mTracks.remove(track);
1451 deleteTrackName_l(track->name());
1452 // redundant as track is about to be destroyed, for dumpsys only
1453 track->mName = -1;
1454 if (track->isFastTrack()) {
1455 int index = track->mFastIndex;
1456 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1457 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1458 mFastTrackAvailMask |= 1 << index;
1459 // redundant as track is about to be destroyed, for dumpsys only
1460 track->mFastIndex = -1;
1461 }
1462 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1463 if (chain != 0) {
1464 chain->decTrackCnt();
1465 }
1466}
1467
Eric Laurentede6c3b2013-09-19 14:37:46 -07001468void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001469{
1470 // Thread could be blocked waiting for async
1471 // so signal it to handle state changes immediately
1472 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1473 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1474 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001475 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001476}
1477
Eric Laurent81784c32012-11-19 14:55:58 -08001478String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1479{
Eric Laurent81784c32012-11-19 14:55:58 -08001480 Mutex::Autolock _l(mLock);
1481 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001482 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001483 }
1484
Glenn Kastend8ea6992013-07-16 14:17:15 -07001485 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1486 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001487 free(s);
1488 return out_s8;
1489}
1490
1491// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1492void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1493 AudioSystem::OutputDescriptor desc;
1494 void *param2 = NULL;
1495
1496 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1497 param);
1498
1499 switch (event) {
1500 case AudioSystem::OUTPUT_OPENED:
1501 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001502 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001503 desc.samplingRate = mSampleRate;
1504 desc.format = mFormat;
1505 desc.frameCount = mNormalFrameCount; // FIXME see
1506 // AudioFlinger::frameCount(audio_io_handle_t)
1507 desc.latency = latency();
1508 param2 = &desc;
1509 break;
1510
1511 case AudioSystem::STREAM_CONFIG_CHANGED:
1512 param2 = &param;
1513 case AudioSystem::OUTPUT_CLOSED:
1514 default:
1515 break;
1516 }
1517 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1518}
1519
Eric Laurentbfb1b832013-01-07 09:53:42 -08001520void AudioFlinger::PlaybackThread::writeCallback()
1521{
1522 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001523 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001524}
1525
1526void AudioFlinger::PlaybackThread::drainCallback()
1527{
1528 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001529 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001530}
1531
Eric Laurent3b4529e2013-09-05 18:09:19 -07001532void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001533{
1534 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001535 // reject out of sequence requests
1536 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1537 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001538 mWaitWorkCV.signal();
1539 }
1540}
1541
Eric Laurent3b4529e2013-09-05 18:09:19 -07001542void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001543{
1544 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001545 // reject out of sequence requests
1546 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1547 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001548 mWaitWorkCV.signal();
1549 }
1550}
1551
1552// static
1553int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1554 void *param,
1555 void *cookie)
1556{
1557 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1558 ALOGV("asyncCallback() event %d", event);
1559 switch (event) {
1560 case STREAM_CBK_EVENT_WRITE_READY:
1561 me->writeCallback();
1562 break;
1563 case STREAM_CBK_EVENT_DRAIN_READY:
1564 me->drainCallback();
1565 break;
1566 default:
1567 ALOGW("asyncCallback() unknown event %d", event);
1568 break;
1569 }
1570 return 0;
1571}
1572
Eric Laurent81784c32012-11-19 14:55:58 -08001573void AudioFlinger::PlaybackThread::readOutputParameters()
1574{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001575 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001576 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1577 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001578 if (!audio_is_output_channel(mChannelMask)) {
1579 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1580 }
1581 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1582 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1583 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1584 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001585 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001586 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001587 if (!audio_is_valid_format(mFormat)) {
1588 LOG_FATAL("HAL format %d not valid for output", mFormat);
1589 }
1590 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1591 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1592 mFormat);
1593 }
Eric Laurent81784c32012-11-19 14:55:58 -08001594 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1595 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1596 if (mFrameCount & 15) {
1597 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1598 mFrameCount);
1599 }
1600
Eric Laurentbfb1b832013-01-07 09:53:42 -08001601 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1602 (mOutput->stream->set_callback != NULL)) {
1603 if (mOutput->stream->set_callback(mOutput->stream,
1604 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1605 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001606 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001607 }
1608 }
1609
Eric Laurent81784c32012-11-19 14:55:58 -08001610 // Calculate size of normal mix buffer relative to the HAL output buffer size
1611 double multiplier = 1.0;
1612 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1613 kUseFastMixer == FastMixer_Dynamic)) {
1614 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1615 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1616 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1617 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1618 maxNormalFrameCount = maxNormalFrameCount & ~15;
1619 if (maxNormalFrameCount < minNormalFrameCount) {
1620 maxNormalFrameCount = minNormalFrameCount;
1621 }
1622 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1623 if (multiplier <= 1.0) {
1624 multiplier = 1.0;
1625 } else if (multiplier <= 2.0) {
1626 if (2 * mFrameCount <= maxNormalFrameCount) {
1627 multiplier = 2.0;
1628 } else {
1629 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1630 }
1631 } else {
1632 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1633 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1634 // track, but we sometimes have to do this to satisfy the maximum frame count
1635 // constraint)
1636 // FIXME this rounding up should not be done if no HAL SRC
1637 uint32_t truncMult = (uint32_t) multiplier;
1638 if ((truncMult & 1)) {
1639 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1640 ++truncMult;
1641 }
1642 }
1643 multiplier = (double) truncMult;
1644 }
1645 }
1646 mNormalFrameCount = multiplier * mFrameCount;
1647 // round up to nearest 16 frames to satisfy AudioMixer
1648 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1649 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1650 mNormalFrameCount);
1651
Eric Laurentbfb1b832013-01-07 09:53:42 -08001652 delete[] mAllocMixBuffer;
1653 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1654 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1655 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1656 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001657
1658 // force reconfiguration of effect chains and engines to take new buffer size and audio
1659 // parameters into account
1660 // Note that mLock is not held when readOutputParameters() is called from the constructor
1661 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1662 // matter.
1663 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1664 Vector< sp<EffectChain> > effectChains = mEffectChains;
1665 for (size_t i = 0; i < effectChains.size(); i ++) {
1666 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1667 }
1668}
1669
1670
1671status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1672{
1673 if (halFrames == NULL || dspFrames == NULL) {
1674 return BAD_VALUE;
1675 }
1676 Mutex::Autolock _l(mLock);
1677 if (initCheck() != NO_ERROR) {
1678 return INVALID_OPERATION;
1679 }
1680 size_t framesWritten = mBytesWritten / mFrameSize;
1681 *halFrames = framesWritten;
1682
1683 if (isSuspended()) {
1684 // return an estimation of rendered frames when the output is suspended
1685 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1686 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1687 return NO_ERROR;
1688 } else {
1689 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1690 }
1691}
1692
1693uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1694{
1695 Mutex::Autolock _l(mLock);
1696 uint32_t result = 0;
1697 if (getEffectChain_l(sessionId) != 0) {
1698 result = EFFECT_SESSION;
1699 }
1700
1701 for (size_t i = 0; i < mTracks.size(); ++i) {
1702 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001703 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001704 result |= TRACK_SESSION;
1705 break;
1706 }
1707 }
1708
1709 return result;
1710}
1711
1712uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1713{
1714 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1715 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1716 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1717 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1718 }
1719 for (size_t i = 0; i < mTracks.size(); i++) {
1720 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001721 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001722 return AudioSystem::getStrategyForStream(track->streamType());
1723 }
1724 }
1725 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1726}
1727
1728
1729AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1730{
1731 Mutex::Autolock _l(mLock);
1732 return mOutput;
1733}
1734
1735AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1736{
1737 Mutex::Autolock _l(mLock);
1738 AudioStreamOut *output = mOutput;
1739 mOutput = NULL;
1740 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1741 // must push a NULL and wait for ack
1742 mOutputSink.clear();
1743 mPipeSink.clear();
1744 mNormalSink.clear();
1745 return output;
1746}
1747
1748// this method must always be called either with ThreadBase mLock held or inside the thread loop
1749audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1750{
1751 if (mOutput == NULL) {
1752 return NULL;
1753 }
1754 return &mOutput->stream->common;
1755}
1756
1757uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1758{
1759 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1760}
1761
1762status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1763{
1764 if (!isValidSyncEvent(event)) {
1765 return BAD_VALUE;
1766 }
1767
1768 Mutex::Autolock _l(mLock);
1769
1770 for (size_t i = 0; i < mTracks.size(); ++i) {
1771 sp<Track> track = mTracks[i];
1772 if (event->triggerSession() == track->sessionId()) {
1773 (void) track->setSyncEvent(event);
1774 return NO_ERROR;
1775 }
1776 }
1777
1778 return NAME_NOT_FOUND;
1779}
1780
1781bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1782{
1783 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1784}
1785
1786void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1787 const Vector< sp<Track> >& tracksToRemove)
1788{
1789 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001790 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001791 for (size_t i = 0 ; i < count ; i++) {
1792 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001793 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001794 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001795#ifdef ADD_BATTERY_DATA
1796 // to track the speaker usage
1797 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1798#endif
1799 if (track->isTerminated()) {
1800 AudioSystem::releaseOutput(mId);
1801 }
Eric Laurent81784c32012-11-19 14:55:58 -08001802 }
1803 }
1804 }
Eric Laurent81784c32012-11-19 14:55:58 -08001805}
1806
1807void AudioFlinger::PlaybackThread::checkSilentMode_l()
1808{
1809 if (!mMasterMute) {
1810 char value[PROPERTY_VALUE_MAX];
1811 if (property_get("ro.audio.silent", value, "0") > 0) {
1812 char *endptr;
1813 unsigned long ul = strtoul(value, &endptr, 0);
1814 if (*endptr == '\0' && ul != 0) {
1815 ALOGD("Silence is golden");
1816 // The setprop command will not allow a property to be changed after
1817 // the first time it is set, so we don't have to worry about un-muting.
1818 setMasterMute_l(true);
1819 }
1820 }
1821 }
1822}
1823
1824// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001825ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001826{
1827 // FIXME rewrite to reduce number of system calls
1828 mLastWriteTime = systemTime();
1829 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001830 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001831
1832 // If an NBAIO sink is present, use it to write the normal mixer's submix
1833 if (mNormalSink != 0) {
1834#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001835 size_t count = mBytesRemaining >> mBitShift;
1836 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001837 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001838 // update the setpoint when AudioFlinger::mScreenState changes
1839 uint32_t screenState = AudioFlinger::mScreenState;
1840 if (screenState != mScreenState) {
1841 mScreenState = screenState;
1842 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1843 if (pipe != NULL) {
1844 pipe->setAvgFrames((mScreenState & 1) ?
1845 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1846 }
1847 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001848 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001849 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001850 if (framesWritten > 0) {
1851 bytesWritten = framesWritten << mBitShift;
1852 } else {
1853 bytesWritten = framesWritten;
1854 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001855 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001856 if (status == NO_ERROR) {
1857 size_t totalFramesWritten = mNormalSink->framesWritten();
1858 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1859 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1860 mLatchDValid = true;
1861 }
1862 }
Eric Laurent81784c32012-11-19 14:55:58 -08001863 // otherwise use the HAL / AudioStreamOut directly
1864 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001865 // Direct output and offload threads
1866 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1867 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001868 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1869 mWriteAckSequence += 2;
1870 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001871 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001872 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001873 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001874 // FIXME We should have an implementation of timestamps for direct output threads.
1875 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001876 bytesWritten = mOutput->stream->write(mOutput->stream,
1877 mMixBuffer + offset, mBytesRemaining);
1878 if (mUseAsyncWrite &&
1879 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1880 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001881 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001883 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001884 }
Eric Laurent81784c32012-11-19 14:55:58 -08001885 }
1886
Eric Laurent81784c32012-11-19 14:55:58 -08001887 mNumWrites++;
1888 mInWrite = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001889
1890 return bytesWritten;
1891}
1892
1893void AudioFlinger::PlaybackThread::threadLoop_drain()
1894{
1895 if (mOutput->stream->drain) {
1896 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1897 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001898 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1899 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001900 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001901 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001902 }
1903 mOutput->stream->drain(mOutput->stream,
1904 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1905 : AUDIO_DRAIN_ALL);
1906 }
1907}
1908
1909void AudioFlinger::PlaybackThread::threadLoop_exit()
1910{
1911 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001912}
1913
1914/*
1915The derived values that are cached:
1916 - mixBufferSize from frame count * frame size
1917 - activeSleepTime from activeSleepTimeUs()
1918 - idleSleepTime from idleSleepTimeUs()
1919 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1920 - maxPeriod from frame count and sample rate (MIXER only)
1921
1922The parameters that affect these derived values are:
1923 - frame count
1924 - frame size
1925 - sample rate
1926 - device type: A2DP or not
1927 - device latency
1928 - format: PCM or not
1929 - active sleep time
1930 - idle sleep time
1931*/
1932
1933void AudioFlinger::PlaybackThread::cacheParameters_l()
1934{
1935 mixBufferSize = mNormalFrameCount * mFrameSize;
1936 activeSleepTime = activeSleepTimeUs();
1937 idleSleepTime = idleSleepTimeUs();
1938}
1939
1940void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1941{
Glenn Kasten7c027242012-12-26 14:43:16 -08001942 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001943 this, streamType, mTracks.size());
1944 Mutex::Autolock _l(mLock);
1945
1946 size_t size = mTracks.size();
1947 for (size_t i = 0; i < size; i++) {
1948 sp<Track> t = mTracks[i];
1949 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001950 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001951 }
1952 }
1953}
1954
1955status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1956{
1957 int session = chain->sessionId();
1958 int16_t *buffer = mMixBuffer;
1959 bool ownsBuffer = false;
1960
1961 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1962 if (session > 0) {
1963 // Only one effect chain can be present in direct output thread and it uses
1964 // the mix buffer as input
1965 if (mType != DIRECT) {
1966 size_t numSamples = mNormalFrameCount * mChannelCount;
1967 buffer = new int16_t[numSamples];
1968 memset(buffer, 0, numSamples * sizeof(int16_t));
1969 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1970 ownsBuffer = true;
1971 }
1972
1973 // Attach all tracks with same session ID to this chain.
1974 for (size_t i = 0; i < mTracks.size(); ++i) {
1975 sp<Track> track = mTracks[i];
1976 if (session == track->sessionId()) {
1977 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1978 buffer);
1979 track->setMainBuffer(buffer);
1980 chain->incTrackCnt();
1981 }
1982 }
1983
1984 // indicate all active tracks in the chain
1985 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1986 sp<Track> track = mActiveTracks[i].promote();
1987 if (track == 0) {
1988 continue;
1989 }
1990 if (session == track->sessionId()) {
1991 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1992 chain->incActiveTrackCnt();
1993 }
1994 }
1995 }
1996
1997 chain->setInBuffer(buffer, ownsBuffer);
1998 chain->setOutBuffer(mMixBuffer);
1999 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2000 // chains list in order to be processed last as it contains output stage effects
2001 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2002 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2003 // after track specific effects and before output stage
2004 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2005 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2006 // Effect chain for other sessions are inserted at beginning of effect
2007 // chains list to be processed before output mix effects. Relative order between other
2008 // sessions is not important
2009 size_t size = mEffectChains.size();
2010 size_t i = 0;
2011 for (i = 0; i < size; i++) {
2012 if (mEffectChains[i]->sessionId() < session) {
2013 break;
2014 }
2015 }
2016 mEffectChains.insertAt(chain, i);
2017 checkSuspendOnAddEffectChain_l(chain);
2018
2019 return NO_ERROR;
2020}
2021
2022size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2023{
2024 int session = chain->sessionId();
2025
2026 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2027
2028 for (size_t i = 0; i < mEffectChains.size(); i++) {
2029 if (chain == mEffectChains[i]) {
2030 mEffectChains.removeAt(i);
2031 // detach all active tracks from the chain
2032 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2033 sp<Track> track = mActiveTracks[i].promote();
2034 if (track == 0) {
2035 continue;
2036 }
2037 if (session == track->sessionId()) {
2038 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2039 chain.get(), session);
2040 chain->decActiveTrackCnt();
2041 }
2042 }
2043
2044 // detach all tracks with same session ID from this chain
2045 for (size_t i = 0; i < mTracks.size(); ++i) {
2046 sp<Track> track = mTracks[i];
2047 if (session == track->sessionId()) {
2048 track->setMainBuffer(mMixBuffer);
2049 chain->decTrackCnt();
2050 }
2051 }
2052 break;
2053 }
2054 }
2055 return mEffectChains.size();
2056}
2057
2058status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2059 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2060{
2061 Mutex::Autolock _l(mLock);
2062 return attachAuxEffect_l(track, EffectId);
2063}
2064
2065status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2066 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2067{
2068 status_t status = NO_ERROR;
2069
2070 if (EffectId == 0) {
2071 track->setAuxBuffer(0, NULL);
2072 } else {
2073 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2074 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2075 if (effect != 0) {
2076 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2077 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2078 } else {
2079 status = INVALID_OPERATION;
2080 }
2081 } else {
2082 status = BAD_VALUE;
2083 }
2084 }
2085 return status;
2086}
2087
2088void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2089{
2090 for (size_t i = 0; i < mTracks.size(); ++i) {
2091 sp<Track> track = mTracks[i];
2092 if (track->auxEffectId() == effectId) {
2093 attachAuxEffect_l(track, 0);
2094 }
2095 }
2096}
2097
2098bool AudioFlinger::PlaybackThread::threadLoop()
2099{
2100 Vector< sp<Track> > tracksToRemove;
2101
2102 standbyTime = systemTime();
2103
2104 // MIXER
2105 nsecs_t lastWarning = 0;
2106
2107 // DUPLICATING
2108 // FIXME could this be made local to while loop?
2109 writeFrames = 0;
2110
2111 cacheParameters_l();
2112 sleepTime = idleSleepTime;
2113
2114 if (mType == MIXER) {
2115 sleepTimeShift = 0;
2116 }
2117
2118 CpuStats cpuStats;
2119 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2120
2121 acquireWakeLock();
2122
Glenn Kasten9e58b552013-01-18 15:09:48 -08002123 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2124 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2125 // and then that string will be logged at the next convenient opportunity.
2126 const char *logString = NULL;
2127
Eric Laurent664539d2013-09-23 18:24:31 -07002128 checkSilentMode_l();
2129
Eric Laurent81784c32012-11-19 14:55:58 -08002130 while (!exitPending())
2131 {
2132 cpuStats.sample(myName);
2133
2134 Vector< sp<EffectChain> > effectChains;
2135
2136 processConfigEvents();
2137
2138 { // scope for mLock
2139
2140 Mutex::Autolock _l(mLock);
2141
Glenn Kasten9e58b552013-01-18 15:09:48 -08002142 if (logString != NULL) {
2143 mNBLogWriter->logTimestamp();
2144 mNBLogWriter->log(logString);
2145 logString = NULL;
2146 }
2147
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002148 if (mLatchDValid) {
2149 mLatchQ = mLatchD;
2150 mLatchDValid = false;
2151 mLatchQValid = true;
2152 }
2153
Eric Laurent81784c32012-11-19 14:55:58 -08002154 if (checkForNewParameters_l()) {
2155 cacheParameters_l();
2156 }
2157
2158 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159 if (mSignalPending) {
2160 // A signal was raised while we were unlocked
2161 mSignalPending = false;
2162 } else if (waitingAsyncCallback_l()) {
2163 if (exitPending()) {
2164 break;
2165 }
2166 releaseWakeLock_l();
2167 ALOGV("wait async completion");
2168 mWaitWorkCV.wait(mLock);
2169 ALOGV("async completion/wake");
2170 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002171 standbyTime = systemTime() + standbyDelay;
2172 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002173
2174 continue;
2175 }
2176 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177 isSuspended()) {
2178 // put audio hardware into standby after short delay
2179 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002180
2181 threadLoop_standby();
2182
2183 mStandby = true;
2184 }
2185
2186 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2187 // we're about to wait, flush the binder command buffer
2188 IPCThreadState::self()->flushCommands();
2189
2190 clearOutputTracks();
2191
2192 if (exitPending()) {
2193 break;
2194 }
2195
2196 releaseWakeLock_l();
2197 // wait until we have something to do...
2198 ALOGV("%s going to sleep", myName.string());
2199 mWaitWorkCV.wait(mLock);
2200 ALOGV("%s waking up", myName.string());
2201 acquireWakeLock_l();
2202
2203 mMixerStatus = MIXER_IDLE;
2204 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2205 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002207 checkSilentMode_l();
2208
2209 standbyTime = systemTime() + standbyDelay;
2210 sleepTime = idleSleepTime;
2211 if (mType == MIXER) {
2212 sleepTimeShift = 0;
2213 }
2214
2215 continue;
2216 }
2217 }
Eric Laurent81784c32012-11-19 14:55:58 -08002218 // mMixerStatusIgnoringFastTracks is also updated internally
2219 mMixerStatus = prepareTracks_l(&tracksToRemove);
2220
2221 // prevent any changes in effect chain list and in each effect chain
2222 // during mixing and effect process as the audio buffers could be deleted
2223 // or modified if an effect is created or deleted
2224 lockEffectChains_l(effectChains);
2225 }
2226
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227 if (mBytesRemaining == 0) {
2228 mCurrentWriteLength = 0;
2229 if (mMixerStatus == MIXER_TRACKS_READY) {
2230 // threadLoop_mix() sets mCurrentWriteLength
2231 threadLoop_mix();
2232 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2233 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2234 // threadLoop_sleepTime sets sleepTime to 0 if data
2235 // must be written to HAL
2236 threadLoop_sleepTime();
2237 if (sleepTime == 0) {
2238 mCurrentWriteLength = mixBufferSize;
2239 }
2240 }
2241 mBytesRemaining = mCurrentWriteLength;
2242 if (isSuspended()) {
2243 sleepTime = suspendSleepTimeUs();
2244 // simulate write to HAL when suspended
2245 mBytesWritten += mixBufferSize;
2246 mBytesRemaining = 0;
2247 }
Eric Laurent81784c32012-11-19 14:55:58 -08002248
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002250 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251 for (size_t i = 0; i < effectChains.size(); i ++) {
2252 effectChains[i]->process_l();
2253 }
Eric Laurent81784c32012-11-19 14:55:58 -08002254 }
2255 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002256 // Process effect chains for offloaded thread even if no audio
2257 // was read from audio track: process only updates effect state
2258 // and thus does have to be synchronized with audio writes but may have
2259 // to be called while waiting for async write callback
2260 if (mType == OFFLOAD) {
2261 for (size_t i = 0; i < effectChains.size(); i ++) {
2262 effectChains[i]->process_l();
2263 }
2264 }
Eric Laurent81784c32012-11-19 14:55:58 -08002265
2266 // enable changes in effect chain
2267 unlockEffectChains(effectChains);
2268
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269 if (!waitingAsyncCallback()) {
2270 // sleepTime == 0 means we must write to audio hardware
2271 if (sleepTime == 0) {
2272 if (mBytesRemaining) {
2273 ssize_t ret = threadLoop_write();
2274 if (ret < 0) {
2275 mBytesRemaining = 0;
2276 } else {
2277 mBytesWritten += ret;
2278 mBytesRemaining -= ret;
2279 }
2280 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2281 (mMixerStatus == MIXER_DRAIN_ALL)) {
2282 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002283 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284if (mType == MIXER) {
2285 // write blocked detection
2286 nsecs_t now = systemTime();
2287 nsecs_t delta = now - mLastWriteTime;
2288 if (!mStandby && delta > maxPeriod) {
2289 mNumDelayedWrites++;
2290 if ((now - lastWarning) > kWarningThrottleNs) {
2291 ATRACE_NAME("underrun");
2292 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2293 ns2ms(delta), mNumDelayedWrites, this);
2294 lastWarning = now;
2295 }
2296 }
Eric Laurent81784c32012-11-19 14:55:58 -08002297}
2298
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299 mStandby = false;
2300 } else {
2301 usleep(sleepTime);
2302 }
Eric Laurent81784c32012-11-19 14:55:58 -08002303 }
2304
2305 // Finally let go of removed track(s), without the lock held
2306 // since we can't guarantee the destructors won't acquire that
2307 // same lock. This will also mutate and push a new fast mixer state.
2308 threadLoop_removeTracks(tracksToRemove);
2309 tracksToRemove.clear();
2310
2311 // FIXME I don't understand the need for this here;
2312 // it was in the original code but maybe the
2313 // assignment in saveOutputTracks() makes this unnecessary?
2314 clearOutputTracks();
2315
2316 // Effect chains will be actually deleted here if they were removed from
2317 // mEffectChains list during mixing or effects processing
2318 effectChains.clear();
2319
2320 // FIXME Note that the above .clear() is no longer necessary since effectChains
2321 // is now local to this block, but will keep it for now (at least until merge done).
2322 }
2323
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 threadLoop_exit();
2325
Eric Laurent81784c32012-11-19 14:55:58 -08002326 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002327 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002328 // put output stream into standby mode
2329 if (!mStandby) {
2330 mOutput->stream->common.standby(&mOutput->stream->common);
2331 }
2332 }
2333
2334 releaseWakeLock();
2335
2336 ALOGV("Thread %p type %d exiting", this, mType);
2337 return false;
2338}
2339
Eric Laurentbfb1b832013-01-07 09:53:42 -08002340// removeTracks_l() must be called with ThreadBase::mLock held
2341void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2342{
2343 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002344 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345 for (size_t i=0 ; i<count ; i++) {
2346 const sp<Track>& track = tracksToRemove.itemAt(i);
2347 mActiveTracks.remove(track);
2348 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2349 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2350 if (chain != 0) {
2351 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2352 track->sessionId());
2353 chain->decActiveTrackCnt();
2354 }
2355 if (track->isTerminated()) {
2356 removeTrack_l(track);
2357 }
2358 }
2359 }
2360
2361}
Eric Laurent81784c32012-11-19 14:55:58 -08002362
Eric Laurentaccc1472013-09-20 09:36:34 -07002363status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2364{
2365 if (mNormalSink != 0) {
2366 return mNormalSink->getTimestamp(timestamp);
2367 }
2368 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2369 uint64_t position64;
2370 int ret = mOutput->stream->get_presentation_position(
2371 mOutput->stream, &position64, &timestamp.mTime);
2372 if (ret == 0) {
2373 timestamp.mPosition = (uint32_t)position64;
2374 return NO_ERROR;
2375 }
2376 }
2377 return INVALID_OPERATION;
2378}
Eric Laurent81784c32012-11-19 14:55:58 -08002379// ----------------------------------------------------------------------------
2380
2381AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2382 audio_io_handle_t id, audio_devices_t device, type_t type)
2383 : PlaybackThread(audioFlinger, output, id, device, type),
2384 // mAudioMixer below
2385 // mFastMixer below
2386 mFastMixerFutex(0)
2387 // mOutputSink below
2388 // mPipeSink below
2389 // mNormalSink below
2390{
2391 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002392 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002393 "mFrameCount=%d, mNormalFrameCount=%d",
2394 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2395 mNormalFrameCount);
2396 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2397
2398 // FIXME - Current mixer implementation only supports stereo output
2399 if (mChannelCount != FCC_2) {
2400 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2401 }
2402
2403 // create an NBAIO sink for the HAL output stream, and negotiate
2404 mOutputSink = new AudioStreamOutSink(output->stream);
2405 size_t numCounterOffers = 0;
2406 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2407 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2408 ALOG_ASSERT(index == 0);
2409
2410 // initialize fast mixer depending on configuration
2411 bool initFastMixer;
2412 switch (kUseFastMixer) {
2413 case FastMixer_Never:
2414 initFastMixer = false;
2415 break;
2416 case FastMixer_Always:
2417 initFastMixer = true;
2418 break;
2419 case FastMixer_Static:
2420 case FastMixer_Dynamic:
2421 initFastMixer = mFrameCount < mNormalFrameCount;
2422 break;
2423 }
2424 if (initFastMixer) {
2425
2426 // create a MonoPipe to connect our submix to FastMixer
2427 NBAIO_Format format = mOutputSink->format();
2428 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2429 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2430 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2431 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2432 const NBAIO_Format offers[1] = {format};
2433 size_t numCounterOffers = 0;
2434 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2435 ALOG_ASSERT(index == 0);
2436 monoPipe->setAvgFrames((mScreenState & 1) ?
2437 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2438 mPipeSink = monoPipe;
2439
Glenn Kasten46909e72013-02-26 09:20:22 -08002440#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002441 if (mTeeSinkOutputEnabled) {
2442 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2443 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2444 numCounterOffers = 0;
2445 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2446 ALOG_ASSERT(index == 0);
2447 mTeeSink = teeSink;
2448 PipeReader *teeSource = new PipeReader(*teeSink);
2449 numCounterOffers = 0;
2450 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2451 ALOG_ASSERT(index == 0);
2452 mTeeSource = teeSource;
2453 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002454#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002455
2456 // create fast mixer and configure it initially with just one fast track for our submix
2457 mFastMixer = new FastMixer();
2458 FastMixerStateQueue *sq = mFastMixer->sq();
2459#ifdef STATE_QUEUE_DUMP
2460 sq->setObserverDump(&mStateQueueObserverDump);
2461 sq->setMutatorDump(&mStateQueueMutatorDump);
2462#endif
2463 FastMixerState *state = sq->begin();
2464 FastTrack *fastTrack = &state->mFastTracks[0];
2465 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2466 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2467 fastTrack->mVolumeProvider = NULL;
2468 fastTrack->mGeneration++;
2469 state->mFastTracksGen++;
2470 state->mTrackMask = 1;
2471 // fast mixer will use the HAL output sink
2472 state->mOutputSink = mOutputSink.get();
2473 state->mOutputSinkGen++;
2474 state->mFrameCount = mFrameCount;
2475 state->mCommand = FastMixerState::COLD_IDLE;
2476 // already done in constructor initialization list
2477 //mFastMixerFutex = 0;
2478 state->mColdFutexAddr = &mFastMixerFutex;
2479 state->mColdGen++;
2480 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002481#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002482 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002483#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002484 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2485 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002486 sq->end();
2487 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2488
2489 // start the fast mixer
2490 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2491 pid_t tid = mFastMixer->getTid();
2492 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2493 if (err != 0) {
2494 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2495 kPriorityFastMixer, getpid_cached, tid, err);
2496 }
2497
2498#ifdef AUDIO_WATCHDOG
2499 // create and start the watchdog
2500 mAudioWatchdog = new AudioWatchdog();
2501 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2502 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2503 tid = mAudioWatchdog->getTid();
2504 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2505 if (err != 0) {
2506 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2507 kPriorityFastMixer, getpid_cached, tid, err);
2508 }
2509#endif
2510
2511 } else {
2512 mFastMixer = NULL;
2513 }
2514
2515 switch (kUseFastMixer) {
2516 case FastMixer_Never:
2517 case FastMixer_Dynamic:
2518 mNormalSink = mOutputSink;
2519 break;
2520 case FastMixer_Always:
2521 mNormalSink = mPipeSink;
2522 break;
2523 case FastMixer_Static:
2524 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2525 break;
2526 }
2527}
2528
2529AudioFlinger::MixerThread::~MixerThread()
2530{
2531 if (mFastMixer != NULL) {
2532 FastMixerStateQueue *sq = mFastMixer->sq();
2533 FastMixerState *state = sq->begin();
2534 if (state->mCommand == FastMixerState::COLD_IDLE) {
2535 int32_t old = android_atomic_inc(&mFastMixerFutex);
2536 if (old == -1) {
2537 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2538 }
2539 }
2540 state->mCommand = FastMixerState::EXIT;
2541 sq->end();
2542 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2543 mFastMixer->join();
2544 // Though the fast mixer thread has exited, it's state queue is still valid.
2545 // We'll use that extract the final state which contains one remaining fast track
2546 // corresponding to our sub-mix.
2547 state = sq->begin();
2548 ALOG_ASSERT(state->mTrackMask == 1);
2549 FastTrack *fastTrack = &state->mFastTracks[0];
2550 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2551 delete fastTrack->mBufferProvider;
2552 sq->end(false /*didModify*/);
2553 delete mFastMixer;
2554#ifdef AUDIO_WATCHDOG
2555 if (mAudioWatchdog != 0) {
2556 mAudioWatchdog->requestExit();
2557 mAudioWatchdog->requestExitAndWait();
2558 mAudioWatchdog.clear();
2559 }
2560#endif
2561 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002562 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002563 delete mAudioMixer;
2564}
2565
2566
2567uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2568{
2569 if (mFastMixer != NULL) {
2570 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2571 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2572 }
2573 return latency;
2574}
2575
2576
2577void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2578{
2579 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2580}
2581
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002583{
2584 // FIXME we should only do one push per cycle; confirm this is true
2585 // Start the fast mixer if it's not already running
2586 if (mFastMixer != NULL) {
2587 FastMixerStateQueue *sq = mFastMixer->sq();
2588 FastMixerState *state = sq->begin();
2589 if (state->mCommand != FastMixerState::MIX_WRITE &&
2590 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2591 if (state->mCommand == FastMixerState::COLD_IDLE) {
2592 int32_t old = android_atomic_inc(&mFastMixerFutex);
2593 if (old == -1) {
2594 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2595 }
2596#ifdef AUDIO_WATCHDOG
2597 if (mAudioWatchdog != 0) {
2598 mAudioWatchdog->resume();
2599 }
2600#endif
2601 }
2602 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002603 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2604 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002605 sq->end();
2606 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2607 if (kUseFastMixer == FastMixer_Dynamic) {
2608 mNormalSink = mPipeSink;
2609 }
2610 } else {
2611 sq->end(false /*didModify*/);
2612 }
2613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002615}
2616
2617void AudioFlinger::MixerThread::threadLoop_standby()
2618{
2619 // Idle the fast mixer if it's currently running
2620 if (mFastMixer != NULL) {
2621 FastMixerStateQueue *sq = mFastMixer->sq();
2622 FastMixerState *state = sq->begin();
2623 if (!(state->mCommand & FastMixerState::IDLE)) {
2624 state->mCommand = FastMixerState::COLD_IDLE;
2625 state->mColdFutexAddr = &mFastMixerFutex;
2626 state->mColdGen++;
2627 mFastMixerFutex = 0;
2628 sq->end();
2629 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2630 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2631 if (kUseFastMixer == FastMixer_Dynamic) {
2632 mNormalSink = mOutputSink;
2633 }
2634#ifdef AUDIO_WATCHDOG
2635 if (mAudioWatchdog != 0) {
2636 mAudioWatchdog->pause();
2637 }
2638#endif
2639 } else {
2640 sq->end(false /*didModify*/);
2641 }
2642 }
2643 PlaybackThread::threadLoop_standby();
2644}
2645
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646// Empty implementation for standard mixer
2647// Overridden for offloaded playback
2648void AudioFlinger::PlaybackThread::flushOutput_l()
2649{
2650}
2651
2652bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2653{
2654 return false;
2655}
2656
2657bool AudioFlinger::PlaybackThread::shouldStandby_l()
2658{
2659 return !mStandby;
2660}
2661
2662bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2663{
2664 Mutex::Autolock _l(mLock);
2665 return waitingAsyncCallback_l();
2666}
2667
Eric Laurent81784c32012-11-19 14:55:58 -08002668// shared by MIXER and DIRECT, overridden by DUPLICATING
2669void AudioFlinger::PlaybackThread::threadLoop_standby()
2670{
2671 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2672 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002674 // discard any pending drain or write ack by incrementing sequence
2675 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2676 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002678 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2679 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 }
Eric Laurent81784c32012-11-19 14:55:58 -08002681}
2682
2683void AudioFlinger::MixerThread::threadLoop_mix()
2684{
2685 // obtain the presentation timestamp of the next output buffer
2686 int64_t pts;
2687 status_t status = INVALID_OPERATION;
2688
2689 if (mNormalSink != 0) {
2690 status = mNormalSink->getNextWriteTimestamp(&pts);
2691 } else {
2692 status = mOutputSink->getNextWriteTimestamp(&pts);
2693 }
2694
2695 if (status != NO_ERROR) {
2696 pts = AudioBufferProvider::kInvalidPTS;
2697 }
2698
2699 // mix buffers...
2700 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002701 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002702 // increase sleep time progressively when application underrun condition clears.
2703 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2704 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2705 // such that we would underrun the audio HAL.
2706 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2707 sleepTimeShift--;
2708 }
2709 sleepTime = 0;
2710 standbyTime = systemTime() + standbyDelay;
2711 //TODO: delay standby when effects have a tail
2712}
2713
2714void AudioFlinger::MixerThread::threadLoop_sleepTime()
2715{
2716 // If no tracks are ready, sleep once for the duration of an output
2717 // buffer size, then write 0s to the output
2718 if (sleepTime == 0) {
2719 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2720 sleepTime = activeSleepTime >> sleepTimeShift;
2721 if (sleepTime < kMinThreadSleepTimeUs) {
2722 sleepTime = kMinThreadSleepTimeUs;
2723 }
2724 // reduce sleep time in case of consecutive application underruns to avoid
2725 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2726 // duration we would end up writing less data than needed by the audio HAL if
2727 // the condition persists.
2728 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2729 sleepTimeShift++;
2730 }
2731 } else {
2732 sleepTime = idleSleepTime;
2733 }
2734 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2735 memset (mMixBuffer, 0, mixBufferSize);
2736 sleepTime = 0;
2737 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2738 "anticipated start");
2739 }
2740 // TODO add standby time extension fct of effect tail
2741}
2742
2743// prepareTracks_l() must be called with ThreadBase::mLock held
2744AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2745 Vector< sp<Track> > *tracksToRemove)
2746{
2747
2748 mixer_state mixerStatus = MIXER_IDLE;
2749 // find out which tracks need to be processed
2750 size_t count = mActiveTracks.size();
2751 size_t mixedTracks = 0;
2752 size_t tracksWithEffect = 0;
2753 // counts only _active_ fast tracks
2754 size_t fastTracks = 0;
2755 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2756
2757 float masterVolume = mMasterVolume;
2758 bool masterMute = mMasterMute;
2759
2760 if (masterMute) {
2761 masterVolume = 0;
2762 }
2763 // Delegate master volume control to effect in output mix effect chain if needed
2764 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2765 if (chain != 0) {
2766 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2767 chain->setVolume_l(&v, &v);
2768 masterVolume = (float)((v + (1 << 23)) >> 24);
2769 chain.clear();
2770 }
2771
2772 // prepare a new state to push
2773 FastMixerStateQueue *sq = NULL;
2774 FastMixerState *state = NULL;
2775 bool didModify = false;
2776 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2777 if (mFastMixer != NULL) {
2778 sq = mFastMixer->sq();
2779 state = sq->begin();
2780 }
2781
2782 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002783 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002784 if (t == 0) {
2785 continue;
2786 }
2787
2788 // this const just means the local variable doesn't change
2789 Track* const track = t.get();
2790
2791 // process fast tracks
2792 if (track->isFastTrack()) {
2793
2794 // It's theoretically possible (though unlikely) for a fast track to be created
2795 // and then removed within the same normal mix cycle. This is not a problem, as
2796 // the track never becomes active so it's fast mixer slot is never touched.
2797 // The converse, of removing an (active) track and then creating a new track
2798 // at the identical fast mixer slot within the same normal mix cycle,
2799 // is impossible because the slot isn't marked available until the end of each cycle.
2800 int j = track->mFastIndex;
2801 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2802 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2803 FastTrack *fastTrack = &state->mFastTracks[j];
2804
2805 // Determine whether the track is currently in underrun condition,
2806 // and whether it had a recent underrun.
2807 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2808 FastTrackUnderruns underruns = ftDump->mUnderruns;
2809 uint32_t recentFull = (underruns.mBitFields.mFull -
2810 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2811 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2812 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2813 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2814 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2815 uint32_t recentUnderruns = recentPartial + recentEmpty;
2816 track->mObservedUnderruns = underruns;
2817 // don't count underruns that occur while stopping or pausing
2818 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002819 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2820 recentUnderruns > 0) {
2821 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2822 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002823 }
2824
2825 // This is similar to the state machine for normal tracks,
2826 // with a few modifications for fast tracks.
2827 bool isActive = true;
2828 switch (track->mState) {
2829 case TrackBase::STOPPING_1:
2830 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002831 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002832 track->mState = TrackBase::STOPPING_2;
2833 }
2834 break;
2835 case TrackBase::PAUSING:
2836 // ramp down is not yet implemented
2837 track->setPaused();
2838 break;
2839 case TrackBase::RESUMING:
2840 // ramp up is not yet implemented
2841 track->mState = TrackBase::ACTIVE;
2842 break;
2843 case TrackBase::ACTIVE:
2844 if (recentFull > 0 || recentPartial > 0) {
2845 // track has provided at least some frames recently: reset retry count
2846 track->mRetryCount = kMaxTrackRetries;
2847 }
2848 if (recentUnderruns == 0) {
2849 // no recent underruns: stay active
2850 break;
2851 }
2852 // there has recently been an underrun of some kind
2853 if (track->sharedBuffer() == 0) {
2854 // were any of the recent underruns "empty" (no frames available)?
2855 if (recentEmpty == 0) {
2856 // no, then ignore the partial underruns as they are allowed indefinitely
2857 break;
2858 }
2859 // there has recently been an "empty" underrun: decrement the retry counter
2860 if (--(track->mRetryCount) > 0) {
2861 break;
2862 }
2863 // indicate to client process that the track was disabled because of underrun;
2864 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002865 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002866 // remove from active list, but state remains ACTIVE [confusing but true]
2867 isActive = false;
2868 break;
2869 }
2870 // fall through
2871 case TrackBase::STOPPING_2:
2872 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002873 case TrackBase::STOPPED:
2874 case TrackBase::FLUSHED: // flush() while active
2875 // Check for presentation complete if track is inactive
2876 // We have consumed all the buffers of this track.
2877 // This would be incomplete if we auto-paused on underrun
2878 {
2879 size_t audioHALFrames =
2880 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2881 size_t framesWritten = mBytesWritten / mFrameSize;
2882 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2883 // track stays in active list until presentation is complete
2884 break;
2885 }
2886 }
2887 if (track->isStopping_2()) {
2888 track->mState = TrackBase::STOPPED;
2889 }
2890 if (track->isStopped()) {
2891 // Can't reset directly, as fast mixer is still polling this track
2892 // track->reset();
2893 // So instead mark this track as needing to be reset after push with ack
2894 resetMask |= 1 << i;
2895 }
2896 isActive = false;
2897 break;
2898 case TrackBase::IDLE:
2899 default:
2900 LOG_FATAL("unexpected track state %d", track->mState);
2901 }
2902
2903 if (isActive) {
2904 // was it previously inactive?
2905 if (!(state->mTrackMask & (1 << j))) {
2906 ExtendedAudioBufferProvider *eabp = track;
2907 VolumeProvider *vp = track;
2908 fastTrack->mBufferProvider = eabp;
2909 fastTrack->mVolumeProvider = vp;
2910 fastTrack->mSampleRate = track->mSampleRate;
2911 fastTrack->mChannelMask = track->mChannelMask;
2912 fastTrack->mGeneration++;
2913 state->mTrackMask |= 1 << j;
2914 didModify = true;
2915 // no acknowledgement required for newly active tracks
2916 }
2917 // cache the combined master volume and stream type volume for fast mixer; this
2918 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002919 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002920 ++fastTracks;
2921 } else {
2922 // was it previously active?
2923 if (state->mTrackMask & (1 << j)) {
2924 fastTrack->mBufferProvider = NULL;
2925 fastTrack->mGeneration++;
2926 state->mTrackMask &= ~(1 << j);
2927 didModify = true;
2928 // If any fast tracks were removed, we must wait for acknowledgement
2929 // because we're about to decrement the last sp<> on those tracks.
2930 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2931 } else {
2932 LOG_FATAL("fast track %d should have been active", j);
2933 }
2934 tracksToRemove->add(track);
2935 // Avoids a misleading display in dumpsys
2936 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2937 }
2938 continue;
2939 }
2940
2941 { // local variable scope to avoid goto warning
2942
2943 audio_track_cblk_t* cblk = track->cblk();
2944
2945 // The first time a track is added we wait
2946 // for all its buffers to be filled before processing it
2947 int name = track->name();
2948 // make sure that we have enough frames to mix one full buffer.
2949 // enforce this condition only once to enable draining the buffer in case the client
2950 // app does not call stop() and relies on underrun to stop:
2951 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2952 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002953 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002954 uint32_t sr = track->sampleRate();
2955 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002956 desiredFrames = mNormalFrameCount;
2957 } else {
2958 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002959 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002960 // add frames already consumed but not yet released by the resampler
2961 // because cblk->framesReady() will include these frames
2962 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2963 // the minimum track buffer size is normally twice the number of frames necessary
2964 // to fill one buffer and the resampler should not leave more than one buffer worth
2965 // of unreleased frames after each pass, but just in case...
2966 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2967 }
Eric Laurent81784c32012-11-19 14:55:58 -08002968 uint32_t minFrames = 1;
2969 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2970 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002971 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08002972 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002973 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2974 size_t framesReady;
2975 if (track->sharedBuffer() == 0) {
2976 framesReady = track->framesReady();
2977 } else if (track->isStopped()) {
2978 framesReady = 0;
2979 } else {
2980 framesReady = 1;
2981 }
2982 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08002983 !track->isPaused() && !track->isTerminated())
2984 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002985 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08002986
2987 mixedTracks++;
2988
2989 // track->mainBuffer() != mMixBuffer means there is an effect chain
2990 // connected to the track
2991 chain.clear();
2992 if (track->mainBuffer() != mMixBuffer) {
2993 chain = getEffectChain_l(track->sessionId());
2994 // Delegate volume control to effect in track effect chain if needed
2995 if (chain != 0) {
2996 tracksWithEffect++;
2997 } else {
2998 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2999 "session %d",
3000 name, track->sessionId());
3001 }
3002 }
3003
3004
3005 int param = AudioMixer::VOLUME;
3006 if (track->mFillingUpStatus == Track::FS_FILLED) {
3007 // no ramp for the first volume setting
3008 track->mFillingUpStatus = Track::FS_ACTIVE;
3009 if (track->mState == TrackBase::RESUMING) {
3010 track->mState = TrackBase::ACTIVE;
3011 param = AudioMixer::RAMP_VOLUME;
3012 }
3013 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003014 // FIXME should not make a decision based on mServer
3015 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003016 // If the track is stopped before the first frame was mixed,
3017 // do not apply ramp
3018 param = AudioMixer::RAMP_VOLUME;
3019 }
3020
3021 // compute volume for this track
3022 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003023 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003024 vl = vr = va = 0;
3025 if (track->isPausing()) {
3026 track->setPaused();
3027 }
3028 } else {
3029
3030 // read original volumes with volume control
3031 float typeVolume = mStreamTypes[track->streamType()].volume;
3032 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003033 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003034 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003035 vl = vlr & 0xFFFF;
3036 vr = vlr >> 16;
3037 // track volumes come from shared memory, so can't be trusted and must be clamped
3038 if (vl > MAX_GAIN_INT) {
3039 ALOGV("Track left volume out of range: %04X", vl);
3040 vl = MAX_GAIN_INT;
3041 }
3042 if (vr > MAX_GAIN_INT) {
3043 ALOGV("Track right volume out of range: %04X", vr);
3044 vr = MAX_GAIN_INT;
3045 }
3046 // now apply the master volume and stream type volume
3047 vl = (uint32_t)(v * vl) << 12;
3048 vr = (uint32_t)(v * vr) << 12;
3049 // assuming master volume and stream type volume each go up to 1.0,
3050 // vl and vr are now in 8.24 format
3051
Glenn Kastene3aa6592012-12-04 12:22:46 -08003052 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003053 // send level comes from shared memory and so may be corrupt
3054 if (sendLevel > MAX_GAIN_INT) {
3055 ALOGV("Track send level out of range: %04X", sendLevel);
3056 sendLevel = MAX_GAIN_INT;
3057 }
3058 va = (uint32_t)(v * sendLevel);
3059 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060
Eric Laurent81784c32012-11-19 14:55:58 -08003061 // Delegate volume control to effect in track effect chain if needed
3062 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3063 // Do not ramp volume if volume is controlled by effect
3064 param = AudioMixer::VOLUME;
3065 track->mHasVolumeController = true;
3066 } else {
3067 // force no volume ramp when volume controller was just disabled or removed
3068 // from effect chain to avoid volume spike
3069 if (track->mHasVolumeController) {
3070 param = AudioMixer::VOLUME;
3071 }
3072 track->mHasVolumeController = false;
3073 }
3074
3075 // Convert volumes from 8.24 to 4.12 format
3076 // This additional clamping is needed in case chain->setVolume_l() overshot
3077 vl = (vl + (1 << 11)) >> 12;
3078 if (vl > MAX_GAIN_INT) {
3079 vl = MAX_GAIN_INT;
3080 }
3081 vr = (vr + (1 << 11)) >> 12;
3082 if (vr > MAX_GAIN_INT) {
3083 vr = MAX_GAIN_INT;
3084 }
3085
3086 if (va > MAX_GAIN_INT) {
3087 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3088 }
3089
3090 // XXX: these things DON'T need to be done each time
3091 mAudioMixer->setBufferProvider(name, track);
3092 mAudioMixer->enable(name);
3093
3094 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3095 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3096 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3097 mAudioMixer->setParameter(
3098 name,
3099 AudioMixer::TRACK,
3100 AudioMixer::FORMAT, (void *)track->format());
3101 mAudioMixer->setParameter(
3102 name,
3103 AudioMixer::TRACK,
3104 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003105 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3106 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003107 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003108 if (reqSampleRate == 0) {
3109 reqSampleRate = mSampleRate;
3110 } else if (reqSampleRate > maxSampleRate) {
3111 reqSampleRate = maxSampleRate;
3112 }
Eric Laurent81784c32012-11-19 14:55:58 -08003113 mAudioMixer->setParameter(
3114 name,
3115 AudioMixer::RESAMPLE,
3116 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003117 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003118 mAudioMixer->setParameter(
3119 name,
3120 AudioMixer::TRACK,
3121 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3122 mAudioMixer->setParameter(
3123 name,
3124 AudioMixer::TRACK,
3125 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3126
3127 // reset retry count
3128 track->mRetryCount = kMaxTrackRetries;
3129
3130 // If one track is ready, set the mixer ready if:
3131 // - the mixer was not ready during previous round OR
3132 // - no other track is not ready
3133 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3134 mixerStatus != MIXER_TRACKS_ENABLED) {
3135 mixerStatus = MIXER_TRACKS_READY;
3136 }
3137 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003138 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003139 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003140 }
Eric Laurent81784c32012-11-19 14:55:58 -08003141 // clear effect chain input buffer if an active track underruns to avoid sending
3142 // previous audio buffer again to effects
3143 chain = getEffectChain_l(track->sessionId());
3144 if (chain != 0) {
3145 chain->clearInputBuffer();
3146 }
3147
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003148 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003149 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3150 track->isStopped() || track->isPaused()) {
3151 // We have consumed all the buffers of this track.
3152 // Remove it from the list of active tracks.
3153 // TODO: use actual buffer filling status instead of latency when available from
3154 // audio HAL
3155 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3156 size_t framesWritten = mBytesWritten / mFrameSize;
3157 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3158 if (track->isStopped()) {
3159 track->reset();
3160 }
3161 tracksToRemove->add(track);
3162 }
3163 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003164 // No buffers for this track. Give it a few chances to
3165 // fill a buffer, then remove it from active list.
3166 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003167 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003168 tracksToRemove->add(track);
3169 // indicate to client process that the track was disabled because of underrun;
3170 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003171 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003172 // If one track is not ready, mark the mixer also not ready if:
3173 // - the mixer was ready during previous round OR
3174 // - no other track is ready
3175 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3176 mixerStatus != MIXER_TRACKS_READY) {
3177 mixerStatus = MIXER_TRACKS_ENABLED;
3178 }
3179 }
3180 mAudioMixer->disable(name);
3181 }
3182
3183 } // local variable scope to avoid goto warning
3184track_is_ready: ;
3185
3186 }
3187
3188 // Push the new FastMixer state if necessary
3189 bool pauseAudioWatchdog = false;
3190 if (didModify) {
3191 state->mFastTracksGen++;
3192 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3193 if (kUseFastMixer == FastMixer_Dynamic &&
3194 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3195 state->mCommand = FastMixerState::COLD_IDLE;
3196 state->mColdFutexAddr = &mFastMixerFutex;
3197 state->mColdGen++;
3198 mFastMixerFutex = 0;
3199 if (kUseFastMixer == FastMixer_Dynamic) {
3200 mNormalSink = mOutputSink;
3201 }
3202 // If we go into cold idle, need to wait for acknowledgement
3203 // so that fast mixer stops doing I/O.
3204 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3205 pauseAudioWatchdog = true;
3206 }
Eric Laurent81784c32012-11-19 14:55:58 -08003207 }
3208 if (sq != NULL) {
3209 sq->end(didModify);
3210 sq->push(block);
3211 }
3212#ifdef AUDIO_WATCHDOG
3213 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3214 mAudioWatchdog->pause();
3215 }
3216#endif
3217
3218 // Now perform the deferred reset on fast tracks that have stopped
3219 while (resetMask != 0) {
3220 size_t i = __builtin_ctz(resetMask);
3221 ALOG_ASSERT(i < count);
3222 resetMask &= ~(1 << i);
3223 sp<Track> t = mActiveTracks[i].promote();
3224 if (t == 0) {
3225 continue;
3226 }
3227 Track* track = t.get();
3228 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3229 track->reset();
3230 }
3231
3232 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003234
3235 // mix buffer must be cleared if all tracks are connected to an
3236 // effect chain as in this case the mixer will not write to
3237 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3239 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003240 // FIXME as a performance optimization, should remember previous zero status
3241 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3242 }
3243
3244 // if any fast tracks, then status is ready
3245 mMixerStatusIgnoringFastTracks = mixerStatus;
3246 if (fastTracks > 0) {
3247 mixerStatus = MIXER_TRACKS_READY;
3248 }
3249 return mixerStatus;
3250}
3251
3252// getTrackName_l() must be called with ThreadBase::mLock held
3253int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3254{
3255 return mAudioMixer->getTrackName(channelMask, sessionId);
3256}
3257
3258// deleteTrackName_l() must be called with ThreadBase::mLock held
3259void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3260{
3261 ALOGV("remove track (%d) and delete from mixer", name);
3262 mAudioMixer->deleteTrackName(name);
3263}
3264
3265// checkForNewParameters_l() must be called with ThreadBase::mLock held
3266bool AudioFlinger::MixerThread::checkForNewParameters_l()
3267{
3268 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3269 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3270 bool reconfig = false;
3271
3272 while (!mNewParameters.isEmpty()) {
3273
3274 if (mFastMixer != NULL) {
3275 FastMixerStateQueue *sq = mFastMixer->sq();
3276 FastMixerState *state = sq->begin();
3277 if (!(state->mCommand & FastMixerState::IDLE)) {
3278 previousCommand = state->mCommand;
3279 state->mCommand = FastMixerState::HOT_IDLE;
3280 sq->end();
3281 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3282 } else {
3283 sq->end(false /*didModify*/);
3284 }
3285 }
3286
3287 status_t status = NO_ERROR;
3288 String8 keyValuePair = mNewParameters[0];
3289 AudioParameter param = AudioParameter(keyValuePair);
3290 int value;
3291
3292 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3293 reconfig = true;
3294 }
3295 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3296 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3297 status = BAD_VALUE;
3298 } else {
3299 reconfig = true;
3300 }
3301 }
3302 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003303 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003304 status = BAD_VALUE;
3305 } else {
3306 reconfig = true;
3307 }
3308 }
3309 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3310 // do not accept frame count changes if tracks are open as the track buffer
3311 // size depends on frame count and correct behavior would not be guaranteed
3312 // if frame count is changed after track creation
3313 if (!mTracks.isEmpty()) {
3314 status = INVALID_OPERATION;
3315 } else {
3316 reconfig = true;
3317 }
3318 }
3319 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3320#ifdef ADD_BATTERY_DATA
3321 // when changing the audio output device, call addBatteryData to notify
3322 // the change
3323 if (mOutDevice != value) {
3324 uint32_t params = 0;
3325 // check whether speaker is on
3326 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3327 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3328 }
3329
3330 audio_devices_t deviceWithoutSpeaker
3331 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3332 // check if any other device (except speaker) is on
3333 if (value & deviceWithoutSpeaker ) {
3334 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3335 }
3336
3337 if (params != 0) {
3338 addBatteryData(params);
3339 }
3340 }
3341#endif
3342
3343 // forward device change to effects that have requested to be
3344 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003345 if (value != AUDIO_DEVICE_NONE) {
3346 mOutDevice = value;
3347 for (size_t i = 0; i < mEffectChains.size(); i++) {
3348 mEffectChains[i]->setDevice_l(mOutDevice);
3349 }
Eric Laurent81784c32012-11-19 14:55:58 -08003350 }
3351 }
3352
3353 if (status == NO_ERROR) {
3354 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3355 keyValuePair.string());
3356 if (!mStandby && status == INVALID_OPERATION) {
3357 mOutput->stream->common.standby(&mOutput->stream->common);
3358 mStandby = true;
3359 mBytesWritten = 0;
3360 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3361 keyValuePair.string());
3362 }
3363 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003364 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003365 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003366 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3367 for (size_t i = 0; i < mTracks.size() ; i++) {
3368 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3369 if (name < 0) {
3370 break;
3371 }
3372 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003373 }
3374 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3375 }
3376 }
3377
3378 mNewParameters.removeAt(0);
3379
3380 mParamStatus = status;
3381 mParamCond.signal();
3382 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3383 // already timed out waiting for the status and will never signal the condition.
3384 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3385 }
3386
3387 if (!(previousCommand & FastMixerState::IDLE)) {
3388 ALOG_ASSERT(mFastMixer != NULL);
3389 FastMixerStateQueue *sq = mFastMixer->sq();
3390 FastMixerState *state = sq->begin();
3391 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3392 state->mCommand = previousCommand;
3393 sq->end();
3394 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3395 }
3396
3397 return reconfig;
3398}
3399
3400
3401void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3402{
3403 const size_t SIZE = 256;
3404 char buffer[SIZE];
3405 String8 result;
3406
3407 PlaybackThread::dumpInternals(fd, args);
3408
3409 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3410 result.append(buffer);
3411 write(fd, result.string(), result.size());
3412
3413 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003414 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003415 copy.dump(fd);
3416
3417#ifdef STATE_QUEUE_DUMP
3418 // Similar for state queue
3419 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3420 observerCopy.dump(fd);
3421 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3422 mutatorCopy.dump(fd);
3423#endif
3424
Glenn Kasten46909e72013-02-26 09:20:22 -08003425#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003426 // Write the tee output to a .wav file
3427 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003428#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003429
3430#ifdef AUDIO_WATCHDOG
3431 if (mAudioWatchdog != 0) {
3432 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3433 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3434 wdCopy.dump(fd);
3435 }
3436#endif
3437}
3438
3439uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3440{
3441 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3442}
3443
3444uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3445{
3446 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3447}
3448
3449void AudioFlinger::MixerThread::cacheParameters_l()
3450{
3451 PlaybackThread::cacheParameters_l();
3452
3453 // FIXME: Relaxed timing because of a certain device that can't meet latency
3454 // Should be reduced to 2x after the vendor fixes the driver issue
3455 // increase threshold again due to low power audio mode. The way this warning
3456 // threshold is calculated and its usefulness should be reconsidered anyway.
3457 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3458}
3459
3460// ----------------------------------------------------------------------------
3461
3462AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3463 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3464 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3465 // mLeftVolFloat, mRightVolFloat
3466{
3467}
3468
Eric Laurentbfb1b832013-01-07 09:53:42 -08003469AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3470 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3471 ThreadBase::type_t type)
3472 : PlaybackThread(audioFlinger, output, id, device, type)
3473 // mLeftVolFloat, mRightVolFloat
3474{
3475}
3476
Eric Laurent81784c32012-11-19 14:55:58 -08003477AudioFlinger::DirectOutputThread::~DirectOutputThread()
3478{
3479}
3480
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3482{
3483 audio_track_cblk_t* cblk = track->cblk();
3484 float left, right;
3485
3486 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3487 left = right = 0;
3488 } else {
3489 float typeVolume = mStreamTypes[track->streamType()].volume;
3490 float v = mMasterVolume * typeVolume;
3491 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3492 uint32_t vlr = proxy->getVolumeLR();
3493 float v_clamped = v * (vlr & 0xFFFF);
3494 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3495 left = v_clamped/MAX_GAIN;
3496 v_clamped = v * (vlr >> 16);
3497 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3498 right = v_clamped/MAX_GAIN;
3499 }
3500
3501 if (lastTrack) {
3502 if (left != mLeftVolFloat || right != mRightVolFloat) {
3503 mLeftVolFloat = left;
3504 mRightVolFloat = right;
3505
3506 // Convert volumes from float to 8.24
3507 uint32_t vl = (uint32_t)(left * (1 << 24));
3508 uint32_t vr = (uint32_t)(right * (1 << 24));
3509
3510 // Delegate volume control to effect in track effect chain if needed
3511 // only one effect chain can be present on DirectOutputThread, so if
3512 // there is one, the track is connected to it
3513 if (!mEffectChains.isEmpty()) {
3514 mEffectChains[0]->setVolume_l(&vl, &vr);
3515 left = (float)vl / (1 << 24);
3516 right = (float)vr / (1 << 24);
3517 }
3518 if (mOutput->stream->set_volume) {
3519 mOutput->stream->set_volume(mOutput->stream, left, right);
3520 }
3521 }
3522 }
3523}
3524
3525
Eric Laurent81784c32012-11-19 14:55:58 -08003526AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3527 Vector< sp<Track> > *tracksToRemove
3528)
3529{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003530 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003531 mixer_state mixerStatus = MIXER_IDLE;
3532
3533 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003534 for (size_t i = 0; i < count; i++) {
3535 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003536 // The track died recently
3537 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003538 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003539 }
3540
3541 Track* const track = t.get();
3542 audio_track_cblk_t* cblk = track->cblk();
3543
3544 // The first time a track is added we wait
3545 // for all its buffers to be filled before processing it
3546 uint32_t minFrames;
3547 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3548 minFrames = mNormalFrameCount;
3549 } else {
3550 minFrames = 1;
3551 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 // Only consider last track started for volume and mixer state control.
3553 // This is the last entry in mActiveTracks unless a track underruns.
3554 // As we only care about the transition phase between two tracks on a
3555 // direct output, it is not a problem to ignore the underrun case.
3556 bool last = (i == (count - 1));
3557
Eric Laurent81784c32012-11-19 14:55:58 -08003558 if ((track->framesReady() >= minFrames) && track->isReady() &&
3559 !track->isPaused() && !track->isTerminated())
3560 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003561 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003562
3563 if (track->mFillingUpStatus == Track::FS_FILLED) {
3564 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003565 // make sure processVolume_l() will apply new volume even if 0
3566 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003567 if (track->mState == TrackBase::RESUMING) {
3568 track->mState = TrackBase::ACTIVE;
3569 }
3570 }
3571
3572 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 processVolume_l(track, last);
3574 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003575 // reset retry count
3576 track->mRetryCount = kMaxTrackRetriesDirect;
3577 mActiveTrack = t;
3578 mixerStatus = MIXER_TRACKS_READY;
3579 }
Eric Laurent81784c32012-11-19 14:55:58 -08003580 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003581 // clear effect chain input buffer if the last active track started underruns
3582 // to avoid sending previous audio buffer again to effects
3583 if (!mEffectChains.isEmpty() && (i == (count -1))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003584 mEffectChains[0]->clearInputBuffer();
3585 }
3586
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003587 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003588 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3589 track->isStopped() || track->isPaused()) {
3590 // We have consumed all the buffers of this track.
3591 // Remove it from the list of active tracks.
3592 // TODO: implement behavior for compressed audio
3593 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3594 size_t framesWritten = mBytesWritten / mFrameSize;
3595 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3596 if (track->isStopped()) {
3597 track->reset();
3598 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003599 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003600 }
3601 } else {
3602 // No buffers for this track. Give it a few chances to
3603 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003604 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003605 if (--(track->mRetryCount) <= 0) {
3606 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003607 tracksToRemove->add(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003608 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003609 mixerStatus = MIXER_TRACKS_ENABLED;
3610 }
3611 }
3612 }
3613 }
3614
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003616 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003617
3618 return mixerStatus;
3619}
3620
3621void AudioFlinger::DirectOutputThread::threadLoop_mix()
3622{
Eric Laurent81784c32012-11-19 14:55:58 -08003623 size_t frameCount = mFrameCount;
3624 int8_t *curBuf = (int8_t *)mMixBuffer;
3625 // output audio to hardware
3626 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003627 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003628 buffer.frameCount = frameCount;
3629 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003630 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003631 memset(curBuf, 0, frameCount * mFrameSize);
3632 break;
3633 }
3634 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3635 frameCount -= buffer.frameCount;
3636 curBuf += buffer.frameCount * mFrameSize;
3637 mActiveTrack->releaseBuffer(&buffer);
3638 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003639 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003640 sleepTime = 0;
3641 standbyTime = systemTime() + standbyDelay;
3642 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003643}
3644
3645void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3646{
3647 if (sleepTime == 0) {
3648 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3649 sleepTime = activeSleepTime;
3650 } else {
3651 sleepTime = idleSleepTime;
3652 }
3653 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3654 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3655 sleepTime = 0;
3656 }
3657}
3658
3659// getTrackName_l() must be called with ThreadBase::mLock held
3660int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3661 int sessionId)
3662{
3663 return 0;
3664}
3665
3666// deleteTrackName_l() must be called with ThreadBase::mLock held
3667void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3668{
3669}
3670
3671// checkForNewParameters_l() must be called with ThreadBase::mLock held
3672bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3673{
3674 bool reconfig = false;
3675
3676 while (!mNewParameters.isEmpty()) {
3677 status_t status = NO_ERROR;
3678 String8 keyValuePair = mNewParameters[0];
3679 AudioParameter param = AudioParameter(keyValuePair);
3680 int value;
3681
3682 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3683 // do not accept frame count changes if tracks are open as the track buffer
3684 // size depends on frame count and correct behavior would not be garantied
3685 // if frame count is changed after track creation
3686 if (!mTracks.isEmpty()) {
3687 status = INVALID_OPERATION;
3688 } else {
3689 reconfig = true;
3690 }
3691 }
3692 if (status == NO_ERROR) {
3693 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3694 keyValuePair.string());
3695 if (!mStandby && status == INVALID_OPERATION) {
3696 mOutput->stream->common.standby(&mOutput->stream->common);
3697 mStandby = true;
3698 mBytesWritten = 0;
3699 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3700 keyValuePair.string());
3701 }
3702 if (status == NO_ERROR && reconfig) {
3703 readOutputParameters();
3704 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3705 }
3706 }
3707
3708 mNewParameters.removeAt(0);
3709
3710 mParamStatus = status;
3711 mParamCond.signal();
3712 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3713 // already timed out waiting for the status and will never signal the condition.
3714 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3715 }
3716 return reconfig;
3717}
3718
3719uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3720{
3721 uint32_t time;
3722 if (audio_is_linear_pcm(mFormat)) {
3723 time = PlaybackThread::activeSleepTimeUs();
3724 } else {
3725 time = 10000;
3726 }
3727 return time;
3728}
3729
3730uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3731{
3732 uint32_t time;
3733 if (audio_is_linear_pcm(mFormat)) {
3734 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3735 } else {
3736 time = 10000;
3737 }
3738 return time;
3739}
3740
3741uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3742{
3743 uint32_t time;
3744 if (audio_is_linear_pcm(mFormat)) {
3745 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3746 } else {
3747 time = 10000;
3748 }
3749 return time;
3750}
3751
3752void AudioFlinger::DirectOutputThread::cacheParameters_l()
3753{
3754 PlaybackThread::cacheParameters_l();
3755
3756 // use shorter standby delay as on normal output to release
3757 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003758 if (audio_is_linear_pcm(mFormat)) {
3759 standbyDelay = microseconds(activeSleepTime*2);
3760 } else {
3761 standbyDelay = kOffloadStandbyDelayNs;
3762 }
Eric Laurent81784c32012-11-19 14:55:58 -08003763}
3764
3765// ----------------------------------------------------------------------------
3766
Eric Laurentbfb1b832013-01-07 09:53:42 -08003767AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003768 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003769 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003770 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003771 mWriteAckSequence(0),
3772 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003773{
3774}
3775
3776AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3777{
3778}
3779
3780void AudioFlinger::AsyncCallbackThread::onFirstRef()
3781{
3782 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3783}
3784
3785bool AudioFlinger::AsyncCallbackThread::threadLoop()
3786{
3787 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003788 uint32_t writeAckSequence;
3789 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003790
3791 {
3792 Mutex::Autolock _l(mLock);
3793 mWaitWorkCV.wait(mLock);
3794 if (exitPending()) {
3795 break;
3796 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003797 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3798 mWriteAckSequence, mDrainSequence);
3799 writeAckSequence = mWriteAckSequence;
3800 mWriteAckSequence &= ~1;
3801 drainSequence = mDrainSequence;
3802 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003803 }
3804 {
Eric Laurent4de95592013-09-26 15:28:21 -07003805 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3806 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003807 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003808 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003810 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003811 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003812 }
3813 }
3814 }
3815 }
3816 return false;
3817}
3818
3819void AudioFlinger::AsyncCallbackThread::exit()
3820{
3821 ALOGV("AsyncCallbackThread::exit");
3822 Mutex::Autolock _l(mLock);
3823 requestExit();
3824 mWaitWorkCV.broadcast();
3825}
3826
Eric Laurent3b4529e2013-09-05 18:09:19 -07003827void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003828{
3829 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003830 // bit 0 is cleared
3831 mWriteAckSequence = sequence << 1;
3832}
3833
3834void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3835{
3836 Mutex::Autolock _l(mLock);
3837 // ignore unexpected callbacks
3838 if (mWriteAckSequence & 2) {
3839 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840 mWaitWorkCV.signal();
3841 }
3842}
3843
Eric Laurent3b4529e2013-09-05 18:09:19 -07003844void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003845{
3846 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003847 // bit 0 is cleared
3848 mDrainSequence = sequence << 1;
3849}
3850
3851void AudioFlinger::AsyncCallbackThread::resetDraining()
3852{
3853 Mutex::Autolock _l(mLock);
3854 // ignore unexpected callbacks
3855 if (mDrainSequence & 2) {
3856 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003857 mWaitWorkCV.signal();
3858 }
3859}
3860
3861
3862// ----------------------------------------------------------------------------
3863AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3864 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3865 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3866 mHwPaused(false),
3867 mPausedBytesRemaining(0)
3868{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869}
3870
3871AudioFlinger::OffloadThread::~OffloadThread()
3872{
3873 mPreviousTrack.clear();
3874}
3875
3876void AudioFlinger::OffloadThread::threadLoop_exit()
3877{
3878 if (mFlushPending || mHwPaused) {
3879 // If a flush is pending or track was paused, just discard buffered data
3880 flushHw_l();
3881 } else {
3882 mMixerStatus = MIXER_DRAIN_ALL;
3883 threadLoop_drain();
3884 }
3885 mCallbackThread->exit();
3886 PlaybackThread::threadLoop_exit();
3887}
3888
3889AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3890 Vector< sp<Track> > *tracksToRemove
3891)
3892{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003893 size_t count = mActiveTracks.size();
3894
3895 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003896 bool doHwPause = false;
3897 bool doHwResume = false;
3898
Eric Laurentede6c3b2013-09-19 14:37:46 -07003899 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3900
Eric Laurentbfb1b832013-01-07 09:53:42 -08003901 // find out which tracks need to be processed
3902 for (size_t i = 0; i < count; i++) {
3903 sp<Track> t = mActiveTracks[i].promote();
3904 // The track died recently
3905 if (t == 0) {
3906 continue;
3907 }
3908 Track* const track = t.get();
3909 audio_track_cblk_t* cblk = track->cblk();
3910 if (mPreviousTrack != NULL) {
3911 if (t != mPreviousTrack) {
3912 // Flush any data still being written from last track
3913 mBytesRemaining = 0;
3914 if (mPausedBytesRemaining) {
3915 // Last track was paused so we also need to flush saved
3916 // mixbuffer state and invalidate track so that it will
3917 // re-submit that unwritten data when it is next resumed
3918 mPausedBytesRemaining = 0;
3919 // Invalidate is a bit drastic - would be more efficient
3920 // to have a flag to tell client that some of the
3921 // previously written data was lost
3922 mPreviousTrack->invalidate();
3923 }
3924 }
3925 }
3926 mPreviousTrack = t;
3927 bool last = (i == (count - 1));
3928 if (track->isPausing()) {
3929 track->setPaused();
3930 if (last) {
3931 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003932 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003933 mHwPaused = true;
3934 }
3935 // If we were part way through writing the mixbuffer to
3936 // the HAL we must save this until we resume
3937 // BUG - this will be wrong if a different track is made active,
3938 // in that case we want to discard the pending data in the
3939 // mixbuffer and tell the client to present it again when the
3940 // track is resumed
3941 mPausedWriteLength = mCurrentWriteLength;
3942 mPausedBytesRemaining = mBytesRemaining;
3943 mBytesRemaining = 0; // stop writing
3944 }
3945 tracksToRemove->add(track);
3946 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07003947 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003948 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003949 if (track->mFillingUpStatus == Track::FS_FILLED) {
3950 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003951 // make sure processVolume_l() will apply new volume even if 0
3952 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003953 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003954 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003955 if (last) {
3956 if (mPausedBytesRemaining) {
3957 // Need to continue write that was interrupted
3958 mCurrentWriteLength = mPausedWriteLength;
3959 mBytesRemaining = mPausedBytesRemaining;
3960 mPausedBytesRemaining = 0;
3961 }
3962 if (mHwPaused) {
3963 doHwResume = true;
3964 mHwPaused = false;
3965 // threadLoop_mix() will handle the case that we need to
3966 // resume an interrupted write
3967 }
3968 // enable write to audio HAL
3969 sleepTime = 0;
3970 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003971 }
3972 }
3973
3974 if (last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003975 // reset retry count
3976 track->mRetryCount = kMaxTrackRetriesOffload;
3977 mActiveTrack = t;
3978 mixerStatus = MIXER_TRACKS_READY;
3979 }
3980 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003981 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003982 if (track->isStopping_1()) {
3983 // Hardware buffer can hold a large amount of audio so we must
3984 // wait for all current track's data to drain before we say
3985 // that the track is stopped.
3986 if (mBytesRemaining == 0) {
3987 // Only start draining when all data in mixbuffer
3988 // has been written
3989 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3990 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurentbfb1b832013-01-07 09:53:42 -08003991 if (last) {
Eric Laurentede6c3b2013-09-19 14:37:46 -07003992 sleepTime = 0;
3993 standbyTime = systemTime() + standbyDelay;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003994 mixerStatus = MIXER_DRAIN_TRACK;
Eric Laurent3b4529e2013-09-05 18:09:19 -07003995 mDrainSequence += 2;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003996 if (mHwPaused) {
3997 // It is possible to move from PAUSED to STOPPING_1 without
3998 // a resume so we must ensure hardware is running
3999 mOutput->stream->resume(mOutput->stream);
4000 mHwPaused = false;
4001 }
4002 }
4003 }
4004 } else if (track->isStopping_2()) {
4005 // Drain has completed, signal presentation complete
Eric Laurent3b4529e2013-09-05 18:09:19 -07004006 if (!(mDrainSequence & 1) || !last) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007 track->mState = TrackBase::STOPPED;
4008 size_t audioHALFrames =
4009 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4010 size_t framesWritten =
4011 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4012 track->presentationComplete(framesWritten, audioHALFrames);
4013 track->reset();
4014 tracksToRemove->add(track);
4015 }
4016 } else {
4017 // No buffers for this track. Give it a few chances to
4018 // fill a buffer, then remove it from active list.
4019 if (--(track->mRetryCount) <= 0) {
4020 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4021 track->name());
4022 tracksToRemove->add(track);
4023 } else if (last){
4024 mixerStatus = MIXER_TRACKS_ENABLED;
4025 }
4026 }
4027 }
4028 // compute volume for this track
4029 processVolume_l(track, last);
4030 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004031
Eric Laurent972a1732013-09-04 09:42:59 -07004032 // make sure the pause/flush/resume sequence is executed in the right order
4033 if (doHwPause) {
4034 mOutput->stream->pause(mOutput->stream);
4035 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004036 if (mFlushPending) {
4037 flushHw_l();
4038 mFlushPending = false;
4039 }
Eric Laurent972a1732013-09-04 09:42:59 -07004040 if (doHwResume) {
4041 mOutput->stream->resume(mOutput->stream);
4042 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004043
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044 // remove all the tracks that need to be...
4045 removeTracks_l(*tracksToRemove);
4046
4047 return mixerStatus;
4048}
4049
4050void AudioFlinger::OffloadThread::flushOutput_l()
4051{
4052 mFlushPending = true;
4053}
4054
4055// must be called with thread mutex locked
4056bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4057{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004058 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4059 mWriteAckSequence, mDrainSequence);
4060 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004061 return true;
4062 }
4063 return false;
4064}
4065
4066// must be called with thread mutex locked
4067bool AudioFlinger::OffloadThread::shouldStandby_l()
4068{
4069 bool TrackPaused = false;
4070
4071 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4072 // after a timeout and we will enter standby then.
4073 if (mTracks.size() > 0) {
4074 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4075 }
4076
4077 return !mStandby && !TrackPaused;
4078}
4079
4080
4081bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4082{
4083 Mutex::Autolock _l(mLock);
4084 return waitingAsyncCallback_l();
4085}
4086
4087void AudioFlinger::OffloadThread::flushHw_l()
4088{
4089 mOutput->stream->flush(mOutput->stream);
4090 // Flush anything still waiting in the mixbuffer
4091 mCurrentWriteLength = 0;
4092 mBytesRemaining = 0;
4093 mPausedWriteLength = 0;
4094 mPausedBytesRemaining = 0;
4095 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004096 // discard any pending drain or write ack by incrementing sequence
4097 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4098 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004100 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4101 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004102 }
4103}
4104
4105// ----------------------------------------------------------------------------
4106
Eric Laurent81784c32012-11-19 14:55:58 -08004107AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4108 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4109 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4110 DUPLICATING),
4111 mWaitTimeMs(UINT_MAX)
4112{
4113 addOutputTrack(mainThread);
4114}
4115
4116AudioFlinger::DuplicatingThread::~DuplicatingThread()
4117{
4118 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4119 mOutputTracks[i]->destroy();
4120 }
4121}
4122
4123void AudioFlinger::DuplicatingThread::threadLoop_mix()
4124{
4125 // mix buffers...
4126 if (outputsReady(outputTracks)) {
4127 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4128 } else {
4129 memset(mMixBuffer, 0, mixBufferSize);
4130 }
4131 sleepTime = 0;
4132 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004133 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004134 standbyTime = systemTime() + standbyDelay;
4135}
4136
4137void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4138{
4139 if (sleepTime == 0) {
4140 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4141 sleepTime = activeSleepTime;
4142 } else {
4143 sleepTime = idleSleepTime;
4144 }
4145 } else if (mBytesWritten != 0) {
4146 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4147 writeFrames = mNormalFrameCount;
4148 memset(mMixBuffer, 0, mixBufferSize);
4149 } else {
4150 // flush remaining overflow buffers in output tracks
4151 writeFrames = 0;
4152 }
4153 sleepTime = 0;
4154 }
4155}
4156
Eric Laurentbfb1b832013-01-07 09:53:42 -08004157ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004158{
4159 for (size_t i = 0; i < outputTracks.size(); i++) {
4160 outputTracks[i]->write(mMixBuffer, writeFrames);
4161 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004163}
4164
4165void AudioFlinger::DuplicatingThread::threadLoop_standby()
4166{
4167 // DuplicatingThread implements standby by stopping all tracks
4168 for (size_t i = 0; i < outputTracks.size(); i++) {
4169 outputTracks[i]->stop();
4170 }
4171}
4172
4173void AudioFlinger::DuplicatingThread::saveOutputTracks()
4174{
4175 outputTracks = mOutputTracks;
4176}
4177
4178void AudioFlinger::DuplicatingThread::clearOutputTracks()
4179{
4180 outputTracks.clear();
4181}
4182
4183void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4184{
4185 Mutex::Autolock _l(mLock);
4186 // FIXME explain this formula
4187 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4188 OutputTrack *outputTrack = new OutputTrack(thread,
4189 this,
4190 mSampleRate,
4191 mFormat,
4192 mChannelMask,
4193 frameCount);
4194 if (outputTrack->cblk() != NULL) {
4195 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4196 mOutputTracks.add(outputTrack);
4197 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4198 updateWaitTime_l();
4199 }
4200}
4201
4202void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4203{
4204 Mutex::Autolock _l(mLock);
4205 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4206 if (mOutputTracks[i]->thread() == thread) {
4207 mOutputTracks[i]->destroy();
4208 mOutputTracks.removeAt(i);
4209 updateWaitTime_l();
4210 return;
4211 }
4212 }
4213 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4214}
4215
4216// caller must hold mLock
4217void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4218{
4219 mWaitTimeMs = UINT_MAX;
4220 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4221 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4222 if (strong != 0) {
4223 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4224 if (waitTimeMs < mWaitTimeMs) {
4225 mWaitTimeMs = waitTimeMs;
4226 }
4227 }
4228 }
4229}
4230
4231
4232bool AudioFlinger::DuplicatingThread::outputsReady(
4233 const SortedVector< sp<OutputTrack> > &outputTracks)
4234{
4235 for (size_t i = 0; i < outputTracks.size(); i++) {
4236 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4237 if (thread == 0) {
4238 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4239 outputTracks[i].get());
4240 return false;
4241 }
4242 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4243 // see note at standby() declaration
4244 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4245 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4246 thread.get());
4247 return false;
4248 }
4249 }
4250 return true;
4251}
4252
4253uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4254{
4255 return (mWaitTimeMs * 1000) / 2;
4256}
4257
4258void AudioFlinger::DuplicatingThread::cacheParameters_l()
4259{
4260 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4261 updateWaitTime_l();
4262
4263 MixerThread::cacheParameters_l();
4264}
4265
4266// ----------------------------------------------------------------------------
4267// Record
4268// ----------------------------------------------------------------------------
4269
4270AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4271 AudioStreamIn *input,
4272 uint32_t sampleRate,
4273 audio_channel_mask_t channelMask,
4274 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004275 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004276 audio_devices_t inDevice
4277#ifdef TEE_SINK
4278 , const sp<NBAIO_Sink>& teeSink
4279#endif
4280 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004281 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004282 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004283 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004284 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004285 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004286 // mBytesRead is only meaningful while active, and so is cleared in start()
4287 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004288#ifdef TEE_SINK
4289 , mTeeSink(teeSink)
4290#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004291{
4292 snprintf(mName, kNameLength, "AudioIn_%X", id);
4293
4294 readInputParameters();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004295 mClientUid = IPCThreadState::self()->getCallingUid();
Eric Laurent81784c32012-11-19 14:55:58 -08004296}
4297
4298
4299AudioFlinger::RecordThread::~RecordThread()
4300{
4301 delete[] mRsmpInBuffer;
4302 delete mResampler;
4303 delete[] mRsmpOutBuffer;
4304}
4305
4306void AudioFlinger::RecordThread::onFirstRef()
4307{
4308 run(mName, PRIORITY_URGENT_AUDIO);
4309}
4310
4311status_t AudioFlinger::RecordThread::readyToRun()
4312{
4313 status_t status = initCheck();
4314 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4315 return status;
4316}
4317
4318bool AudioFlinger::RecordThread::threadLoop()
4319{
4320 AudioBufferProvider::Buffer buffer;
4321 sp<RecordTrack> activeTrack;
4322 Vector< sp<EffectChain> > effectChains;
4323
4324 nsecs_t lastWarning = 0;
4325
4326 inputStandBy();
Marco Nelissene14a5d62013-10-03 08:51:24 -07004327 acquireWakeLock(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004328
4329 // used to verify we've read at least once before evaluating how many bytes were read
4330 bool readOnce = false;
4331
4332 // start recording
4333 while (!exitPending()) {
4334
4335 processConfigEvents();
4336
4337 { // scope for mLock
4338 Mutex::Autolock _l(mLock);
4339 checkForNewParameters_l();
4340 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4341 standby();
4342
4343 if (exitPending()) {
4344 break;
4345 }
4346
4347 releaseWakeLock_l();
4348 ALOGV("RecordThread: loop stopping");
4349 // go to sleep
4350 mWaitWorkCV.wait(mLock);
4351 ALOGV("RecordThread: loop starting");
Marco Nelissene14a5d62013-10-03 08:51:24 -07004352 acquireWakeLock_l(mClientUid);
Eric Laurent81784c32012-11-19 14:55:58 -08004353 continue;
4354 }
4355 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 if (mActiveTrack->isTerminated()) {
4357 removeTrack_l(mActiveTrack);
4358 mActiveTrack.clear();
4359 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004360 standby();
4361 mActiveTrack.clear();
4362 mStartStopCond.broadcast();
4363 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4364 if (mReqChannelCount != mActiveTrack->channelCount()) {
4365 mActiveTrack.clear();
4366 mStartStopCond.broadcast();
4367 } else if (readOnce) {
4368 // record start succeeds only if first read from audio input
4369 // succeeds
4370 if (mBytesRead >= 0) {
4371 mActiveTrack->mState = TrackBase::ACTIVE;
4372 } else {
4373 mActiveTrack.clear();
4374 }
4375 mStartStopCond.broadcast();
4376 }
4377 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004378 }
4379 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004380
Eric Laurent81784c32012-11-19 14:55:58 -08004381 lockEffectChains_l(effectChains);
4382 }
4383
4384 if (mActiveTrack != 0) {
4385 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4386 mActiveTrack->mState != TrackBase::RESUMING) {
4387 unlockEffectChains(effectChains);
4388 usleep(kRecordThreadSleepUs);
4389 continue;
4390 }
4391 for (size_t i = 0; i < effectChains.size(); i ++) {
4392 effectChains[i]->process_l();
4393 }
4394
4395 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004396 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004397 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004398 readOnce = true;
4399 size_t framesOut = buffer.frameCount;
4400 if (mResampler == NULL) {
4401 // no resampling
4402 while (framesOut) {
4403 size_t framesIn = mFrameCount - mRsmpInIndex;
4404 if (framesIn) {
4405 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4406 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4407 mActiveTrack->mFrameSize;
4408 if (framesIn > framesOut)
4409 framesIn = framesOut;
4410 mRsmpInIndex += framesIn;
4411 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004412 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004413 memcpy(dst, src, framesIn * mFrameSize);
4414 } else {
4415 if (mChannelCount == 1) {
4416 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4417 (int16_t *)src, framesIn);
4418 } else {
4419 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4420 (int16_t *)src, framesIn);
4421 }
4422 }
4423 }
4424 if (framesOut && mFrameCount == mRsmpInIndex) {
4425 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004426 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004427 readInto = buffer.raw;
4428 framesOut = 0;
4429 } else {
4430 readInto = mRsmpInBuffer;
4431 mRsmpInIndex = 0;
4432 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004433 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004434 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004435 if (mBytesRead <= 0) {
4436 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4437 {
4438 ALOGE("Error reading audio input");
4439 // Force input into standby so that it tries to
4440 // recover at next read attempt
4441 inputStandBy();
4442 usleep(kRecordThreadSleepUs);
4443 }
4444 mRsmpInIndex = mFrameCount;
4445 framesOut = 0;
4446 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004447 }
4448#ifdef TEE_SINK
4449 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004450 (void) mTeeSink->write(readInto,
4451 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4452 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004453#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004454 }
4455 }
4456 } else {
4457 // resampling
4458
Glenn Kasten34af0262013-07-30 11:52:39 -07004459 // resampler accumulates, but we only have one source track
4460 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // alter output frame count as if we were expecting stereo samples
4462 if (mChannelCount == 1 && mReqChannelCount == 1) {
4463 framesOut >>= 1;
4464 }
4465 mResampler->resample(mRsmpOutBuffer, framesOut,
4466 this /* AudioBufferProvider* */);
4467 // ditherAndClamp() works as long as all buffers returned by
4468 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4469 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004470 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004471 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4472 // the resampler always outputs stereo samples:
4473 // do post stereo to mono conversion
4474 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4475 framesOut);
4476 } else {
4477 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4478 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004479 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004480
4481 }
4482 if (mFramestoDrop == 0) {
4483 mActiveTrack->releaseBuffer(&buffer);
4484 } else {
4485 if (mFramestoDrop > 0) {
4486 mFramestoDrop -= buffer.frameCount;
4487 if (mFramestoDrop <= 0) {
4488 clearSyncStartEvent();
4489 }
4490 } else {
4491 mFramestoDrop += buffer.frameCount;
4492 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4493 mSyncStartEvent->isCancelled()) {
4494 ALOGW("Synced record %s, session %d, trigger session %d",
4495 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4496 mActiveTrack->sessionId(),
4497 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4498 clearSyncStartEvent();
4499 }
4500 }
4501 }
4502 mActiveTrack->clearOverflow();
4503 }
4504 // client isn't retrieving buffers fast enough
4505 else {
4506 if (!mActiveTrack->setOverflow()) {
4507 nsecs_t now = systemTime();
4508 if ((now - lastWarning) > kWarningThrottleNs) {
4509 ALOGW("RecordThread: buffer overflow");
4510 lastWarning = now;
4511 }
4512 }
4513 // Release the processor for a while before asking for a new buffer.
4514 // This will give the application more chance to read from the buffer and
4515 // clear the overflow.
4516 usleep(kRecordThreadSleepUs);
4517 }
4518 }
4519 // enable changes in effect chain
4520 unlockEffectChains(effectChains);
4521 effectChains.clear();
4522 }
4523
4524 standby();
4525
4526 {
4527 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004528 for (size_t i = 0; i < mTracks.size(); i++) {
4529 sp<RecordTrack> track = mTracks[i];
4530 track->invalidate();
4531 }
Eric Laurent81784c32012-11-19 14:55:58 -08004532 mActiveTrack.clear();
4533 mStartStopCond.broadcast();
4534 }
4535
4536 releaseWakeLock();
4537
4538 ALOGV("RecordThread %p exiting", this);
4539 return false;
4540}
4541
4542void AudioFlinger::RecordThread::standby()
4543{
4544 if (!mStandby) {
4545 inputStandBy();
4546 mStandby = true;
4547 }
4548}
4549
4550void AudioFlinger::RecordThread::inputStandBy()
4551{
4552 mInput->stream->common.standby(&mInput->stream->common);
4553}
4554
4555sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4556 const sp<AudioFlinger::Client>& client,
4557 uint32_t sampleRate,
4558 audio_format_t format,
4559 audio_channel_mask_t channelMask,
4560 size_t frameCount,
4561 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004562 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004563 pid_t tid,
4564 status_t *status)
4565{
4566 sp<RecordTrack> track;
4567 status_t lStatus;
4568
4569 lStatus = initCheck();
4570 if (lStatus != NO_ERROR) {
4571 ALOGE("Audio driver not initialized.");
4572 goto Exit;
4573 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004574 // client expresses a preference for FAST, but we get the final say
4575 if (*flags & IAudioFlinger::TRACK_FAST) {
4576 if (
4577 // use case: callback handler and frame count is default or at least as large as HAL
4578 (
4579 (tid != -1) &&
4580 ((frameCount == 0) ||
4581 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4582 ) &&
4583 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4584 // mono or stereo
4585 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4586 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4587 // hardware sample rate
4588 (sampleRate == mSampleRate) &&
4589 // record thread has an associated fast recorder
4590 hasFastRecorder()
4591 // FIXME test that RecordThread for this fast track has a capable output HAL
4592 // FIXME add a permission test also?
4593 ) {
4594 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4595 if (frameCount == 0) {
4596 frameCount = mFrameCount * kFastTrackMultiplier;
4597 }
4598 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4599 frameCount, mFrameCount);
4600 } else {
4601 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4602 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4603 "hasFastRecorder=%d tid=%d",
4604 frameCount, mFrameCount, format,
4605 audio_is_linear_pcm(format),
4606 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4607 *flags &= ~IAudioFlinger::TRACK_FAST;
4608 // For compatibility with AudioRecord calculation, buffer depth is forced
4609 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4610 // This is probably too conservative, but legacy application code may depend on it.
4611 // If you change this calculation, also review the start threshold which is related.
4612 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4613 size_t mNormalFrameCount = 2048; // FIXME
4614 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4615 if (minBufCount < 2) {
4616 minBufCount = 2;
4617 }
4618 size_t minFrameCount = mNormalFrameCount * minBufCount;
4619 if (frameCount < minFrameCount) {
4620 frameCount = minFrameCount;
4621 }
4622 }
4623 }
4624
Eric Laurent81784c32012-11-19 14:55:58 -08004625 // FIXME use flags and tid similar to createTrack_l()
4626
4627 { // scope for mLock
4628 Mutex::Autolock _l(mLock);
4629
4630 track = new RecordTrack(this, client, sampleRate,
4631 format, channelMask, frameCount, sessionId);
4632
4633 if (track->getCblk() == 0) {
4634 lStatus = NO_MEMORY;
4635 goto Exit;
4636 }
4637 mTracks.add(track);
4638
4639 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4640 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4641 mAudioFlinger->btNrecIsOff();
4642 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4643 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004644
4645 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4646 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4647 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4648 // so ask activity manager to do this on our behalf
4649 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4650 }
Eric Laurent81784c32012-11-19 14:55:58 -08004651 }
4652 lStatus = NO_ERROR;
4653
4654Exit:
4655 if (status) {
4656 *status = lStatus;
4657 }
4658 return track;
4659}
4660
4661status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4662 AudioSystem::sync_event_t event,
4663 int triggerSession)
4664{
4665 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4666 sp<ThreadBase> strongMe = this;
4667 status_t status = NO_ERROR;
4668
4669 if (event == AudioSystem::SYNC_EVENT_NONE) {
4670 clearSyncStartEvent();
4671 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4672 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4673 triggerSession,
4674 recordTrack->sessionId(),
4675 syncStartEventCallback,
4676 this);
4677 // Sync event can be cancelled by the trigger session if the track is not in a
4678 // compatible state in which case we start record immediately
4679 if (mSyncStartEvent->isCancelled()) {
4680 clearSyncStartEvent();
4681 } else {
4682 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4683 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4684 }
4685 }
4686
4687 {
4688 AutoMutex lock(mLock);
4689 if (mActiveTrack != 0) {
4690 if (recordTrack != mActiveTrack.get()) {
4691 status = -EBUSY;
4692 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4693 mActiveTrack->mState = TrackBase::ACTIVE;
4694 }
4695 return status;
4696 }
4697
4698 recordTrack->mState = TrackBase::IDLE;
4699 mActiveTrack = recordTrack;
4700 mLock.unlock();
4701 status_t status = AudioSystem::startInput(mId);
4702 mLock.lock();
4703 if (status != NO_ERROR) {
4704 mActiveTrack.clear();
4705 clearSyncStartEvent();
4706 return status;
4707 }
4708 mRsmpInIndex = mFrameCount;
4709 mBytesRead = 0;
4710 if (mResampler != NULL) {
4711 mResampler->reset();
4712 }
4713 mActiveTrack->mState = TrackBase::RESUMING;
4714 // signal thread to start
4715 ALOGV("Signal record thread");
4716 mWaitWorkCV.broadcast();
4717 // do not wait for mStartStopCond if exiting
4718 if (exitPending()) {
4719 mActiveTrack.clear();
4720 status = INVALID_OPERATION;
4721 goto startError;
4722 }
4723 mStartStopCond.wait(mLock);
4724 if (mActiveTrack == 0) {
4725 ALOGV("Record failed to start");
4726 status = BAD_VALUE;
4727 goto startError;
4728 }
4729 ALOGV("Record started OK");
4730 return status;
4731 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004732
Eric Laurent81784c32012-11-19 14:55:58 -08004733startError:
4734 AudioSystem::stopInput(mId);
4735 clearSyncStartEvent();
4736 return status;
4737}
4738
4739void AudioFlinger::RecordThread::clearSyncStartEvent()
4740{
4741 if (mSyncStartEvent != 0) {
4742 mSyncStartEvent->cancel();
4743 }
4744 mSyncStartEvent.clear();
4745 mFramestoDrop = 0;
4746}
4747
4748void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4749{
4750 sp<SyncEvent> strongEvent = event.promote();
4751
4752 if (strongEvent != 0) {
4753 RecordThread *me = (RecordThread *)strongEvent->cookie();
4754 me->handleSyncStartEvent(strongEvent);
4755 }
4756}
4757
4758void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4759{
4760 if (event == mSyncStartEvent) {
4761 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4762 // from audio HAL
4763 mFramestoDrop = mFrameCount * 2;
4764 }
4765}
4766
Glenn Kastena8356f62013-07-25 14:37:52 -07004767bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004768 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004769 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004770 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4771 return false;
4772 }
4773 recordTrack->mState = TrackBase::PAUSING;
4774 // do not wait for mStartStopCond if exiting
4775 if (exitPending()) {
4776 return true;
4777 }
4778 mStartStopCond.wait(mLock);
4779 // if we have been restarted, recordTrack == mActiveTrack.get() here
4780 if (exitPending() || recordTrack != mActiveTrack.get()) {
4781 ALOGV("Record stopped OK");
4782 return true;
4783 }
4784 return false;
4785}
4786
4787bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4788{
4789 return false;
4790}
4791
4792status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4793{
4794#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4795 if (!isValidSyncEvent(event)) {
4796 return BAD_VALUE;
4797 }
4798
4799 int eventSession = event->triggerSession();
4800 status_t ret = NAME_NOT_FOUND;
4801
4802 Mutex::Autolock _l(mLock);
4803
4804 for (size_t i = 0; i < mTracks.size(); i++) {
4805 sp<RecordTrack> track = mTracks[i];
4806 if (eventSession == track->sessionId()) {
4807 (void) track->setSyncEvent(event);
4808 ret = NO_ERROR;
4809 }
4810 }
4811 return ret;
4812#else
4813 return BAD_VALUE;
4814#endif
4815}
4816
4817// destroyTrack_l() must be called with ThreadBase::mLock held
4818void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4819{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820 track->terminate();
4821 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004822 // active tracks are removed by threadLoop()
4823 if (mActiveTrack != track) {
4824 removeTrack_l(track);
4825 }
4826}
4827
4828void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4829{
4830 mTracks.remove(track);
4831 // need anything related to effects here?
4832}
4833
4834void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4835{
4836 dumpInternals(fd, args);
4837 dumpTracks(fd, args);
4838 dumpEffectChains(fd, args);
4839}
4840
4841void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4842{
4843 const size_t SIZE = 256;
4844 char buffer[SIZE];
4845 String8 result;
4846
4847 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4848 result.append(buffer);
4849
4850 if (mActiveTrack != 0) {
4851 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4852 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004853 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004854 result.append(buffer);
4855 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4856 result.append(buffer);
4857 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4858 result.append(buffer);
4859 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4860 result.append(buffer);
4861 } else {
4862 result.append("No active record client\n");
4863 }
4864
4865 write(fd, result.string(), result.size());
4866
4867 dumpBase(fd, args);
4868}
4869
4870void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4871{
4872 const size_t SIZE = 256;
4873 char buffer[SIZE];
4874 String8 result;
4875
4876 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4877 result.append(buffer);
4878 RecordTrack::appendDumpHeader(result);
4879 for (size_t i = 0; i < mTracks.size(); ++i) {
4880 sp<RecordTrack> track = mTracks[i];
4881 if (track != 0) {
4882 track->dump(buffer, SIZE);
4883 result.append(buffer);
4884 }
4885 }
4886
4887 if (mActiveTrack != 0) {
4888 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4889 result.append(buffer);
4890 RecordTrack::appendDumpHeader(result);
4891 mActiveTrack->dump(buffer, SIZE);
4892 result.append(buffer);
4893
4894 }
4895 write(fd, result.string(), result.size());
4896}
4897
4898// AudioBufferProvider interface
4899status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4900{
4901 size_t framesReq = buffer->frameCount;
4902 size_t framesReady = mFrameCount - mRsmpInIndex;
4903 int channelCount;
4904
4905 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08004906 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004907 if (mBytesRead <= 0) {
4908 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4909 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4910 // Force input into standby so that it tries to
4911 // recover at next read attempt
4912 inputStandBy();
4913 usleep(kRecordThreadSleepUs);
4914 }
4915 buffer->raw = NULL;
4916 buffer->frameCount = 0;
4917 return NOT_ENOUGH_DATA;
4918 }
4919 mRsmpInIndex = 0;
4920 framesReady = mFrameCount;
4921 }
4922
4923 if (framesReq > framesReady) {
4924 framesReq = framesReady;
4925 }
4926
4927 if (mChannelCount == 1 && mReqChannelCount == 2) {
4928 channelCount = 1;
4929 } else {
4930 channelCount = 2;
4931 }
4932 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4933 buffer->frameCount = framesReq;
4934 return NO_ERROR;
4935}
4936
4937// AudioBufferProvider interface
4938void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4939{
4940 mRsmpInIndex += buffer->frameCount;
4941 buffer->frameCount = 0;
4942}
4943
4944bool AudioFlinger::RecordThread::checkForNewParameters_l()
4945{
4946 bool reconfig = false;
4947
4948 while (!mNewParameters.isEmpty()) {
4949 status_t status = NO_ERROR;
4950 String8 keyValuePair = mNewParameters[0];
4951 AudioParameter param = AudioParameter(keyValuePair);
4952 int value;
4953 audio_format_t reqFormat = mFormat;
4954 uint32_t reqSamplingRate = mReqSampleRate;
4955 uint32_t reqChannelCount = mReqChannelCount;
4956
4957 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4958 reqSamplingRate = value;
4959 reconfig = true;
4960 }
4961 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004962 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4963 status = BAD_VALUE;
4964 } else {
4965 reqFormat = (audio_format_t) value;
4966 reconfig = true;
4967 }
Eric Laurent81784c32012-11-19 14:55:58 -08004968 }
4969 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4970 reqChannelCount = popcount(value);
4971 reconfig = true;
4972 }
4973 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4974 // do not accept frame count changes if tracks are open as the track buffer
4975 // size depends on frame count and correct behavior would not be guaranteed
4976 // if frame count is changed after track creation
4977 if (mActiveTrack != 0) {
4978 status = INVALID_OPERATION;
4979 } else {
4980 reconfig = true;
4981 }
4982 }
4983 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4984 // forward device change to effects that have requested to be
4985 // aware of attached audio device.
4986 for (size_t i = 0; i < mEffectChains.size(); i++) {
4987 mEffectChains[i]->setDevice_l(value);
4988 }
4989
4990 // store input device and output device but do not forward output device to audio HAL.
4991 // Note that status is ignored by the caller for output device
4992 // (see AudioFlinger::setParameters()
4993 if (audio_is_output_devices(value)) {
4994 mOutDevice = value;
4995 status = BAD_VALUE;
4996 } else {
4997 mInDevice = value;
4998 // disable AEC and NS if the device is a BT SCO headset supporting those
4999 // pre processings
5000 if (mTracks.size() > 0) {
5001 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5002 mAudioFlinger->btNrecIsOff();
5003 for (size_t i = 0; i < mTracks.size(); i++) {
5004 sp<RecordTrack> track = mTracks[i];
5005 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5006 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5007 }
5008 }
5009 }
5010 }
5011 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5012 mAudioSource != (audio_source_t)value) {
5013 // forward device change to effects that have requested to be
5014 // aware of attached audio device.
5015 for (size_t i = 0; i < mEffectChains.size(); i++) {
5016 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5017 }
5018 mAudioSource = (audio_source_t)value;
5019 }
5020 if (status == NO_ERROR) {
5021 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5022 keyValuePair.string());
5023 if (status == INVALID_OPERATION) {
5024 inputStandBy();
5025 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5026 keyValuePair.string());
5027 }
5028 if (reconfig) {
5029 if (status == BAD_VALUE &&
5030 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5031 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005032 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005033 <= (2 * reqSamplingRate)) &&
5034 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5035 <= FCC_2 &&
5036 (reqChannelCount <= FCC_2)) {
5037 status = NO_ERROR;
5038 }
5039 if (status == NO_ERROR) {
5040 readInputParameters();
5041 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5042 }
5043 }
5044 }
5045
5046 mNewParameters.removeAt(0);
5047
5048 mParamStatus = status;
5049 mParamCond.signal();
5050 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5051 // already timed out waiting for the status and will never signal the condition.
5052 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5053 }
5054 return reconfig;
5055}
5056
5057String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5058{
Eric Laurent81784c32012-11-19 14:55:58 -08005059 Mutex::Autolock _l(mLock);
5060 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005061 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005062 }
5063
Glenn Kastend8ea6992013-07-16 14:17:15 -07005064 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5065 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005066 free(s);
5067 return out_s8;
5068}
5069
5070void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5071 AudioSystem::OutputDescriptor desc;
5072 void *param2 = NULL;
5073
5074 switch (event) {
5075 case AudioSystem::INPUT_OPENED:
5076 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005077 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005078 desc.samplingRate = mSampleRate;
5079 desc.format = mFormat;
5080 desc.frameCount = mFrameCount;
5081 desc.latency = 0;
5082 param2 = &desc;
5083 break;
5084
5085 case AudioSystem::INPUT_CLOSED:
5086 default:
5087 break;
5088 }
5089 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5090}
5091
5092void AudioFlinger::RecordThread::readInputParameters()
5093{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005094 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005095 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005096 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005097 mRsmpOutBuffer = NULL;
5098 delete mResampler;
5099 mResampler = NULL;
5100
5101 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5102 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005103 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005104 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005105 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5106 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5107 }
Eric Laurent81784c32012-11-19 14:55:58 -08005108 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005109 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5110 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005111 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5112
5113 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5114 {
5115 int channelCount;
5116 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5117 // stereo to mono post process as the resampler always outputs stereo.
5118 if (mChannelCount == 1 && mReqChannelCount == 2) {
5119 channelCount = 1;
5120 } else {
5121 channelCount = 2;
5122 }
5123 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5124 mResampler->setSampleRate(mSampleRate);
5125 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005126 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005127
5128 // optmization: if mono to mono, alter input frame count as if we were inputing
5129 // stereo samples
5130 if (mChannelCount == 1 && mReqChannelCount == 1) {
5131 mFrameCount >>= 1;
5132 }
5133
5134 }
5135 mRsmpInIndex = mFrameCount;
5136}
5137
5138unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5139{
5140 Mutex::Autolock _l(mLock);
5141 if (initCheck() != NO_ERROR) {
5142 return 0;
5143 }
5144
5145 return mInput->stream->get_input_frames_lost(mInput->stream);
5146}
5147
5148uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5149{
5150 Mutex::Autolock _l(mLock);
5151 uint32_t result = 0;
5152 if (getEffectChain_l(sessionId) != 0) {
5153 result = EFFECT_SESSION;
5154 }
5155
5156 for (size_t i = 0; i < mTracks.size(); ++i) {
5157 if (sessionId == mTracks[i]->sessionId()) {
5158 result |= TRACK_SESSION;
5159 break;
5160 }
5161 }
5162
5163 return result;
5164}
5165
5166KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5167{
5168 KeyedVector<int, bool> ids;
5169 Mutex::Autolock _l(mLock);
5170 for (size_t j = 0; j < mTracks.size(); ++j) {
5171 sp<RecordThread::RecordTrack> track = mTracks[j];
5172 int sessionId = track->sessionId();
5173 if (ids.indexOfKey(sessionId) < 0) {
5174 ids.add(sessionId, true);
5175 }
5176 }
5177 return ids;
5178}
5179
5180AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5181{
5182 Mutex::Autolock _l(mLock);
5183 AudioStreamIn *input = mInput;
5184 mInput = NULL;
5185 return input;
5186}
5187
5188// this method must always be called either with ThreadBase mLock held or inside the thread loop
5189audio_stream_t* AudioFlinger::RecordThread::stream() const
5190{
5191 if (mInput == NULL) {
5192 return NULL;
5193 }
5194 return &mInput->stream->common;
5195}
5196
5197status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5198{
5199 // only one chain per input thread
5200 if (mEffectChains.size() != 0) {
5201 return INVALID_OPERATION;
5202 }
5203 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5204
5205 chain->setInBuffer(NULL);
5206 chain->setOutBuffer(NULL);
5207
5208 checkSuspendOnAddEffectChain_l(chain);
5209
5210 mEffectChains.add(chain);
5211
5212 return NO_ERROR;
5213}
5214
5215size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5216{
5217 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5218 ALOGW_IF(mEffectChains.size() != 1,
5219 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5220 chain.get(), mEffectChains.size(), this);
5221 if (mEffectChains.size() == 1) {
5222 mEffectChains.removeAt(0);
5223 }
5224 return 0;
5225}
5226
5227}; // namespace android