blob: 110e45cf709f34cc33b78419272855d817a98b4d [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),
Eric Laurentfd477972013-10-25 18:10:40 -0700275 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800276 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
277 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
278 // mName will be set by concrete (non-virtual) subclass
279 mDeathRecipient(new PMDeathRecipient(this))
280{
281}
282
283AudioFlinger::ThreadBase::~ThreadBase()
284{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700285 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
286 for (size_t i = 0; i < mConfigEvents.size(); i++) {
287 delete mConfigEvents[i];
288 }
289 mConfigEvents.clear();
290
Eric Laurent81784c32012-11-19 14:55:58 -0800291 mParamCond.broadcast();
292 // do not lock the mutex in destructor
293 releaseWakeLock_l();
294 if (mPowerManager != 0) {
295 sp<IBinder> binder = mPowerManager->asBinder();
296 binder->unlinkToDeath(mDeathRecipient);
297 }
298}
299
300void AudioFlinger::ThreadBase::exit()
301{
302 ALOGV("ThreadBase::exit");
303 // do any cleanup required for exit to succeed
304 preExit();
305 {
306 // This lock prevents the following race in thread (uniprocessor for illustration):
307 // if (!exitPending()) {
308 // // context switch from here to exit()
309 // // exit() calls requestExit(), what exitPending() observes
310 // // exit() calls signal(), which is dropped since no waiters
311 // // context switch back from exit() to here
312 // mWaitWorkCV.wait(...);
313 // // now thread is hung
314 // }
315 AutoMutex lock(mLock);
316 requestExit();
317 mWaitWorkCV.broadcast();
318 }
319 // When Thread::requestExitAndWait is made virtual and this method is renamed to
320 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
321 requestExitAndWait();
322}
323
324status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
325{
326 status_t status;
327
328 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
329 Mutex::Autolock _l(mLock);
330
331 mNewParameters.add(keyValuePairs);
332 mWaitWorkCV.signal();
333 // wait condition with timeout in case the thread loop has exited
334 // before the request could be processed
335 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
336 status = mParamStatus;
337 mWaitWorkCV.signal();
338 } else {
339 status = TIMED_OUT;
340 }
341 return status;
342}
343
344void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
345{
346 Mutex::Autolock _l(mLock);
347 sendIoConfigEvent_l(event, param);
348}
349
350// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
351void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
352{
353 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
354 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
355 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
356 param);
357 mWaitWorkCV.signal();
358}
359
360// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
361void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
362{
363 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
364 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
365 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
366 mConfigEvents.size(), pid, tid, prio);
367 mWaitWorkCV.signal();
368}
369
370void AudioFlinger::ThreadBase::processConfigEvents()
371{
372 mLock.lock();
373 while (!mConfigEvents.isEmpty()) {
374 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
375 ConfigEvent *event = mConfigEvents[0];
376 mConfigEvents.removeAt(0);
377 // release mLock before locking AudioFlinger mLock: lock order is always
378 // AudioFlinger then ThreadBase to avoid cross deadlock
379 mLock.unlock();
380 switch(event->type()) {
381 case CFG_EVENT_PRIO: {
382 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
Glenn Kastena07f17c2013-04-23 12:39:37 -0700383 // FIXME Need to understand why this has be done asynchronously
384 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
385 true /*asynchronous*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800386 if (err != 0) {
387 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
388 "error %d",
389 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
390 }
391 } break;
392 case CFG_EVENT_IO: {
393 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
394 mAudioFlinger->mLock.lock();
395 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
396 mAudioFlinger->mLock.unlock();
397 } break;
398 default:
399 ALOGE("processConfigEvents() unknown event type %d", event->type());
400 break;
401 }
402 delete event;
403 mLock.lock();
404 }
405 mLock.unlock();
406}
407
408void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
412 String8 result;
413
414 bool locked = AudioFlinger::dumpTryLock(mLock);
415 if (!locked) {
416 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
417 write(fd, buffer, strlen(buffer));
418 }
419
420 snprintf(buffer, SIZE, "io handle: %d\n", mId);
421 result.append(buffer);
422 snprintf(buffer, SIZE, "TID: %d\n", getTid());
423 result.append(buffer);
424 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
425 result.append(buffer);
426 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
427 result.append(buffer);
428 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
429 result.append(buffer);
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700430 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -0800431 result.append(buffer);
432 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
433 result.append(buffer);
434 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
435 result.append(buffer);
436 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
437 result.append(buffer);
438
439 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
440 result.append(buffer);
441 result.append(" Index Command");
442 for (size_t i = 0; i < mNewParameters.size(); ++i) {
443 snprintf(buffer, SIZE, "\n %02d ", i);
444 result.append(buffer);
445 result.append(mNewParameters[i]);
446 }
447
448 snprintf(buffer, SIZE, "\n\nPending config events: \n");
449 result.append(buffer);
450 for (size_t i = 0; i < mConfigEvents.size(); i++) {
451 mConfigEvents[i]->dump(buffer, SIZE);
452 result.append(buffer);
453 }
454 result.append("\n");
455
456 write(fd, result.string(), result.size());
457
458 if (locked) {
459 mLock.unlock();
460 }
461}
462
463void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
464{
465 const size_t SIZE = 256;
466 char buffer[SIZE];
467 String8 result;
468
469 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
470 write(fd, buffer, strlen(buffer));
471
472 for (size_t i = 0; i < mEffectChains.size(); ++i) {
473 sp<EffectChain> chain = mEffectChains[i];
474 if (chain != 0) {
475 chain->dump(fd, args);
476 }
477 }
478}
479
Marco Nelissene14a5d62013-10-03 08:51:24 -0700480void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800481{
482 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700483 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800484}
485
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100486String16 AudioFlinger::ThreadBase::getWakeLockTag()
487{
488 switch (mType) {
489 case MIXER:
490 return String16("AudioMix");
491 case DIRECT:
492 return String16("AudioDirectOut");
493 case DUPLICATING:
494 return String16("AudioDup");
495 case RECORD:
496 return String16("AudioIn");
497 case OFFLOAD:
498 return String16("AudioOffload");
499 default:
500 ALOG_ASSERT(false);
501 return String16("AudioUnknown");
502 }
503}
504
Marco Nelissene14a5d62013-10-03 08:51:24 -0700505void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800506{
Marco Nelissen9cae2172013-01-14 14:12:05 -0800507 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800508 if (mPowerManager != 0) {
509 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700510 status_t status;
511 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700512 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700513 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100514 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700515 String16("media"),
516 uid);
517 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700518 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700519 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100520 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700521 String16("media"));
522 }
Eric Laurent81784c32012-11-19 14:55:58 -0800523 if (status == NO_ERROR) {
524 mWakeLockToken = binder;
525 }
526 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
527 }
528}
529
530void AudioFlinger::ThreadBase::releaseWakeLock()
531{
532 Mutex::Autolock _l(mLock);
533 releaseWakeLock_l();
534}
535
536void AudioFlinger::ThreadBase::releaseWakeLock_l()
537{
538 if (mWakeLockToken != 0) {
539 ALOGV("releaseWakeLock_l() %s", mName);
540 if (mPowerManager != 0) {
541 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
542 }
543 mWakeLockToken.clear();
544 }
545}
546
Marco Nelissen9cae2172013-01-14 14:12:05 -0800547void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
548 Mutex::Autolock _l(mLock);
549 updateWakeLockUids_l(uids);
550}
551
552void AudioFlinger::ThreadBase::getPowerManager_l() {
553
554 if (mPowerManager == 0) {
555 // use checkService() to avoid blocking if power service is not up yet
556 sp<IBinder> binder =
557 defaultServiceManager()->checkService(String16("power"));
558 if (binder == 0) {
559 ALOGW("Thread %s cannot connect to the power manager service", mName);
560 } else {
561 mPowerManager = interface_cast<IPowerManager>(binder);
562 binder->linkToDeath(mDeathRecipient);
563 }
564 }
565}
566
567void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
568
569 getPowerManager_l();
570 if (mWakeLockToken == NULL) {
571 ALOGE("no wake lock to update!");
572 return;
573 }
574 if (mPowerManager != 0) {
575 sp<IBinder> binder = new BBinder();
576 status_t status;
577 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
578 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
579 }
580}
581
Eric Laurent81784c32012-11-19 14:55:58 -0800582void AudioFlinger::ThreadBase::clearPowerManager()
583{
584 Mutex::Autolock _l(mLock);
585 releaseWakeLock_l();
586 mPowerManager.clear();
587}
588
589void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
590{
591 sp<ThreadBase> thread = mThread.promote();
592 if (thread != 0) {
593 thread->clearPowerManager();
594 }
595 ALOGW("power manager service died !!!");
596}
597
598void AudioFlinger::ThreadBase::setEffectSuspended(
599 const effect_uuid_t *type, bool suspend, int sessionId)
600{
601 Mutex::Autolock _l(mLock);
602 setEffectSuspended_l(type, suspend, sessionId);
603}
604
605void AudioFlinger::ThreadBase::setEffectSuspended_l(
606 const effect_uuid_t *type, bool suspend, int sessionId)
607{
608 sp<EffectChain> chain = getEffectChain_l(sessionId);
609 if (chain != 0) {
610 if (type != NULL) {
611 chain->setEffectSuspended_l(type, suspend);
612 } else {
613 chain->setEffectSuspendedAll_l(suspend);
614 }
615 }
616
617 updateSuspendedSessions_l(type, suspend, sessionId);
618}
619
620void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
621{
622 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
623 if (index < 0) {
624 return;
625 }
626
627 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
628 mSuspendedSessions.valueAt(index);
629
630 for (size_t i = 0; i < sessionEffects.size(); i++) {
631 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
632 for (int j = 0; j < desc->mRefCount; j++) {
633 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
634 chain->setEffectSuspendedAll_l(true);
635 } else {
636 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
637 desc->mType.timeLow);
638 chain->setEffectSuspended_l(&desc->mType, true);
639 }
640 }
641 }
642}
643
644void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
645 bool suspend,
646 int sessionId)
647{
648 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
649
650 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
651
652 if (suspend) {
653 if (index >= 0) {
654 sessionEffects = mSuspendedSessions.valueAt(index);
655 } else {
656 mSuspendedSessions.add(sessionId, sessionEffects);
657 }
658 } else {
659 if (index < 0) {
660 return;
661 }
662 sessionEffects = mSuspendedSessions.valueAt(index);
663 }
664
665
666 int key = EffectChain::kKeyForSuspendAll;
667 if (type != NULL) {
668 key = type->timeLow;
669 }
670 index = sessionEffects.indexOfKey(key);
671
672 sp<SuspendedSessionDesc> desc;
673 if (suspend) {
674 if (index >= 0) {
675 desc = sessionEffects.valueAt(index);
676 } else {
677 desc = new SuspendedSessionDesc();
678 if (type != NULL) {
679 desc->mType = *type;
680 }
681 sessionEffects.add(key, desc);
682 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
683 }
684 desc->mRefCount++;
685 } else {
686 if (index < 0) {
687 return;
688 }
689 desc = sessionEffects.valueAt(index);
690 if (--desc->mRefCount == 0) {
691 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
692 sessionEffects.removeItemsAt(index);
693 if (sessionEffects.isEmpty()) {
694 ALOGV("updateSuspendedSessions_l() restore removing session %d",
695 sessionId);
696 mSuspendedSessions.removeItem(sessionId);
697 }
698 }
699 }
700 if (!sessionEffects.isEmpty()) {
701 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
702 }
703}
704
705void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
706 bool enabled,
707 int sessionId)
708{
709 Mutex::Autolock _l(mLock);
710 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
711}
712
713void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
714 bool enabled,
715 int sessionId)
716{
717 if (mType != RECORD) {
718 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
719 // another session. This gives the priority to well behaved effect control panels
720 // and applications not using global effects.
721 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
722 // global effects
723 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
724 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
725 }
726 }
727
728 sp<EffectChain> chain = getEffectChain_l(sessionId);
729 if (chain != 0) {
730 chain->checkSuspendOnEffectEnabled(effect, enabled);
731 }
732}
733
734// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
735sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
736 const sp<AudioFlinger::Client>& client,
737 const sp<IEffectClient>& effectClient,
738 int32_t priority,
739 int sessionId,
740 effect_descriptor_t *desc,
741 int *enabled,
742 status_t *status
743 )
744{
745 sp<EffectModule> effect;
746 sp<EffectHandle> handle;
747 status_t lStatus;
748 sp<EffectChain> chain;
749 bool chainCreated = false;
750 bool effectCreated = false;
751 bool effectRegistered = false;
752
753 lStatus = initCheck();
754 if (lStatus != NO_ERROR) {
755 ALOGW("createEffect_l() Audio driver not initialized.");
756 goto Exit;
757 }
758
Eric Laurent5baf2af2013-09-12 17:37:00 -0700759 // Allow global effects only on offloaded and mixer threads
760 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
761 switch (mType) {
762 case MIXER:
763 case OFFLOAD:
764 break;
765 case DIRECT:
766 case DUPLICATING:
767 case RECORD:
768 default:
769 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
770 lStatus = BAD_VALUE;
771 goto Exit;
772 }
Eric Laurent81784c32012-11-19 14:55:58 -0800773 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700774
Eric Laurent81784c32012-11-19 14:55:58 -0800775 // Only Pre processor effects are allowed on input threads and only on input threads
776 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
777 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
778 desc->name, desc->flags, mType);
779 lStatus = BAD_VALUE;
780 goto Exit;
781 }
782
783 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
784
785 { // scope for mLock
786 Mutex::Autolock _l(mLock);
787
788 // check for existing effect chain with the requested audio session
789 chain = getEffectChain_l(sessionId);
790 if (chain == 0) {
791 // create a new chain for this session
792 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
793 chain = new EffectChain(this, sessionId);
794 addEffectChain_l(chain);
795 chain->setStrategy(getStrategyForSession_l(sessionId));
796 chainCreated = true;
797 } else {
798 effect = chain->getEffectFromDesc_l(desc);
799 }
800
801 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
802
803 if (effect == 0) {
804 int id = mAudioFlinger->nextUniqueId();
805 // Check CPU and memory usage
806 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
807 if (lStatus != NO_ERROR) {
808 goto Exit;
809 }
810 effectRegistered = true;
811 // create a new effect module if none present in the chain
812 effect = new EffectModule(this, chain, desc, id, sessionId);
813 lStatus = effect->status();
814 if (lStatus != NO_ERROR) {
815 goto Exit;
816 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700817 effect->setOffloaded(mType == OFFLOAD, mId);
818
Eric Laurent81784c32012-11-19 14:55:58 -0800819 lStatus = chain->addEffect_l(effect);
820 if (lStatus != NO_ERROR) {
821 goto Exit;
822 }
823 effectCreated = true;
824
825 effect->setDevice(mOutDevice);
826 effect->setDevice(mInDevice);
827 effect->setMode(mAudioFlinger->getMode());
828 effect->setAudioSource(mAudioSource);
829 }
830 // create effect handle and connect it to effect module
831 handle = new EffectHandle(effect, client, effectClient, priority);
832 lStatus = effect->addHandle(handle.get());
833 if (enabled != NULL) {
834 *enabled = (int)effect->isEnabled();
835 }
836 }
837
838Exit:
839 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
840 Mutex::Autolock _l(mLock);
841 if (effectCreated) {
842 chain->removeEffect_l(effect);
843 }
844 if (effectRegistered) {
845 AudioSystem::unregisterEffect(effect->id());
846 }
847 if (chainCreated) {
848 removeEffectChain_l(chain);
849 }
850 handle.clear();
851 }
852
853 if (status != NULL) {
854 *status = lStatus;
855 }
856 return handle;
857}
858
859sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
860{
861 Mutex::Autolock _l(mLock);
862 return getEffect_l(sessionId, effectId);
863}
864
865sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
866{
867 sp<EffectChain> chain = getEffectChain_l(sessionId);
868 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
869}
870
871// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
872// PlaybackThread::mLock held
873status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
874{
875 // check for existing effect chain with the requested audio session
876 int sessionId = effect->sessionId();
877 sp<EffectChain> chain = getEffectChain_l(sessionId);
878 bool chainCreated = false;
879
Eric Laurent5baf2af2013-09-12 17:37:00 -0700880 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
881 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
882 this, effect->desc().name, effect->desc().flags);
883
Eric Laurent81784c32012-11-19 14:55:58 -0800884 if (chain == 0) {
885 // create a new chain for this session
886 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
887 chain = new EffectChain(this, sessionId);
888 addEffectChain_l(chain);
889 chain->setStrategy(getStrategyForSession_l(sessionId));
890 chainCreated = true;
891 }
892 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
893
894 if (chain->getEffectFromId_l(effect->id()) != 0) {
895 ALOGW("addEffect_l() %p effect %s already present in chain %p",
896 this, effect->desc().name, chain.get());
897 return BAD_VALUE;
898 }
899
Eric Laurent5baf2af2013-09-12 17:37:00 -0700900 effect->setOffloaded(mType == OFFLOAD, mId);
901
Eric Laurent81784c32012-11-19 14:55:58 -0800902 status_t status = chain->addEffect_l(effect);
903 if (status != NO_ERROR) {
904 if (chainCreated) {
905 removeEffectChain_l(chain);
906 }
907 return status;
908 }
909
910 effect->setDevice(mOutDevice);
911 effect->setDevice(mInDevice);
912 effect->setMode(mAudioFlinger->getMode());
913 effect->setAudioSource(mAudioSource);
914 return NO_ERROR;
915}
916
917void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
918
919 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
920 effect_descriptor_t desc = effect->desc();
921 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
922 detachAuxEffect_l(effect->id());
923 }
924
925 sp<EffectChain> chain = effect->chain().promote();
926 if (chain != 0) {
927 // remove effect chain if removing last effect
928 if (chain->removeEffect_l(effect) == 0) {
929 removeEffectChain_l(chain);
930 }
931 } else {
932 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
933 }
934}
935
936void AudioFlinger::ThreadBase::lockEffectChains_l(
937 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
938{
939 effectChains = mEffectChains;
940 for (size_t i = 0; i < mEffectChains.size(); i++) {
941 mEffectChains[i]->lock();
942 }
943}
944
945void AudioFlinger::ThreadBase::unlockEffectChains(
946 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
947{
948 for (size_t i = 0; i < effectChains.size(); i++) {
949 effectChains[i]->unlock();
950 }
951}
952
953sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
954{
955 Mutex::Autolock _l(mLock);
956 return getEffectChain_l(sessionId);
957}
958
959sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
960{
961 size_t size = mEffectChains.size();
962 for (size_t i = 0; i < size; i++) {
963 if (mEffectChains[i]->sessionId() == sessionId) {
964 return mEffectChains[i];
965 }
966 }
967 return 0;
968}
969
970void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
971{
972 Mutex::Autolock _l(mLock);
973 size_t size = mEffectChains.size();
974 for (size_t i = 0; i < size; i++) {
975 mEffectChains[i]->setMode_l(mode);
976 }
977}
978
979void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
980 EffectHandle *handle,
981 bool unpinIfLast) {
982
983 Mutex::Autolock _l(mLock);
984 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
985 // delete the effect module if removing last handle on it
986 if (effect->removeHandle(handle) == 0) {
987 if (!effect->isPinned() || unpinIfLast) {
988 removeEffect_l(effect);
989 AudioSystem::unregisterEffect(effect->id());
990 }
991 }
992}
993
994// ----------------------------------------------------------------------------
995// Playback
996// ----------------------------------------------------------------------------
997
998AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
999 AudioStreamOut* output,
1000 audio_io_handle_t id,
1001 audio_devices_t device,
1002 type_t type)
1003 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten9b58f632013-07-16 11:37:48 -07001004 mNormalFrameCount(0), mMixBuffer(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001005 mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Marco Nelissen9cae2172013-01-14 14:12:05 -08001006 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001007 // mStreamTypes[] initialized in constructor body
1008 mOutput(output),
1009 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1010 mMixerStatus(MIXER_IDLE),
1011 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1012 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001013 mBytesRemaining(0),
1014 mCurrentWriteLength(0),
1015 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001016 mWriteAckSequence(0),
1017 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001018 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001019 mScreenState(AudioFlinger::mScreenState),
1020 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001021 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1022 // mLatchD, mLatchQ,
1023 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
1025 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001026 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001027
1028 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1029 // it would be safer to explicitly pass initial masterVolume/masterMute as
1030 // parameter.
1031 //
1032 // If the HAL we are using has support for master volume or master mute,
1033 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1034 // and the mute set to false).
1035 mMasterVolume = audioFlinger->masterVolume_l();
1036 mMasterMute = audioFlinger->masterMute_l();
1037 if (mOutput && mOutput->audioHwDev) {
1038 if (mOutput->audioHwDev->canSetMasterVolume()) {
1039 mMasterVolume = 1.0;
1040 }
1041
1042 if (mOutput->audioHwDev->canSetMasterMute()) {
1043 mMasterMute = false;
1044 }
1045 }
1046
1047 readOutputParameters();
1048
1049 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1050 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1051 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1052 stream = (audio_stream_type_t) (stream + 1)) {
1053 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1054 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1055 }
1056 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1057 // because mAudioFlinger doesn't have one to copy from
1058}
1059
1060AudioFlinger::PlaybackThread::~PlaybackThread()
1061{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001062 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001063 delete [] mAllocMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001064}
1065
1066void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1067{
1068 dumpInternals(fd, args);
1069 dumpTracks(fd, args);
1070 dumpEffectChains(fd, args);
1071}
1072
1073void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1074{
1075 const size_t SIZE = 256;
1076 char buffer[SIZE];
1077 String8 result;
1078
1079 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1080 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1081 const stream_type_t *st = &mStreamTypes[i];
1082 if (i > 0) {
1083 result.appendFormat(", ");
1084 }
1085 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1086 if (st->mute) {
1087 result.append("M");
1088 }
1089 }
1090 result.append("\n");
1091 write(fd, result.string(), result.length());
1092 result.clear();
1093
1094 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1095 result.append(buffer);
1096 Track::appendDumpHeader(result);
1097 for (size_t i = 0; i < mTracks.size(); ++i) {
1098 sp<Track> track = mTracks[i];
1099 if (track != 0) {
1100 track->dump(buffer, SIZE);
1101 result.append(buffer);
1102 }
1103 }
1104
1105 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1106 result.append(buffer);
1107 Track::appendDumpHeader(result);
1108 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1109 sp<Track> track = mActiveTracks[i].promote();
1110 if (track != 0) {
1111 track->dump(buffer, SIZE);
1112 result.append(buffer);
1113 }
1114 }
1115 write(fd, result.string(), result.size());
1116
1117 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1118 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1119 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1120 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1121}
1122
1123void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1124{
1125 const size_t SIZE = 256;
1126 char buffer[SIZE];
1127 String8 result;
1128
1129 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1130 result.append(buffer);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001131 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1132 result.append(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001133 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1134 ns2ms(systemTime() - mLastWriteTime));
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1137 result.append(buffer);
1138 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1139 result.append(buffer);
1140 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1141 result.append(buffer);
1142 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1143 result.append(buffer);
1144 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1145 result.append(buffer);
1146 write(fd, result.string(), result.size());
1147 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1148
1149 dumpBase(fd, args);
1150}
1151
1152// Thread virtuals
1153status_t AudioFlinger::PlaybackThread::readyToRun()
1154{
1155 status_t status = initCheck();
1156 if (status == NO_ERROR) {
1157 ALOGI("AudioFlinger's thread %p ready to run", this);
1158 } else {
1159 ALOGE("No working audio driver found.");
1160 }
1161 return status;
1162}
1163
1164void AudioFlinger::PlaybackThread::onFirstRef()
1165{
1166 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1167}
1168
1169// ThreadBase virtuals
1170void AudioFlinger::PlaybackThread::preExit()
1171{
1172 ALOGV(" preExit()");
1173 // FIXME this is using hard-coded strings but in the future, this functionality will be
1174 // converted to use audio HAL extensions required to support tunneling
1175 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1176}
1177
1178// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1179sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1180 const sp<AudioFlinger::Client>& client,
1181 audio_stream_type_t streamType,
1182 uint32_t sampleRate,
1183 audio_format_t format,
1184 audio_channel_mask_t channelMask,
1185 size_t frameCount,
1186 const sp<IMemory>& sharedBuffer,
1187 int sessionId,
1188 IAudioFlinger::track_flags_t *flags,
1189 pid_t tid,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001190 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001191 status_t *status)
1192{
1193 sp<Track> track;
1194 status_t lStatus;
1195
1196 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1197
1198 // client expresses a preference for FAST, but we get the final say
1199 if (*flags & IAudioFlinger::TRACK_FAST) {
1200 if (
1201 // not timed
1202 (!isTimed) &&
1203 // either of these use cases:
1204 (
1205 // use case 1: shared buffer with any frame count
1206 (
1207 (sharedBuffer != 0)
1208 ) ||
1209 // use case 2: callback handler and frame count is default or at least as large as HAL
1210 (
1211 (tid != -1) &&
1212 ((frameCount == 0) ||
1213 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1214 )
1215 ) &&
1216 // PCM data
1217 audio_is_linear_pcm(format) &&
1218 // mono or stereo
1219 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1220 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1221#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1222 // hardware sample rate
1223 (sampleRate == mSampleRate) &&
1224#endif
1225 // normal mixer has an associated fast mixer
1226 hasFastMixer() &&
1227 // there are sufficient fast track slots available
1228 (mFastTrackAvailMask != 0)
1229 // FIXME test that MixerThread for this fast track has a capable output HAL
1230 // FIXME add a permission test also?
1231 ) {
1232 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1233 if (frameCount == 0) {
1234 frameCount = mFrameCount * kFastTrackMultiplier;
1235 }
1236 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1237 frameCount, mFrameCount);
1238 } else {
1239 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1240 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1241 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1242 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1243 audio_is_linear_pcm(format),
1244 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1245 *flags &= ~IAudioFlinger::TRACK_FAST;
1246 // For compatibility with AudioTrack calculation, buffer depth is forced
1247 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1248 // This is probably too conservative, but legacy application code may depend on it.
1249 // If you change this calculation, also review the start threshold which is related.
1250 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1251 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1252 if (minBufCount < 2) {
1253 minBufCount = 2;
1254 }
1255 size_t minFrameCount = mNormalFrameCount * minBufCount;
1256 if (frameCount < minFrameCount) {
1257 frameCount = minFrameCount;
1258 }
1259 }
1260 }
1261
1262 if (mType == DIRECT) {
1263 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1264 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1265 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1266 "for output %p with format %d",
1267 sampleRate, format, channelMask, mOutput, mFormat);
1268 lStatus = BAD_VALUE;
1269 goto Exit;
1270 }
1271 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001272 } else if (mType == OFFLOAD) {
1273 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1274 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1275 "for output %p with format %d",
1276 sampleRate, format, channelMask, mOutput, mFormat);
1277 lStatus = BAD_VALUE;
1278 goto Exit;
1279 }
Eric Laurent81784c32012-11-19 14:55:58 -08001280 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001281 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1282 ALOGE("createTrack_l() Bad parameter: format %d \""
1283 "for output %p with format %d",
1284 format, mOutput, mFormat);
1285 lStatus = BAD_VALUE;
1286 goto Exit;
1287 }
Eric Laurent81784c32012-11-19 14:55:58 -08001288 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1289 if (sampleRate > mSampleRate*2) {
1290 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1291 lStatus = BAD_VALUE;
1292 goto Exit;
1293 }
1294 }
1295
1296 lStatus = initCheck();
1297 if (lStatus != NO_ERROR) {
1298 ALOGE("Audio driver not initialized.");
1299 goto Exit;
1300 }
1301
1302 { // scope for mLock
1303 Mutex::Autolock _l(mLock);
1304
1305 // all tracks in same audio session must share the same routing strategy otherwise
1306 // conflicts will happen when tracks are moved from one output to another by audio policy
1307 // manager
1308 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1309 for (size_t i = 0; i < mTracks.size(); ++i) {
1310 sp<Track> t = mTracks[i];
1311 if (t != 0 && !t->isOutputTrack()) {
1312 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1313 if (sessionId == t->sessionId() && strategy != actual) {
1314 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1315 strategy, actual);
1316 lStatus = BAD_VALUE;
1317 goto Exit;
1318 }
1319 }
1320 }
1321
1322 if (!isTimed) {
1323 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001324 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 } else {
1326 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001327 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 }
Haynes Mathew Georgee010f652013-12-13 15:40:13 -08001329
Eric Laurent81784c32012-11-19 14:55:58 -08001330 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1331 lStatus = NO_MEMORY;
Haynes Mathew Georgee010f652013-12-13 15:40:13 -08001332 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001333 goto Exit;
1334 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001335
Eric Laurent81784c32012-11-19 14:55:58 -08001336 mTracks.add(track);
1337
1338 sp<EffectChain> chain = getEffectChain_l(sessionId);
1339 if (chain != 0) {
1340 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1341 track->setMainBuffer(chain->inBuffer());
1342 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1343 chain->incTrackCnt();
1344 }
1345
1346 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1347 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1348 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1349 // so ask activity manager to do this on our behalf
1350 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1351 }
1352 }
1353
1354 lStatus = NO_ERROR;
1355
1356Exit:
1357 if (status) {
1358 *status = lStatus;
1359 }
1360 return track;
1361}
1362
1363uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1364{
1365 return latency;
1366}
1367
1368uint32_t AudioFlinger::PlaybackThread::latency() const
1369{
1370 Mutex::Autolock _l(mLock);
1371 return latency_l();
1372}
1373uint32_t AudioFlinger::PlaybackThread::latency_l() const
1374{
1375 if (initCheck() == NO_ERROR) {
1376 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1377 } else {
1378 return 0;
1379 }
1380}
1381
1382void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1383{
1384 Mutex::Autolock _l(mLock);
1385 // Don't apply master volume in SW if our HAL can do it for us.
1386 if (mOutput && mOutput->audioHwDev &&
1387 mOutput->audioHwDev->canSetMasterVolume()) {
1388 mMasterVolume = 1.0;
1389 } else {
1390 mMasterVolume = value;
1391 }
1392}
1393
1394void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1395{
1396 Mutex::Autolock _l(mLock);
1397 // Don't apply master mute in SW if our HAL can do it for us.
1398 if (mOutput && mOutput->audioHwDev &&
1399 mOutput->audioHwDev->canSetMasterMute()) {
1400 mMasterMute = false;
1401 } else {
1402 mMasterMute = muted;
1403 }
1404}
1405
1406void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1407{
1408 Mutex::Autolock _l(mLock);
1409 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001410 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001411}
1412
1413void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1414{
1415 Mutex::Autolock _l(mLock);
1416 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001417 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001418}
1419
1420float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1421{
1422 Mutex::Autolock _l(mLock);
1423 return mStreamTypes[stream].volume;
1424}
1425
1426// addTrack_l() must be called with ThreadBase::mLock held
1427status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1428{
1429 status_t status = ALREADY_EXISTS;
1430
1431 // set retry count for buffer fill
1432 track->mRetryCount = kMaxTrackStartupRetries;
1433 if (mActiveTracks.indexOf(track) < 0) {
1434 // the track is newly added, make sure it fills up all its
1435 // buffers before playing. This is to ensure the client will
1436 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001437 if (!track->isOutputTrack()) {
1438 TrackBase::track_state state = track->mState;
1439 mLock.unlock();
1440 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1441 mLock.lock();
1442 // abort track was stopped/paused while we released the lock
1443 if (state != track->mState) {
1444 if (status == NO_ERROR) {
1445 mLock.unlock();
1446 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1447 mLock.lock();
1448 }
1449 return INVALID_OPERATION;
1450 }
1451 // abort if start is rejected by audio policy manager
1452 if (status != NO_ERROR) {
1453 return PERMISSION_DENIED;
1454 }
1455#ifdef ADD_BATTERY_DATA
1456 // to track the speaker usage
1457 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1458#endif
1459 }
1460
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001461 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001462 track->mResetDone = false;
1463 track->mPresentationCompleteFrames = 0;
1464 mActiveTracks.add(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08001465 mWakeLockUids.add(track->uid());
1466 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001467 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001468 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1469 if (chain != 0) {
1470 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1471 track->sessionId());
1472 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001473 }
1474
1475 status = NO_ERROR;
1476 }
1477
Eric Laurentede6c3b2013-09-19 14:37:46 -07001478 ALOGV("signal playback thread");
1479 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001480
1481 return status;
1482}
1483
Eric Laurentbfb1b832013-01-07 09:53:42 -08001484bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001485{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001486 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001487 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001488 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1489 track->mState = TrackBase::STOPPED;
1490 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001491 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001492 } else if (track->isFastTrack() || track->isOffloaded()) {
1493 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001495
1496 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001497}
1498
1499void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1500{
1501 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1502 mTracks.remove(track);
1503 deleteTrackName_l(track->name());
1504 // redundant as track is about to be destroyed, for dumpsys only
1505 track->mName = -1;
1506 if (track->isFastTrack()) {
1507 int index = track->mFastIndex;
1508 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1509 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1510 mFastTrackAvailMask |= 1 << index;
1511 // redundant as track is about to be destroyed, for dumpsys only
1512 track->mFastIndex = -1;
1513 }
1514 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1515 if (chain != 0) {
1516 chain->decTrackCnt();
1517 }
1518}
1519
Eric Laurentede6c3b2013-09-19 14:37:46 -07001520void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001521{
1522 // Thread could be blocked waiting for async
1523 // so signal it to handle state changes immediately
1524 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1525 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1526 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001527 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001528}
1529
Eric Laurent81784c32012-11-19 14:55:58 -08001530String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1531{
Eric Laurent81784c32012-11-19 14:55:58 -08001532 Mutex::Autolock _l(mLock);
1533 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001534 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001535 }
1536
Glenn Kastend8ea6992013-07-16 14:17:15 -07001537 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1538 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001539 free(s);
1540 return out_s8;
1541}
1542
1543// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1544void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1545 AudioSystem::OutputDescriptor desc;
1546 void *param2 = NULL;
1547
1548 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1549 param);
1550
1551 switch (event) {
1552 case AudioSystem::OUTPUT_OPENED:
1553 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001554 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001555 desc.samplingRate = mSampleRate;
1556 desc.format = mFormat;
1557 desc.frameCount = mNormalFrameCount; // FIXME see
1558 // AudioFlinger::frameCount(audio_io_handle_t)
1559 desc.latency = latency();
1560 param2 = &desc;
1561 break;
1562
1563 case AudioSystem::STREAM_CONFIG_CHANGED:
1564 param2 = &param;
1565 case AudioSystem::OUTPUT_CLOSED:
1566 default:
1567 break;
1568 }
1569 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1570}
1571
Eric Laurentbfb1b832013-01-07 09:53:42 -08001572void AudioFlinger::PlaybackThread::writeCallback()
1573{
1574 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001575 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001576}
1577
1578void AudioFlinger::PlaybackThread::drainCallback()
1579{
1580 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001581 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001582}
1583
Eric Laurent3b4529e2013-09-05 18:09:19 -07001584void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001585{
1586 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001587 // reject out of sequence requests
1588 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1589 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001590 mWaitWorkCV.signal();
1591 }
1592}
1593
Eric Laurent3b4529e2013-09-05 18:09:19 -07001594void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001595{
1596 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001597 // reject out of sequence requests
1598 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1599 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001600 mWaitWorkCV.signal();
1601 }
1602}
1603
1604// static
1605int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1606 void *param,
1607 void *cookie)
1608{
1609 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1610 ALOGV("asyncCallback() event %d", event);
1611 switch (event) {
1612 case STREAM_CBK_EVENT_WRITE_READY:
1613 me->writeCallback();
1614 break;
1615 case STREAM_CBK_EVENT_DRAIN_READY:
1616 me->drainCallback();
1617 break;
1618 default:
1619 ALOGW("asyncCallback() unknown event %d", event);
1620 break;
1621 }
1622 return 0;
1623}
1624
Eric Laurent81784c32012-11-19 14:55:58 -08001625void AudioFlinger::PlaybackThread::readOutputParameters()
1626{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001627 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001628 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1629 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001630 if (!audio_is_output_channel(mChannelMask)) {
1631 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1632 }
1633 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1634 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1635 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1636 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001637 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001638 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001639 if (!audio_is_valid_format(mFormat)) {
1640 LOG_FATAL("HAL format %d not valid for output", mFormat);
1641 }
1642 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1643 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1644 mFormat);
1645 }
Eric Laurent81784c32012-11-19 14:55:58 -08001646 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1647 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1648 if (mFrameCount & 15) {
1649 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1650 mFrameCount);
1651 }
1652
Eric Laurentbfb1b832013-01-07 09:53:42 -08001653 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1654 (mOutput->stream->set_callback != NULL)) {
1655 if (mOutput->stream->set_callback(mOutput->stream,
1656 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1657 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001658 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001659 }
1660 }
1661
Eric Laurent81784c32012-11-19 14:55:58 -08001662 // Calculate size of normal mix buffer relative to the HAL output buffer size
1663 double multiplier = 1.0;
1664 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1665 kUseFastMixer == FastMixer_Dynamic)) {
1666 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1667 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1668 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1669 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1670 maxNormalFrameCount = maxNormalFrameCount & ~15;
1671 if (maxNormalFrameCount < minNormalFrameCount) {
1672 maxNormalFrameCount = minNormalFrameCount;
1673 }
1674 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1675 if (multiplier <= 1.0) {
1676 multiplier = 1.0;
1677 } else if (multiplier <= 2.0) {
1678 if (2 * mFrameCount <= maxNormalFrameCount) {
1679 multiplier = 2.0;
1680 } else {
1681 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1682 }
1683 } else {
1684 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1685 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1686 // track, but we sometimes have to do this to satisfy the maximum frame count
1687 // constraint)
1688 // FIXME this rounding up should not be done if no HAL SRC
1689 uint32_t truncMult = (uint32_t) multiplier;
1690 if ((truncMult & 1)) {
1691 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1692 ++truncMult;
1693 }
1694 }
1695 multiplier = (double) truncMult;
1696 }
1697 }
1698 mNormalFrameCount = multiplier * mFrameCount;
1699 // round up to nearest 16 frames to satisfy AudioMixer
1700 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1701 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1702 mNormalFrameCount);
1703
Eric Laurentbfb1b832013-01-07 09:53:42 -08001704 delete[] mAllocMixBuffer;
1705 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1706 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1707 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1708 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001709
1710 // force reconfiguration of effect chains and engines to take new buffer size and audio
1711 // parameters into account
1712 // Note that mLock is not held when readOutputParameters() is called from the constructor
1713 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1714 // matter.
1715 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1716 Vector< sp<EffectChain> > effectChains = mEffectChains;
1717 for (size_t i = 0; i < effectChains.size(); i ++) {
1718 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1719 }
1720}
1721
1722
1723status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1724{
1725 if (halFrames == NULL || dspFrames == NULL) {
1726 return BAD_VALUE;
1727 }
1728 Mutex::Autolock _l(mLock);
1729 if (initCheck() != NO_ERROR) {
1730 return INVALID_OPERATION;
1731 }
1732 size_t framesWritten = mBytesWritten / mFrameSize;
1733 *halFrames = framesWritten;
1734
1735 if (isSuspended()) {
1736 // return an estimation of rendered frames when the output is suspended
1737 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1738 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1739 return NO_ERROR;
1740 } else {
1741 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1742 }
1743}
1744
1745uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1746{
1747 Mutex::Autolock _l(mLock);
1748 uint32_t result = 0;
1749 if (getEffectChain_l(sessionId) != 0) {
1750 result = EFFECT_SESSION;
1751 }
1752
1753 for (size_t i = 0; i < mTracks.size(); ++i) {
1754 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001755 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001756 result |= TRACK_SESSION;
1757 break;
1758 }
1759 }
1760
1761 return result;
1762}
1763
1764uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1765{
1766 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1767 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1768 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1769 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1770 }
1771 for (size_t i = 0; i < mTracks.size(); i++) {
1772 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001773 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001774 return AudioSystem::getStrategyForStream(track->streamType());
1775 }
1776 }
1777 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1778}
1779
1780
1781AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1782{
1783 Mutex::Autolock _l(mLock);
1784 return mOutput;
1785}
1786
1787AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1788{
1789 Mutex::Autolock _l(mLock);
1790 AudioStreamOut *output = mOutput;
1791 mOutput = NULL;
1792 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1793 // must push a NULL and wait for ack
1794 mOutputSink.clear();
1795 mPipeSink.clear();
1796 mNormalSink.clear();
1797 return output;
1798}
1799
1800// this method must always be called either with ThreadBase mLock held or inside the thread loop
1801audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1802{
1803 if (mOutput == NULL) {
1804 return NULL;
1805 }
1806 return &mOutput->stream->common;
1807}
1808
1809uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1810{
1811 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1812}
1813
1814status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1815{
1816 if (!isValidSyncEvent(event)) {
1817 return BAD_VALUE;
1818 }
1819
1820 Mutex::Autolock _l(mLock);
1821
1822 for (size_t i = 0; i < mTracks.size(); ++i) {
1823 sp<Track> track = mTracks[i];
1824 if (event->triggerSession() == track->sessionId()) {
1825 (void) track->setSyncEvent(event);
1826 return NO_ERROR;
1827 }
1828 }
1829
1830 return NAME_NOT_FOUND;
1831}
1832
1833bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1834{
1835 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1836}
1837
1838void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1839 const Vector< sp<Track> >& tracksToRemove)
1840{
1841 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001842 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001843 for (size_t i = 0 ; i < count ; i++) {
1844 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001846 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001847#ifdef ADD_BATTERY_DATA
1848 // to track the speaker usage
1849 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1850#endif
1851 if (track->isTerminated()) {
1852 AudioSystem::releaseOutput(mId);
1853 }
Eric Laurent81784c32012-11-19 14:55:58 -08001854 }
1855 }
1856 }
Eric Laurent81784c32012-11-19 14:55:58 -08001857}
1858
1859void AudioFlinger::PlaybackThread::checkSilentMode_l()
1860{
1861 if (!mMasterMute) {
1862 char value[PROPERTY_VALUE_MAX];
1863 if (property_get("ro.audio.silent", value, "0") > 0) {
1864 char *endptr;
1865 unsigned long ul = strtoul(value, &endptr, 0);
1866 if (*endptr == '\0' && ul != 0) {
1867 ALOGD("Silence is golden");
1868 // The setprop command will not allow a property to be changed after
1869 // the first time it is set, so we don't have to worry about un-muting.
1870 setMasterMute_l(true);
1871 }
1872 }
1873 }
1874}
1875
1876// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001877ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001878{
1879 // FIXME rewrite to reduce number of system calls
1880 mLastWriteTime = systemTime();
1881 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001883
1884 // If an NBAIO sink is present, use it to write the normal mixer's submix
1885 if (mNormalSink != 0) {
1886#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001887 size_t count = mBytesRemaining >> mBitShift;
1888 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001889 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001890 // update the setpoint when AudioFlinger::mScreenState changes
1891 uint32_t screenState = AudioFlinger::mScreenState;
1892 if (screenState != mScreenState) {
1893 mScreenState = screenState;
1894 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1895 if (pipe != NULL) {
1896 pipe->setAvgFrames((mScreenState & 1) ?
1897 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1898 }
1899 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001900 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001901 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001902 if (framesWritten > 0) {
1903 bytesWritten = framesWritten << mBitShift;
1904 } else {
1905 bytesWritten = framesWritten;
1906 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001907 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001908 if (status == NO_ERROR) {
1909 size_t totalFramesWritten = mNormalSink->framesWritten();
1910 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1911 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1912 mLatchDValid = true;
1913 }
1914 }
Eric Laurent81784c32012-11-19 14:55:58 -08001915 // otherwise use the HAL / AudioStreamOut directly
1916 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001917 // Direct output and offload threads
1918 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1919 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001920 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1921 mWriteAckSequence += 2;
1922 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001923 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001924 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001925 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001926 // FIXME We should have an implementation of timestamps for direct output threads.
1927 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001928 bytesWritten = mOutput->stream->write(mOutput->stream,
1929 mMixBuffer + offset, mBytesRemaining);
1930 if (mUseAsyncWrite &&
1931 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1932 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001933 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001934 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001935 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001936 }
Eric Laurent81784c32012-11-19 14:55:58 -08001937 }
1938
Eric Laurent81784c32012-11-19 14:55:58 -08001939 mNumWrites++;
1940 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001941 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 return bytesWritten;
1943}
1944
1945void AudioFlinger::PlaybackThread::threadLoop_drain()
1946{
1947 if (mOutput->stream->drain) {
1948 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1949 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001950 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1951 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001953 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954 }
1955 mOutput->stream->drain(mOutput->stream,
1956 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1957 : AUDIO_DRAIN_ALL);
1958 }
1959}
1960
1961void AudioFlinger::PlaybackThread::threadLoop_exit()
1962{
1963 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001964}
1965
1966/*
1967The derived values that are cached:
1968 - mixBufferSize from frame count * frame size
1969 - activeSleepTime from activeSleepTimeUs()
1970 - idleSleepTime from idleSleepTimeUs()
1971 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1972 - maxPeriod from frame count and sample rate (MIXER only)
1973
1974The parameters that affect these derived values are:
1975 - frame count
1976 - frame size
1977 - sample rate
1978 - device type: A2DP or not
1979 - device latency
1980 - format: PCM or not
1981 - active sleep time
1982 - idle sleep time
1983*/
1984
1985void AudioFlinger::PlaybackThread::cacheParameters_l()
1986{
1987 mixBufferSize = mNormalFrameCount * mFrameSize;
1988 activeSleepTime = activeSleepTimeUs();
1989 idleSleepTime = idleSleepTimeUs();
1990}
1991
1992void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1993{
Glenn Kasten7c027242012-12-26 14:43:16 -08001994 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001995 this, streamType, mTracks.size());
1996 Mutex::Autolock _l(mLock);
1997
1998 size_t size = mTracks.size();
1999 for (size_t i = 0; i < size; i++) {
2000 sp<Track> t = mTracks[i];
2001 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002002 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002003 }
2004 }
2005}
2006
2007status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2008{
2009 int session = chain->sessionId();
2010 int16_t *buffer = mMixBuffer;
2011 bool ownsBuffer = false;
2012
2013 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2014 if (session > 0) {
2015 // Only one effect chain can be present in direct output thread and it uses
2016 // the mix buffer as input
2017 if (mType != DIRECT) {
2018 size_t numSamples = mNormalFrameCount * mChannelCount;
2019 buffer = new int16_t[numSamples];
2020 memset(buffer, 0, numSamples * sizeof(int16_t));
2021 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2022 ownsBuffer = true;
2023 }
2024
2025 // Attach all tracks with same session ID to this chain.
2026 for (size_t i = 0; i < mTracks.size(); ++i) {
2027 sp<Track> track = mTracks[i];
2028 if (session == track->sessionId()) {
2029 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2030 buffer);
2031 track->setMainBuffer(buffer);
2032 chain->incTrackCnt();
2033 }
2034 }
2035
2036 // indicate all active tracks in the chain
2037 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2038 sp<Track> track = mActiveTracks[i].promote();
2039 if (track == 0) {
2040 continue;
2041 }
2042 if (session == track->sessionId()) {
2043 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2044 chain->incActiveTrackCnt();
2045 }
2046 }
2047 }
2048
2049 chain->setInBuffer(buffer, ownsBuffer);
2050 chain->setOutBuffer(mMixBuffer);
2051 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2052 // chains list in order to be processed last as it contains output stage effects
2053 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2054 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2055 // after track specific effects and before output stage
2056 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2057 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2058 // Effect chain for other sessions are inserted at beginning of effect
2059 // chains list to be processed before output mix effects. Relative order between other
2060 // sessions is not important
2061 size_t size = mEffectChains.size();
2062 size_t i = 0;
2063 for (i = 0; i < size; i++) {
2064 if (mEffectChains[i]->sessionId() < session) {
2065 break;
2066 }
2067 }
2068 mEffectChains.insertAt(chain, i);
2069 checkSuspendOnAddEffectChain_l(chain);
2070
2071 return NO_ERROR;
2072}
2073
2074size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2075{
2076 int session = chain->sessionId();
2077
2078 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2079
2080 for (size_t i = 0; i < mEffectChains.size(); i++) {
2081 if (chain == mEffectChains[i]) {
2082 mEffectChains.removeAt(i);
2083 // detach all active tracks from the chain
2084 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2085 sp<Track> track = mActiveTracks[i].promote();
2086 if (track == 0) {
2087 continue;
2088 }
2089 if (session == track->sessionId()) {
2090 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2091 chain.get(), session);
2092 chain->decActiveTrackCnt();
2093 }
2094 }
2095
2096 // detach all tracks with same session ID from this chain
2097 for (size_t i = 0; i < mTracks.size(); ++i) {
2098 sp<Track> track = mTracks[i];
2099 if (session == track->sessionId()) {
2100 track->setMainBuffer(mMixBuffer);
2101 chain->decTrackCnt();
2102 }
2103 }
2104 break;
2105 }
2106 }
2107 return mEffectChains.size();
2108}
2109
2110status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2111 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2112{
2113 Mutex::Autolock _l(mLock);
2114 return attachAuxEffect_l(track, EffectId);
2115}
2116
2117status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2118 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2119{
2120 status_t status = NO_ERROR;
2121
2122 if (EffectId == 0) {
2123 track->setAuxBuffer(0, NULL);
2124 } else {
2125 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2126 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2127 if (effect != 0) {
2128 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2129 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2130 } else {
2131 status = INVALID_OPERATION;
2132 }
2133 } else {
2134 status = BAD_VALUE;
2135 }
2136 }
2137 return status;
2138}
2139
2140void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2141{
2142 for (size_t i = 0; i < mTracks.size(); ++i) {
2143 sp<Track> track = mTracks[i];
2144 if (track->auxEffectId() == effectId) {
2145 attachAuxEffect_l(track, 0);
2146 }
2147 }
2148}
2149
2150bool AudioFlinger::PlaybackThread::threadLoop()
2151{
2152 Vector< sp<Track> > tracksToRemove;
2153
2154 standbyTime = systemTime();
2155
2156 // MIXER
2157 nsecs_t lastWarning = 0;
2158
2159 // DUPLICATING
2160 // FIXME could this be made local to while loop?
2161 writeFrames = 0;
2162
Marco Nelissen9cae2172013-01-14 14:12:05 -08002163 int lastGeneration = 0;
2164
Eric Laurent81784c32012-11-19 14:55:58 -08002165 cacheParameters_l();
2166 sleepTime = idleSleepTime;
2167
2168 if (mType == MIXER) {
2169 sleepTimeShift = 0;
2170 }
2171
2172 CpuStats cpuStats;
2173 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2174
2175 acquireWakeLock();
2176
Glenn Kasten9e58b552013-01-18 15:09:48 -08002177 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2178 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2179 // and then that string will be logged at the next convenient opportunity.
2180 const char *logString = NULL;
2181
Eric Laurent664539d2013-09-23 18:24:31 -07002182 checkSilentMode_l();
2183
Eric Laurent81784c32012-11-19 14:55:58 -08002184 while (!exitPending())
2185 {
2186 cpuStats.sample(myName);
2187
2188 Vector< sp<EffectChain> > effectChains;
2189
2190 processConfigEvents();
2191
2192 { // scope for mLock
2193
2194 Mutex::Autolock _l(mLock);
2195
Glenn Kasten9e58b552013-01-18 15:09:48 -08002196 if (logString != NULL) {
2197 mNBLogWriter->logTimestamp();
2198 mNBLogWriter->log(logString);
2199 logString = NULL;
2200 }
2201
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002202 if (mLatchDValid) {
2203 mLatchQ = mLatchD;
2204 mLatchDValid = false;
2205 mLatchQValid = true;
2206 }
2207
Eric Laurent81784c32012-11-19 14:55:58 -08002208 if (checkForNewParameters_l()) {
2209 cacheParameters_l();
2210 }
2211
2212 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213 if (mSignalPending) {
2214 // A signal was raised while we were unlocked
2215 mSignalPending = false;
2216 } else if (waitingAsyncCallback_l()) {
2217 if (exitPending()) {
2218 break;
2219 }
2220 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002221 mWakeLockUids.clear();
2222 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002223 ALOGV("wait async completion");
2224 mWaitWorkCV.wait(mLock);
2225 ALOGV("async completion/wake");
2226 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002227 standbyTime = systemTime() + standbyDelay;
2228 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002229
2230 continue;
2231 }
2232 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002233 isSuspended()) {
2234 // put audio hardware into standby after short delay
2235 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002236
2237 threadLoop_standby();
2238
2239 mStandby = true;
2240 }
2241
2242 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2243 // we're about to wait, flush the binder command buffer
2244 IPCThreadState::self()->flushCommands();
2245
2246 clearOutputTracks();
2247
2248 if (exitPending()) {
2249 break;
2250 }
2251
2252 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002253 mWakeLockUids.clear();
2254 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002255 // wait until we have something to do...
2256 ALOGV("%s going to sleep", myName.string());
2257 mWaitWorkCV.wait(mLock);
2258 ALOGV("%s waking up", myName.string());
2259 acquireWakeLock_l();
2260
2261 mMixerStatus = MIXER_IDLE;
2262 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2263 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002264 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002265 checkSilentMode_l();
2266
2267 standbyTime = systemTime() + standbyDelay;
2268 sleepTime = idleSleepTime;
2269 if (mType == MIXER) {
2270 sleepTimeShift = 0;
2271 }
2272
2273 continue;
2274 }
2275 }
Eric Laurent81784c32012-11-19 14:55:58 -08002276 // mMixerStatusIgnoringFastTracks is also updated internally
2277 mMixerStatus = prepareTracks_l(&tracksToRemove);
2278
Marco Nelissen9cae2172013-01-14 14:12:05 -08002279 // compare with previously applied list
2280 if (lastGeneration != mActiveTracksGeneration) {
2281 // update wakelock
2282 updateWakeLockUids_l(mWakeLockUids);
2283 lastGeneration = mActiveTracksGeneration;
2284 }
2285
Eric Laurent81784c32012-11-19 14:55:58 -08002286 // prevent any changes in effect chain list and in each effect chain
2287 // during mixing and effect process as the audio buffers could be deleted
2288 // or modified if an effect is created or deleted
2289 lockEffectChains_l(effectChains);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002290 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002291
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292 if (mBytesRemaining == 0) {
2293 mCurrentWriteLength = 0;
2294 if (mMixerStatus == MIXER_TRACKS_READY) {
2295 // threadLoop_mix() sets mCurrentWriteLength
2296 threadLoop_mix();
2297 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2298 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2299 // threadLoop_sleepTime sets sleepTime to 0 if data
2300 // must be written to HAL
2301 threadLoop_sleepTime();
2302 if (sleepTime == 0) {
2303 mCurrentWriteLength = mixBufferSize;
2304 }
2305 }
2306 mBytesRemaining = mCurrentWriteLength;
2307 if (isSuspended()) {
2308 sleepTime = suspendSleepTimeUs();
2309 // simulate write to HAL when suspended
2310 mBytesWritten += mixBufferSize;
2311 mBytesRemaining = 0;
2312 }
Eric Laurent81784c32012-11-19 14:55:58 -08002313
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002315 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316 for (size_t i = 0; i < effectChains.size(); i ++) {
2317 effectChains[i]->process_l();
2318 }
Eric Laurent81784c32012-11-19 14:55:58 -08002319 }
2320 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002321 // Process effect chains for offloaded thread even if no audio
2322 // was read from audio track: process only updates effect state
2323 // and thus does have to be synchronized with audio writes but may have
2324 // to be called while waiting for async write callback
2325 if (mType == OFFLOAD) {
2326 for (size_t i = 0; i < effectChains.size(); i ++) {
2327 effectChains[i]->process_l();
2328 }
2329 }
Eric Laurent81784c32012-11-19 14:55:58 -08002330
2331 // enable changes in effect chain
2332 unlockEffectChains(effectChains);
2333
Eric Laurentbfb1b832013-01-07 09:53:42 -08002334 if (!waitingAsyncCallback()) {
2335 // sleepTime == 0 means we must write to audio hardware
2336 if (sleepTime == 0) {
2337 if (mBytesRemaining) {
2338 ssize_t ret = threadLoop_write();
2339 if (ret < 0) {
2340 mBytesRemaining = 0;
2341 } else {
2342 mBytesWritten += ret;
2343 mBytesRemaining -= ret;
2344 }
2345 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2346 (mMixerStatus == MIXER_DRAIN_ALL)) {
2347 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002348 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002349if (mType == MIXER) {
2350 // write blocked detection
2351 nsecs_t now = systemTime();
2352 nsecs_t delta = now - mLastWriteTime;
2353 if (!mStandby && delta > maxPeriod) {
2354 mNumDelayedWrites++;
2355 if ((now - lastWarning) > kWarningThrottleNs) {
2356 ATRACE_NAME("underrun");
2357 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2358 ns2ms(delta), mNumDelayedWrites, this);
2359 lastWarning = now;
2360 }
2361 }
Eric Laurent81784c32012-11-19 14:55:58 -08002362}
2363
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 } else {
2365 usleep(sleepTime);
2366 }
Eric Laurent81784c32012-11-19 14:55:58 -08002367 }
2368
2369 // Finally let go of removed track(s), without the lock held
2370 // since we can't guarantee the destructors won't acquire that
2371 // same lock. This will also mutate and push a new fast mixer state.
2372 threadLoop_removeTracks(tracksToRemove);
2373 tracksToRemove.clear();
2374
2375 // FIXME I don't understand the need for this here;
2376 // it was in the original code but maybe the
2377 // assignment in saveOutputTracks() makes this unnecessary?
2378 clearOutputTracks();
2379
2380 // Effect chains will be actually deleted here if they were removed from
2381 // mEffectChains list during mixing or effects processing
2382 effectChains.clear();
2383
2384 // FIXME Note that the above .clear() is no longer necessary since effectChains
2385 // is now local to this block, but will keep it for now (at least until merge done).
2386 }
2387
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388 threadLoop_exit();
2389
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002391 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002392 // put output stream into standby mode
2393 if (!mStandby) {
2394 mOutput->stream->common.standby(&mOutput->stream->common);
2395 }
2396 }
2397
2398 releaseWakeLock();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002399 mWakeLockUids.clear();
2400 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002401
2402 ALOGV("Thread %p type %d exiting", this, mType);
2403 return false;
2404}
2405
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406// removeTracks_l() must be called with ThreadBase::mLock held
2407void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2408{
2409 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002410 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002411 for (size_t i=0 ; i<count ; i++) {
2412 const sp<Track>& track = tracksToRemove.itemAt(i);
2413 mActiveTracks.remove(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002414 mWakeLockUids.remove(track->uid());
2415 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002416 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2417 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2418 if (chain != 0) {
2419 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2420 track->sessionId());
2421 chain->decActiveTrackCnt();
2422 }
2423 if (track->isTerminated()) {
2424 removeTrack_l(track);
2425 }
2426 }
2427 }
2428
2429}
Eric Laurent81784c32012-11-19 14:55:58 -08002430
Eric Laurentaccc1472013-09-20 09:36:34 -07002431status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2432{
2433 if (mNormalSink != 0) {
2434 return mNormalSink->getTimestamp(timestamp);
2435 }
2436 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2437 uint64_t position64;
2438 int ret = mOutput->stream->get_presentation_position(
2439 mOutput->stream, &position64, &timestamp.mTime);
2440 if (ret == 0) {
2441 timestamp.mPosition = (uint32_t)position64;
2442 return NO_ERROR;
2443 }
2444 }
2445 return INVALID_OPERATION;
2446}
Eric Laurent81784c32012-11-19 14:55:58 -08002447// ----------------------------------------------------------------------------
2448
2449AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2450 audio_io_handle_t id, audio_devices_t device, type_t type)
2451 : PlaybackThread(audioFlinger, output, id, device, type),
2452 // mAudioMixer below
2453 // mFastMixer below
2454 mFastMixerFutex(0)
2455 // mOutputSink below
2456 // mPipeSink below
2457 // mNormalSink below
2458{
2459 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002460 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002461 "mFrameCount=%d, mNormalFrameCount=%d",
2462 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2463 mNormalFrameCount);
2464 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2465
2466 // FIXME - Current mixer implementation only supports stereo output
2467 if (mChannelCount != FCC_2) {
2468 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2469 }
2470
2471 // create an NBAIO sink for the HAL output stream, and negotiate
2472 mOutputSink = new AudioStreamOutSink(output->stream);
2473 size_t numCounterOffers = 0;
2474 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2475 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2476 ALOG_ASSERT(index == 0);
2477
2478 // initialize fast mixer depending on configuration
2479 bool initFastMixer;
2480 switch (kUseFastMixer) {
2481 case FastMixer_Never:
2482 initFastMixer = false;
2483 break;
2484 case FastMixer_Always:
2485 initFastMixer = true;
2486 break;
2487 case FastMixer_Static:
2488 case FastMixer_Dynamic:
2489 initFastMixer = mFrameCount < mNormalFrameCount;
2490 break;
2491 }
2492 if (initFastMixer) {
2493
2494 // create a MonoPipe to connect our submix to FastMixer
2495 NBAIO_Format format = mOutputSink->format();
2496 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2497 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2498 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2499 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2500 const NBAIO_Format offers[1] = {format};
2501 size_t numCounterOffers = 0;
2502 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2503 ALOG_ASSERT(index == 0);
2504 monoPipe->setAvgFrames((mScreenState & 1) ?
2505 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2506 mPipeSink = monoPipe;
2507
Glenn Kasten46909e72013-02-26 09:20:22 -08002508#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002509 if (mTeeSinkOutputEnabled) {
2510 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2511 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2512 numCounterOffers = 0;
2513 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2514 ALOG_ASSERT(index == 0);
2515 mTeeSink = teeSink;
2516 PipeReader *teeSource = new PipeReader(*teeSink);
2517 numCounterOffers = 0;
2518 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2519 ALOG_ASSERT(index == 0);
2520 mTeeSource = teeSource;
2521 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002522#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002523
2524 // create fast mixer and configure it initially with just one fast track for our submix
2525 mFastMixer = new FastMixer();
2526 FastMixerStateQueue *sq = mFastMixer->sq();
2527#ifdef STATE_QUEUE_DUMP
2528 sq->setObserverDump(&mStateQueueObserverDump);
2529 sq->setMutatorDump(&mStateQueueMutatorDump);
2530#endif
2531 FastMixerState *state = sq->begin();
2532 FastTrack *fastTrack = &state->mFastTracks[0];
2533 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2534 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2535 fastTrack->mVolumeProvider = NULL;
2536 fastTrack->mGeneration++;
2537 state->mFastTracksGen++;
2538 state->mTrackMask = 1;
2539 // fast mixer will use the HAL output sink
2540 state->mOutputSink = mOutputSink.get();
2541 state->mOutputSinkGen++;
2542 state->mFrameCount = mFrameCount;
2543 state->mCommand = FastMixerState::COLD_IDLE;
2544 // already done in constructor initialization list
2545 //mFastMixerFutex = 0;
2546 state->mColdFutexAddr = &mFastMixerFutex;
2547 state->mColdGen++;
2548 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002549#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002550 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002551#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002552 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2553 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002554 sq->end();
2555 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2556
2557 // start the fast mixer
2558 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2559 pid_t tid = mFastMixer->getTid();
2560 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2561 if (err != 0) {
2562 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2563 kPriorityFastMixer, getpid_cached, tid, err);
2564 }
2565
2566#ifdef AUDIO_WATCHDOG
2567 // create and start the watchdog
2568 mAudioWatchdog = new AudioWatchdog();
2569 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2570 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2571 tid = mAudioWatchdog->getTid();
2572 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2573 if (err != 0) {
2574 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2575 kPriorityFastMixer, getpid_cached, tid, err);
2576 }
2577#endif
2578
2579 } else {
2580 mFastMixer = NULL;
2581 }
2582
2583 switch (kUseFastMixer) {
2584 case FastMixer_Never:
2585 case FastMixer_Dynamic:
2586 mNormalSink = mOutputSink;
2587 break;
2588 case FastMixer_Always:
2589 mNormalSink = mPipeSink;
2590 break;
2591 case FastMixer_Static:
2592 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2593 break;
2594 }
2595}
2596
2597AudioFlinger::MixerThread::~MixerThread()
2598{
2599 if (mFastMixer != NULL) {
2600 FastMixerStateQueue *sq = mFastMixer->sq();
2601 FastMixerState *state = sq->begin();
2602 if (state->mCommand == FastMixerState::COLD_IDLE) {
2603 int32_t old = android_atomic_inc(&mFastMixerFutex);
2604 if (old == -1) {
2605 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2606 }
2607 }
2608 state->mCommand = FastMixerState::EXIT;
2609 sq->end();
2610 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2611 mFastMixer->join();
2612 // Though the fast mixer thread has exited, it's state queue is still valid.
2613 // We'll use that extract the final state which contains one remaining fast track
2614 // corresponding to our sub-mix.
2615 state = sq->begin();
2616 ALOG_ASSERT(state->mTrackMask == 1);
2617 FastTrack *fastTrack = &state->mFastTracks[0];
2618 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2619 delete fastTrack->mBufferProvider;
2620 sq->end(false /*didModify*/);
2621 delete mFastMixer;
2622#ifdef AUDIO_WATCHDOG
2623 if (mAudioWatchdog != 0) {
2624 mAudioWatchdog->requestExit();
2625 mAudioWatchdog->requestExitAndWait();
2626 mAudioWatchdog.clear();
2627 }
2628#endif
2629 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002630 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002631 delete mAudioMixer;
2632}
2633
2634
2635uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2636{
2637 if (mFastMixer != NULL) {
2638 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2639 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2640 }
2641 return latency;
2642}
2643
2644
2645void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2646{
2647 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2648}
2649
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002651{
2652 // FIXME we should only do one push per cycle; confirm this is true
2653 // Start the fast mixer if it's not already running
2654 if (mFastMixer != NULL) {
2655 FastMixerStateQueue *sq = mFastMixer->sq();
2656 FastMixerState *state = sq->begin();
2657 if (state->mCommand != FastMixerState::MIX_WRITE &&
2658 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2659 if (state->mCommand == FastMixerState::COLD_IDLE) {
2660 int32_t old = android_atomic_inc(&mFastMixerFutex);
2661 if (old == -1) {
2662 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2663 }
2664#ifdef AUDIO_WATCHDOG
2665 if (mAudioWatchdog != 0) {
2666 mAudioWatchdog->resume();
2667 }
2668#endif
2669 }
2670 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002671 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2672 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002673 sq->end();
2674 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2675 if (kUseFastMixer == FastMixer_Dynamic) {
2676 mNormalSink = mPipeSink;
2677 }
2678 } else {
2679 sq->end(false /*didModify*/);
2680 }
2681 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002683}
2684
2685void AudioFlinger::MixerThread::threadLoop_standby()
2686{
2687 // Idle the fast mixer if it's currently running
2688 if (mFastMixer != NULL) {
2689 FastMixerStateQueue *sq = mFastMixer->sq();
2690 FastMixerState *state = sq->begin();
2691 if (!(state->mCommand & FastMixerState::IDLE)) {
2692 state->mCommand = FastMixerState::COLD_IDLE;
2693 state->mColdFutexAddr = &mFastMixerFutex;
2694 state->mColdGen++;
2695 mFastMixerFutex = 0;
2696 sq->end();
2697 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2698 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2699 if (kUseFastMixer == FastMixer_Dynamic) {
2700 mNormalSink = mOutputSink;
2701 }
2702#ifdef AUDIO_WATCHDOG
2703 if (mAudioWatchdog != 0) {
2704 mAudioWatchdog->pause();
2705 }
2706#endif
2707 } else {
2708 sq->end(false /*didModify*/);
2709 }
2710 }
2711 PlaybackThread::threadLoop_standby();
2712}
2713
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714// Empty implementation for standard mixer
2715// Overridden for offloaded playback
2716void AudioFlinger::PlaybackThread::flushOutput_l()
2717{
2718}
2719
2720bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2721{
2722 return false;
2723}
2724
2725bool AudioFlinger::PlaybackThread::shouldStandby_l()
2726{
2727 return !mStandby;
2728}
2729
2730bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2731{
2732 Mutex::Autolock _l(mLock);
2733 return waitingAsyncCallback_l();
2734}
2735
Eric Laurent81784c32012-11-19 14:55:58 -08002736// shared by MIXER and DIRECT, overridden by DUPLICATING
2737void AudioFlinger::PlaybackThread::threadLoop_standby()
2738{
2739 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2740 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002741 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002742 // discard any pending drain or write ack by incrementing sequence
2743 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2744 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002745 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002746 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2747 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748 }
Eric Laurent81784c32012-11-19 14:55:58 -08002749}
2750
2751void AudioFlinger::MixerThread::threadLoop_mix()
2752{
2753 // obtain the presentation timestamp of the next output buffer
2754 int64_t pts;
2755 status_t status = INVALID_OPERATION;
2756
2757 if (mNormalSink != 0) {
2758 status = mNormalSink->getNextWriteTimestamp(&pts);
2759 } else {
2760 status = mOutputSink->getNextWriteTimestamp(&pts);
2761 }
2762
2763 if (status != NO_ERROR) {
2764 pts = AudioBufferProvider::kInvalidPTS;
2765 }
2766
2767 // mix buffers...
2768 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002770 // increase sleep time progressively when application underrun condition clears.
2771 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2772 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2773 // such that we would underrun the audio HAL.
2774 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2775 sleepTimeShift--;
2776 }
2777 sleepTime = 0;
2778 standbyTime = systemTime() + standbyDelay;
2779 //TODO: delay standby when effects have a tail
2780}
2781
2782void AudioFlinger::MixerThread::threadLoop_sleepTime()
2783{
2784 // If no tracks are ready, sleep once for the duration of an output
2785 // buffer size, then write 0s to the output
2786 if (sleepTime == 0) {
2787 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2788 sleepTime = activeSleepTime >> sleepTimeShift;
2789 if (sleepTime < kMinThreadSleepTimeUs) {
2790 sleepTime = kMinThreadSleepTimeUs;
2791 }
2792 // reduce sleep time in case of consecutive application underruns to avoid
2793 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2794 // duration we would end up writing less data than needed by the audio HAL if
2795 // the condition persists.
2796 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2797 sleepTimeShift++;
2798 }
2799 } else {
2800 sleepTime = idleSleepTime;
2801 }
2802 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2803 memset (mMixBuffer, 0, mixBufferSize);
2804 sleepTime = 0;
2805 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2806 "anticipated start");
2807 }
2808 // TODO add standby time extension fct of effect tail
2809}
2810
2811// prepareTracks_l() must be called with ThreadBase::mLock held
2812AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2813 Vector< sp<Track> > *tracksToRemove)
2814{
2815
2816 mixer_state mixerStatus = MIXER_IDLE;
2817 // find out which tracks need to be processed
2818 size_t count = mActiveTracks.size();
2819 size_t mixedTracks = 0;
2820 size_t tracksWithEffect = 0;
2821 // counts only _active_ fast tracks
2822 size_t fastTracks = 0;
2823 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2824
2825 float masterVolume = mMasterVolume;
2826 bool masterMute = mMasterMute;
2827
2828 if (masterMute) {
2829 masterVolume = 0;
2830 }
2831 // Delegate master volume control to effect in output mix effect chain if needed
2832 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2833 if (chain != 0) {
2834 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2835 chain->setVolume_l(&v, &v);
2836 masterVolume = (float)((v + (1 << 23)) >> 24);
2837 chain.clear();
2838 }
2839
2840 // prepare a new state to push
2841 FastMixerStateQueue *sq = NULL;
2842 FastMixerState *state = NULL;
2843 bool didModify = false;
2844 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2845 if (mFastMixer != NULL) {
2846 sq = mFastMixer->sq();
2847 state = sq->begin();
2848 }
2849
2850 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002851 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002852 if (t == 0) {
2853 continue;
2854 }
2855
2856 // this const just means the local variable doesn't change
2857 Track* const track = t.get();
2858
2859 // process fast tracks
2860 if (track->isFastTrack()) {
2861
2862 // It's theoretically possible (though unlikely) for a fast track to be created
2863 // and then removed within the same normal mix cycle. This is not a problem, as
2864 // the track never becomes active so it's fast mixer slot is never touched.
2865 // The converse, of removing an (active) track and then creating a new track
2866 // at the identical fast mixer slot within the same normal mix cycle,
2867 // is impossible because the slot isn't marked available until the end of each cycle.
2868 int j = track->mFastIndex;
2869 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2870 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2871 FastTrack *fastTrack = &state->mFastTracks[j];
2872
2873 // Determine whether the track is currently in underrun condition,
2874 // and whether it had a recent underrun.
2875 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2876 FastTrackUnderruns underruns = ftDump->mUnderruns;
2877 uint32_t recentFull = (underruns.mBitFields.mFull -
2878 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2879 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2880 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2881 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2882 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2883 uint32_t recentUnderruns = recentPartial + recentEmpty;
2884 track->mObservedUnderruns = underruns;
2885 // don't count underruns that occur while stopping or pausing
2886 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002887 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2888 recentUnderruns > 0) {
2889 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2890 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002891 }
2892
2893 // This is similar to the state machine for normal tracks,
2894 // with a few modifications for fast tracks.
2895 bool isActive = true;
2896 switch (track->mState) {
2897 case TrackBase::STOPPING_1:
2898 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002900 track->mState = TrackBase::STOPPING_2;
2901 }
2902 break;
2903 case TrackBase::PAUSING:
2904 // ramp down is not yet implemented
2905 track->setPaused();
2906 break;
2907 case TrackBase::RESUMING:
2908 // ramp up is not yet implemented
2909 track->mState = TrackBase::ACTIVE;
2910 break;
2911 case TrackBase::ACTIVE:
2912 if (recentFull > 0 || recentPartial > 0) {
2913 // track has provided at least some frames recently: reset retry count
2914 track->mRetryCount = kMaxTrackRetries;
2915 }
2916 if (recentUnderruns == 0) {
2917 // no recent underruns: stay active
2918 break;
2919 }
2920 // there has recently been an underrun of some kind
2921 if (track->sharedBuffer() == 0) {
2922 // were any of the recent underruns "empty" (no frames available)?
2923 if (recentEmpty == 0) {
2924 // no, then ignore the partial underruns as they are allowed indefinitely
2925 break;
2926 }
2927 // there has recently been an "empty" underrun: decrement the retry counter
2928 if (--(track->mRetryCount) > 0) {
2929 break;
2930 }
2931 // indicate to client process that the track was disabled because of underrun;
2932 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002933 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002934 // remove from active list, but state remains ACTIVE [confusing but true]
2935 isActive = false;
2936 break;
2937 }
2938 // fall through
2939 case TrackBase::STOPPING_2:
2940 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002941 case TrackBase::STOPPED:
2942 case TrackBase::FLUSHED: // flush() while active
2943 // Check for presentation complete if track is inactive
2944 // We have consumed all the buffers of this track.
2945 // This would be incomplete if we auto-paused on underrun
2946 {
2947 size_t audioHALFrames =
2948 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2949 size_t framesWritten = mBytesWritten / mFrameSize;
2950 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2951 // track stays in active list until presentation is complete
2952 break;
2953 }
2954 }
2955 if (track->isStopping_2()) {
2956 track->mState = TrackBase::STOPPED;
2957 }
2958 if (track->isStopped()) {
2959 // Can't reset directly, as fast mixer is still polling this track
2960 // track->reset();
2961 // So instead mark this track as needing to be reset after push with ack
2962 resetMask |= 1 << i;
2963 }
2964 isActive = false;
2965 break;
2966 case TrackBase::IDLE:
2967 default:
2968 LOG_FATAL("unexpected track state %d", track->mState);
2969 }
2970
2971 if (isActive) {
2972 // was it previously inactive?
2973 if (!(state->mTrackMask & (1 << j))) {
2974 ExtendedAudioBufferProvider *eabp = track;
2975 VolumeProvider *vp = track;
2976 fastTrack->mBufferProvider = eabp;
2977 fastTrack->mVolumeProvider = vp;
2978 fastTrack->mSampleRate = track->mSampleRate;
2979 fastTrack->mChannelMask = track->mChannelMask;
2980 fastTrack->mGeneration++;
2981 state->mTrackMask |= 1 << j;
2982 didModify = true;
2983 // no acknowledgement required for newly active tracks
2984 }
2985 // cache the combined master volume and stream type volume for fast mixer; this
2986 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002987 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002988 ++fastTracks;
2989 } else {
2990 // was it previously active?
2991 if (state->mTrackMask & (1 << j)) {
2992 fastTrack->mBufferProvider = NULL;
2993 fastTrack->mGeneration++;
2994 state->mTrackMask &= ~(1 << j);
2995 didModify = true;
2996 // If any fast tracks were removed, we must wait for acknowledgement
2997 // because we're about to decrement the last sp<> on those tracks.
2998 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2999 } else {
3000 LOG_FATAL("fast track %d should have been active", j);
3001 }
3002 tracksToRemove->add(track);
3003 // Avoids a misleading display in dumpsys
3004 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3005 }
3006 continue;
3007 }
3008
3009 { // local variable scope to avoid goto warning
3010
3011 audio_track_cblk_t* cblk = track->cblk();
3012
3013 // The first time a track is added we wait
3014 // for all its buffers to be filled before processing it
3015 int name = track->name();
3016 // make sure that we have enough frames to mix one full buffer.
3017 // enforce this condition only once to enable draining the buffer in case the client
3018 // app does not call stop() and relies on underrun to stop:
3019 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3020 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003021 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003022 uint32_t sr = track->sampleRate();
3023 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003024 desiredFrames = mNormalFrameCount;
3025 } else {
3026 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003027 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003028 // add frames already consumed but not yet released by the resampler
3029 // because cblk->framesReady() will include these frames
3030 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3031 // the minimum track buffer size is normally twice the number of frames necessary
3032 // to fill one buffer and the resampler should not leave more than one buffer worth
3033 // of unreleased frames after each pass, but just in case...
3034 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3035 }
Eric Laurent81784c32012-11-19 14:55:58 -08003036 uint32_t minFrames = 1;
3037 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3038 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003039 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003040 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003041 // It's not safe to call framesReady() for a static buffer track, so assume it's ready
3042 size_t framesReady;
3043 if (track->sharedBuffer() == 0) {
3044 framesReady = track->framesReady();
3045 } else if (track->isStopped()) {
3046 framesReady = 0;
3047 } else {
3048 framesReady = 1;
3049 }
3050 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003051 !track->isPaused() && !track->isTerminated())
3052 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003053 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003054
3055 mixedTracks++;
3056
3057 // track->mainBuffer() != mMixBuffer means there is an effect chain
3058 // connected to the track
3059 chain.clear();
3060 if (track->mainBuffer() != mMixBuffer) {
3061 chain = getEffectChain_l(track->sessionId());
3062 // Delegate volume control to effect in track effect chain if needed
3063 if (chain != 0) {
3064 tracksWithEffect++;
3065 } else {
3066 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3067 "session %d",
3068 name, track->sessionId());
3069 }
3070 }
3071
3072
3073 int param = AudioMixer::VOLUME;
3074 if (track->mFillingUpStatus == Track::FS_FILLED) {
3075 // no ramp for the first volume setting
3076 track->mFillingUpStatus = Track::FS_ACTIVE;
3077 if (track->mState == TrackBase::RESUMING) {
3078 track->mState = TrackBase::ACTIVE;
3079 param = AudioMixer::RAMP_VOLUME;
3080 }
3081 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003082 // FIXME should not make a decision based on mServer
3083 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003084 // If the track is stopped before the first frame was mixed,
3085 // do not apply ramp
3086 param = AudioMixer::RAMP_VOLUME;
3087 }
3088
3089 // compute volume for this track
3090 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003091 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003092 vl = vr = va = 0;
3093 if (track->isPausing()) {
3094 track->setPaused();
3095 }
3096 } else {
3097
3098 // read original volumes with volume control
3099 float typeVolume = mStreamTypes[track->streamType()].volume;
3100 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003101 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003102 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003103 vl = vlr & 0xFFFF;
3104 vr = vlr >> 16;
3105 // track volumes come from shared memory, so can't be trusted and must be clamped
3106 if (vl > MAX_GAIN_INT) {
3107 ALOGV("Track left volume out of range: %04X", vl);
3108 vl = MAX_GAIN_INT;
3109 }
3110 if (vr > MAX_GAIN_INT) {
3111 ALOGV("Track right volume out of range: %04X", vr);
3112 vr = MAX_GAIN_INT;
3113 }
3114 // now apply the master volume and stream type volume
3115 vl = (uint32_t)(v * vl) << 12;
3116 vr = (uint32_t)(v * vr) << 12;
3117 // assuming master volume and stream type volume each go up to 1.0,
3118 // vl and vr are now in 8.24 format
3119
Glenn Kastene3aa6592012-12-04 12:22:46 -08003120 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003121 // send level comes from shared memory and so may be corrupt
3122 if (sendLevel > MAX_GAIN_INT) {
3123 ALOGV("Track send level out of range: %04X", sendLevel);
3124 sendLevel = MAX_GAIN_INT;
3125 }
3126 va = (uint32_t)(v * sendLevel);
3127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128
Eric Laurent81784c32012-11-19 14:55:58 -08003129 // Delegate volume control to effect in track effect chain if needed
3130 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3131 // Do not ramp volume if volume is controlled by effect
3132 param = AudioMixer::VOLUME;
3133 track->mHasVolumeController = true;
3134 } else {
3135 // force no volume ramp when volume controller was just disabled or removed
3136 // from effect chain to avoid volume spike
3137 if (track->mHasVolumeController) {
3138 param = AudioMixer::VOLUME;
3139 }
3140 track->mHasVolumeController = false;
3141 }
3142
3143 // Convert volumes from 8.24 to 4.12 format
3144 // This additional clamping is needed in case chain->setVolume_l() overshot
3145 vl = (vl + (1 << 11)) >> 12;
3146 if (vl > MAX_GAIN_INT) {
3147 vl = MAX_GAIN_INT;
3148 }
3149 vr = (vr + (1 << 11)) >> 12;
3150 if (vr > MAX_GAIN_INT) {
3151 vr = MAX_GAIN_INT;
3152 }
3153
3154 if (va > MAX_GAIN_INT) {
3155 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3156 }
3157
3158 // XXX: these things DON'T need to be done each time
3159 mAudioMixer->setBufferProvider(name, track);
3160 mAudioMixer->enable(name);
3161
3162 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3163 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3164 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3165 mAudioMixer->setParameter(
3166 name,
3167 AudioMixer::TRACK,
3168 AudioMixer::FORMAT, (void *)track->format());
3169 mAudioMixer->setParameter(
3170 name,
3171 AudioMixer::TRACK,
3172 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003173 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3174 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003175 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003176 if (reqSampleRate == 0) {
3177 reqSampleRate = mSampleRate;
3178 } else if (reqSampleRate > maxSampleRate) {
3179 reqSampleRate = maxSampleRate;
3180 }
Eric Laurent81784c32012-11-19 14:55:58 -08003181 mAudioMixer->setParameter(
3182 name,
3183 AudioMixer::RESAMPLE,
3184 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003185 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003186 mAudioMixer->setParameter(
3187 name,
3188 AudioMixer::TRACK,
3189 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3190 mAudioMixer->setParameter(
3191 name,
3192 AudioMixer::TRACK,
3193 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3194
3195 // reset retry count
3196 track->mRetryCount = kMaxTrackRetries;
3197
3198 // If one track is ready, set the mixer ready if:
3199 // - the mixer was not ready during previous round OR
3200 // - no other track is not ready
3201 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3202 mixerStatus != MIXER_TRACKS_ENABLED) {
3203 mixerStatus = MIXER_TRACKS_READY;
3204 }
3205 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003206 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003207 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003208 }
Eric Laurent81784c32012-11-19 14:55:58 -08003209 // clear effect chain input buffer if an active track underruns to avoid sending
3210 // previous audio buffer again to effects
3211 chain = getEffectChain_l(track->sessionId());
3212 if (chain != 0) {
3213 chain->clearInputBuffer();
3214 }
3215
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003216 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003217 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3218 track->isStopped() || track->isPaused()) {
3219 // We have consumed all the buffers of this track.
3220 // Remove it from the list of active tracks.
3221 // TODO: use actual buffer filling status instead of latency when available from
3222 // audio HAL
3223 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3224 size_t framesWritten = mBytesWritten / mFrameSize;
3225 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3226 if (track->isStopped()) {
3227 track->reset();
3228 }
3229 tracksToRemove->add(track);
3230 }
3231 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003232 // No buffers for this track. Give it a few chances to
3233 // fill a buffer, then remove it from active list.
3234 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003235 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003236 tracksToRemove->add(track);
3237 // indicate to client process that the track was disabled because of underrun;
3238 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003239 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003240 // If one track is not ready, mark the mixer also not ready if:
3241 // - the mixer was ready during previous round OR
3242 // - no other track is ready
3243 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3244 mixerStatus != MIXER_TRACKS_READY) {
3245 mixerStatus = MIXER_TRACKS_ENABLED;
3246 }
3247 }
3248 mAudioMixer->disable(name);
3249 }
3250
3251 } // local variable scope to avoid goto warning
3252track_is_ready: ;
3253
3254 }
3255
3256 // Push the new FastMixer state if necessary
3257 bool pauseAudioWatchdog = false;
3258 if (didModify) {
3259 state->mFastTracksGen++;
3260 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3261 if (kUseFastMixer == FastMixer_Dynamic &&
3262 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3263 state->mCommand = FastMixerState::COLD_IDLE;
3264 state->mColdFutexAddr = &mFastMixerFutex;
3265 state->mColdGen++;
3266 mFastMixerFutex = 0;
3267 if (kUseFastMixer == FastMixer_Dynamic) {
3268 mNormalSink = mOutputSink;
3269 }
3270 // If we go into cold idle, need to wait for acknowledgement
3271 // so that fast mixer stops doing I/O.
3272 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3273 pauseAudioWatchdog = true;
3274 }
Eric Laurent81784c32012-11-19 14:55:58 -08003275 }
3276 if (sq != NULL) {
3277 sq->end(didModify);
3278 sq->push(block);
3279 }
3280#ifdef AUDIO_WATCHDOG
3281 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3282 mAudioWatchdog->pause();
3283 }
3284#endif
3285
3286 // Now perform the deferred reset on fast tracks that have stopped
3287 while (resetMask != 0) {
3288 size_t i = __builtin_ctz(resetMask);
3289 ALOG_ASSERT(i < count);
3290 resetMask &= ~(1 << i);
3291 sp<Track> t = mActiveTracks[i].promote();
3292 if (t == 0) {
3293 continue;
3294 }
3295 Track* track = t.get();
3296 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3297 track->reset();
3298 }
3299
3300 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003301 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003302
3303 // mix buffer must be cleared if all tracks are connected to an
3304 // effect chain as in this case the mixer will not write to
3305 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3307 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003308 // FIXME as a performance optimization, should remember previous zero status
3309 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3310 }
3311
3312 // if any fast tracks, then status is ready
3313 mMixerStatusIgnoringFastTracks = mixerStatus;
3314 if (fastTracks > 0) {
3315 mixerStatus = MIXER_TRACKS_READY;
3316 }
3317 return mixerStatus;
3318}
3319
3320// getTrackName_l() must be called with ThreadBase::mLock held
3321int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3322{
3323 return mAudioMixer->getTrackName(channelMask, sessionId);
3324}
3325
3326// deleteTrackName_l() must be called with ThreadBase::mLock held
3327void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3328{
3329 ALOGV("remove track (%d) and delete from mixer", name);
3330 mAudioMixer->deleteTrackName(name);
3331}
3332
3333// checkForNewParameters_l() must be called with ThreadBase::mLock held
3334bool AudioFlinger::MixerThread::checkForNewParameters_l()
3335{
3336 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3337 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3338 bool reconfig = false;
3339
3340 while (!mNewParameters.isEmpty()) {
3341
3342 if (mFastMixer != NULL) {
3343 FastMixerStateQueue *sq = mFastMixer->sq();
3344 FastMixerState *state = sq->begin();
3345 if (!(state->mCommand & FastMixerState::IDLE)) {
3346 previousCommand = state->mCommand;
3347 state->mCommand = FastMixerState::HOT_IDLE;
3348 sq->end();
3349 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3350 } else {
3351 sq->end(false /*didModify*/);
3352 }
3353 }
3354
3355 status_t status = NO_ERROR;
3356 String8 keyValuePair = mNewParameters[0];
3357 AudioParameter param = AudioParameter(keyValuePair);
3358 int value;
3359
3360 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3361 reconfig = true;
3362 }
3363 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3364 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3365 status = BAD_VALUE;
3366 } else {
3367 reconfig = true;
3368 }
3369 }
3370 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003371 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003372 status = BAD_VALUE;
3373 } else {
3374 reconfig = true;
3375 }
3376 }
3377 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3378 // do not accept frame count changes if tracks are open as the track buffer
3379 // size depends on frame count and correct behavior would not be guaranteed
3380 // if frame count is changed after track creation
3381 if (!mTracks.isEmpty()) {
3382 status = INVALID_OPERATION;
3383 } else {
3384 reconfig = true;
3385 }
3386 }
3387 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3388#ifdef ADD_BATTERY_DATA
3389 // when changing the audio output device, call addBatteryData to notify
3390 // the change
3391 if (mOutDevice != value) {
3392 uint32_t params = 0;
3393 // check whether speaker is on
3394 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3395 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3396 }
3397
3398 audio_devices_t deviceWithoutSpeaker
3399 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3400 // check if any other device (except speaker) is on
3401 if (value & deviceWithoutSpeaker ) {
3402 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3403 }
3404
3405 if (params != 0) {
3406 addBatteryData(params);
3407 }
3408 }
3409#endif
3410
3411 // forward device change to effects that have requested to be
3412 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003413 if (value != AUDIO_DEVICE_NONE) {
3414 mOutDevice = value;
3415 for (size_t i = 0; i < mEffectChains.size(); i++) {
3416 mEffectChains[i]->setDevice_l(mOutDevice);
3417 }
Eric Laurent81784c32012-11-19 14:55:58 -08003418 }
3419 }
3420
3421 if (status == NO_ERROR) {
3422 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3423 keyValuePair.string());
3424 if (!mStandby && status == INVALID_OPERATION) {
3425 mOutput->stream->common.standby(&mOutput->stream->common);
3426 mStandby = true;
3427 mBytesWritten = 0;
3428 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3429 keyValuePair.string());
3430 }
3431 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003432 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003433 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003434 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3435 for (size_t i = 0; i < mTracks.size() ; i++) {
3436 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3437 if (name < 0) {
3438 break;
3439 }
3440 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003441 }
3442 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3443 }
3444 }
3445
3446 mNewParameters.removeAt(0);
3447
3448 mParamStatus = status;
3449 mParamCond.signal();
3450 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3451 // already timed out waiting for the status and will never signal the condition.
3452 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3453 }
3454
3455 if (!(previousCommand & FastMixerState::IDLE)) {
3456 ALOG_ASSERT(mFastMixer != NULL);
3457 FastMixerStateQueue *sq = mFastMixer->sq();
3458 FastMixerState *state = sq->begin();
3459 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3460 state->mCommand = previousCommand;
3461 sq->end();
3462 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3463 }
3464
3465 return reconfig;
3466}
3467
3468
3469void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3470{
3471 const size_t SIZE = 256;
3472 char buffer[SIZE];
3473 String8 result;
3474
3475 PlaybackThread::dumpInternals(fd, args);
3476
3477 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3478 result.append(buffer);
3479 write(fd, result.string(), result.size());
3480
3481 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003482 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 copy.dump(fd);
3484
3485#ifdef STATE_QUEUE_DUMP
3486 // Similar for state queue
3487 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3488 observerCopy.dump(fd);
3489 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3490 mutatorCopy.dump(fd);
3491#endif
3492
Glenn Kasten46909e72013-02-26 09:20:22 -08003493#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003494 // Write the tee output to a .wav file
3495 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003496#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003497
3498#ifdef AUDIO_WATCHDOG
3499 if (mAudioWatchdog != 0) {
3500 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3501 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3502 wdCopy.dump(fd);
3503 }
3504#endif
3505}
3506
3507uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3508{
3509 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3510}
3511
3512uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3513{
3514 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3515}
3516
3517void AudioFlinger::MixerThread::cacheParameters_l()
3518{
3519 PlaybackThread::cacheParameters_l();
3520
3521 // FIXME: Relaxed timing because of a certain device that can't meet latency
3522 // Should be reduced to 2x after the vendor fixes the driver issue
3523 // increase threshold again due to low power audio mode. The way this warning
3524 // threshold is calculated and its usefulness should be reconsidered anyway.
3525 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3526}
3527
3528// ----------------------------------------------------------------------------
3529
3530AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3531 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3532 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3533 // mLeftVolFloat, mRightVolFloat
3534{
3535}
3536
Eric Laurentbfb1b832013-01-07 09:53:42 -08003537AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3538 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3539 ThreadBase::type_t type)
3540 : PlaybackThread(audioFlinger, output, id, device, type)
3541 // mLeftVolFloat, mRightVolFloat
3542{
3543}
3544
Eric Laurent81784c32012-11-19 14:55:58 -08003545AudioFlinger::DirectOutputThread::~DirectOutputThread()
3546{
3547}
3548
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3550{
3551 audio_track_cblk_t* cblk = track->cblk();
3552 float left, right;
3553
3554 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3555 left = right = 0;
3556 } else {
3557 float typeVolume = mStreamTypes[track->streamType()].volume;
3558 float v = mMasterVolume * typeVolume;
3559 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3560 uint32_t vlr = proxy->getVolumeLR();
3561 float v_clamped = v * (vlr & 0xFFFF);
3562 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3563 left = v_clamped/MAX_GAIN;
3564 v_clamped = v * (vlr >> 16);
3565 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3566 right = v_clamped/MAX_GAIN;
3567 }
3568
3569 if (lastTrack) {
3570 if (left != mLeftVolFloat || right != mRightVolFloat) {
3571 mLeftVolFloat = left;
3572 mRightVolFloat = right;
3573
3574 // Convert volumes from float to 8.24
3575 uint32_t vl = (uint32_t)(left * (1 << 24));
3576 uint32_t vr = (uint32_t)(right * (1 << 24));
3577
3578 // Delegate volume control to effect in track effect chain if needed
3579 // only one effect chain can be present on DirectOutputThread, so if
3580 // there is one, the track is connected to it
3581 if (!mEffectChains.isEmpty()) {
3582 mEffectChains[0]->setVolume_l(&vl, &vr);
3583 left = (float)vl / (1 << 24);
3584 right = (float)vr / (1 << 24);
3585 }
3586 if (mOutput->stream->set_volume) {
3587 mOutput->stream->set_volume(mOutput->stream, left, right);
3588 }
3589 }
3590 }
3591}
3592
3593
Eric Laurent81784c32012-11-19 14:55:58 -08003594AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3595 Vector< sp<Track> > *tracksToRemove
3596)
3597{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003598 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003599 mixer_state mixerStatus = MIXER_IDLE;
3600
3601 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003602 for (size_t i = 0; i < count; i++) {
3603 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003604 // The track died recently
3605 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003606 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003607 }
3608
3609 Track* const track = t.get();
3610 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003611 // Only consider last track started for volume and mixer state control.
3612 // In theory an older track could underrun and restart after the new one starts
3613 // but as we only care about the transition phase between two tracks on a
3614 // direct output, it is not a problem to ignore the underrun case.
3615 sp<Track> l = mLatestActiveTrack.promote();
3616 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003617
3618 // The first time a track is added we wait
3619 // for all its buffers to be filled before processing it
3620 uint32_t minFrames;
3621 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3622 minFrames = mNormalFrameCount;
3623 } else {
3624 minFrames = 1;
3625 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626
Eric Laurent81784c32012-11-19 14:55:58 -08003627 if ((track->framesReady() >= minFrames) && track->isReady() &&
3628 !track->isPaused() && !track->isTerminated())
3629 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003630 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003631
3632 if (track->mFillingUpStatus == Track::FS_FILLED) {
3633 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003634 // make sure processVolume_l() will apply new volume even if 0
3635 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003636 if (track->mState == TrackBase::RESUMING) {
3637 track->mState = TrackBase::ACTIVE;
3638 }
3639 }
3640
3641 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003642 processVolume_l(track, last);
3643 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003644 // reset retry count
3645 track->mRetryCount = kMaxTrackRetriesDirect;
3646 mActiveTrack = t;
3647 mixerStatus = MIXER_TRACKS_READY;
3648 }
Eric Laurent81784c32012-11-19 14:55:58 -08003649 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003650 // clear effect chain input buffer if the last active track started underruns
3651 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003652 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003653 mEffectChains[0]->clearInputBuffer();
3654 }
3655
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003656 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003657 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3658 track->isStopped() || track->isPaused()) {
3659 // We have consumed all the buffers of this track.
3660 // Remove it from the list of active tracks.
3661 // TODO: implement behavior for compressed audio
3662 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3663 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003664 if (mStandby || !last ||
3665 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003666 if (track->isStopped()) {
3667 track->reset();
3668 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003669 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003670 }
3671 } else {
3672 // No buffers for this track. Give it a few chances to
3673 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003674 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003675 if (--(track->mRetryCount) <= 0) {
3676 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003677 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003678 // indicate to client process that the track was disabled because of underrun;
3679 // it will then automatically call start() when data is available
3680 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003682 mixerStatus = MIXER_TRACKS_ENABLED;
3683 }
3684 }
3685 }
3686 }
3687
Eric Laurent81784c32012-11-19 14:55:58 -08003688 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003689 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003690
3691 return mixerStatus;
3692}
3693
3694void AudioFlinger::DirectOutputThread::threadLoop_mix()
3695{
Eric Laurent81784c32012-11-19 14:55:58 -08003696 size_t frameCount = mFrameCount;
3697 int8_t *curBuf = (int8_t *)mMixBuffer;
3698 // output audio to hardware
3699 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003700 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003701 buffer.frameCount = frameCount;
3702 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003703 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003704 memset(curBuf, 0, frameCount * mFrameSize);
3705 break;
3706 }
3707 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3708 frameCount -= buffer.frameCount;
3709 curBuf += buffer.frameCount * mFrameSize;
3710 mActiveTrack->releaseBuffer(&buffer);
3711 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003712 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003713 sleepTime = 0;
3714 standbyTime = systemTime() + standbyDelay;
3715 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003716}
3717
3718void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3719{
3720 if (sleepTime == 0) {
3721 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3722 sleepTime = activeSleepTime;
3723 } else {
3724 sleepTime = idleSleepTime;
3725 }
3726 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3727 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3728 sleepTime = 0;
3729 }
3730}
3731
3732// getTrackName_l() must be called with ThreadBase::mLock held
3733int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3734 int sessionId)
3735{
3736 return 0;
3737}
3738
3739// deleteTrackName_l() must be called with ThreadBase::mLock held
3740void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3741{
3742}
3743
3744// checkForNewParameters_l() must be called with ThreadBase::mLock held
3745bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3746{
3747 bool reconfig = false;
3748
3749 while (!mNewParameters.isEmpty()) {
3750 status_t status = NO_ERROR;
3751 String8 keyValuePair = mNewParameters[0];
3752 AudioParameter param = AudioParameter(keyValuePair);
3753 int value;
3754
3755 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3756 // do not accept frame count changes if tracks are open as the track buffer
3757 // size depends on frame count and correct behavior would not be garantied
3758 // if frame count is changed after track creation
3759 if (!mTracks.isEmpty()) {
3760 status = INVALID_OPERATION;
3761 } else {
3762 reconfig = true;
3763 }
3764 }
3765 if (status == NO_ERROR) {
3766 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3767 keyValuePair.string());
3768 if (!mStandby && status == INVALID_OPERATION) {
3769 mOutput->stream->common.standby(&mOutput->stream->common);
3770 mStandby = true;
3771 mBytesWritten = 0;
3772 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3773 keyValuePair.string());
3774 }
3775 if (status == NO_ERROR && reconfig) {
3776 readOutputParameters();
3777 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3778 }
3779 }
3780
3781 mNewParameters.removeAt(0);
3782
3783 mParamStatus = status;
3784 mParamCond.signal();
3785 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3786 // already timed out waiting for the status and will never signal the condition.
3787 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3788 }
3789 return reconfig;
3790}
3791
3792uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3793{
3794 uint32_t time;
3795 if (audio_is_linear_pcm(mFormat)) {
3796 time = PlaybackThread::activeSleepTimeUs();
3797 } else {
3798 time = 10000;
3799 }
3800 return time;
3801}
3802
3803uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3804{
3805 uint32_t time;
3806 if (audio_is_linear_pcm(mFormat)) {
3807 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3808 } else {
3809 time = 10000;
3810 }
3811 return time;
3812}
3813
3814uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3815{
3816 uint32_t time;
3817 if (audio_is_linear_pcm(mFormat)) {
3818 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3819 } else {
3820 time = 10000;
3821 }
3822 return time;
3823}
3824
3825void AudioFlinger::DirectOutputThread::cacheParameters_l()
3826{
3827 PlaybackThread::cacheParameters_l();
3828
3829 // use shorter standby delay as on normal output to release
3830 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003831 if (audio_is_linear_pcm(mFormat)) {
3832 standbyDelay = microseconds(activeSleepTime*2);
3833 } else {
3834 standbyDelay = kOffloadStandbyDelayNs;
3835 }
Eric Laurent81784c32012-11-19 14:55:58 -08003836}
3837
3838// ----------------------------------------------------------------------------
3839
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003841 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003842 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003843 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003844 mWriteAckSequence(0),
3845 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003846{
3847}
3848
3849AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3850{
3851}
3852
3853void AudioFlinger::AsyncCallbackThread::onFirstRef()
3854{
3855 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3856}
3857
3858bool AudioFlinger::AsyncCallbackThread::threadLoop()
3859{
3860 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003861 uint32_t writeAckSequence;
3862 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003863
3864 {
3865 Mutex::Autolock _l(mLock);
Haynes Mathew George50c31572013-12-03 21:26:02 -08003866 while (!((mWriteAckSequence & 1) ||
3867 (mDrainSequence & 1) ||
3868 exitPending())) {
3869 mWaitWorkCV.wait(mLock);
3870 }
3871
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872 if (exitPending()) {
3873 break;
3874 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003875 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3876 mWriteAckSequence, mDrainSequence);
3877 writeAckSequence = mWriteAckSequence;
3878 mWriteAckSequence &= ~1;
3879 drainSequence = mDrainSequence;
3880 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003881 }
3882 {
Eric Laurent4de95592013-09-26 15:28:21 -07003883 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3884 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003885 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003886 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003887 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003888 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003889 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003890 }
3891 }
3892 }
3893 }
3894 return false;
3895}
3896
3897void AudioFlinger::AsyncCallbackThread::exit()
3898{
3899 ALOGV("AsyncCallbackThread::exit");
3900 Mutex::Autolock _l(mLock);
3901 requestExit();
3902 mWaitWorkCV.broadcast();
3903}
3904
Eric Laurent3b4529e2013-09-05 18:09:19 -07003905void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003906{
3907 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003908 // bit 0 is cleared
3909 mWriteAckSequence = sequence << 1;
3910}
3911
3912void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3913{
3914 Mutex::Autolock _l(mLock);
3915 // ignore unexpected callbacks
3916 if (mWriteAckSequence & 2) {
3917 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 mWaitWorkCV.signal();
3919 }
3920}
3921
Eric Laurent3b4529e2013-09-05 18:09:19 -07003922void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003923{
3924 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003925 // bit 0 is cleared
3926 mDrainSequence = sequence << 1;
3927}
3928
3929void AudioFlinger::AsyncCallbackThread::resetDraining()
3930{
3931 Mutex::Autolock _l(mLock);
3932 // ignore unexpected callbacks
3933 if (mDrainSequence & 2) {
3934 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003935 mWaitWorkCV.signal();
3936 }
3937}
3938
3939
3940// ----------------------------------------------------------------------------
3941AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3942 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3943 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3944 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003945 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003946 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003947{
Eric Laurentfd477972013-10-25 18:10:40 -07003948 //FIXME: mStandby should be set to true by ThreadBase constructor
3949 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003950}
3951
Eric Laurentbfb1b832013-01-07 09:53:42 -08003952void AudioFlinger::OffloadThread::threadLoop_exit()
3953{
3954 if (mFlushPending || mHwPaused) {
3955 // If a flush is pending or track was paused, just discard buffered data
3956 flushHw_l();
3957 } else {
3958 mMixerStatus = MIXER_DRAIN_ALL;
3959 threadLoop_drain();
3960 }
3961 mCallbackThread->exit();
3962 PlaybackThread::threadLoop_exit();
3963}
3964
3965AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3966 Vector< sp<Track> > *tracksToRemove
3967)
3968{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003969 size_t count = mActiveTracks.size();
3970
3971 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003972 bool doHwPause = false;
3973 bool doHwResume = false;
3974
Eric Laurentede6c3b2013-09-19 14:37:46 -07003975 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3976
Eric Laurentbfb1b832013-01-07 09:53:42 -08003977 // find out which tracks need to be processed
3978 for (size_t i = 0; i < count; i++) {
3979 sp<Track> t = mActiveTracks[i].promote();
3980 // The track died recently
3981 if (t == 0) {
3982 continue;
3983 }
3984 Track* const track = t.get();
3985 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003986 // Only consider last track started for volume and mixer state control.
3987 // In theory an older track could underrun and restart after the new one starts
3988 // but as we only care about the transition phase between two tracks on a
3989 // direct output, it is not a problem to ignore the underrun case.
3990 sp<Track> l = mLatestActiveTrack.promote();
3991 bool last = l.get() == track;
3992
Eric Laurentbfb1b832013-01-07 09:53:42 -08003993 if (track->isPausing()) {
3994 track->setPaused();
3995 if (last) {
3996 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003997 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003998 mHwPaused = true;
3999 }
4000 // If we were part way through writing the mixbuffer to
4001 // the HAL we must save this until we resume
4002 // BUG - this will be wrong if a different track is made active,
4003 // in that case we want to discard the pending data in the
4004 // mixbuffer and tell the client to present it again when the
4005 // track is resumed
4006 mPausedWriteLength = mCurrentWriteLength;
4007 mPausedBytesRemaining = mBytesRemaining;
4008 mBytesRemaining = 0; // stop writing
4009 }
4010 tracksToRemove->add(track);
4011 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004012 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004013 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004014 if (track->mFillingUpStatus == Track::FS_FILLED) {
4015 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004016 // make sure processVolume_l() will apply new volume even if 0
4017 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004018 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004019 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004020 if (last) {
4021 if (mPausedBytesRemaining) {
4022 // Need to continue write that was interrupted
4023 mCurrentWriteLength = mPausedWriteLength;
4024 mBytesRemaining = mPausedBytesRemaining;
4025 mPausedBytesRemaining = 0;
4026 }
4027 if (mHwPaused) {
4028 doHwResume = true;
4029 mHwPaused = false;
4030 // threadLoop_mix() will handle the case that we need to
4031 // resume an interrupted write
4032 }
4033 // enable write to audio HAL
4034 sleepTime = 0;
4035 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004036 }
4037 }
4038
4039 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004040 sp<Track> previousTrack = mPreviousTrack.promote();
4041 if (previousTrack != 0) {
4042 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004043 // Flush any data still being written from last track
4044 mBytesRemaining = 0;
4045 if (mPausedBytesRemaining) {
4046 // Last track was paused so we also need to flush saved
4047 // mixbuffer state and invalidate track so that it will
4048 // re-submit that unwritten data when it is next resumed
4049 mPausedBytesRemaining = 0;
4050 // Invalidate is a bit drastic - would be more efficient
4051 // to have a flag to tell client that some of the
4052 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004053 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004054 }
4055 // flush data already sent to the DSP if changing audio session as audio
4056 // comes from a different source. Also invalidate previous track to force a
4057 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004058 if (previousTrack->sessionId() != track->sessionId()) {
4059 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004060 mFlushPending = true;
4061 }
4062 }
4063 }
4064 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065 // reset retry count
4066 track->mRetryCount = kMaxTrackRetriesOffload;
4067 mActiveTrack = t;
4068 mixerStatus = MIXER_TRACKS_READY;
4069 }
4070 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004071 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004072 if (track->isStopping_1()) {
4073 // Hardware buffer can hold a large amount of audio so we must
4074 // wait for all current track's data to drain before we say
4075 // that the track is stopped.
4076 if (mBytesRemaining == 0) {
4077 // Only start draining when all data in mixbuffer
4078 // has been written
4079 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4080 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004081 // do not drain if no data was ever sent to HAL (mStandby == true)
4082 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004083 // do not modify drain sequence if we are already draining. This happens
4084 // when resuming from pause after drain.
4085 if ((mDrainSequence & 1) == 0) {
4086 sleepTime = 0;
4087 standbyTime = systemTime() + standbyDelay;
4088 mixerStatus = MIXER_DRAIN_TRACK;
4089 mDrainSequence += 2;
4090 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004091 if (mHwPaused) {
4092 // It is possible to move from PAUSED to STOPPING_1 without
4093 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004094 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004095 mHwPaused = false;
4096 }
4097 }
4098 }
4099 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004100 // Drain has completed or we are in standby, signal presentation complete
4101 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004102 track->mState = TrackBase::STOPPED;
4103 size_t audioHALFrames =
4104 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4105 size_t framesWritten =
4106 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4107 track->presentationComplete(framesWritten, audioHALFrames);
4108 track->reset();
4109 tracksToRemove->add(track);
4110 }
4111 } else {
4112 // No buffers for this track. Give it a few chances to
4113 // fill a buffer, then remove it from active list.
4114 if (--(track->mRetryCount) <= 0) {
4115 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4116 track->name());
4117 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004118 // indicate to client process that the track was disabled because of underrun;
4119 // it will then automatically call start() when data is available
4120 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121 } else if (last){
4122 mixerStatus = MIXER_TRACKS_ENABLED;
4123 }
4124 }
4125 }
4126 // compute volume for this track
4127 processVolume_l(track, last);
4128 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004129
Eric Laurentea0fade2013-10-04 16:23:48 -07004130 // make sure the pause/flush/resume sequence is executed in the right order.
4131 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4132 // before flush and then resume HW. This can happen in case of pause/flush/resume
4133 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004134 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004135 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004136 if (!doHwPause) {
4137 doHwResume = true;
4138 }
Eric Laurent972a1732013-09-04 09:42:59 -07004139 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004140 if (mFlushPending) {
4141 flushHw_l();
4142 mFlushPending = false;
4143 }
Eric Laurentfd477972013-10-25 18:10:40 -07004144 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004145 mOutput->stream->resume(mOutput->stream);
4146 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004147
Eric Laurentbfb1b832013-01-07 09:53:42 -08004148 // remove all the tracks that need to be...
4149 removeTracks_l(*tracksToRemove);
4150
4151 return mixerStatus;
4152}
4153
4154void AudioFlinger::OffloadThread::flushOutput_l()
4155{
4156 mFlushPending = true;
4157}
4158
4159// must be called with thread mutex locked
4160bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4161{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004162 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4163 mWriteAckSequence, mDrainSequence);
4164 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 return true;
4166 }
4167 return false;
4168}
4169
4170// must be called with thread mutex locked
4171bool AudioFlinger::OffloadThread::shouldStandby_l()
4172{
4173 bool TrackPaused = false;
4174
4175 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4176 // after a timeout and we will enter standby then.
4177 if (mTracks.size() > 0) {
4178 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4179 }
4180
4181 return !mStandby && !TrackPaused;
4182}
4183
4184
4185bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4186{
4187 Mutex::Autolock _l(mLock);
4188 return waitingAsyncCallback_l();
4189}
4190
4191void AudioFlinger::OffloadThread::flushHw_l()
4192{
4193 mOutput->stream->flush(mOutput->stream);
4194 // Flush anything still waiting in the mixbuffer
4195 mCurrentWriteLength = 0;
4196 mBytesRemaining = 0;
4197 mPausedWriteLength = 0;
4198 mPausedBytesRemaining = 0;
4199 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004200 // discard any pending drain or write ack by incrementing sequence
4201 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4202 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004203 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004204 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4205 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004206 }
4207}
4208
4209// ----------------------------------------------------------------------------
4210
Eric Laurent81784c32012-11-19 14:55:58 -08004211AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4212 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4213 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4214 DUPLICATING),
4215 mWaitTimeMs(UINT_MAX)
4216{
4217 addOutputTrack(mainThread);
4218}
4219
4220AudioFlinger::DuplicatingThread::~DuplicatingThread()
4221{
4222 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4223 mOutputTracks[i]->destroy();
4224 }
4225}
4226
4227void AudioFlinger::DuplicatingThread::threadLoop_mix()
4228{
4229 // mix buffers...
4230 if (outputsReady(outputTracks)) {
4231 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4232 } else {
4233 memset(mMixBuffer, 0, mixBufferSize);
4234 }
4235 sleepTime = 0;
4236 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004237 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004238 standbyTime = systemTime() + standbyDelay;
4239}
4240
4241void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4242{
4243 if (sleepTime == 0) {
4244 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4245 sleepTime = activeSleepTime;
4246 } else {
4247 sleepTime = idleSleepTime;
4248 }
4249 } else if (mBytesWritten != 0) {
4250 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4251 writeFrames = mNormalFrameCount;
4252 memset(mMixBuffer, 0, mixBufferSize);
4253 } else {
4254 // flush remaining overflow buffers in output tracks
4255 writeFrames = 0;
4256 }
4257 sleepTime = 0;
4258 }
4259}
4260
Eric Laurentbfb1b832013-01-07 09:53:42 -08004261ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004262{
4263 for (size_t i = 0; i < outputTracks.size(); i++) {
4264 outputTracks[i]->write(mMixBuffer, writeFrames);
4265 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004266 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004267 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004268}
4269
4270void AudioFlinger::DuplicatingThread::threadLoop_standby()
4271{
4272 // DuplicatingThread implements standby by stopping all tracks
4273 for (size_t i = 0; i < outputTracks.size(); i++) {
4274 outputTracks[i]->stop();
4275 }
4276}
4277
4278void AudioFlinger::DuplicatingThread::saveOutputTracks()
4279{
4280 outputTracks = mOutputTracks;
4281}
4282
4283void AudioFlinger::DuplicatingThread::clearOutputTracks()
4284{
4285 outputTracks.clear();
4286}
4287
4288void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4289{
4290 Mutex::Autolock _l(mLock);
4291 // FIXME explain this formula
4292 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4293 OutputTrack *outputTrack = new OutputTrack(thread,
4294 this,
4295 mSampleRate,
4296 mFormat,
4297 mChannelMask,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004298 frameCount,
4299 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004300 if (outputTrack->cblk() != NULL) {
4301 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4302 mOutputTracks.add(outputTrack);
4303 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4304 updateWaitTime_l();
4305 }
4306}
4307
4308void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4309{
4310 Mutex::Autolock _l(mLock);
4311 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4312 if (mOutputTracks[i]->thread() == thread) {
4313 mOutputTracks[i]->destroy();
4314 mOutputTracks.removeAt(i);
4315 updateWaitTime_l();
4316 return;
4317 }
4318 }
4319 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4320}
4321
4322// caller must hold mLock
4323void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4324{
4325 mWaitTimeMs = UINT_MAX;
4326 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4327 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4328 if (strong != 0) {
4329 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4330 if (waitTimeMs < mWaitTimeMs) {
4331 mWaitTimeMs = waitTimeMs;
4332 }
4333 }
4334 }
4335}
4336
4337
4338bool AudioFlinger::DuplicatingThread::outputsReady(
4339 const SortedVector< sp<OutputTrack> > &outputTracks)
4340{
4341 for (size_t i = 0; i < outputTracks.size(); i++) {
4342 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4343 if (thread == 0) {
4344 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4345 outputTracks[i].get());
4346 return false;
4347 }
4348 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4349 // see note at standby() declaration
4350 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4351 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4352 thread.get());
4353 return false;
4354 }
4355 }
4356 return true;
4357}
4358
4359uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4360{
4361 return (mWaitTimeMs * 1000) / 2;
4362}
4363
4364void AudioFlinger::DuplicatingThread::cacheParameters_l()
4365{
4366 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4367 updateWaitTime_l();
4368
4369 MixerThread::cacheParameters_l();
4370}
4371
4372// ----------------------------------------------------------------------------
4373// Record
4374// ----------------------------------------------------------------------------
4375
4376AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4377 AudioStreamIn *input,
4378 uint32_t sampleRate,
4379 audio_channel_mask_t channelMask,
4380 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004381 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004382 audio_devices_t inDevice
4383#ifdef TEE_SINK
4384 , const sp<NBAIO_Sink>& teeSink
4385#endif
4386 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004387 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004388 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004389 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004390 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004391 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004392 // mBytesRead is only meaningful while active, and so is cleared in start()
4393 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004394#ifdef TEE_SINK
4395 , mTeeSink(teeSink)
4396#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004397{
4398 snprintf(mName, kNameLength, "AudioIn_%X", id);
4399
4400 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004401}
4402
4403
4404AudioFlinger::RecordThread::~RecordThread()
4405{
4406 delete[] mRsmpInBuffer;
4407 delete mResampler;
4408 delete[] mRsmpOutBuffer;
4409}
4410
4411void AudioFlinger::RecordThread::onFirstRef()
4412{
4413 run(mName, PRIORITY_URGENT_AUDIO);
4414}
4415
4416status_t AudioFlinger::RecordThread::readyToRun()
4417{
4418 status_t status = initCheck();
4419 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4420 return status;
4421}
4422
4423bool AudioFlinger::RecordThread::threadLoop()
4424{
4425 AudioBufferProvider::Buffer buffer;
4426 sp<RecordTrack> activeTrack;
4427 Vector< sp<EffectChain> > effectChains;
4428
4429 nsecs_t lastWarning = 0;
4430
4431 inputStandBy();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004432 {
4433 Mutex::Autolock _l(mLock);
4434 activeTrack = mActiveTrack;
4435 acquireWakeLock_l(activeTrack != 0 ? activeTrack->uid() : -1);
4436 }
Eric Laurent81784c32012-11-19 14:55:58 -08004437
4438 // used to verify we've read at least once before evaluating how many bytes were read
4439 bool readOnce = false;
4440
4441 // start recording
4442 while (!exitPending()) {
4443
4444 processConfigEvents();
4445
4446 { // scope for mLock
4447 Mutex::Autolock _l(mLock);
4448 checkForNewParameters_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004449 if (mActiveTrack != 0 && activeTrack != mActiveTrack) {
4450 SortedVector<int> tmp;
4451 tmp.add(mActiveTrack->uid());
4452 updateWakeLockUids_l(tmp);
4453 }
4454 activeTrack = mActiveTrack;
Eric Laurent81784c32012-11-19 14:55:58 -08004455 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4456 standby();
4457
4458 if (exitPending()) {
4459 break;
4460 }
4461
4462 releaseWakeLock_l();
4463 ALOGV("RecordThread: loop stopping");
4464 // go to sleep
4465 mWaitWorkCV.wait(mLock);
4466 ALOGV("RecordThread: loop starting");
Marco Nelissen9cae2172013-01-14 14:12:05 -08004467 acquireWakeLock_l(mActiveTrack != 0 ? mActiveTrack->uid() : -1);
Eric Laurent81784c32012-11-19 14:55:58 -08004468 continue;
4469 }
4470 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 if (mActiveTrack->isTerminated()) {
4472 removeTrack_l(mActiveTrack);
4473 mActiveTrack.clear();
4474 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004475 standby();
4476 mActiveTrack.clear();
4477 mStartStopCond.broadcast();
4478 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4479 if (mReqChannelCount != mActiveTrack->channelCount()) {
4480 mActiveTrack.clear();
4481 mStartStopCond.broadcast();
4482 } else if (readOnce) {
4483 // record start succeeds only if first read from audio input
4484 // succeeds
4485 if (mBytesRead >= 0) {
4486 mActiveTrack->mState = TrackBase::ACTIVE;
4487 } else {
4488 mActiveTrack.clear();
4489 }
4490 mStartStopCond.broadcast();
4491 }
4492 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004493 }
4494 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004495
Eric Laurent81784c32012-11-19 14:55:58 -08004496 lockEffectChains_l(effectChains);
4497 }
4498
4499 if (mActiveTrack != 0) {
4500 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4501 mActiveTrack->mState != TrackBase::RESUMING) {
4502 unlockEffectChains(effectChains);
4503 usleep(kRecordThreadSleepUs);
4504 continue;
4505 }
4506 for (size_t i = 0; i < effectChains.size(); i ++) {
4507 effectChains[i]->process_l();
4508 }
4509
4510 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004511 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004512 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004513 readOnce = true;
4514 size_t framesOut = buffer.frameCount;
4515 if (mResampler == NULL) {
4516 // no resampling
4517 while (framesOut) {
4518 size_t framesIn = mFrameCount - mRsmpInIndex;
4519 if (framesIn) {
4520 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4521 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4522 mActiveTrack->mFrameSize;
4523 if (framesIn > framesOut)
4524 framesIn = framesOut;
4525 mRsmpInIndex += framesIn;
4526 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004527 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004528 memcpy(dst, src, framesIn * mFrameSize);
4529 } else {
4530 if (mChannelCount == 1) {
4531 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4532 (int16_t *)src, framesIn);
4533 } else {
4534 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4535 (int16_t *)src, framesIn);
4536 }
4537 }
4538 }
4539 if (framesOut && mFrameCount == mRsmpInIndex) {
4540 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004541 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004542 readInto = buffer.raw;
4543 framesOut = 0;
4544 } else {
4545 readInto = mRsmpInBuffer;
4546 mRsmpInIndex = 0;
4547 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004548 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004549 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004550 if (mBytesRead <= 0) {
4551 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4552 {
4553 ALOGE("Error reading audio input");
4554 // Force input into standby so that it tries to
4555 // recover at next read attempt
4556 inputStandBy();
4557 usleep(kRecordThreadSleepUs);
4558 }
4559 mRsmpInIndex = mFrameCount;
4560 framesOut = 0;
4561 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004562 }
4563#ifdef TEE_SINK
4564 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004565 (void) mTeeSink->write(readInto,
4566 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4567 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004568#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004569 }
4570 }
4571 } else {
4572 // resampling
4573
Glenn Kasten34af0262013-07-30 11:52:39 -07004574 // resampler accumulates, but we only have one source track
4575 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004576 // alter output frame count as if we were expecting stereo samples
4577 if (mChannelCount == 1 && mReqChannelCount == 1) {
4578 framesOut >>= 1;
4579 }
4580 mResampler->resample(mRsmpOutBuffer, framesOut,
4581 this /* AudioBufferProvider* */);
4582 // ditherAndClamp() works as long as all buffers returned by
4583 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4584 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004585 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004586 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4587 // the resampler always outputs stereo samples:
4588 // do post stereo to mono conversion
4589 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4590 framesOut);
4591 } else {
4592 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4593 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004594 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004595
4596 }
4597 if (mFramestoDrop == 0) {
4598 mActiveTrack->releaseBuffer(&buffer);
4599 } else {
4600 if (mFramestoDrop > 0) {
4601 mFramestoDrop -= buffer.frameCount;
4602 if (mFramestoDrop <= 0) {
4603 clearSyncStartEvent();
4604 }
4605 } else {
4606 mFramestoDrop += buffer.frameCount;
4607 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4608 mSyncStartEvent->isCancelled()) {
4609 ALOGW("Synced record %s, session %d, trigger session %d",
4610 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4611 mActiveTrack->sessionId(),
4612 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4613 clearSyncStartEvent();
4614 }
4615 }
4616 }
4617 mActiveTrack->clearOverflow();
4618 }
4619 // client isn't retrieving buffers fast enough
4620 else {
4621 if (!mActiveTrack->setOverflow()) {
4622 nsecs_t now = systemTime();
4623 if ((now - lastWarning) > kWarningThrottleNs) {
4624 ALOGW("RecordThread: buffer overflow");
4625 lastWarning = now;
4626 }
4627 }
4628 // Release the processor for a while before asking for a new buffer.
4629 // This will give the application more chance to read from the buffer and
4630 // clear the overflow.
4631 usleep(kRecordThreadSleepUs);
4632 }
4633 }
4634 // enable changes in effect chain
4635 unlockEffectChains(effectChains);
4636 effectChains.clear();
4637 }
4638
4639 standby();
4640
4641 {
4642 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004643 for (size_t i = 0; i < mTracks.size(); i++) {
4644 sp<RecordTrack> track = mTracks[i];
4645 track->invalidate();
4646 }
Eric Laurent81784c32012-11-19 14:55:58 -08004647 mActiveTrack.clear();
4648 mStartStopCond.broadcast();
4649 }
4650
4651 releaseWakeLock();
4652
4653 ALOGV("RecordThread %p exiting", this);
4654 return false;
4655}
4656
4657void AudioFlinger::RecordThread::standby()
4658{
4659 if (!mStandby) {
4660 inputStandBy();
4661 mStandby = true;
4662 }
4663}
4664
4665void AudioFlinger::RecordThread::inputStandBy()
4666{
4667 mInput->stream->common.standby(&mInput->stream->common);
4668}
4669
4670sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4671 const sp<AudioFlinger::Client>& client,
4672 uint32_t sampleRate,
4673 audio_format_t format,
4674 audio_channel_mask_t channelMask,
4675 size_t frameCount,
4676 int sessionId,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004677 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004678 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004679 pid_t tid,
4680 status_t *status)
4681{
4682 sp<RecordTrack> track;
4683 status_t lStatus;
4684
4685 lStatus = initCheck();
4686 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004687 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004688 goto Exit;
4689 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004690 // client expresses a preference for FAST, but we get the final say
4691 if (*flags & IAudioFlinger::TRACK_FAST) {
4692 if (
4693 // use case: callback handler and frame count is default or at least as large as HAL
4694 (
4695 (tid != -1) &&
4696 ((frameCount == 0) ||
4697 (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4698 ) &&
4699 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4700 // mono or stereo
4701 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4702 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4703 // hardware sample rate
4704 (sampleRate == mSampleRate) &&
4705 // record thread has an associated fast recorder
4706 hasFastRecorder()
4707 // FIXME test that RecordThread for this fast track has a capable output HAL
4708 // FIXME add a permission test also?
4709 ) {
4710 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4711 if (frameCount == 0) {
4712 frameCount = mFrameCount * kFastTrackMultiplier;
4713 }
4714 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4715 frameCount, mFrameCount);
4716 } else {
4717 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4718 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4719 "hasFastRecorder=%d tid=%d",
4720 frameCount, mFrameCount, format,
4721 audio_is_linear_pcm(format),
4722 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4723 *flags &= ~IAudioFlinger::TRACK_FAST;
4724 // For compatibility with AudioRecord calculation, buffer depth is forced
4725 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4726 // This is probably too conservative, but legacy application code may depend on it.
4727 // If you change this calculation, also review the start threshold which is related.
4728 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4729 size_t mNormalFrameCount = 2048; // FIXME
4730 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4731 if (minBufCount < 2) {
4732 minBufCount = 2;
4733 }
4734 size_t minFrameCount = mNormalFrameCount * minBufCount;
4735 if (frameCount < minFrameCount) {
4736 frameCount = minFrameCount;
4737 }
4738 }
4739 }
4740
Eric Laurent81784c32012-11-19 14:55:58 -08004741 // FIXME use flags and tid similar to createTrack_l()
4742
4743 { // scope for mLock
4744 Mutex::Autolock _l(mLock);
4745
4746 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004747 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004748
4749 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004750 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004751 lStatus = NO_MEMORY;
Haynes Mathew Georgee010f652013-12-13 15:40:13 -08004752 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08004753 goto Exit;
4754 }
4755 mTracks.add(track);
4756
4757 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4758 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4759 mAudioFlinger->btNrecIsOff();
4760 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4761 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004762
4763 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4764 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4765 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4766 // so ask activity manager to do this on our behalf
4767 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4768 }
Eric Laurent81784c32012-11-19 14:55:58 -08004769 }
4770 lStatus = NO_ERROR;
4771
4772Exit:
4773 if (status) {
4774 *status = lStatus;
4775 }
4776 return track;
4777}
4778
4779status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4780 AudioSystem::sync_event_t event,
4781 int triggerSession)
4782{
4783 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4784 sp<ThreadBase> strongMe = this;
4785 status_t status = NO_ERROR;
4786
4787 if (event == AudioSystem::SYNC_EVENT_NONE) {
4788 clearSyncStartEvent();
4789 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4790 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4791 triggerSession,
4792 recordTrack->sessionId(),
4793 syncStartEventCallback,
4794 this);
4795 // Sync event can be cancelled by the trigger session if the track is not in a
4796 // compatible state in which case we start record immediately
4797 if (mSyncStartEvent->isCancelled()) {
4798 clearSyncStartEvent();
4799 } else {
4800 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4801 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4802 }
4803 }
4804
4805 {
4806 AutoMutex lock(mLock);
4807 if (mActiveTrack != 0) {
4808 if (recordTrack != mActiveTrack.get()) {
4809 status = -EBUSY;
4810 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4811 mActiveTrack->mState = TrackBase::ACTIVE;
4812 }
4813 return status;
4814 }
4815
4816 recordTrack->mState = TrackBase::IDLE;
4817 mActiveTrack = recordTrack;
4818 mLock.unlock();
4819 status_t status = AudioSystem::startInput(mId);
4820 mLock.lock();
4821 if (status != NO_ERROR) {
4822 mActiveTrack.clear();
4823 clearSyncStartEvent();
4824 return status;
4825 }
4826 mRsmpInIndex = mFrameCount;
4827 mBytesRead = 0;
4828 if (mResampler != NULL) {
4829 mResampler->reset();
4830 }
4831 mActiveTrack->mState = TrackBase::RESUMING;
4832 // signal thread to start
4833 ALOGV("Signal record thread");
4834 mWaitWorkCV.broadcast();
4835 // do not wait for mStartStopCond if exiting
4836 if (exitPending()) {
4837 mActiveTrack.clear();
4838 status = INVALID_OPERATION;
4839 goto startError;
4840 }
4841 mStartStopCond.wait(mLock);
4842 if (mActiveTrack == 0) {
4843 ALOGV("Record failed to start");
4844 status = BAD_VALUE;
4845 goto startError;
4846 }
4847 ALOGV("Record started OK");
4848 return status;
4849 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004850
Eric Laurent81784c32012-11-19 14:55:58 -08004851startError:
4852 AudioSystem::stopInput(mId);
4853 clearSyncStartEvent();
4854 return status;
4855}
4856
4857void AudioFlinger::RecordThread::clearSyncStartEvent()
4858{
4859 if (mSyncStartEvent != 0) {
4860 mSyncStartEvent->cancel();
4861 }
4862 mSyncStartEvent.clear();
4863 mFramestoDrop = 0;
4864}
4865
4866void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4867{
4868 sp<SyncEvent> strongEvent = event.promote();
4869
4870 if (strongEvent != 0) {
4871 RecordThread *me = (RecordThread *)strongEvent->cookie();
4872 me->handleSyncStartEvent(strongEvent);
4873 }
4874}
4875
4876void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4877{
4878 if (event == mSyncStartEvent) {
4879 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4880 // from audio HAL
4881 mFramestoDrop = mFrameCount * 2;
4882 }
4883}
4884
Glenn Kastena8356f62013-07-25 14:37:52 -07004885bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004886 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004887 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004888 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4889 return false;
4890 }
4891 recordTrack->mState = TrackBase::PAUSING;
4892 // do not wait for mStartStopCond if exiting
4893 if (exitPending()) {
4894 return true;
4895 }
4896 mStartStopCond.wait(mLock);
4897 // if we have been restarted, recordTrack == mActiveTrack.get() here
4898 if (exitPending() || recordTrack != mActiveTrack.get()) {
4899 ALOGV("Record stopped OK");
4900 return true;
4901 }
4902 return false;
4903}
4904
4905bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4906{
4907 return false;
4908}
4909
4910status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4911{
4912#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4913 if (!isValidSyncEvent(event)) {
4914 return BAD_VALUE;
4915 }
4916
4917 int eventSession = event->triggerSession();
4918 status_t ret = NAME_NOT_FOUND;
4919
4920 Mutex::Autolock _l(mLock);
4921
4922 for (size_t i = 0; i < mTracks.size(); i++) {
4923 sp<RecordTrack> track = mTracks[i];
4924 if (eventSession == track->sessionId()) {
4925 (void) track->setSyncEvent(event);
4926 ret = NO_ERROR;
4927 }
4928 }
4929 return ret;
4930#else
4931 return BAD_VALUE;
4932#endif
4933}
4934
4935// destroyTrack_l() must be called with ThreadBase::mLock held
4936void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4937{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004938 track->terminate();
4939 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004940 // active tracks are removed by threadLoop()
4941 if (mActiveTrack != track) {
4942 removeTrack_l(track);
4943 }
4944}
4945
4946void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4947{
4948 mTracks.remove(track);
4949 // need anything related to effects here?
4950}
4951
4952void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4953{
4954 dumpInternals(fd, args);
4955 dumpTracks(fd, args);
4956 dumpEffectChains(fd, args);
4957}
4958
4959void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4960{
4961 const size_t SIZE = 256;
4962 char buffer[SIZE];
4963 String8 result;
4964
4965 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4966 result.append(buffer);
4967
4968 if (mActiveTrack != 0) {
4969 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4970 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004971 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004972 result.append(buffer);
4973 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4974 result.append(buffer);
4975 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4976 result.append(buffer);
4977 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4978 result.append(buffer);
4979 } else {
4980 result.append("No active record client\n");
4981 }
4982
4983 write(fd, result.string(), result.size());
4984
4985 dumpBase(fd, args);
4986}
4987
4988void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4989{
4990 const size_t SIZE = 256;
4991 char buffer[SIZE];
4992 String8 result;
4993
4994 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4995 result.append(buffer);
4996 RecordTrack::appendDumpHeader(result);
4997 for (size_t i = 0; i < mTracks.size(); ++i) {
4998 sp<RecordTrack> track = mTracks[i];
4999 if (track != 0) {
5000 track->dump(buffer, SIZE);
5001 result.append(buffer);
5002 }
5003 }
5004
5005 if (mActiveTrack != 0) {
5006 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5007 result.append(buffer);
5008 RecordTrack::appendDumpHeader(result);
5009 mActiveTrack->dump(buffer, SIZE);
5010 result.append(buffer);
5011
5012 }
5013 write(fd, result.string(), result.size());
5014}
5015
5016// AudioBufferProvider interface
5017status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5018{
5019 size_t framesReq = buffer->frameCount;
5020 size_t framesReady = mFrameCount - mRsmpInIndex;
5021 int channelCount;
5022
5023 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08005024 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005025 if (mBytesRead <= 0) {
5026 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5027 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5028 // Force input into standby so that it tries to
5029 // recover at next read attempt
5030 inputStandBy();
5031 usleep(kRecordThreadSleepUs);
5032 }
5033 buffer->raw = NULL;
5034 buffer->frameCount = 0;
5035 return NOT_ENOUGH_DATA;
5036 }
5037 mRsmpInIndex = 0;
5038 framesReady = mFrameCount;
5039 }
5040
5041 if (framesReq > framesReady) {
5042 framesReq = framesReady;
5043 }
5044
5045 if (mChannelCount == 1 && mReqChannelCount == 2) {
5046 channelCount = 1;
5047 } else {
5048 channelCount = 2;
5049 }
5050 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5051 buffer->frameCount = framesReq;
5052 return NO_ERROR;
5053}
5054
5055// AudioBufferProvider interface
5056void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5057{
5058 mRsmpInIndex += buffer->frameCount;
5059 buffer->frameCount = 0;
5060}
5061
5062bool AudioFlinger::RecordThread::checkForNewParameters_l()
5063{
5064 bool reconfig = false;
5065
5066 while (!mNewParameters.isEmpty()) {
5067 status_t status = NO_ERROR;
5068 String8 keyValuePair = mNewParameters[0];
5069 AudioParameter param = AudioParameter(keyValuePair);
5070 int value;
5071 audio_format_t reqFormat = mFormat;
5072 uint32_t reqSamplingRate = mReqSampleRate;
5073 uint32_t reqChannelCount = mReqChannelCount;
5074
5075 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5076 reqSamplingRate = value;
5077 reconfig = true;
5078 }
5079 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005080 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5081 status = BAD_VALUE;
5082 } else {
5083 reqFormat = (audio_format_t) value;
5084 reconfig = true;
5085 }
Eric Laurent81784c32012-11-19 14:55:58 -08005086 }
5087 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5088 reqChannelCount = popcount(value);
5089 reconfig = true;
5090 }
5091 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5092 // do not accept frame count changes if tracks are open as the track buffer
5093 // size depends on frame count and correct behavior would not be guaranteed
5094 // if frame count is changed after track creation
5095 if (mActiveTrack != 0) {
5096 status = INVALID_OPERATION;
5097 } else {
5098 reconfig = true;
5099 }
5100 }
5101 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5102 // forward device change to effects that have requested to be
5103 // aware of attached audio device.
5104 for (size_t i = 0; i < mEffectChains.size(); i++) {
5105 mEffectChains[i]->setDevice_l(value);
5106 }
5107
5108 // store input device and output device but do not forward output device to audio HAL.
5109 // Note that status is ignored by the caller for output device
5110 // (see AudioFlinger::setParameters()
5111 if (audio_is_output_devices(value)) {
5112 mOutDevice = value;
5113 status = BAD_VALUE;
5114 } else {
5115 mInDevice = value;
5116 // disable AEC and NS if the device is a BT SCO headset supporting those
5117 // pre processings
5118 if (mTracks.size() > 0) {
5119 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5120 mAudioFlinger->btNrecIsOff();
5121 for (size_t i = 0; i < mTracks.size(); i++) {
5122 sp<RecordTrack> track = mTracks[i];
5123 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5124 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5125 }
5126 }
5127 }
5128 }
5129 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5130 mAudioSource != (audio_source_t)value) {
5131 // forward device change to effects that have requested to be
5132 // aware of attached audio device.
5133 for (size_t i = 0; i < mEffectChains.size(); i++) {
5134 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5135 }
5136 mAudioSource = (audio_source_t)value;
5137 }
5138 if (status == NO_ERROR) {
5139 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5140 keyValuePair.string());
5141 if (status == INVALID_OPERATION) {
5142 inputStandBy();
5143 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5144 keyValuePair.string());
5145 }
5146 if (reconfig) {
5147 if (status == BAD_VALUE &&
5148 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5149 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005150 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005151 <= (2 * reqSamplingRate)) &&
5152 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5153 <= FCC_2 &&
5154 (reqChannelCount <= FCC_2)) {
5155 status = NO_ERROR;
5156 }
5157 if (status == NO_ERROR) {
5158 readInputParameters();
5159 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5160 }
5161 }
5162 }
5163
5164 mNewParameters.removeAt(0);
5165
5166 mParamStatus = status;
5167 mParamCond.signal();
5168 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5169 // already timed out waiting for the status and will never signal the condition.
5170 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5171 }
5172 return reconfig;
5173}
5174
5175String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5176{
Eric Laurent81784c32012-11-19 14:55:58 -08005177 Mutex::Autolock _l(mLock);
5178 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005179 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005180 }
5181
Glenn Kastend8ea6992013-07-16 14:17:15 -07005182 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5183 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005184 free(s);
5185 return out_s8;
5186}
5187
5188void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5189 AudioSystem::OutputDescriptor desc;
5190 void *param2 = NULL;
5191
5192 switch (event) {
5193 case AudioSystem::INPUT_OPENED:
5194 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005195 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005196 desc.samplingRate = mSampleRate;
5197 desc.format = mFormat;
5198 desc.frameCount = mFrameCount;
5199 desc.latency = 0;
5200 param2 = &desc;
5201 break;
5202
5203 case AudioSystem::INPUT_CLOSED:
5204 default:
5205 break;
5206 }
5207 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5208}
5209
5210void AudioFlinger::RecordThread::readInputParameters()
5211{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005212 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005213 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005214 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005215 mRsmpOutBuffer = NULL;
5216 delete mResampler;
5217 mResampler = NULL;
5218
5219 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5220 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005221 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005222 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005223 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5224 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5225 }
Eric Laurent81784c32012-11-19 14:55:58 -08005226 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005227 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5228 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005229 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5230
5231 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5232 {
5233 int channelCount;
5234 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5235 // stereo to mono post process as the resampler always outputs stereo.
5236 if (mChannelCount == 1 && mReqChannelCount == 2) {
5237 channelCount = 1;
5238 } else {
5239 channelCount = 2;
5240 }
5241 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5242 mResampler->setSampleRate(mSampleRate);
5243 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005244 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005245
5246 // optmization: if mono to mono, alter input frame count as if we were inputing
5247 // stereo samples
5248 if (mChannelCount == 1 && mReqChannelCount == 1) {
5249 mFrameCount >>= 1;
5250 }
5251
5252 }
5253 mRsmpInIndex = mFrameCount;
5254}
5255
5256unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5257{
5258 Mutex::Autolock _l(mLock);
5259 if (initCheck() != NO_ERROR) {
5260 return 0;
5261 }
5262
5263 return mInput->stream->get_input_frames_lost(mInput->stream);
5264}
5265
5266uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5267{
5268 Mutex::Autolock _l(mLock);
5269 uint32_t result = 0;
5270 if (getEffectChain_l(sessionId) != 0) {
5271 result = EFFECT_SESSION;
5272 }
5273
5274 for (size_t i = 0; i < mTracks.size(); ++i) {
5275 if (sessionId == mTracks[i]->sessionId()) {
5276 result |= TRACK_SESSION;
5277 break;
5278 }
5279 }
5280
5281 return result;
5282}
5283
5284KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5285{
5286 KeyedVector<int, bool> ids;
5287 Mutex::Autolock _l(mLock);
5288 for (size_t j = 0; j < mTracks.size(); ++j) {
5289 sp<RecordThread::RecordTrack> track = mTracks[j];
5290 int sessionId = track->sessionId();
5291 if (ids.indexOfKey(sessionId) < 0) {
5292 ids.add(sessionId, true);
5293 }
5294 }
5295 return ids;
5296}
5297
5298AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5299{
5300 Mutex::Autolock _l(mLock);
5301 AudioStreamIn *input = mInput;
5302 mInput = NULL;
5303 return input;
5304}
5305
5306// this method must always be called either with ThreadBase mLock held or inside the thread loop
5307audio_stream_t* AudioFlinger::RecordThread::stream() const
5308{
5309 if (mInput == NULL) {
5310 return NULL;
5311 }
5312 return &mInput->stream->common;
5313}
5314
5315status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5316{
5317 // only one chain per input thread
5318 if (mEffectChains.size() != 0) {
5319 return INVALID_OPERATION;
5320 }
5321 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5322
5323 chain->setInBuffer(NULL);
5324 chain->setOutBuffer(NULL);
5325
5326 checkSuspendOnAddEffectChain_l(chain);
5327
5328 mEffectChains.add(chain);
5329
5330 return NO_ERROR;
5331}
5332
5333size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5334{
5335 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5336 ALOGW_IF(mEffectChains.size() != 1,
5337 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5338 chain.get(), mEffectChains.size(), this);
5339 if (mEffectChains.size() == 1) {
5340 mEffectChains.removeAt(0);
5341 }
5342 return 0;
5343}
5344
5345}; // namespace android