blob: 072e5fd4b04ffe3d392e349f82eb68f3c7900d1e [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.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800138// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
139// So for now we just assume that client is double-buffered for fast tracks.
140// FIXME It would be better for client to tell AudioFlinger the value of N,
141// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800142// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800143static const int kFastTrackMultiplier = 2;
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) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001213 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001214 )
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) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001221 // hardware sample rate
1222 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001223 // normal mixer has an associated fast mixer
1224 hasFastMixer() &&
1225 // there are sufficient fast track slots available
1226 (mFastTrackAvailMask != 0)
1227 // FIXME test that MixerThread for this fast track has a capable output HAL
1228 // FIXME add a permission test also?
1229 ) {
1230 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1231 if (frameCount == 0) {
1232 frameCount = mFrameCount * kFastTrackMultiplier;
1233 }
1234 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1235 frameCount, mFrameCount);
1236 } else {
1237 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1238 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1239 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1240 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1241 audio_is_linear_pcm(format),
1242 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1243 *flags &= ~IAudioFlinger::TRACK_FAST;
1244 // For compatibility with AudioTrack calculation, buffer depth is forced
1245 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1246 // This is probably too conservative, but legacy application code may depend on it.
1247 // If you change this calculation, also review the start threshold which is related.
1248 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1249 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1250 if (minBufCount < 2) {
1251 minBufCount = 2;
1252 }
1253 size_t minFrameCount = mNormalFrameCount * minBufCount;
1254 if (frameCount < minFrameCount) {
1255 frameCount = minFrameCount;
1256 }
1257 }
1258 }
1259
1260 if (mType == DIRECT) {
1261 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1262 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1263 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1264 "for output %p with format %d",
1265 sampleRate, format, channelMask, mOutput, mFormat);
1266 lStatus = BAD_VALUE;
1267 goto Exit;
1268 }
1269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001270 } else if (mType == OFFLOAD) {
1271 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1272 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1273 "for output %p with format %d",
1274 sampleRate, format, channelMask, mOutput, mFormat);
1275 lStatus = BAD_VALUE;
1276 goto Exit;
1277 }
Eric Laurent81784c32012-11-19 14:55:58 -08001278 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001279 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1280 ALOGE("createTrack_l() Bad parameter: format %d \""
1281 "for output %p with format %d",
1282 format, mOutput, mFormat);
1283 lStatus = BAD_VALUE;
1284 goto Exit;
1285 }
Eric Laurent81784c32012-11-19 14:55:58 -08001286 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1287 if (sampleRate > mSampleRate*2) {
1288 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1289 lStatus = BAD_VALUE;
1290 goto Exit;
1291 }
1292 }
1293
1294 lStatus = initCheck();
1295 if (lStatus != NO_ERROR) {
1296 ALOGE("Audio driver not initialized.");
1297 goto Exit;
1298 }
1299
1300 { // scope for mLock
1301 Mutex::Autolock _l(mLock);
1302
1303 // all tracks in same audio session must share the same routing strategy otherwise
1304 // conflicts will happen when tracks are moved from one output to another by audio policy
1305 // manager
1306 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1307 for (size_t i = 0; i < mTracks.size(); ++i) {
1308 sp<Track> t = mTracks[i];
1309 if (t != 0 && !t->isOutputTrack()) {
1310 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1311 if (sessionId == t->sessionId() && strategy != actual) {
1312 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1313 strategy, actual);
1314 lStatus = BAD_VALUE;
1315 goto Exit;
1316 }
1317 }
1318 }
1319
1320 if (!isTimed) {
1321 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001322 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 } else {
1324 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen9cae2172013-01-14 14:12:05 -08001325 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001326 }
1327 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1328 lStatus = NO_MEMORY;
1329 goto Exit;
1330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 mTracks.add(track);
1333
1334 sp<EffectChain> chain = getEffectChain_l(sessionId);
1335 if (chain != 0) {
1336 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1337 track->setMainBuffer(chain->inBuffer());
1338 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1339 chain->incTrackCnt();
1340 }
1341
1342 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1343 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1344 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1345 // so ask activity manager to do this on our behalf
1346 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1347 }
1348 }
1349
1350 lStatus = NO_ERROR;
1351
1352Exit:
1353 if (status) {
1354 *status = lStatus;
1355 }
1356 return track;
1357}
1358
1359uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1360{
1361 return latency;
1362}
1363
1364uint32_t AudioFlinger::PlaybackThread::latency() const
1365{
1366 Mutex::Autolock _l(mLock);
1367 return latency_l();
1368}
1369uint32_t AudioFlinger::PlaybackThread::latency_l() const
1370{
1371 if (initCheck() == NO_ERROR) {
1372 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1373 } else {
1374 return 0;
1375 }
1376}
1377
1378void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1379{
1380 Mutex::Autolock _l(mLock);
1381 // Don't apply master volume in SW if our HAL can do it for us.
1382 if (mOutput && mOutput->audioHwDev &&
1383 mOutput->audioHwDev->canSetMasterVolume()) {
1384 mMasterVolume = 1.0;
1385 } else {
1386 mMasterVolume = value;
1387 }
1388}
1389
1390void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1391{
1392 Mutex::Autolock _l(mLock);
1393 // Don't apply master mute in SW if our HAL can do it for us.
1394 if (mOutput && mOutput->audioHwDev &&
1395 mOutput->audioHwDev->canSetMasterMute()) {
1396 mMasterMute = false;
1397 } else {
1398 mMasterMute = muted;
1399 }
1400}
1401
1402void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1403{
1404 Mutex::Autolock _l(mLock);
1405 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001406 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001407}
1408
1409void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1410{
1411 Mutex::Autolock _l(mLock);
1412 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001413 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001414}
1415
1416float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1417{
1418 Mutex::Autolock _l(mLock);
1419 return mStreamTypes[stream].volume;
1420}
1421
1422// addTrack_l() must be called with ThreadBase::mLock held
1423status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1424{
1425 status_t status = ALREADY_EXISTS;
1426
1427 // set retry count for buffer fill
1428 track->mRetryCount = kMaxTrackStartupRetries;
1429 if (mActiveTracks.indexOf(track) < 0) {
1430 // the track is newly added, make sure it fills up all its
1431 // buffers before playing. This is to ensure the client will
1432 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001433 if (!track->isOutputTrack()) {
1434 TrackBase::track_state state = track->mState;
1435 mLock.unlock();
1436 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1437 mLock.lock();
1438 // abort track was stopped/paused while we released the lock
1439 if (state != track->mState) {
1440 if (status == NO_ERROR) {
1441 mLock.unlock();
1442 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1443 mLock.lock();
1444 }
1445 return INVALID_OPERATION;
1446 }
1447 // abort if start is rejected by audio policy manager
1448 if (status != NO_ERROR) {
1449 return PERMISSION_DENIED;
1450 }
1451#ifdef ADD_BATTERY_DATA
1452 // to track the speaker usage
1453 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1454#endif
1455 }
1456
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001457 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001458 track->mResetDone = false;
1459 track->mPresentationCompleteFrames = 0;
1460 mActiveTracks.add(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08001461 mWakeLockUids.add(track->uid());
1462 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001463 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001464 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1465 if (chain != 0) {
1466 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1467 track->sessionId());
1468 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001469 }
1470
1471 status = NO_ERROR;
1472 }
1473
Eric Laurentede6c3b2013-09-19 14:37:46 -07001474 ALOGV("signal playback thread");
1475 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001476
1477 return status;
1478}
1479
Eric Laurentbfb1b832013-01-07 09:53:42 -08001480bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001481{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001482 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001483 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001484 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1485 track->mState = TrackBase::STOPPED;
1486 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001487 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001488 } else if (track->isFastTrack() || track->isOffloaded()) {
1489 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001490 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001491
1492 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001493}
1494
1495void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1496{
1497 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1498 mTracks.remove(track);
1499 deleteTrackName_l(track->name());
1500 // redundant as track is about to be destroyed, for dumpsys only
1501 track->mName = -1;
1502 if (track->isFastTrack()) {
1503 int index = track->mFastIndex;
1504 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1505 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1506 mFastTrackAvailMask |= 1 << index;
1507 // redundant as track is about to be destroyed, for dumpsys only
1508 track->mFastIndex = -1;
1509 }
1510 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1511 if (chain != 0) {
1512 chain->decTrackCnt();
1513 }
1514}
1515
Eric Laurentede6c3b2013-09-19 14:37:46 -07001516void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001517{
1518 // Thread could be blocked waiting for async
1519 // so signal it to handle state changes immediately
1520 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1521 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1522 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001523 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001524}
1525
Eric Laurent81784c32012-11-19 14:55:58 -08001526String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1527{
Eric Laurent81784c32012-11-19 14:55:58 -08001528 Mutex::Autolock _l(mLock);
1529 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001530 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001531 }
1532
Glenn Kastend8ea6992013-07-16 14:17:15 -07001533 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1534 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001535 free(s);
1536 return out_s8;
1537}
1538
1539// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1540void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1541 AudioSystem::OutputDescriptor desc;
1542 void *param2 = NULL;
1543
1544 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1545 param);
1546
1547 switch (event) {
1548 case AudioSystem::OUTPUT_OPENED:
1549 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001550 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001551 desc.samplingRate = mSampleRate;
1552 desc.format = mFormat;
1553 desc.frameCount = mNormalFrameCount; // FIXME see
1554 // AudioFlinger::frameCount(audio_io_handle_t)
1555 desc.latency = latency();
1556 param2 = &desc;
1557 break;
1558
1559 case AudioSystem::STREAM_CONFIG_CHANGED:
1560 param2 = &param;
1561 case AudioSystem::OUTPUT_CLOSED:
1562 default:
1563 break;
1564 }
1565 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1566}
1567
Eric Laurentbfb1b832013-01-07 09:53:42 -08001568void AudioFlinger::PlaybackThread::writeCallback()
1569{
1570 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001571 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001572}
1573
1574void AudioFlinger::PlaybackThread::drainCallback()
1575{
1576 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001577 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001578}
1579
Eric Laurent3b4529e2013-09-05 18:09:19 -07001580void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001581{
1582 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001583 // reject out of sequence requests
1584 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1585 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001586 mWaitWorkCV.signal();
1587 }
1588}
1589
Eric Laurent3b4529e2013-09-05 18:09:19 -07001590void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001591{
1592 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001593 // reject out of sequence requests
1594 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1595 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001596 mWaitWorkCV.signal();
1597 }
1598}
1599
1600// static
1601int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1602 void *param,
1603 void *cookie)
1604{
1605 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1606 ALOGV("asyncCallback() event %d", event);
1607 switch (event) {
1608 case STREAM_CBK_EVENT_WRITE_READY:
1609 me->writeCallback();
1610 break;
1611 case STREAM_CBK_EVENT_DRAIN_READY:
1612 me->drainCallback();
1613 break;
1614 default:
1615 ALOGW("asyncCallback() unknown event %d", event);
1616 break;
1617 }
1618 return 0;
1619}
1620
Eric Laurent81784c32012-11-19 14:55:58 -08001621void AudioFlinger::PlaybackThread::readOutputParameters()
1622{
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001623 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001624 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1625 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001626 if (!audio_is_output_channel(mChannelMask)) {
1627 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1628 }
1629 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1630 LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1631 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1632 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001633 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001634 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001635 if (!audio_is_valid_format(mFormat)) {
1636 LOG_FATAL("HAL format %d not valid for output", mFormat);
1637 }
1638 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1639 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1640 mFormat);
1641 }
Eric Laurent81784c32012-11-19 14:55:58 -08001642 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1643 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1644 if (mFrameCount & 15) {
1645 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1646 mFrameCount);
1647 }
1648
Eric Laurentbfb1b832013-01-07 09:53:42 -08001649 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1650 (mOutput->stream->set_callback != NULL)) {
1651 if (mOutput->stream->set_callback(mOutput->stream,
1652 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1653 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001654 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655 }
1656 }
1657
Eric Laurent81784c32012-11-19 14:55:58 -08001658 // Calculate size of normal mix buffer relative to the HAL output buffer size
1659 double multiplier = 1.0;
1660 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1661 kUseFastMixer == FastMixer_Dynamic)) {
1662 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1663 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1664 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1665 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1666 maxNormalFrameCount = maxNormalFrameCount & ~15;
1667 if (maxNormalFrameCount < minNormalFrameCount) {
1668 maxNormalFrameCount = minNormalFrameCount;
1669 }
1670 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1671 if (multiplier <= 1.0) {
1672 multiplier = 1.0;
1673 } else if (multiplier <= 2.0) {
1674 if (2 * mFrameCount <= maxNormalFrameCount) {
1675 multiplier = 2.0;
1676 } else {
1677 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1678 }
1679 } else {
1680 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1681 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1682 // track, but we sometimes have to do this to satisfy the maximum frame count
1683 // constraint)
1684 // FIXME this rounding up should not be done if no HAL SRC
1685 uint32_t truncMult = (uint32_t) multiplier;
1686 if ((truncMult & 1)) {
1687 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1688 ++truncMult;
1689 }
1690 }
1691 multiplier = (double) truncMult;
1692 }
1693 }
1694 mNormalFrameCount = multiplier * mFrameCount;
1695 // round up to nearest 16 frames to satisfy AudioMixer
1696 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1697 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1698 mNormalFrameCount);
1699
Eric Laurentbfb1b832013-01-07 09:53:42 -08001700 delete[] mAllocMixBuffer;
1701 size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1702 mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1703 mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1704 memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001705
1706 // force reconfiguration of effect chains and engines to take new buffer size and audio
1707 // parameters into account
1708 // Note that mLock is not held when readOutputParameters() is called from the constructor
1709 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1710 // matter.
1711 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1712 Vector< sp<EffectChain> > effectChains = mEffectChains;
1713 for (size_t i = 0; i < effectChains.size(); i ++) {
1714 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1715 }
1716}
1717
1718
1719status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1720{
1721 if (halFrames == NULL || dspFrames == NULL) {
1722 return BAD_VALUE;
1723 }
1724 Mutex::Autolock _l(mLock);
1725 if (initCheck() != NO_ERROR) {
1726 return INVALID_OPERATION;
1727 }
1728 size_t framesWritten = mBytesWritten / mFrameSize;
1729 *halFrames = framesWritten;
1730
1731 if (isSuspended()) {
1732 // return an estimation of rendered frames when the output is suspended
1733 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1734 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1735 return NO_ERROR;
1736 } else {
1737 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1738 }
1739}
1740
1741uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1742{
1743 Mutex::Autolock _l(mLock);
1744 uint32_t result = 0;
1745 if (getEffectChain_l(sessionId) != 0) {
1746 result = EFFECT_SESSION;
1747 }
1748
1749 for (size_t i = 0; i < mTracks.size(); ++i) {
1750 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001751 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001752 result |= TRACK_SESSION;
1753 break;
1754 }
1755 }
1756
1757 return result;
1758}
1759
1760uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1761{
1762 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1763 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1764 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1765 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1766 }
1767 for (size_t i = 0; i < mTracks.size(); i++) {
1768 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001769 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001770 return AudioSystem::getStrategyForStream(track->streamType());
1771 }
1772 }
1773 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1774}
1775
1776
1777AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1778{
1779 Mutex::Autolock _l(mLock);
1780 return mOutput;
1781}
1782
1783AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1784{
1785 Mutex::Autolock _l(mLock);
1786 AudioStreamOut *output = mOutput;
1787 mOutput = NULL;
1788 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1789 // must push a NULL and wait for ack
1790 mOutputSink.clear();
1791 mPipeSink.clear();
1792 mNormalSink.clear();
1793 return output;
1794}
1795
1796// this method must always be called either with ThreadBase mLock held or inside the thread loop
1797audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1798{
1799 if (mOutput == NULL) {
1800 return NULL;
1801 }
1802 return &mOutput->stream->common;
1803}
1804
1805uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1806{
1807 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1808}
1809
1810status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1811{
1812 if (!isValidSyncEvent(event)) {
1813 return BAD_VALUE;
1814 }
1815
1816 Mutex::Autolock _l(mLock);
1817
1818 for (size_t i = 0; i < mTracks.size(); ++i) {
1819 sp<Track> track = mTracks[i];
1820 if (event->triggerSession() == track->sessionId()) {
1821 (void) track->setSyncEvent(event);
1822 return NO_ERROR;
1823 }
1824 }
1825
1826 return NAME_NOT_FOUND;
1827}
1828
1829bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1830{
1831 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1832}
1833
1834void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1835 const Vector< sp<Track> >& tracksToRemove)
1836{
1837 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07001838 if (count) {
Eric Laurent81784c32012-11-19 14:55:58 -08001839 for (size_t i = 0 ; i < count ; i++) {
1840 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001841 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001842 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843#ifdef ADD_BATTERY_DATA
1844 // to track the speaker usage
1845 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1846#endif
1847 if (track->isTerminated()) {
1848 AudioSystem::releaseOutput(mId);
1849 }
Eric Laurent81784c32012-11-19 14:55:58 -08001850 }
1851 }
1852 }
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
1855void AudioFlinger::PlaybackThread::checkSilentMode_l()
1856{
1857 if (!mMasterMute) {
1858 char value[PROPERTY_VALUE_MAX];
1859 if (property_get("ro.audio.silent", value, "0") > 0) {
1860 char *endptr;
1861 unsigned long ul = strtoul(value, &endptr, 0);
1862 if (*endptr == '\0' && ul != 0) {
1863 ALOGD("Silence is golden");
1864 // The setprop command will not allow a property to be changed after
1865 // the first time it is set, so we don't have to worry about un-muting.
1866 setMasterMute_l(true);
1867 }
1868 }
1869 }
1870}
1871
1872// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001873ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001874{
1875 // FIXME rewrite to reduce number of system calls
1876 mLastWriteTime = systemTime();
1877 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001878 ssize_t bytesWritten;
Eric Laurent81784c32012-11-19 14:55:58 -08001879
1880 // If an NBAIO sink is present, use it to write the normal mixer's submix
1881 if (mNormalSink != 0) {
1882#define mBitShift 2 // FIXME
Eric Laurentbfb1b832013-01-07 09:53:42 -08001883 size_t count = mBytesRemaining >> mBitShift;
1884 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
Simon Wilson2d590962012-11-29 15:18:50 -08001885 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08001886 // update the setpoint when AudioFlinger::mScreenState changes
1887 uint32_t screenState = AudioFlinger::mScreenState;
1888 if (screenState != mScreenState) {
1889 mScreenState = screenState;
1890 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1891 if (pipe != NULL) {
1892 pipe->setAvgFrames((mScreenState & 1) ?
1893 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1894 }
1895 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001896 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08001897 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08001898 if (framesWritten > 0) {
1899 bytesWritten = framesWritten << mBitShift;
1900 } else {
1901 bytesWritten = framesWritten;
1902 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001903 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001904 if (status == NO_ERROR) {
1905 size_t totalFramesWritten = mNormalSink->framesWritten();
1906 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1907 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1908 mLatchDValid = true;
1909 }
1910 }
Eric Laurent81784c32012-11-19 14:55:58 -08001911 // otherwise use the HAL / AudioStreamOut directly
1912 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001913 // Direct output and offload threads
1914 size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1915 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001916 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1917 mWriteAckSequence += 2;
1918 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001920 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001921 }
Glenn Kasten767094d2013-08-23 13:51:43 -07001922 // FIXME We should have an implementation of timestamps for direct output threads.
1923 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001924 bytesWritten = mOutput->stream->write(mOutput->stream,
1925 mMixBuffer + offset, mBytesRemaining);
1926 if (mUseAsyncWrite &&
1927 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1928 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07001929 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001930 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001931 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932 }
Eric Laurent81784c32012-11-19 14:55:58 -08001933 }
1934
Eric Laurent81784c32012-11-19 14:55:58 -08001935 mNumWrites++;
1936 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07001937 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001938 return bytesWritten;
1939}
1940
1941void AudioFlinger::PlaybackThread::threadLoop_drain()
1942{
1943 if (mOutput->stream->drain) {
1944 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1945 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07001946 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1947 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001949 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 }
1951 mOutput->stream->drain(mOutput->stream,
1952 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1953 : AUDIO_DRAIN_ALL);
1954 }
1955}
1956
1957void AudioFlinger::PlaybackThread::threadLoop_exit()
1958{
1959 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08001960}
1961
1962/*
1963The derived values that are cached:
1964 - mixBufferSize from frame count * frame size
1965 - activeSleepTime from activeSleepTimeUs()
1966 - idleSleepTime from idleSleepTimeUs()
1967 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1968 - maxPeriod from frame count and sample rate (MIXER only)
1969
1970The parameters that affect these derived values are:
1971 - frame count
1972 - frame size
1973 - sample rate
1974 - device type: A2DP or not
1975 - device latency
1976 - format: PCM or not
1977 - active sleep time
1978 - idle sleep time
1979*/
1980
1981void AudioFlinger::PlaybackThread::cacheParameters_l()
1982{
1983 mixBufferSize = mNormalFrameCount * mFrameSize;
1984 activeSleepTime = activeSleepTimeUs();
1985 idleSleepTime = idleSleepTimeUs();
1986}
1987
1988void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1989{
Glenn Kasten7c027242012-12-26 14:43:16 -08001990 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08001991 this, streamType, mTracks.size());
1992 Mutex::Autolock _l(mLock);
1993
1994 size_t size = mTracks.size();
1995 for (size_t i = 0; i < size; i++) {
1996 sp<Track> t = mTracks[i];
1997 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08001998 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08001999 }
2000 }
2001}
2002
2003status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2004{
2005 int session = chain->sessionId();
2006 int16_t *buffer = mMixBuffer;
2007 bool ownsBuffer = false;
2008
2009 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2010 if (session > 0) {
2011 // Only one effect chain can be present in direct output thread and it uses
2012 // the mix buffer as input
2013 if (mType != DIRECT) {
2014 size_t numSamples = mNormalFrameCount * mChannelCount;
2015 buffer = new int16_t[numSamples];
2016 memset(buffer, 0, numSamples * sizeof(int16_t));
2017 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2018 ownsBuffer = true;
2019 }
2020
2021 // Attach all tracks with same session ID to this chain.
2022 for (size_t i = 0; i < mTracks.size(); ++i) {
2023 sp<Track> track = mTracks[i];
2024 if (session == track->sessionId()) {
2025 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2026 buffer);
2027 track->setMainBuffer(buffer);
2028 chain->incTrackCnt();
2029 }
2030 }
2031
2032 // indicate all active tracks in the chain
2033 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2034 sp<Track> track = mActiveTracks[i].promote();
2035 if (track == 0) {
2036 continue;
2037 }
2038 if (session == track->sessionId()) {
2039 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2040 chain->incActiveTrackCnt();
2041 }
2042 }
2043 }
2044
2045 chain->setInBuffer(buffer, ownsBuffer);
2046 chain->setOutBuffer(mMixBuffer);
2047 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2048 // chains list in order to be processed last as it contains output stage effects
2049 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2050 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2051 // after track specific effects and before output stage
2052 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2053 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2054 // Effect chain for other sessions are inserted at beginning of effect
2055 // chains list to be processed before output mix effects. Relative order between other
2056 // sessions is not important
2057 size_t size = mEffectChains.size();
2058 size_t i = 0;
2059 for (i = 0; i < size; i++) {
2060 if (mEffectChains[i]->sessionId() < session) {
2061 break;
2062 }
2063 }
2064 mEffectChains.insertAt(chain, i);
2065 checkSuspendOnAddEffectChain_l(chain);
2066
2067 return NO_ERROR;
2068}
2069
2070size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2071{
2072 int session = chain->sessionId();
2073
2074 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2075
2076 for (size_t i = 0; i < mEffectChains.size(); i++) {
2077 if (chain == mEffectChains[i]) {
2078 mEffectChains.removeAt(i);
2079 // detach all active tracks from the chain
2080 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2081 sp<Track> track = mActiveTracks[i].promote();
2082 if (track == 0) {
2083 continue;
2084 }
2085 if (session == track->sessionId()) {
2086 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2087 chain.get(), session);
2088 chain->decActiveTrackCnt();
2089 }
2090 }
2091
2092 // detach all tracks with same session ID from this chain
2093 for (size_t i = 0; i < mTracks.size(); ++i) {
2094 sp<Track> track = mTracks[i];
2095 if (session == track->sessionId()) {
2096 track->setMainBuffer(mMixBuffer);
2097 chain->decTrackCnt();
2098 }
2099 }
2100 break;
2101 }
2102 }
2103 return mEffectChains.size();
2104}
2105
2106status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2107 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2108{
2109 Mutex::Autolock _l(mLock);
2110 return attachAuxEffect_l(track, EffectId);
2111}
2112
2113status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2114 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2115{
2116 status_t status = NO_ERROR;
2117
2118 if (EffectId == 0) {
2119 track->setAuxBuffer(0, NULL);
2120 } else {
2121 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2122 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2123 if (effect != 0) {
2124 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2125 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2126 } else {
2127 status = INVALID_OPERATION;
2128 }
2129 } else {
2130 status = BAD_VALUE;
2131 }
2132 }
2133 return status;
2134}
2135
2136void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2137{
2138 for (size_t i = 0; i < mTracks.size(); ++i) {
2139 sp<Track> track = mTracks[i];
2140 if (track->auxEffectId() == effectId) {
2141 attachAuxEffect_l(track, 0);
2142 }
2143 }
2144}
2145
2146bool AudioFlinger::PlaybackThread::threadLoop()
2147{
2148 Vector< sp<Track> > tracksToRemove;
2149
2150 standbyTime = systemTime();
2151
2152 // MIXER
2153 nsecs_t lastWarning = 0;
2154
2155 // DUPLICATING
2156 // FIXME could this be made local to while loop?
2157 writeFrames = 0;
2158
Marco Nelissen9cae2172013-01-14 14:12:05 -08002159 int lastGeneration = 0;
2160
Eric Laurent81784c32012-11-19 14:55:58 -08002161 cacheParameters_l();
2162 sleepTime = idleSleepTime;
2163
2164 if (mType == MIXER) {
2165 sleepTimeShift = 0;
2166 }
2167
2168 CpuStats cpuStats;
2169 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2170
2171 acquireWakeLock();
2172
Glenn Kasten9e58b552013-01-18 15:09:48 -08002173 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2174 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2175 // and then that string will be logged at the next convenient opportunity.
2176 const char *logString = NULL;
2177
Eric Laurent664539d2013-09-23 18:24:31 -07002178 checkSilentMode_l();
2179
Eric Laurent81784c32012-11-19 14:55:58 -08002180 while (!exitPending())
2181 {
2182 cpuStats.sample(myName);
2183
2184 Vector< sp<EffectChain> > effectChains;
2185
2186 processConfigEvents();
2187
2188 { // scope for mLock
2189
2190 Mutex::Autolock _l(mLock);
2191
Glenn Kasten9e58b552013-01-18 15:09:48 -08002192 if (logString != NULL) {
2193 mNBLogWriter->logTimestamp();
2194 mNBLogWriter->log(logString);
2195 logString = NULL;
2196 }
2197
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002198 if (mLatchDValid) {
2199 mLatchQ = mLatchD;
2200 mLatchDValid = false;
2201 mLatchQValid = true;
2202 }
2203
Eric Laurent81784c32012-11-19 14:55:58 -08002204 if (checkForNewParameters_l()) {
2205 cacheParameters_l();
2206 }
2207
2208 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209 if (mSignalPending) {
2210 // A signal was raised while we were unlocked
2211 mSignalPending = false;
2212 } else if (waitingAsyncCallback_l()) {
2213 if (exitPending()) {
2214 break;
2215 }
2216 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002217 mWakeLockUids.clear();
2218 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002219 ALOGV("wait async completion");
2220 mWaitWorkCV.wait(mLock);
2221 ALOGV("async completion/wake");
2222 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002223 standbyTime = systemTime() + standbyDelay;
2224 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002225
2226 continue;
2227 }
2228 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002229 isSuspended()) {
2230 // put audio hardware into standby after short delay
2231 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002232
2233 threadLoop_standby();
2234
2235 mStandby = true;
2236 }
2237
2238 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2239 // we're about to wait, flush the binder command buffer
2240 IPCThreadState::self()->flushCommands();
2241
2242 clearOutputTracks();
2243
2244 if (exitPending()) {
2245 break;
2246 }
2247
2248 releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002249 mWakeLockUids.clear();
2250 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002251 // wait until we have something to do...
2252 ALOGV("%s going to sleep", myName.string());
2253 mWaitWorkCV.wait(mLock);
2254 ALOGV("%s waking up", myName.string());
2255 acquireWakeLock_l();
2256
2257 mMixerStatus = MIXER_IDLE;
2258 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2259 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002261 checkSilentMode_l();
2262
2263 standbyTime = systemTime() + standbyDelay;
2264 sleepTime = idleSleepTime;
2265 if (mType == MIXER) {
2266 sleepTimeShift = 0;
2267 }
2268
2269 continue;
2270 }
2271 }
Eric Laurent81784c32012-11-19 14:55:58 -08002272 // mMixerStatusIgnoringFastTracks is also updated internally
2273 mMixerStatus = prepareTracks_l(&tracksToRemove);
2274
Marco Nelissen9cae2172013-01-14 14:12:05 -08002275 // compare with previously applied list
2276 if (lastGeneration != mActiveTracksGeneration) {
2277 // update wakelock
2278 updateWakeLockUids_l(mWakeLockUids);
2279 lastGeneration = mActiveTracksGeneration;
2280 }
2281
Eric Laurent81784c32012-11-19 14:55:58 -08002282 // prevent any changes in effect chain list and in each effect chain
2283 // during mixing and effect process as the audio buffers could be deleted
2284 // or modified if an effect is created or deleted
2285 lockEffectChains_l(effectChains);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002286 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002287
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 if (mBytesRemaining == 0) {
2289 mCurrentWriteLength = 0;
2290 if (mMixerStatus == MIXER_TRACKS_READY) {
2291 // threadLoop_mix() sets mCurrentWriteLength
2292 threadLoop_mix();
2293 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2294 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2295 // threadLoop_sleepTime sets sleepTime to 0 if data
2296 // must be written to HAL
2297 threadLoop_sleepTime();
2298 if (sleepTime == 0) {
2299 mCurrentWriteLength = mixBufferSize;
2300 }
2301 }
2302 mBytesRemaining = mCurrentWriteLength;
2303 if (isSuspended()) {
2304 sleepTime = suspendSleepTimeUs();
2305 // simulate write to HAL when suspended
2306 mBytesWritten += mixBufferSize;
2307 mBytesRemaining = 0;
2308 }
Eric Laurent81784c32012-11-19 14:55:58 -08002309
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002311 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002312 for (size_t i = 0; i < effectChains.size(); i ++) {
2313 effectChains[i]->process_l();
2314 }
Eric Laurent81784c32012-11-19 14:55:58 -08002315 }
2316 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002317 // Process effect chains for offloaded thread even if no audio
2318 // was read from audio track: process only updates effect state
2319 // and thus does have to be synchronized with audio writes but may have
2320 // to be called while waiting for async write callback
2321 if (mType == OFFLOAD) {
2322 for (size_t i = 0; i < effectChains.size(); i ++) {
2323 effectChains[i]->process_l();
2324 }
2325 }
Eric Laurent81784c32012-11-19 14:55:58 -08002326
2327 // enable changes in effect chain
2328 unlockEffectChains(effectChains);
2329
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 if (!waitingAsyncCallback()) {
2331 // sleepTime == 0 means we must write to audio hardware
2332 if (sleepTime == 0) {
2333 if (mBytesRemaining) {
2334 ssize_t ret = threadLoop_write();
2335 if (ret < 0) {
2336 mBytesRemaining = 0;
2337 } else {
2338 mBytesWritten += ret;
2339 mBytesRemaining -= ret;
2340 }
2341 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2342 (mMixerStatus == MIXER_DRAIN_ALL)) {
2343 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002344 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345if (mType == MIXER) {
2346 // write blocked detection
2347 nsecs_t now = systemTime();
2348 nsecs_t delta = now - mLastWriteTime;
2349 if (!mStandby && delta > maxPeriod) {
2350 mNumDelayedWrites++;
2351 if ((now - lastWarning) > kWarningThrottleNs) {
2352 ATRACE_NAME("underrun");
2353 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2354 ns2ms(delta), mNumDelayedWrites, this);
2355 lastWarning = now;
2356 }
2357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358}
2359
Eric Laurentbfb1b832013-01-07 09:53:42 -08002360 } else {
2361 usleep(sleepTime);
2362 }
Eric Laurent81784c32012-11-19 14:55:58 -08002363 }
2364
2365 // Finally let go of removed track(s), without the lock held
2366 // since we can't guarantee the destructors won't acquire that
2367 // same lock. This will also mutate and push a new fast mixer state.
2368 threadLoop_removeTracks(tracksToRemove);
2369 tracksToRemove.clear();
2370
2371 // FIXME I don't understand the need for this here;
2372 // it was in the original code but maybe the
2373 // assignment in saveOutputTracks() makes this unnecessary?
2374 clearOutputTracks();
2375
2376 // Effect chains will be actually deleted here if they were removed from
2377 // mEffectChains list during mixing or effects processing
2378 effectChains.clear();
2379
2380 // FIXME Note that the above .clear() is no longer necessary since effectChains
2381 // is now local to this block, but will keep it for now (at least until merge done).
2382 }
2383
Eric Laurentbfb1b832013-01-07 09:53:42 -08002384 threadLoop_exit();
2385
Eric Laurent81784c32012-11-19 14:55:58 -08002386 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002388 // put output stream into standby mode
2389 if (!mStandby) {
2390 mOutput->stream->common.standby(&mOutput->stream->common);
2391 }
2392 }
2393
2394 releaseWakeLock();
Marco Nelissen9cae2172013-01-14 14:12:05 -08002395 mWakeLockUids.clear();
2396 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002397
2398 ALOGV("Thread %p type %d exiting", this, mType);
2399 return false;
2400}
2401
Eric Laurentbfb1b832013-01-07 09:53:42 -08002402// removeTracks_l() must be called with ThreadBase::mLock held
2403void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2404{
2405 size_t count = tracksToRemove.size();
Glenn Kastenfa319e62013-07-29 17:17:38 -07002406 if (count) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 for (size_t i=0 ; i<count ; i++) {
2408 const sp<Track>& track = tracksToRemove.itemAt(i);
2409 mActiveTracks.remove(track);
Marco Nelissen9cae2172013-01-14 14:12:05 -08002410 mWakeLockUids.remove(track->uid());
2411 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2413 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2414 if (chain != 0) {
2415 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2416 track->sessionId());
2417 chain->decActiveTrackCnt();
2418 }
2419 if (track->isTerminated()) {
2420 removeTrack_l(track);
2421 }
2422 }
2423 }
2424
2425}
Eric Laurent81784c32012-11-19 14:55:58 -08002426
Eric Laurentaccc1472013-09-20 09:36:34 -07002427status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2428{
2429 if (mNormalSink != 0) {
2430 return mNormalSink->getTimestamp(timestamp);
2431 }
2432 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2433 uint64_t position64;
2434 int ret = mOutput->stream->get_presentation_position(
2435 mOutput->stream, &position64, &timestamp.mTime);
2436 if (ret == 0) {
2437 timestamp.mPosition = (uint32_t)position64;
2438 return NO_ERROR;
2439 }
2440 }
2441 return INVALID_OPERATION;
2442}
Eric Laurent81784c32012-11-19 14:55:58 -08002443// ----------------------------------------------------------------------------
2444
2445AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2446 audio_io_handle_t id, audio_devices_t device, type_t type)
2447 : PlaybackThread(audioFlinger, output, id, device, type),
2448 // mAudioMixer below
2449 // mFastMixer below
2450 mFastMixerFutex(0)
2451 // mOutputSink below
2452 // mPipeSink below
2453 // mNormalSink below
2454{
2455 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002456 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002457 "mFrameCount=%d, mNormalFrameCount=%d",
2458 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2459 mNormalFrameCount);
2460 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2461
2462 // FIXME - Current mixer implementation only supports stereo output
2463 if (mChannelCount != FCC_2) {
2464 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2465 }
2466
2467 // create an NBAIO sink for the HAL output stream, and negotiate
2468 mOutputSink = new AudioStreamOutSink(output->stream);
2469 size_t numCounterOffers = 0;
2470 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2471 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2472 ALOG_ASSERT(index == 0);
2473
2474 // initialize fast mixer depending on configuration
2475 bool initFastMixer;
2476 switch (kUseFastMixer) {
2477 case FastMixer_Never:
2478 initFastMixer = false;
2479 break;
2480 case FastMixer_Always:
2481 initFastMixer = true;
2482 break;
2483 case FastMixer_Static:
2484 case FastMixer_Dynamic:
2485 initFastMixer = mFrameCount < mNormalFrameCount;
2486 break;
2487 }
2488 if (initFastMixer) {
2489
2490 // create a MonoPipe to connect our submix to FastMixer
2491 NBAIO_Format format = mOutputSink->format();
2492 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2493 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2494 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2495 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2496 const NBAIO_Format offers[1] = {format};
2497 size_t numCounterOffers = 0;
2498 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2499 ALOG_ASSERT(index == 0);
2500 monoPipe->setAvgFrames((mScreenState & 1) ?
2501 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2502 mPipeSink = monoPipe;
2503
Glenn Kasten46909e72013-02-26 09:20:22 -08002504#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002505 if (mTeeSinkOutputEnabled) {
2506 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2507 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2508 numCounterOffers = 0;
2509 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2510 ALOG_ASSERT(index == 0);
2511 mTeeSink = teeSink;
2512 PipeReader *teeSource = new PipeReader(*teeSink);
2513 numCounterOffers = 0;
2514 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2515 ALOG_ASSERT(index == 0);
2516 mTeeSource = teeSource;
2517 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002518#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002519
2520 // create fast mixer and configure it initially with just one fast track for our submix
2521 mFastMixer = new FastMixer();
2522 FastMixerStateQueue *sq = mFastMixer->sq();
2523#ifdef STATE_QUEUE_DUMP
2524 sq->setObserverDump(&mStateQueueObserverDump);
2525 sq->setMutatorDump(&mStateQueueMutatorDump);
2526#endif
2527 FastMixerState *state = sq->begin();
2528 FastTrack *fastTrack = &state->mFastTracks[0];
2529 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2530 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2531 fastTrack->mVolumeProvider = NULL;
2532 fastTrack->mGeneration++;
2533 state->mFastTracksGen++;
2534 state->mTrackMask = 1;
2535 // fast mixer will use the HAL output sink
2536 state->mOutputSink = mOutputSink.get();
2537 state->mOutputSinkGen++;
2538 state->mFrameCount = mFrameCount;
2539 state->mCommand = FastMixerState::COLD_IDLE;
2540 // already done in constructor initialization list
2541 //mFastMixerFutex = 0;
2542 state->mColdFutexAddr = &mFastMixerFutex;
2543 state->mColdGen++;
2544 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002545#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002546 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002547#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002548 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2549 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002550 sq->end();
2551 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2552
2553 // start the fast mixer
2554 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2555 pid_t tid = mFastMixer->getTid();
2556 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2557 if (err != 0) {
2558 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2559 kPriorityFastMixer, getpid_cached, tid, err);
2560 }
2561
2562#ifdef AUDIO_WATCHDOG
2563 // create and start the watchdog
2564 mAudioWatchdog = new AudioWatchdog();
2565 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2566 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2567 tid = mAudioWatchdog->getTid();
2568 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2569 if (err != 0) {
2570 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2571 kPriorityFastMixer, getpid_cached, tid, err);
2572 }
2573#endif
2574
2575 } else {
2576 mFastMixer = NULL;
2577 }
2578
2579 switch (kUseFastMixer) {
2580 case FastMixer_Never:
2581 case FastMixer_Dynamic:
2582 mNormalSink = mOutputSink;
2583 break;
2584 case FastMixer_Always:
2585 mNormalSink = mPipeSink;
2586 break;
2587 case FastMixer_Static:
2588 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2589 break;
2590 }
2591}
2592
2593AudioFlinger::MixerThread::~MixerThread()
2594{
2595 if (mFastMixer != NULL) {
2596 FastMixerStateQueue *sq = mFastMixer->sq();
2597 FastMixerState *state = sq->begin();
2598 if (state->mCommand == FastMixerState::COLD_IDLE) {
2599 int32_t old = android_atomic_inc(&mFastMixerFutex);
2600 if (old == -1) {
2601 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2602 }
2603 }
2604 state->mCommand = FastMixerState::EXIT;
2605 sq->end();
2606 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2607 mFastMixer->join();
2608 // Though the fast mixer thread has exited, it's state queue is still valid.
2609 // We'll use that extract the final state which contains one remaining fast track
2610 // corresponding to our sub-mix.
2611 state = sq->begin();
2612 ALOG_ASSERT(state->mTrackMask == 1);
2613 FastTrack *fastTrack = &state->mFastTracks[0];
2614 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2615 delete fastTrack->mBufferProvider;
2616 sq->end(false /*didModify*/);
2617 delete mFastMixer;
2618#ifdef AUDIO_WATCHDOG
2619 if (mAudioWatchdog != 0) {
2620 mAudioWatchdog->requestExit();
2621 mAudioWatchdog->requestExitAndWait();
2622 mAudioWatchdog.clear();
2623 }
2624#endif
2625 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002626 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002627 delete mAudioMixer;
2628}
2629
2630
2631uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2632{
2633 if (mFastMixer != NULL) {
2634 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2635 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2636 }
2637 return latency;
2638}
2639
2640
2641void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2642{
2643 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2644}
2645
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002647{
2648 // FIXME we should only do one push per cycle; confirm this is true
2649 // Start the fast mixer if it's not already running
2650 if (mFastMixer != NULL) {
2651 FastMixerStateQueue *sq = mFastMixer->sq();
2652 FastMixerState *state = sq->begin();
2653 if (state->mCommand != FastMixerState::MIX_WRITE &&
2654 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2655 if (state->mCommand == FastMixerState::COLD_IDLE) {
2656 int32_t old = android_atomic_inc(&mFastMixerFutex);
2657 if (old == -1) {
2658 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2659 }
2660#ifdef AUDIO_WATCHDOG
2661 if (mAudioWatchdog != 0) {
2662 mAudioWatchdog->resume();
2663 }
2664#endif
2665 }
2666 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002667 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2668 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002669 sq->end();
2670 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2671 if (kUseFastMixer == FastMixer_Dynamic) {
2672 mNormalSink = mPipeSink;
2673 }
2674 } else {
2675 sq->end(false /*didModify*/);
2676 }
2677 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002679}
2680
2681void AudioFlinger::MixerThread::threadLoop_standby()
2682{
2683 // Idle the fast mixer if it's currently running
2684 if (mFastMixer != NULL) {
2685 FastMixerStateQueue *sq = mFastMixer->sq();
2686 FastMixerState *state = sq->begin();
2687 if (!(state->mCommand & FastMixerState::IDLE)) {
2688 state->mCommand = FastMixerState::COLD_IDLE;
2689 state->mColdFutexAddr = &mFastMixerFutex;
2690 state->mColdGen++;
2691 mFastMixerFutex = 0;
2692 sq->end();
2693 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2694 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2695 if (kUseFastMixer == FastMixer_Dynamic) {
2696 mNormalSink = mOutputSink;
2697 }
2698#ifdef AUDIO_WATCHDOG
2699 if (mAudioWatchdog != 0) {
2700 mAudioWatchdog->pause();
2701 }
2702#endif
2703 } else {
2704 sq->end(false /*didModify*/);
2705 }
2706 }
2707 PlaybackThread::threadLoop_standby();
2708}
2709
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710// Empty implementation for standard mixer
2711// Overridden for offloaded playback
2712void AudioFlinger::PlaybackThread::flushOutput_l()
2713{
2714}
2715
2716bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2717{
2718 return false;
2719}
2720
2721bool AudioFlinger::PlaybackThread::shouldStandby_l()
2722{
2723 return !mStandby;
2724}
2725
2726bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2727{
2728 Mutex::Autolock _l(mLock);
2729 return waitingAsyncCallback_l();
2730}
2731
Eric Laurent81784c32012-11-19 14:55:58 -08002732// shared by MIXER and DIRECT, overridden by DUPLICATING
2733void AudioFlinger::PlaybackThread::threadLoop_standby()
2734{
2735 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2736 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002737 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002738 // discard any pending drain or write ack by incrementing sequence
2739 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2740 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002741 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002742 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2743 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002744 }
Eric Laurent81784c32012-11-19 14:55:58 -08002745}
2746
2747void AudioFlinger::MixerThread::threadLoop_mix()
2748{
2749 // obtain the presentation timestamp of the next output buffer
2750 int64_t pts;
2751 status_t status = INVALID_OPERATION;
2752
2753 if (mNormalSink != 0) {
2754 status = mNormalSink->getNextWriteTimestamp(&pts);
2755 } else {
2756 status = mOutputSink->getNextWriteTimestamp(&pts);
2757 }
2758
2759 if (status != NO_ERROR) {
2760 pts = AudioBufferProvider::kInvalidPTS;
2761 }
2762
2763 // mix buffers...
2764 mAudioMixer->process(pts);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002766 // increase sleep time progressively when application underrun condition clears.
2767 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2768 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2769 // such that we would underrun the audio HAL.
2770 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2771 sleepTimeShift--;
2772 }
2773 sleepTime = 0;
2774 standbyTime = systemTime() + standbyDelay;
2775 //TODO: delay standby when effects have a tail
2776}
2777
2778void AudioFlinger::MixerThread::threadLoop_sleepTime()
2779{
2780 // If no tracks are ready, sleep once for the duration of an output
2781 // buffer size, then write 0s to the output
2782 if (sleepTime == 0) {
2783 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2784 sleepTime = activeSleepTime >> sleepTimeShift;
2785 if (sleepTime < kMinThreadSleepTimeUs) {
2786 sleepTime = kMinThreadSleepTimeUs;
2787 }
2788 // reduce sleep time in case of consecutive application underruns to avoid
2789 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2790 // duration we would end up writing less data than needed by the audio HAL if
2791 // the condition persists.
2792 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2793 sleepTimeShift++;
2794 }
2795 } else {
2796 sleepTime = idleSleepTime;
2797 }
2798 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2799 memset (mMixBuffer, 0, mixBufferSize);
2800 sleepTime = 0;
2801 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2802 "anticipated start");
2803 }
2804 // TODO add standby time extension fct of effect tail
2805}
2806
2807// prepareTracks_l() must be called with ThreadBase::mLock held
2808AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2809 Vector< sp<Track> > *tracksToRemove)
2810{
2811
2812 mixer_state mixerStatus = MIXER_IDLE;
2813 // find out which tracks need to be processed
2814 size_t count = mActiveTracks.size();
2815 size_t mixedTracks = 0;
2816 size_t tracksWithEffect = 0;
2817 // counts only _active_ fast tracks
2818 size_t fastTracks = 0;
2819 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2820
2821 float masterVolume = mMasterVolume;
2822 bool masterMute = mMasterMute;
2823
2824 if (masterMute) {
2825 masterVolume = 0;
2826 }
2827 // Delegate master volume control to effect in output mix effect chain if needed
2828 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2829 if (chain != 0) {
2830 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2831 chain->setVolume_l(&v, &v);
2832 masterVolume = (float)((v + (1 << 23)) >> 24);
2833 chain.clear();
2834 }
2835
2836 // prepare a new state to push
2837 FastMixerStateQueue *sq = NULL;
2838 FastMixerState *state = NULL;
2839 bool didModify = false;
2840 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2841 if (mFastMixer != NULL) {
2842 sq = mFastMixer->sq();
2843 state = sq->begin();
2844 }
2845
2846 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07002847 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08002848 if (t == 0) {
2849 continue;
2850 }
2851
2852 // this const just means the local variable doesn't change
2853 Track* const track = t.get();
2854
2855 // process fast tracks
2856 if (track->isFastTrack()) {
2857
2858 // It's theoretically possible (though unlikely) for a fast track to be created
2859 // and then removed within the same normal mix cycle. This is not a problem, as
2860 // the track never becomes active so it's fast mixer slot is never touched.
2861 // The converse, of removing an (active) track and then creating a new track
2862 // at the identical fast mixer slot within the same normal mix cycle,
2863 // is impossible because the slot isn't marked available until the end of each cycle.
2864 int j = track->mFastIndex;
2865 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2866 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2867 FastTrack *fastTrack = &state->mFastTracks[j];
2868
2869 // Determine whether the track is currently in underrun condition,
2870 // and whether it had a recent underrun.
2871 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2872 FastTrackUnderruns underruns = ftDump->mUnderruns;
2873 uint32_t recentFull = (underruns.mBitFields.mFull -
2874 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2875 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2876 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2877 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2878 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2879 uint32_t recentUnderruns = recentPartial + recentEmpty;
2880 track->mObservedUnderruns = underruns;
2881 // don't count underruns that occur while stopping or pausing
2882 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07002883 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2884 recentUnderruns > 0) {
2885 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2886 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002887 }
2888
2889 // This is similar to the state machine for normal tracks,
2890 // with a few modifications for fast tracks.
2891 bool isActive = true;
2892 switch (track->mState) {
2893 case TrackBase::STOPPING_1:
2894 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002896 track->mState = TrackBase::STOPPING_2;
2897 }
2898 break;
2899 case TrackBase::PAUSING:
2900 // ramp down is not yet implemented
2901 track->setPaused();
2902 break;
2903 case TrackBase::RESUMING:
2904 // ramp up is not yet implemented
2905 track->mState = TrackBase::ACTIVE;
2906 break;
2907 case TrackBase::ACTIVE:
2908 if (recentFull > 0 || recentPartial > 0) {
2909 // track has provided at least some frames recently: reset retry count
2910 track->mRetryCount = kMaxTrackRetries;
2911 }
2912 if (recentUnderruns == 0) {
2913 // no recent underruns: stay active
2914 break;
2915 }
2916 // there has recently been an underrun of some kind
2917 if (track->sharedBuffer() == 0) {
2918 // were any of the recent underruns "empty" (no frames available)?
2919 if (recentEmpty == 0) {
2920 // no, then ignore the partial underruns as they are allowed indefinitely
2921 break;
2922 }
2923 // there has recently been an "empty" underrun: decrement the retry counter
2924 if (--(track->mRetryCount) > 0) {
2925 break;
2926 }
2927 // indicate to client process that the track was disabled because of underrun;
2928 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07002929 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002930 // remove from active list, but state remains ACTIVE [confusing but true]
2931 isActive = false;
2932 break;
2933 }
2934 // fall through
2935 case TrackBase::STOPPING_2:
2936 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002937 case TrackBase::STOPPED:
2938 case TrackBase::FLUSHED: // flush() while active
2939 // Check for presentation complete if track is inactive
2940 // We have consumed all the buffers of this track.
2941 // This would be incomplete if we auto-paused on underrun
2942 {
2943 size_t audioHALFrames =
2944 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2945 size_t framesWritten = mBytesWritten / mFrameSize;
2946 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2947 // track stays in active list until presentation is complete
2948 break;
2949 }
2950 }
2951 if (track->isStopping_2()) {
2952 track->mState = TrackBase::STOPPED;
2953 }
2954 if (track->isStopped()) {
2955 // Can't reset directly, as fast mixer is still polling this track
2956 // track->reset();
2957 // So instead mark this track as needing to be reset after push with ack
2958 resetMask |= 1 << i;
2959 }
2960 isActive = false;
2961 break;
2962 case TrackBase::IDLE:
2963 default:
2964 LOG_FATAL("unexpected track state %d", track->mState);
2965 }
2966
2967 if (isActive) {
2968 // was it previously inactive?
2969 if (!(state->mTrackMask & (1 << j))) {
2970 ExtendedAudioBufferProvider *eabp = track;
2971 VolumeProvider *vp = track;
2972 fastTrack->mBufferProvider = eabp;
2973 fastTrack->mVolumeProvider = vp;
2974 fastTrack->mSampleRate = track->mSampleRate;
2975 fastTrack->mChannelMask = track->mChannelMask;
2976 fastTrack->mGeneration++;
2977 state->mTrackMask |= 1 << j;
2978 didModify = true;
2979 // no acknowledgement required for newly active tracks
2980 }
2981 // cache the combined master volume and stream type volume for fast mixer; this
2982 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08002983 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08002984 ++fastTracks;
2985 } else {
2986 // was it previously active?
2987 if (state->mTrackMask & (1 << j)) {
2988 fastTrack->mBufferProvider = NULL;
2989 fastTrack->mGeneration++;
2990 state->mTrackMask &= ~(1 << j);
2991 didModify = true;
2992 // If any fast tracks were removed, we must wait for acknowledgement
2993 // because we're about to decrement the last sp<> on those tracks.
2994 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2995 } else {
2996 LOG_FATAL("fast track %d should have been active", j);
2997 }
2998 tracksToRemove->add(track);
2999 // Avoids a misleading display in dumpsys
3000 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3001 }
3002 continue;
3003 }
3004
3005 { // local variable scope to avoid goto warning
3006
3007 audio_track_cblk_t* cblk = track->cblk();
3008
3009 // The first time a track is added we wait
3010 // for all its buffers to be filled before processing it
3011 int name = track->name();
3012 // make sure that we have enough frames to mix one full buffer.
3013 // enforce this condition only once to enable draining the buffer in case the client
3014 // app does not call stop() and relies on underrun to stop:
3015 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3016 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003017 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003018 uint32_t sr = track->sampleRate();
3019 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003020 desiredFrames = mNormalFrameCount;
3021 } else {
3022 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003023 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003024 // add frames already consumed but not yet released by the resampler
3025 // because cblk->framesReady() will include these frames
3026 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3027 // the minimum track buffer size is normally twice the number of frames necessary
3028 // to fill one buffer and the resampler should not leave more than one buffer worth
3029 // of unreleased frames after each pass, but just in case...
3030 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3031 }
Eric Laurent81784c32012-11-19 14:55:58 -08003032 uint32_t minFrames = 1;
3033 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3034 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003035 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
Eric Laurent745e9a82013-12-20 17:36:01 -08003037
3038 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003039 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003040 !track->isPaused() && !track->isTerminated())
3041 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003042 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003043
3044 mixedTracks++;
3045
3046 // track->mainBuffer() != mMixBuffer means there is an effect chain
3047 // connected to the track
3048 chain.clear();
3049 if (track->mainBuffer() != mMixBuffer) {
3050 chain = getEffectChain_l(track->sessionId());
3051 // Delegate volume control to effect in track effect chain if needed
3052 if (chain != 0) {
3053 tracksWithEffect++;
3054 } else {
3055 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3056 "session %d",
3057 name, track->sessionId());
3058 }
3059 }
3060
3061
3062 int param = AudioMixer::VOLUME;
3063 if (track->mFillingUpStatus == Track::FS_FILLED) {
3064 // no ramp for the first volume setting
3065 track->mFillingUpStatus = Track::FS_ACTIVE;
3066 if (track->mState == TrackBase::RESUMING) {
3067 track->mState = TrackBase::ACTIVE;
3068 param = AudioMixer::RAMP_VOLUME;
3069 }
3070 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003071 // FIXME should not make a decision based on mServer
3072 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003073 // If the track is stopped before the first frame was mixed,
3074 // do not apply ramp
3075 param = AudioMixer::RAMP_VOLUME;
3076 }
3077
3078 // compute volume for this track
3079 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003080 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003081 vl = vr = va = 0;
3082 if (track->isPausing()) {
3083 track->setPaused();
3084 }
3085 } else {
3086
3087 // read original volumes with volume control
3088 float typeVolume = mStreamTypes[track->streamType()].volume;
3089 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003090 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003091 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003092 vl = vlr & 0xFFFF;
3093 vr = vlr >> 16;
3094 // track volumes come from shared memory, so can't be trusted and must be clamped
3095 if (vl > MAX_GAIN_INT) {
3096 ALOGV("Track left volume out of range: %04X", vl);
3097 vl = MAX_GAIN_INT;
3098 }
3099 if (vr > MAX_GAIN_INT) {
3100 ALOGV("Track right volume out of range: %04X", vr);
3101 vr = MAX_GAIN_INT;
3102 }
3103 // now apply the master volume and stream type volume
3104 vl = (uint32_t)(v * vl) << 12;
3105 vr = (uint32_t)(v * vr) << 12;
3106 // assuming master volume and stream type volume each go up to 1.0,
3107 // vl and vr are now in 8.24 format
3108
Glenn Kastene3aa6592012-12-04 12:22:46 -08003109 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003110 // send level comes from shared memory and so may be corrupt
3111 if (sendLevel > MAX_GAIN_INT) {
3112 ALOGV("Track send level out of range: %04X", sendLevel);
3113 sendLevel = MAX_GAIN_INT;
3114 }
3115 va = (uint32_t)(v * sendLevel);
3116 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117
Eric Laurent81784c32012-11-19 14:55:58 -08003118 // Delegate volume control to effect in track effect chain if needed
3119 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3120 // Do not ramp volume if volume is controlled by effect
3121 param = AudioMixer::VOLUME;
3122 track->mHasVolumeController = true;
3123 } else {
3124 // force no volume ramp when volume controller was just disabled or removed
3125 // from effect chain to avoid volume spike
3126 if (track->mHasVolumeController) {
3127 param = AudioMixer::VOLUME;
3128 }
3129 track->mHasVolumeController = false;
3130 }
3131
3132 // Convert volumes from 8.24 to 4.12 format
3133 // This additional clamping is needed in case chain->setVolume_l() overshot
3134 vl = (vl + (1 << 11)) >> 12;
3135 if (vl > MAX_GAIN_INT) {
3136 vl = MAX_GAIN_INT;
3137 }
3138 vr = (vr + (1 << 11)) >> 12;
3139 if (vr > MAX_GAIN_INT) {
3140 vr = MAX_GAIN_INT;
3141 }
3142
3143 if (va > MAX_GAIN_INT) {
3144 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3145 }
3146
3147 // XXX: these things DON'T need to be done each time
3148 mAudioMixer->setBufferProvider(name, track);
3149 mAudioMixer->enable(name);
3150
3151 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3152 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3153 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3154 mAudioMixer->setParameter(
3155 name,
3156 AudioMixer::TRACK,
3157 AudioMixer::FORMAT, (void *)track->format());
3158 mAudioMixer->setParameter(
3159 name,
3160 AudioMixer::TRACK,
3161 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003162 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3163 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003164 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003165 if (reqSampleRate == 0) {
3166 reqSampleRate = mSampleRate;
3167 } else if (reqSampleRate > maxSampleRate) {
3168 reqSampleRate = maxSampleRate;
3169 }
Eric Laurent81784c32012-11-19 14:55:58 -08003170 mAudioMixer->setParameter(
3171 name,
3172 AudioMixer::RESAMPLE,
3173 AudioMixer::SAMPLE_RATE,
Glenn Kastene3aa6592012-12-04 12:22:46 -08003174 (void *)reqSampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08003175 mAudioMixer->setParameter(
3176 name,
3177 AudioMixer::TRACK,
3178 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3179 mAudioMixer->setParameter(
3180 name,
3181 AudioMixer::TRACK,
3182 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3183
3184 // reset retry count
3185 track->mRetryCount = kMaxTrackRetries;
3186
3187 // If one track is ready, set the mixer ready if:
3188 // - the mixer was not ready during previous round OR
3189 // - no other track is not ready
3190 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3191 mixerStatus != MIXER_TRACKS_ENABLED) {
3192 mixerStatus = MIXER_TRACKS_READY;
3193 }
3194 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003195 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003196 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003197 }
Eric Laurent81784c32012-11-19 14:55:58 -08003198 // clear effect chain input buffer if an active track underruns to avoid sending
3199 // previous audio buffer again to effects
3200 chain = getEffectChain_l(track->sessionId());
3201 if (chain != 0) {
3202 chain->clearInputBuffer();
3203 }
3204
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003205 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003206 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3207 track->isStopped() || track->isPaused()) {
3208 // We have consumed all the buffers of this track.
3209 // Remove it from the list of active tracks.
3210 // TODO: use actual buffer filling status instead of latency when available from
3211 // audio HAL
3212 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3213 size_t framesWritten = mBytesWritten / mFrameSize;
3214 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3215 if (track->isStopped()) {
3216 track->reset();
3217 }
3218 tracksToRemove->add(track);
3219 }
3220 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003221 // No buffers for this track. Give it a few chances to
3222 // fill a buffer, then remove it from active list.
3223 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003224 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003225 tracksToRemove->add(track);
3226 // indicate to client process that the track was disabled because of underrun;
3227 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003228 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003229 // If one track is not ready, mark the mixer also not ready if:
3230 // - the mixer was ready during previous round OR
3231 // - no other track is ready
3232 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3233 mixerStatus != MIXER_TRACKS_READY) {
3234 mixerStatus = MIXER_TRACKS_ENABLED;
3235 }
3236 }
3237 mAudioMixer->disable(name);
3238 }
3239
3240 } // local variable scope to avoid goto warning
3241track_is_ready: ;
3242
3243 }
3244
3245 // Push the new FastMixer state if necessary
3246 bool pauseAudioWatchdog = false;
3247 if (didModify) {
3248 state->mFastTracksGen++;
3249 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3250 if (kUseFastMixer == FastMixer_Dynamic &&
3251 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3252 state->mCommand = FastMixerState::COLD_IDLE;
3253 state->mColdFutexAddr = &mFastMixerFutex;
3254 state->mColdGen++;
3255 mFastMixerFutex = 0;
3256 if (kUseFastMixer == FastMixer_Dynamic) {
3257 mNormalSink = mOutputSink;
3258 }
3259 // If we go into cold idle, need to wait for acknowledgement
3260 // so that fast mixer stops doing I/O.
3261 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3262 pauseAudioWatchdog = true;
3263 }
Eric Laurent81784c32012-11-19 14:55:58 -08003264 }
3265 if (sq != NULL) {
3266 sq->end(didModify);
3267 sq->push(block);
3268 }
3269#ifdef AUDIO_WATCHDOG
3270 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3271 mAudioWatchdog->pause();
3272 }
3273#endif
3274
3275 // Now perform the deferred reset on fast tracks that have stopped
3276 while (resetMask != 0) {
3277 size_t i = __builtin_ctz(resetMask);
3278 ALOG_ASSERT(i < count);
3279 resetMask &= ~(1 << i);
3280 sp<Track> t = mActiveTracks[i].promote();
3281 if (t == 0) {
3282 continue;
3283 }
3284 Track* track = t.get();
3285 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3286 track->reset();
3287 }
3288
3289 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003291
3292 // mix buffer must be cleared if all tracks are connected to an
3293 // effect chain as in this case the mixer will not write to
3294 // mix buffer and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3296 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003297 // FIXME as a performance optimization, should remember previous zero status
3298 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3299 }
3300
3301 // if any fast tracks, then status is ready
3302 mMixerStatusIgnoringFastTracks = mixerStatus;
3303 if (fastTracks > 0) {
3304 mixerStatus = MIXER_TRACKS_READY;
3305 }
3306 return mixerStatus;
3307}
3308
3309// getTrackName_l() must be called with ThreadBase::mLock held
3310int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3311{
3312 return mAudioMixer->getTrackName(channelMask, sessionId);
3313}
3314
3315// deleteTrackName_l() must be called with ThreadBase::mLock held
3316void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3317{
3318 ALOGV("remove track (%d) and delete from mixer", name);
3319 mAudioMixer->deleteTrackName(name);
3320}
3321
3322// checkForNewParameters_l() must be called with ThreadBase::mLock held
3323bool AudioFlinger::MixerThread::checkForNewParameters_l()
3324{
3325 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3326 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3327 bool reconfig = false;
3328
3329 while (!mNewParameters.isEmpty()) {
3330
3331 if (mFastMixer != NULL) {
3332 FastMixerStateQueue *sq = mFastMixer->sq();
3333 FastMixerState *state = sq->begin();
3334 if (!(state->mCommand & FastMixerState::IDLE)) {
3335 previousCommand = state->mCommand;
3336 state->mCommand = FastMixerState::HOT_IDLE;
3337 sq->end();
3338 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3339 } else {
3340 sq->end(false /*didModify*/);
3341 }
3342 }
3343
3344 status_t status = NO_ERROR;
3345 String8 keyValuePair = mNewParameters[0];
3346 AudioParameter param = AudioParameter(keyValuePair);
3347 int value;
3348
3349 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3350 reconfig = true;
3351 }
3352 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3353 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3354 status = BAD_VALUE;
3355 } else {
3356 reconfig = true;
3357 }
3358 }
3359 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003360 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003361 status = BAD_VALUE;
3362 } else {
3363 reconfig = true;
3364 }
3365 }
3366 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3367 // do not accept frame count changes if tracks are open as the track buffer
3368 // size depends on frame count and correct behavior would not be guaranteed
3369 // if frame count is changed after track creation
3370 if (!mTracks.isEmpty()) {
3371 status = INVALID_OPERATION;
3372 } else {
3373 reconfig = true;
3374 }
3375 }
3376 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3377#ifdef ADD_BATTERY_DATA
3378 // when changing the audio output device, call addBatteryData to notify
3379 // the change
3380 if (mOutDevice != value) {
3381 uint32_t params = 0;
3382 // check whether speaker is on
3383 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3384 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3385 }
3386
3387 audio_devices_t deviceWithoutSpeaker
3388 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3389 // check if any other device (except speaker) is on
3390 if (value & deviceWithoutSpeaker ) {
3391 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3392 }
3393
3394 if (params != 0) {
3395 addBatteryData(params);
3396 }
3397 }
3398#endif
3399
3400 // forward device change to effects that have requested to be
3401 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003402 if (value != AUDIO_DEVICE_NONE) {
3403 mOutDevice = value;
3404 for (size_t i = 0; i < mEffectChains.size(); i++) {
3405 mEffectChains[i]->setDevice_l(mOutDevice);
3406 }
Eric Laurent81784c32012-11-19 14:55:58 -08003407 }
3408 }
3409
3410 if (status == NO_ERROR) {
3411 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3412 keyValuePair.string());
3413 if (!mStandby && status == INVALID_OPERATION) {
3414 mOutput->stream->common.standby(&mOutput->stream->common);
3415 mStandby = true;
3416 mBytesWritten = 0;
3417 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3418 keyValuePair.string());
3419 }
3420 if (status == NO_ERROR && reconfig) {
Eric Laurent81784c32012-11-19 14:55:58 -08003421 readOutputParameters();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003422 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003423 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3424 for (size_t i = 0; i < mTracks.size() ; i++) {
3425 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3426 if (name < 0) {
3427 break;
3428 }
3429 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003430 }
3431 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3432 }
3433 }
3434
3435 mNewParameters.removeAt(0);
3436
3437 mParamStatus = status;
3438 mParamCond.signal();
3439 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3440 // already timed out waiting for the status and will never signal the condition.
3441 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3442 }
3443
3444 if (!(previousCommand & FastMixerState::IDLE)) {
3445 ALOG_ASSERT(mFastMixer != NULL);
3446 FastMixerStateQueue *sq = mFastMixer->sq();
3447 FastMixerState *state = sq->begin();
3448 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3449 state->mCommand = previousCommand;
3450 sq->end();
3451 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3452 }
3453
3454 return reconfig;
3455}
3456
3457
3458void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3459{
3460 const size_t SIZE = 256;
3461 char buffer[SIZE];
3462 String8 result;
3463
3464 PlaybackThread::dumpInternals(fd, args);
3465
3466 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3467 result.append(buffer);
3468 write(fd, result.string(), result.size());
3469
3470 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003471 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003472 copy.dump(fd);
3473
3474#ifdef STATE_QUEUE_DUMP
3475 // Similar for state queue
3476 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3477 observerCopy.dump(fd);
3478 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3479 mutatorCopy.dump(fd);
3480#endif
3481
Glenn Kasten46909e72013-02-26 09:20:22 -08003482#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003483 // Write the tee output to a .wav file
3484 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003485#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003486
3487#ifdef AUDIO_WATCHDOG
3488 if (mAudioWatchdog != 0) {
3489 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3490 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3491 wdCopy.dump(fd);
3492 }
3493#endif
3494}
3495
3496uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3497{
3498 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3499}
3500
3501uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3502{
3503 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3504}
3505
3506void AudioFlinger::MixerThread::cacheParameters_l()
3507{
3508 PlaybackThread::cacheParameters_l();
3509
3510 // FIXME: Relaxed timing because of a certain device that can't meet latency
3511 // Should be reduced to 2x after the vendor fixes the driver issue
3512 // increase threshold again due to low power audio mode. The way this warning
3513 // threshold is calculated and its usefulness should be reconsidered anyway.
3514 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3515}
3516
3517// ----------------------------------------------------------------------------
3518
3519AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3520 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3521 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3522 // mLeftVolFloat, mRightVolFloat
3523{
3524}
3525
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3527 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3528 ThreadBase::type_t type)
3529 : PlaybackThread(audioFlinger, output, id, device, type)
3530 // mLeftVolFloat, mRightVolFloat
3531{
3532}
3533
Eric Laurent81784c32012-11-19 14:55:58 -08003534AudioFlinger::DirectOutputThread::~DirectOutputThread()
3535{
3536}
3537
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3539{
3540 audio_track_cblk_t* cblk = track->cblk();
3541 float left, right;
3542
3543 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3544 left = right = 0;
3545 } else {
3546 float typeVolume = mStreamTypes[track->streamType()].volume;
3547 float v = mMasterVolume * typeVolume;
3548 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3549 uint32_t vlr = proxy->getVolumeLR();
3550 float v_clamped = v * (vlr & 0xFFFF);
3551 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3552 left = v_clamped/MAX_GAIN;
3553 v_clamped = v * (vlr >> 16);
3554 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3555 right = v_clamped/MAX_GAIN;
3556 }
3557
3558 if (lastTrack) {
3559 if (left != mLeftVolFloat || right != mRightVolFloat) {
3560 mLeftVolFloat = left;
3561 mRightVolFloat = right;
3562
3563 // Convert volumes from float to 8.24
3564 uint32_t vl = (uint32_t)(left * (1 << 24));
3565 uint32_t vr = (uint32_t)(right * (1 << 24));
3566
3567 // Delegate volume control to effect in track effect chain if needed
3568 // only one effect chain can be present on DirectOutputThread, so if
3569 // there is one, the track is connected to it
3570 if (!mEffectChains.isEmpty()) {
3571 mEffectChains[0]->setVolume_l(&vl, &vr);
3572 left = (float)vl / (1 << 24);
3573 right = (float)vr / (1 << 24);
3574 }
3575 if (mOutput->stream->set_volume) {
3576 mOutput->stream->set_volume(mOutput->stream, left, right);
3577 }
3578 }
3579 }
3580}
3581
3582
Eric Laurent81784c32012-11-19 14:55:58 -08003583AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3584 Vector< sp<Track> > *tracksToRemove
3585)
3586{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003587 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003588 mixer_state mixerStatus = MIXER_IDLE;
3589
3590 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003591 for (size_t i = 0; i < count; i++) {
3592 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003593 // The track died recently
3594 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003595 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003596 }
3597
3598 Track* const track = t.get();
3599 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003600 // Only consider last track started for volume and mixer state control.
3601 // In theory an older track could underrun and restart after the new one starts
3602 // but as we only care about the transition phase between two tracks on a
3603 // direct output, it is not a problem to ignore the underrun case.
3604 sp<Track> l = mLatestActiveTrack.promote();
3605 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003606
3607 // The first time a track is added we wait
3608 // for all its buffers to be filled before processing it
3609 uint32_t minFrames;
3610 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3611 minFrames = mNormalFrameCount;
3612 } else {
3613 minFrames = 1;
3614 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615
Eric Laurent81784c32012-11-19 14:55:58 -08003616 if ((track->framesReady() >= minFrames) && track->isReady() &&
3617 !track->isPaused() && !track->isTerminated())
3618 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003619 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003620
3621 if (track->mFillingUpStatus == Track::FS_FILLED) {
3622 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003623 // make sure processVolume_l() will apply new volume even if 0
3624 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003625 if (track->mState == TrackBase::RESUMING) {
3626 track->mState = TrackBase::ACTIVE;
3627 }
3628 }
3629
3630 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003631 processVolume_l(track, last);
3632 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003633 // reset retry count
3634 track->mRetryCount = kMaxTrackRetriesDirect;
3635 mActiveTrack = t;
3636 mixerStatus = MIXER_TRACKS_READY;
3637 }
Eric Laurent81784c32012-11-19 14:55:58 -08003638 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003639 // clear effect chain input buffer if the last active track started underruns
3640 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003641 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003642 mEffectChains[0]->clearInputBuffer();
3643 }
3644
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003645 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003646 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3647 track->isStopped() || track->isPaused()) {
3648 // We have consumed all the buffers of this track.
3649 // Remove it from the list of active tracks.
3650 // TODO: implement behavior for compressed audio
3651 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3652 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003653 if (mStandby || !last ||
3654 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003655 if (track->isStopped()) {
3656 track->reset();
3657 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003658 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003659 }
3660 } else {
3661 // No buffers for this track. Give it a few chances to
3662 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003663 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003664 if (--(track->mRetryCount) <= 0) {
3665 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003666 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003667 // indicate to client process that the track was disabled because of underrun;
3668 // it will then automatically call start() when data is available
3669 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003671 mixerStatus = MIXER_TRACKS_ENABLED;
3672 }
3673 }
3674 }
3675 }
3676
Eric Laurent81784c32012-11-19 14:55:58 -08003677 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003678 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003679
3680 return mixerStatus;
3681}
3682
3683void AudioFlinger::DirectOutputThread::threadLoop_mix()
3684{
Eric Laurent81784c32012-11-19 14:55:58 -08003685 size_t frameCount = mFrameCount;
3686 int8_t *curBuf = (int8_t *)mMixBuffer;
3687 // output audio to hardware
3688 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003689 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003690 buffer.frameCount = frameCount;
3691 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003692 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003693 memset(curBuf, 0, frameCount * mFrameSize);
3694 break;
3695 }
3696 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3697 frameCount -= buffer.frameCount;
3698 curBuf += buffer.frameCount * mFrameSize;
3699 mActiveTrack->releaseBuffer(&buffer);
3700 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003701 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003702 sleepTime = 0;
3703 standbyTime = systemTime() + standbyDelay;
3704 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003705}
3706
3707void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3708{
3709 if (sleepTime == 0) {
3710 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3711 sleepTime = activeSleepTime;
3712 } else {
3713 sleepTime = idleSleepTime;
3714 }
3715 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3716 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3717 sleepTime = 0;
3718 }
3719}
3720
3721// getTrackName_l() must be called with ThreadBase::mLock held
3722int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3723 int sessionId)
3724{
3725 return 0;
3726}
3727
3728// deleteTrackName_l() must be called with ThreadBase::mLock held
3729void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3730{
3731}
3732
3733// checkForNewParameters_l() must be called with ThreadBase::mLock held
3734bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3735{
3736 bool reconfig = false;
3737
3738 while (!mNewParameters.isEmpty()) {
3739 status_t status = NO_ERROR;
3740 String8 keyValuePair = mNewParameters[0];
3741 AudioParameter param = AudioParameter(keyValuePair);
3742 int value;
3743
3744 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3745 // do not accept frame count changes if tracks are open as the track buffer
3746 // size depends on frame count and correct behavior would not be garantied
3747 // if frame count is changed after track creation
3748 if (!mTracks.isEmpty()) {
3749 status = INVALID_OPERATION;
3750 } else {
3751 reconfig = true;
3752 }
3753 }
3754 if (status == NO_ERROR) {
3755 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3756 keyValuePair.string());
3757 if (!mStandby && status == INVALID_OPERATION) {
3758 mOutput->stream->common.standby(&mOutput->stream->common);
3759 mStandby = true;
3760 mBytesWritten = 0;
3761 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3762 keyValuePair.string());
3763 }
3764 if (status == NO_ERROR && reconfig) {
3765 readOutputParameters();
3766 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3767 }
3768 }
3769
3770 mNewParameters.removeAt(0);
3771
3772 mParamStatus = status;
3773 mParamCond.signal();
3774 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3775 // already timed out waiting for the status and will never signal the condition.
3776 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3777 }
3778 return reconfig;
3779}
3780
3781uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3782{
3783 uint32_t time;
3784 if (audio_is_linear_pcm(mFormat)) {
3785 time = PlaybackThread::activeSleepTimeUs();
3786 } else {
3787 time = 10000;
3788 }
3789 return time;
3790}
3791
3792uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3793{
3794 uint32_t time;
3795 if (audio_is_linear_pcm(mFormat)) {
3796 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3797 } else {
3798 time = 10000;
3799 }
3800 return time;
3801}
3802
3803uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3804{
3805 uint32_t time;
3806 if (audio_is_linear_pcm(mFormat)) {
3807 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3808 } else {
3809 time = 10000;
3810 }
3811 return time;
3812}
3813
3814void AudioFlinger::DirectOutputThread::cacheParameters_l()
3815{
3816 PlaybackThread::cacheParameters_l();
3817
3818 // use shorter standby delay as on normal output to release
3819 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07003820 if (audio_is_linear_pcm(mFormat)) {
3821 standbyDelay = microseconds(activeSleepTime*2);
3822 } else {
3823 standbyDelay = kOffloadStandbyDelayNs;
3824 }
Eric Laurent81784c32012-11-19 14:55:58 -08003825}
3826
3827// ----------------------------------------------------------------------------
3828
Eric Laurentbfb1b832013-01-07 09:53:42 -08003829AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07003830 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07003832 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07003833 mWriteAckSequence(0),
3834 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003835{
3836}
3837
3838AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3839{
3840}
3841
3842void AudioFlinger::AsyncCallbackThread::onFirstRef()
3843{
3844 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3845}
3846
3847bool AudioFlinger::AsyncCallbackThread::threadLoop()
3848{
3849 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003850 uint32_t writeAckSequence;
3851 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003852
3853 {
3854 Mutex::Autolock _l(mLock);
Haynes Mathew Georgec9561632013-12-03 21:26:02 -08003855 while (!((mWriteAckSequence & 1) ||
3856 (mDrainSequence & 1) ||
3857 exitPending())) {
3858 mWaitWorkCV.wait(mLock);
3859 }
3860
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861 if (exitPending()) {
3862 break;
3863 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003864 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3865 mWriteAckSequence, mDrainSequence);
3866 writeAckSequence = mWriteAckSequence;
3867 mWriteAckSequence &= ~1;
3868 drainSequence = mDrainSequence;
3869 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003870 }
3871 {
Eric Laurent4de95592013-09-26 15:28:21 -07003872 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3873 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003874 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003875 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003876 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07003877 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07003878 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003879 }
3880 }
3881 }
3882 }
3883 return false;
3884}
3885
3886void AudioFlinger::AsyncCallbackThread::exit()
3887{
3888 ALOGV("AsyncCallbackThread::exit");
3889 Mutex::Autolock _l(mLock);
3890 requestExit();
3891 mWaitWorkCV.broadcast();
3892}
3893
Eric Laurent3b4529e2013-09-05 18:09:19 -07003894void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003895{
3896 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003897 // bit 0 is cleared
3898 mWriteAckSequence = sequence << 1;
3899}
3900
3901void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3902{
3903 Mutex::Autolock _l(mLock);
3904 // ignore unexpected callbacks
3905 if (mWriteAckSequence & 2) {
3906 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003907 mWaitWorkCV.signal();
3908 }
3909}
3910
Eric Laurent3b4529e2013-09-05 18:09:19 -07003911void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912{
3913 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003914 // bit 0 is cleared
3915 mDrainSequence = sequence << 1;
3916}
3917
3918void AudioFlinger::AsyncCallbackThread::resetDraining()
3919{
3920 Mutex::Autolock _l(mLock);
3921 // ignore unexpected callbacks
3922 if (mDrainSequence & 2) {
3923 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003924 mWaitWorkCV.signal();
3925 }
3926}
3927
3928
3929// ----------------------------------------------------------------------------
3930AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3931 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3932 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3933 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07003934 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08003935 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003936{
Eric Laurentfd477972013-10-25 18:10:40 -07003937 //FIXME: mStandby should be set to true by ThreadBase constructor
3938 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003939}
3940
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941void AudioFlinger::OffloadThread::threadLoop_exit()
3942{
3943 if (mFlushPending || mHwPaused) {
3944 // If a flush is pending or track was paused, just discard buffered data
3945 flushHw_l();
3946 } else {
3947 mMixerStatus = MIXER_DRAIN_ALL;
3948 threadLoop_drain();
3949 }
3950 mCallbackThread->exit();
3951 PlaybackThread::threadLoop_exit();
3952}
3953
3954AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3955 Vector< sp<Track> > *tracksToRemove
3956)
3957{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003958 size_t count = mActiveTracks.size();
3959
3960 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07003961 bool doHwPause = false;
3962 bool doHwResume = false;
3963
Eric Laurentede6c3b2013-09-19 14:37:46 -07003964 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3965
Eric Laurentbfb1b832013-01-07 09:53:42 -08003966 // find out which tracks need to be processed
3967 for (size_t i = 0; i < count; i++) {
3968 sp<Track> t = mActiveTracks[i].promote();
3969 // The track died recently
3970 if (t == 0) {
3971 continue;
3972 }
3973 Track* const track = t.get();
3974 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003975 // Only consider last track started for volume and mixer state control.
3976 // In theory an older track could underrun and restart after the new one starts
3977 // but as we only care about the transition phase between two tracks on a
3978 // direct output, it is not a problem to ignore the underrun case.
3979 sp<Track> l = mLatestActiveTrack.promote();
3980 bool last = l.get() == track;
3981
Eric Laurentbfb1b832013-01-07 09:53:42 -08003982 if (track->isPausing()) {
3983 track->setPaused();
3984 if (last) {
3985 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07003986 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003987 mHwPaused = true;
3988 }
3989 // If we were part way through writing the mixbuffer to
3990 // the HAL we must save this until we resume
3991 // BUG - this will be wrong if a different track is made active,
3992 // in that case we want to discard the pending data in the
3993 // mixbuffer and tell the client to present it again when the
3994 // track is resumed
3995 mPausedWriteLength = mCurrentWriteLength;
3996 mPausedBytesRemaining = mBytesRemaining;
3997 mBytesRemaining = 0; // stop writing
3998 }
3999 tracksToRemove->add(track);
4000 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004001 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004002 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004003 if (track->mFillingUpStatus == Track::FS_FILLED) {
4004 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004005 // make sure processVolume_l() will apply new volume even if 0
4006 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007 if (track->mState == TrackBase::RESUMING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004008 track->mState = TrackBase::ACTIVE;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004009 if (last) {
4010 if (mPausedBytesRemaining) {
4011 // Need to continue write that was interrupted
4012 mCurrentWriteLength = mPausedWriteLength;
4013 mBytesRemaining = mPausedBytesRemaining;
4014 mPausedBytesRemaining = 0;
4015 }
4016 if (mHwPaused) {
4017 doHwResume = true;
4018 mHwPaused = false;
4019 // threadLoop_mix() will handle the case that we need to
4020 // resume an interrupted write
4021 }
4022 // enable write to audio HAL
4023 sleepTime = 0;
4024 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004025 }
4026 }
4027
4028 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004029 sp<Track> previousTrack = mPreviousTrack.promote();
4030 if (previousTrack != 0) {
4031 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004032 // Flush any data still being written from last track
4033 mBytesRemaining = 0;
4034 if (mPausedBytesRemaining) {
4035 // Last track was paused so we also need to flush saved
4036 // mixbuffer state and invalidate track so that it will
4037 // re-submit that unwritten data when it is next resumed
4038 mPausedBytesRemaining = 0;
4039 // Invalidate is a bit drastic - would be more efficient
4040 // to have a flag to tell client that some of the
4041 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004042 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004043 }
4044 // flush data already sent to the DSP if changing audio session as audio
4045 // comes from a different source. Also invalidate previous track to force a
4046 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004047 if (previousTrack->sessionId() != track->sessionId()) {
4048 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004049 mFlushPending = true;
4050 }
4051 }
4052 }
4053 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004054 // reset retry count
4055 track->mRetryCount = kMaxTrackRetriesOffload;
4056 mActiveTrack = t;
4057 mixerStatus = MIXER_TRACKS_READY;
4058 }
4059 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004060 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004061 if (track->isStopping_1()) {
4062 // Hardware buffer can hold a large amount of audio so we must
4063 // wait for all current track's data to drain before we say
4064 // that the track is stopped.
4065 if (mBytesRemaining == 0) {
4066 // Only start draining when all data in mixbuffer
4067 // has been written
4068 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4069 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004070 // do not drain if no data was ever sent to HAL (mStandby == true)
4071 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004072 // do not modify drain sequence if we are already draining. This happens
4073 // when resuming from pause after drain.
4074 if ((mDrainSequence & 1) == 0) {
4075 sleepTime = 0;
4076 standbyTime = systemTime() + standbyDelay;
4077 mixerStatus = MIXER_DRAIN_TRACK;
4078 mDrainSequence += 2;
4079 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004080 if (mHwPaused) {
4081 // It is possible to move from PAUSED to STOPPING_1 without
4082 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004083 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 mHwPaused = false;
4085 }
4086 }
4087 }
4088 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004089 // Drain has completed or we are in standby, signal presentation complete
4090 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004091 track->mState = TrackBase::STOPPED;
4092 size_t audioHALFrames =
4093 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4094 size_t framesWritten =
4095 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4096 track->presentationComplete(framesWritten, audioHALFrames);
4097 track->reset();
4098 tracksToRemove->add(track);
4099 }
4100 } else {
4101 // No buffers for this track. Give it a few chances to
4102 // fill a buffer, then remove it from active list.
4103 if (--(track->mRetryCount) <= 0) {
4104 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4105 track->name());
4106 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004107 // indicate to client process that the track was disabled because of underrun;
4108 // it will then automatically call start() when data is available
4109 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004110 } else if (last){
4111 mixerStatus = MIXER_TRACKS_ENABLED;
4112 }
4113 }
4114 }
4115 // compute volume for this track
4116 processVolume_l(track, last);
4117 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004118
Eric Laurentea0fade2013-10-04 16:23:48 -07004119 // make sure the pause/flush/resume sequence is executed in the right order.
4120 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4121 // before flush and then resume HW. This can happen in case of pause/flush/resume
4122 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004123 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004124 mOutput->stream->pause(mOutput->stream);
Eric Laurentea0fade2013-10-04 16:23:48 -07004125 if (!doHwPause) {
4126 doHwResume = true;
4127 }
Eric Laurent972a1732013-09-04 09:42:59 -07004128 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004129 if (mFlushPending) {
4130 flushHw_l();
4131 mFlushPending = false;
4132 }
Eric Laurentfd477972013-10-25 18:10:40 -07004133 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004134 mOutput->stream->resume(mOutput->stream);
4135 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004136
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137 // remove all the tracks that need to be...
4138 removeTracks_l(*tracksToRemove);
4139
4140 return mixerStatus;
4141}
4142
4143void AudioFlinger::OffloadThread::flushOutput_l()
4144{
4145 mFlushPending = true;
4146}
4147
4148// must be called with thread mutex locked
4149bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4150{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004151 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4152 mWriteAckSequence, mDrainSequence);
4153 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 return true;
4155 }
4156 return false;
4157}
4158
4159// must be called with thread mutex locked
4160bool AudioFlinger::OffloadThread::shouldStandby_l()
4161{
4162 bool TrackPaused = false;
4163
4164 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4165 // after a timeout and we will enter standby then.
4166 if (mTracks.size() > 0) {
4167 TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4168 }
4169
4170 return !mStandby && !TrackPaused;
4171}
4172
4173
4174bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4175{
4176 Mutex::Autolock _l(mLock);
4177 return waitingAsyncCallback_l();
4178}
4179
4180void AudioFlinger::OffloadThread::flushHw_l()
4181{
4182 mOutput->stream->flush(mOutput->stream);
4183 // Flush anything still waiting in the mixbuffer
4184 mCurrentWriteLength = 0;
4185 mBytesRemaining = 0;
4186 mPausedWriteLength = 0;
4187 mPausedBytesRemaining = 0;
4188 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004189 // discard any pending drain or write ack by incrementing sequence
4190 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4191 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004193 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4194 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195 }
4196}
4197
4198// ----------------------------------------------------------------------------
4199
Eric Laurent81784c32012-11-19 14:55:58 -08004200AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4201 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4202 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4203 DUPLICATING),
4204 mWaitTimeMs(UINT_MAX)
4205{
4206 addOutputTrack(mainThread);
4207}
4208
4209AudioFlinger::DuplicatingThread::~DuplicatingThread()
4210{
4211 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4212 mOutputTracks[i]->destroy();
4213 }
4214}
4215
4216void AudioFlinger::DuplicatingThread::threadLoop_mix()
4217{
4218 // mix buffers...
4219 if (outputsReady(outputTracks)) {
4220 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4221 } else {
4222 memset(mMixBuffer, 0, mixBufferSize);
4223 }
4224 sleepTime = 0;
4225 writeFrames = mNormalFrameCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004226 mCurrentWriteLength = mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004227 standbyTime = systemTime() + standbyDelay;
4228}
4229
4230void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4231{
4232 if (sleepTime == 0) {
4233 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4234 sleepTime = activeSleepTime;
4235 } else {
4236 sleepTime = idleSleepTime;
4237 }
4238 } else if (mBytesWritten != 0) {
4239 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4240 writeFrames = mNormalFrameCount;
4241 memset(mMixBuffer, 0, mixBufferSize);
4242 } else {
4243 // flush remaining overflow buffers in output tracks
4244 writeFrames = 0;
4245 }
4246 sleepTime = 0;
4247 }
4248}
4249
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004251{
4252 for (size_t i = 0; i < outputTracks.size(); i++) {
4253 outputTracks[i]->write(mMixBuffer, writeFrames);
4254 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004255 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004256 return (ssize_t)mixBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004257}
4258
4259void AudioFlinger::DuplicatingThread::threadLoop_standby()
4260{
4261 // DuplicatingThread implements standby by stopping all tracks
4262 for (size_t i = 0; i < outputTracks.size(); i++) {
4263 outputTracks[i]->stop();
4264 }
4265}
4266
4267void AudioFlinger::DuplicatingThread::saveOutputTracks()
4268{
4269 outputTracks = mOutputTracks;
4270}
4271
4272void AudioFlinger::DuplicatingThread::clearOutputTracks()
4273{
4274 outputTracks.clear();
4275}
4276
4277void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4278{
4279 Mutex::Autolock _l(mLock);
4280 // FIXME explain this formula
4281 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4282 OutputTrack *outputTrack = new OutputTrack(thread,
4283 this,
4284 mSampleRate,
4285 mFormat,
4286 mChannelMask,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004287 frameCount,
4288 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004289 if (outputTrack->cblk() != NULL) {
4290 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4291 mOutputTracks.add(outputTrack);
4292 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4293 updateWaitTime_l();
4294 }
4295}
4296
4297void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4298{
4299 Mutex::Autolock _l(mLock);
4300 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4301 if (mOutputTracks[i]->thread() == thread) {
4302 mOutputTracks[i]->destroy();
4303 mOutputTracks.removeAt(i);
4304 updateWaitTime_l();
4305 return;
4306 }
4307 }
4308 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4309}
4310
4311// caller must hold mLock
4312void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4313{
4314 mWaitTimeMs = UINT_MAX;
4315 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4316 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4317 if (strong != 0) {
4318 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4319 if (waitTimeMs < mWaitTimeMs) {
4320 mWaitTimeMs = waitTimeMs;
4321 }
4322 }
4323 }
4324}
4325
4326
4327bool AudioFlinger::DuplicatingThread::outputsReady(
4328 const SortedVector< sp<OutputTrack> > &outputTracks)
4329{
4330 for (size_t i = 0; i < outputTracks.size(); i++) {
4331 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4332 if (thread == 0) {
4333 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4334 outputTracks[i].get());
4335 return false;
4336 }
4337 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4338 // see note at standby() declaration
4339 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4340 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4341 thread.get());
4342 return false;
4343 }
4344 }
4345 return true;
4346}
4347
4348uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4349{
4350 return (mWaitTimeMs * 1000) / 2;
4351}
4352
4353void AudioFlinger::DuplicatingThread::cacheParameters_l()
4354{
4355 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4356 updateWaitTime_l();
4357
4358 MixerThread::cacheParameters_l();
4359}
4360
4361// ----------------------------------------------------------------------------
4362// Record
4363// ----------------------------------------------------------------------------
4364
4365AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4366 AudioStreamIn *input,
4367 uint32_t sampleRate,
4368 audio_channel_mask_t channelMask,
4369 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004370 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004371 audio_devices_t inDevice
4372#ifdef TEE_SINK
4373 , const sp<NBAIO_Sink>& teeSink
4374#endif
4375 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004376 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Eric Laurent81784c32012-11-19 14:55:58 -08004377 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten548efc92012-11-29 08:48:51 -08004378 // mRsmpInIndex and mBufferSize set by readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -08004379 mReqChannelCount(popcount(channelMask)),
Glenn Kasten46909e72013-02-26 09:20:22 -08004380 mReqSampleRate(sampleRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004381 // mBytesRead is only meaningful while active, and so is cleared in start()
4382 // (but might be better to also clear here for dump?)
Glenn Kasten46909e72013-02-26 09:20:22 -08004383#ifdef TEE_SINK
4384 , mTeeSink(teeSink)
4385#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004386{
4387 snprintf(mName, kNameLength, "AudioIn_%X", id);
4388
4389 readInputParameters();
Eric Laurent81784c32012-11-19 14:55:58 -08004390}
4391
4392
4393AudioFlinger::RecordThread::~RecordThread()
4394{
4395 delete[] mRsmpInBuffer;
4396 delete mResampler;
4397 delete[] mRsmpOutBuffer;
4398}
4399
4400void AudioFlinger::RecordThread::onFirstRef()
4401{
4402 run(mName, PRIORITY_URGENT_AUDIO);
4403}
4404
4405status_t AudioFlinger::RecordThread::readyToRun()
4406{
4407 status_t status = initCheck();
4408 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4409 return status;
4410}
4411
4412bool AudioFlinger::RecordThread::threadLoop()
4413{
4414 AudioBufferProvider::Buffer buffer;
4415 sp<RecordTrack> activeTrack;
4416 Vector< sp<EffectChain> > effectChains;
4417
4418 nsecs_t lastWarning = 0;
4419
4420 inputStandBy();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004421 {
4422 Mutex::Autolock _l(mLock);
4423 activeTrack = mActiveTrack;
4424 acquireWakeLock_l(activeTrack != 0 ? activeTrack->uid() : -1);
4425 }
Eric Laurent81784c32012-11-19 14:55:58 -08004426
4427 // used to verify we've read at least once before evaluating how many bytes were read
4428 bool readOnce = false;
4429
4430 // start recording
4431 while (!exitPending()) {
4432
4433 processConfigEvents();
4434
4435 { // scope for mLock
4436 Mutex::Autolock _l(mLock);
4437 checkForNewParameters_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -08004438 if (mActiveTrack != 0 && activeTrack != mActiveTrack) {
4439 SortedVector<int> tmp;
4440 tmp.add(mActiveTrack->uid());
4441 updateWakeLockUids_l(tmp);
4442 }
4443 activeTrack = mActiveTrack;
Eric Laurent81784c32012-11-19 14:55:58 -08004444 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4445 standby();
4446
4447 if (exitPending()) {
4448 break;
4449 }
4450
4451 releaseWakeLock_l();
4452 ALOGV("RecordThread: loop stopping");
4453 // go to sleep
4454 mWaitWorkCV.wait(mLock);
4455 ALOGV("RecordThread: loop starting");
Marco Nelissen9cae2172013-01-14 14:12:05 -08004456 acquireWakeLock_l(mActiveTrack != 0 ? mActiveTrack->uid() : -1);
Eric Laurent81784c32012-11-19 14:55:58 -08004457 continue;
4458 }
4459 if (mActiveTrack != 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004460 if (mActiveTrack->isTerminated()) {
4461 removeTrack_l(mActiveTrack);
4462 mActiveTrack.clear();
4463 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08004464 standby();
4465 mActiveTrack.clear();
4466 mStartStopCond.broadcast();
4467 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4468 if (mReqChannelCount != mActiveTrack->channelCount()) {
4469 mActiveTrack.clear();
4470 mStartStopCond.broadcast();
4471 } else if (readOnce) {
4472 // record start succeeds only if first read from audio input
4473 // succeeds
4474 if (mBytesRead >= 0) {
4475 mActiveTrack->mState = TrackBase::ACTIVE;
4476 } else {
4477 mActiveTrack.clear();
4478 }
4479 mStartStopCond.broadcast();
4480 }
4481 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004482 }
4483 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07004484
Eric Laurent81784c32012-11-19 14:55:58 -08004485 lockEffectChains_l(effectChains);
4486 }
4487
4488 if (mActiveTrack != 0) {
4489 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4490 mActiveTrack->mState != TrackBase::RESUMING) {
4491 unlockEffectChains(effectChains);
4492 usleep(kRecordThreadSleepUs);
4493 continue;
4494 }
4495 for (size_t i = 0; i < effectChains.size(); i ++) {
4496 effectChains[i]->process_l();
4497 }
4498
4499 buffer.frameCount = mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004500 status_t status = mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004501 if (status == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004502 readOnce = true;
4503 size_t framesOut = buffer.frameCount;
4504 if (mResampler == NULL) {
4505 // no resampling
4506 while (framesOut) {
4507 size_t framesIn = mFrameCount - mRsmpInIndex;
4508 if (framesIn) {
4509 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4510 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4511 mActiveTrack->mFrameSize;
4512 if (framesIn > framesOut)
4513 framesIn = framesOut;
4514 mRsmpInIndex += framesIn;
4515 framesOut -= framesIn;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004516 if (mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004517 memcpy(dst, src, framesIn * mFrameSize);
4518 } else {
4519 if (mChannelCount == 1) {
4520 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4521 (int16_t *)src, framesIn);
4522 } else {
4523 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4524 (int16_t *)src, framesIn);
4525 }
4526 }
4527 }
4528 if (framesOut && mFrameCount == mRsmpInIndex) {
4529 void *readInto;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07004530 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08004531 readInto = buffer.raw;
4532 framesOut = 0;
4533 } else {
4534 readInto = mRsmpInBuffer;
4535 mRsmpInIndex = 0;
4536 }
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004537 mBytesRead = mInput->stream->read(mInput->stream, readInto,
Glenn Kasten548efc92012-11-29 08:48:51 -08004538 mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004539 if (mBytesRead <= 0) {
4540 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4541 {
4542 ALOGE("Error reading audio input");
4543 // Force input into standby so that it tries to
4544 // recover at next read attempt
4545 inputStandBy();
4546 usleep(kRecordThreadSleepUs);
4547 }
4548 mRsmpInIndex = mFrameCount;
4549 framesOut = 0;
4550 buffer.frameCount = 0;
Glenn Kasten46909e72013-02-26 09:20:22 -08004551 }
4552#ifdef TEE_SINK
4553 else if (mTeeSink != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004554 (void) mTeeSink->write(readInto,
4555 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4556 }
Glenn Kasten46909e72013-02-26 09:20:22 -08004557#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004558 }
4559 }
4560 } else {
4561 // resampling
4562
Glenn Kasten34af0262013-07-30 11:52:39 -07004563 // resampler accumulates, but we only have one source track
4564 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
Eric Laurent81784c32012-11-19 14:55:58 -08004565 // alter output frame count as if we were expecting stereo samples
4566 if (mChannelCount == 1 && mReqChannelCount == 1) {
4567 framesOut >>= 1;
4568 }
4569 mResampler->resample(mRsmpOutBuffer, framesOut,
4570 this /* AudioBufferProvider* */);
4571 // ditherAndClamp() works as long as all buffers returned by
4572 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4573 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten34af0262013-07-30 11:52:39 -07004574 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
Eric Laurent81784c32012-11-19 14:55:58 -08004575 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4576 // the resampler always outputs stereo samples:
4577 // do post stereo to mono conversion
4578 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4579 framesOut);
4580 } else {
4581 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4582 }
Glenn Kasten34af0262013-07-30 11:52:39 -07004583 // now done with mRsmpOutBuffer
Eric Laurent81784c32012-11-19 14:55:58 -08004584
4585 }
4586 if (mFramestoDrop == 0) {
4587 mActiveTrack->releaseBuffer(&buffer);
4588 } else {
4589 if (mFramestoDrop > 0) {
4590 mFramestoDrop -= buffer.frameCount;
4591 if (mFramestoDrop <= 0) {
4592 clearSyncStartEvent();
4593 }
4594 } else {
4595 mFramestoDrop += buffer.frameCount;
4596 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4597 mSyncStartEvent->isCancelled()) {
4598 ALOGW("Synced record %s, session %d, trigger session %d",
4599 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4600 mActiveTrack->sessionId(),
4601 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4602 clearSyncStartEvent();
4603 }
4604 }
4605 }
4606 mActiveTrack->clearOverflow();
4607 }
4608 // client isn't retrieving buffers fast enough
4609 else {
4610 if (!mActiveTrack->setOverflow()) {
4611 nsecs_t now = systemTime();
4612 if ((now - lastWarning) > kWarningThrottleNs) {
4613 ALOGW("RecordThread: buffer overflow");
4614 lastWarning = now;
4615 }
4616 }
4617 // Release the processor for a while before asking for a new buffer.
4618 // This will give the application more chance to read from the buffer and
4619 // clear the overflow.
4620 usleep(kRecordThreadSleepUs);
4621 }
4622 }
4623 // enable changes in effect chain
4624 unlockEffectChains(effectChains);
4625 effectChains.clear();
4626 }
4627
4628 standby();
4629
4630 {
4631 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07004632 for (size_t i = 0; i < mTracks.size(); i++) {
4633 sp<RecordTrack> track = mTracks[i];
4634 track->invalidate();
4635 }
Eric Laurent81784c32012-11-19 14:55:58 -08004636 mActiveTrack.clear();
4637 mStartStopCond.broadcast();
4638 }
4639
4640 releaseWakeLock();
4641
4642 ALOGV("RecordThread %p exiting", this);
4643 return false;
4644}
4645
4646void AudioFlinger::RecordThread::standby()
4647{
4648 if (!mStandby) {
4649 inputStandBy();
4650 mStandby = true;
4651 }
4652}
4653
4654void AudioFlinger::RecordThread::inputStandBy()
4655{
4656 mInput->stream->common.standby(&mInput->stream->common);
4657}
4658
4659sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4660 const sp<AudioFlinger::Client>& client,
4661 uint32_t sampleRate,
4662 audio_format_t format,
4663 audio_channel_mask_t channelMask,
4664 size_t frameCount,
4665 int sessionId,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004666 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07004667 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08004668 pid_t tid,
4669 status_t *status)
4670{
4671 sp<RecordTrack> track;
4672 status_t lStatus;
4673
4674 lStatus = initCheck();
4675 if (lStatus != NO_ERROR) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004676 ALOGE("createRecordTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08004677 goto Exit;
4678 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07004679 // client expresses a preference for FAST, but we get the final say
4680 if (*flags & IAudioFlinger::TRACK_FAST) {
4681 if (
4682 // use case: callback handler and frame count is default or at least as large as HAL
4683 (
4684 (tid != -1) &&
4685 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08004686 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07004687 ) &&
4688 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4689 // mono or stereo
4690 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4691 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4692 // hardware sample rate
4693 (sampleRate == mSampleRate) &&
4694 // record thread has an associated fast recorder
4695 hasFastRecorder()
4696 // FIXME test that RecordThread for this fast track has a capable output HAL
4697 // FIXME add a permission test also?
4698 ) {
4699 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4700 if (frameCount == 0) {
4701 frameCount = mFrameCount * kFastTrackMultiplier;
4702 }
4703 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4704 frameCount, mFrameCount);
4705 } else {
4706 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4707 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4708 "hasFastRecorder=%d tid=%d",
4709 frameCount, mFrameCount, format,
4710 audio_is_linear_pcm(format),
4711 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4712 *flags &= ~IAudioFlinger::TRACK_FAST;
4713 // For compatibility with AudioRecord calculation, buffer depth is forced
4714 // to be at least 2 x the record thread frame count and cover audio hardware latency.
4715 // This is probably too conservative, but legacy application code may depend on it.
4716 // If you change this calculation, also review the start threshold which is related.
4717 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4718 size_t mNormalFrameCount = 2048; // FIXME
4719 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4720 if (minBufCount < 2) {
4721 minBufCount = 2;
4722 }
4723 size_t minFrameCount = mNormalFrameCount * minBufCount;
4724 if (frameCount < minFrameCount) {
4725 frameCount = minFrameCount;
4726 }
4727 }
4728 }
4729
Eric Laurent81784c32012-11-19 14:55:58 -08004730 // FIXME use flags and tid similar to createTrack_l()
4731
4732 { // scope for mLock
4733 Mutex::Autolock _l(mLock);
4734
4735 track = new RecordTrack(this, client, sampleRate,
Marco Nelissen9cae2172013-01-14 14:12:05 -08004736 format, channelMask, frameCount, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08004737
4738 if (track->getCblk() == 0) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004739 ALOGE("createRecordTrack_l() no control block");
Eric Laurent81784c32012-11-19 14:55:58 -08004740 lStatus = NO_MEMORY;
Glenn Kastene93cf2c2013-09-24 11:52:37 -07004741 track.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004742 goto Exit;
4743 }
4744 mTracks.add(track);
4745
4746 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4747 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4748 mAudioFlinger->btNrecIsOff();
4749 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4750 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07004751
4752 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4753 pid_t callingPid = IPCThreadState::self()->getCallingPid();
4754 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4755 // so ask activity manager to do this on our behalf
4756 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4757 }
Eric Laurent81784c32012-11-19 14:55:58 -08004758 }
4759 lStatus = NO_ERROR;
4760
4761Exit:
4762 if (status) {
4763 *status = lStatus;
4764 }
4765 return track;
4766}
4767
4768status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4769 AudioSystem::sync_event_t event,
4770 int triggerSession)
4771{
4772 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4773 sp<ThreadBase> strongMe = this;
4774 status_t status = NO_ERROR;
4775
4776 if (event == AudioSystem::SYNC_EVENT_NONE) {
4777 clearSyncStartEvent();
4778 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4779 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4780 triggerSession,
4781 recordTrack->sessionId(),
4782 syncStartEventCallback,
4783 this);
4784 // Sync event can be cancelled by the trigger session if the track is not in a
4785 // compatible state in which case we start record immediately
4786 if (mSyncStartEvent->isCancelled()) {
4787 clearSyncStartEvent();
4788 } else {
4789 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4790 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4791 }
4792 }
4793
4794 {
4795 AutoMutex lock(mLock);
4796 if (mActiveTrack != 0) {
4797 if (recordTrack != mActiveTrack.get()) {
4798 status = -EBUSY;
4799 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4800 mActiveTrack->mState = TrackBase::ACTIVE;
4801 }
4802 return status;
4803 }
4804
4805 recordTrack->mState = TrackBase::IDLE;
4806 mActiveTrack = recordTrack;
4807 mLock.unlock();
4808 status_t status = AudioSystem::startInput(mId);
4809 mLock.lock();
4810 if (status != NO_ERROR) {
4811 mActiveTrack.clear();
4812 clearSyncStartEvent();
4813 return status;
4814 }
4815 mRsmpInIndex = mFrameCount;
4816 mBytesRead = 0;
4817 if (mResampler != NULL) {
4818 mResampler->reset();
4819 }
4820 mActiveTrack->mState = TrackBase::RESUMING;
4821 // signal thread to start
4822 ALOGV("Signal record thread");
4823 mWaitWorkCV.broadcast();
4824 // do not wait for mStartStopCond if exiting
4825 if (exitPending()) {
4826 mActiveTrack.clear();
4827 status = INVALID_OPERATION;
4828 goto startError;
4829 }
4830 mStartStopCond.wait(mLock);
4831 if (mActiveTrack == 0) {
4832 ALOGV("Record failed to start");
4833 status = BAD_VALUE;
4834 goto startError;
4835 }
4836 ALOGV("Record started OK");
4837 return status;
4838 }
Glenn Kasten7c027242012-12-26 14:43:16 -08004839
Eric Laurent81784c32012-11-19 14:55:58 -08004840startError:
4841 AudioSystem::stopInput(mId);
4842 clearSyncStartEvent();
4843 return status;
4844}
4845
4846void AudioFlinger::RecordThread::clearSyncStartEvent()
4847{
4848 if (mSyncStartEvent != 0) {
4849 mSyncStartEvent->cancel();
4850 }
4851 mSyncStartEvent.clear();
4852 mFramestoDrop = 0;
4853}
4854
4855void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4856{
4857 sp<SyncEvent> strongEvent = event.promote();
4858
4859 if (strongEvent != 0) {
4860 RecordThread *me = (RecordThread *)strongEvent->cookie();
4861 me->handleSyncStartEvent(strongEvent);
4862 }
4863}
4864
4865void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4866{
4867 if (event == mSyncStartEvent) {
4868 // TODO: use actual buffer filling status instead of 2 buffers when info is available
4869 // from audio HAL
4870 mFramestoDrop = mFrameCount * 2;
4871 }
4872}
4873
Glenn Kastena8356f62013-07-25 14:37:52 -07004874bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08004875 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07004876 AutoMutex _l(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08004877 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4878 return false;
4879 }
4880 recordTrack->mState = TrackBase::PAUSING;
4881 // do not wait for mStartStopCond if exiting
4882 if (exitPending()) {
4883 return true;
4884 }
4885 mStartStopCond.wait(mLock);
4886 // if we have been restarted, recordTrack == mActiveTrack.get() here
4887 if (exitPending() || recordTrack != mActiveTrack.get()) {
4888 ALOGV("Record stopped OK");
4889 return true;
4890 }
4891 return false;
4892}
4893
4894bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4895{
4896 return false;
4897}
4898
4899status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4900{
4901#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
4902 if (!isValidSyncEvent(event)) {
4903 return BAD_VALUE;
4904 }
4905
4906 int eventSession = event->triggerSession();
4907 status_t ret = NAME_NOT_FOUND;
4908
4909 Mutex::Autolock _l(mLock);
4910
4911 for (size_t i = 0; i < mTracks.size(); i++) {
4912 sp<RecordTrack> track = mTracks[i];
4913 if (eventSession == track->sessionId()) {
4914 (void) track->setSyncEvent(event);
4915 ret = NO_ERROR;
4916 }
4917 }
4918 return ret;
4919#else
4920 return BAD_VALUE;
4921#endif
4922}
4923
4924// destroyTrack_l() must be called with ThreadBase::mLock held
4925void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4926{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004927 track->terminate();
4928 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08004929 // active tracks are removed by threadLoop()
4930 if (mActiveTrack != track) {
4931 removeTrack_l(track);
4932 }
4933}
4934
4935void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4936{
4937 mTracks.remove(track);
4938 // need anything related to effects here?
4939}
4940
4941void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4942{
4943 dumpInternals(fd, args);
4944 dumpTracks(fd, args);
4945 dumpEffectChains(fd, args);
4946}
4947
4948void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4949{
4950 const size_t SIZE = 256;
4951 char buffer[SIZE];
4952 String8 result;
4953
4954 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4955 result.append(buffer);
4956
4957 if (mActiveTrack != 0) {
4958 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4959 result.append(buffer);
Glenn Kasten548efc92012-11-29 08:48:51 -08004960 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004961 result.append(buffer);
4962 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4963 result.append(buffer);
4964 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4965 result.append(buffer);
4966 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4967 result.append(buffer);
4968 } else {
4969 result.append("No active record client\n");
4970 }
4971
4972 write(fd, result.string(), result.size());
4973
4974 dumpBase(fd, args);
4975}
4976
4977void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4978{
4979 const size_t SIZE = 256;
4980 char buffer[SIZE];
4981 String8 result;
4982
4983 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4984 result.append(buffer);
4985 RecordTrack::appendDumpHeader(result);
4986 for (size_t i = 0; i < mTracks.size(); ++i) {
4987 sp<RecordTrack> track = mTracks[i];
4988 if (track != 0) {
4989 track->dump(buffer, SIZE);
4990 result.append(buffer);
4991 }
4992 }
4993
4994 if (mActiveTrack != 0) {
4995 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4996 result.append(buffer);
4997 RecordTrack::appendDumpHeader(result);
4998 mActiveTrack->dump(buffer, SIZE);
4999 result.append(buffer);
5000
5001 }
5002 write(fd, result.string(), result.size());
5003}
5004
5005// AudioBufferProvider interface
5006status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5007{
5008 size_t framesReq = buffer->frameCount;
5009 size_t framesReady = mFrameCount - mRsmpInIndex;
5010 int channelCount;
5011
5012 if (framesReady == 0) {
Glenn Kasten548efc92012-11-29 08:48:51 -08005013 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005014 if (mBytesRead <= 0) {
5015 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5016 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5017 // Force input into standby so that it tries to
5018 // recover at next read attempt
5019 inputStandBy();
5020 usleep(kRecordThreadSleepUs);
5021 }
5022 buffer->raw = NULL;
5023 buffer->frameCount = 0;
5024 return NOT_ENOUGH_DATA;
5025 }
5026 mRsmpInIndex = 0;
5027 framesReady = mFrameCount;
5028 }
5029
5030 if (framesReq > framesReady) {
5031 framesReq = framesReady;
5032 }
5033
5034 if (mChannelCount == 1 && mReqChannelCount == 2) {
5035 channelCount = 1;
5036 } else {
5037 channelCount = 2;
5038 }
5039 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5040 buffer->frameCount = framesReq;
5041 return NO_ERROR;
5042}
5043
5044// AudioBufferProvider interface
5045void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5046{
5047 mRsmpInIndex += buffer->frameCount;
5048 buffer->frameCount = 0;
5049}
5050
5051bool AudioFlinger::RecordThread::checkForNewParameters_l()
5052{
5053 bool reconfig = false;
5054
5055 while (!mNewParameters.isEmpty()) {
5056 status_t status = NO_ERROR;
5057 String8 keyValuePair = mNewParameters[0];
5058 AudioParameter param = AudioParameter(keyValuePair);
5059 int value;
5060 audio_format_t reqFormat = mFormat;
5061 uint32_t reqSamplingRate = mReqSampleRate;
5062 uint32_t reqChannelCount = mReqChannelCount;
5063
5064 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5065 reqSamplingRate = value;
5066 reconfig = true;
5067 }
5068 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005069 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5070 status = BAD_VALUE;
5071 } else {
5072 reqFormat = (audio_format_t) value;
5073 reconfig = true;
5074 }
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
5076 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5077 reqChannelCount = popcount(value);
5078 reconfig = true;
5079 }
5080 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5081 // do not accept frame count changes if tracks are open as the track buffer
5082 // size depends on frame count and correct behavior would not be guaranteed
5083 // if frame count is changed after track creation
5084 if (mActiveTrack != 0) {
5085 status = INVALID_OPERATION;
5086 } else {
5087 reconfig = true;
5088 }
5089 }
5090 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5091 // forward device change to effects that have requested to be
5092 // aware of attached audio device.
5093 for (size_t i = 0; i < mEffectChains.size(); i++) {
5094 mEffectChains[i]->setDevice_l(value);
5095 }
5096
5097 // store input device and output device but do not forward output device to audio HAL.
5098 // Note that status is ignored by the caller for output device
5099 // (see AudioFlinger::setParameters()
5100 if (audio_is_output_devices(value)) {
5101 mOutDevice = value;
5102 status = BAD_VALUE;
5103 } else {
5104 mInDevice = value;
5105 // disable AEC and NS if the device is a BT SCO headset supporting those
5106 // pre processings
5107 if (mTracks.size() > 0) {
5108 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5109 mAudioFlinger->btNrecIsOff();
5110 for (size_t i = 0; i < mTracks.size(); i++) {
5111 sp<RecordTrack> track = mTracks[i];
5112 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5113 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5114 }
5115 }
5116 }
5117 }
5118 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5119 mAudioSource != (audio_source_t)value) {
5120 // forward device change to effects that have requested to be
5121 // aware of attached audio device.
5122 for (size_t i = 0; i < mEffectChains.size(); i++) {
5123 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5124 }
5125 mAudioSource = (audio_source_t)value;
5126 }
5127 if (status == NO_ERROR) {
5128 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5129 keyValuePair.string());
5130 if (status == INVALID_OPERATION) {
5131 inputStandBy();
5132 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5133 keyValuePair.string());
5134 }
5135 if (reconfig) {
5136 if (status == BAD_VALUE &&
5137 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5138 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005139 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Eric Laurent81784c32012-11-19 14:55:58 -08005140 <= (2 * reqSamplingRate)) &&
5141 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5142 <= FCC_2 &&
5143 (reqChannelCount <= FCC_2)) {
5144 status = NO_ERROR;
5145 }
5146 if (status == NO_ERROR) {
5147 readInputParameters();
5148 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5149 }
5150 }
5151 }
5152
5153 mNewParameters.removeAt(0);
5154
5155 mParamStatus = status;
5156 mParamCond.signal();
5157 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5158 // already timed out waiting for the status and will never signal the condition.
5159 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5160 }
5161 return reconfig;
5162}
5163
5164String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5165{
Eric Laurent81784c32012-11-19 14:55:58 -08005166 Mutex::Autolock _l(mLock);
5167 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005168 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005169 }
5170
Glenn Kastend8ea6992013-07-16 14:17:15 -07005171 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5172 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005173 free(s);
5174 return out_s8;
5175}
5176
5177void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5178 AudioSystem::OutputDescriptor desc;
5179 void *param2 = NULL;
5180
5181 switch (event) {
5182 case AudioSystem::INPUT_OPENED:
5183 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005184 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005185 desc.samplingRate = mSampleRate;
5186 desc.format = mFormat;
5187 desc.frameCount = mFrameCount;
5188 desc.latency = 0;
5189 param2 = &desc;
5190 break;
5191
5192 case AudioSystem::INPUT_CLOSED:
5193 default:
5194 break;
5195 }
5196 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5197}
5198
5199void AudioFlinger::RecordThread::readInputParameters()
5200{
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005201 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005202 // mRsmpInBuffer is always assigned a new[] below
Andrei V. FOMITCHEVeb144bb2012-10-09 11:33:25 +02005203 delete[] mRsmpOutBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005204 mRsmpOutBuffer = NULL;
5205 delete mResampler;
5206 mResampler = NULL;
5207
5208 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5209 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005210 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005211 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005212 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5213 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5214 }
Eric Laurent81784c32012-11-19 14:55:58 -08005215 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005216 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5217 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005218 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5219
5220 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5221 {
5222 int channelCount;
5223 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5224 // stereo to mono post process as the resampler always outputs stereo.
5225 if (mChannelCount == 1 && mReqChannelCount == 2) {
5226 channelCount = 1;
5227 } else {
5228 channelCount = 2;
5229 }
5230 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5231 mResampler->setSampleRate(mSampleRate);
5232 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
Glenn Kasten34af0262013-07-30 11:52:39 -07005233 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
Eric Laurent81784c32012-11-19 14:55:58 -08005234
5235 // optmization: if mono to mono, alter input frame count as if we were inputing
5236 // stereo samples
5237 if (mChannelCount == 1 && mReqChannelCount == 1) {
5238 mFrameCount >>= 1;
5239 }
5240
5241 }
5242 mRsmpInIndex = mFrameCount;
5243}
5244
5245unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5246{
5247 Mutex::Autolock _l(mLock);
5248 if (initCheck() != NO_ERROR) {
5249 return 0;
5250 }
5251
5252 return mInput->stream->get_input_frames_lost(mInput->stream);
5253}
5254
5255uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5256{
5257 Mutex::Autolock _l(mLock);
5258 uint32_t result = 0;
5259 if (getEffectChain_l(sessionId) != 0) {
5260 result = EFFECT_SESSION;
5261 }
5262
5263 for (size_t i = 0; i < mTracks.size(); ++i) {
5264 if (sessionId == mTracks[i]->sessionId()) {
5265 result |= TRACK_SESSION;
5266 break;
5267 }
5268 }
5269
5270 return result;
5271}
5272
5273KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5274{
5275 KeyedVector<int, bool> ids;
5276 Mutex::Autolock _l(mLock);
5277 for (size_t j = 0; j < mTracks.size(); ++j) {
5278 sp<RecordThread::RecordTrack> track = mTracks[j];
5279 int sessionId = track->sessionId();
5280 if (ids.indexOfKey(sessionId) < 0) {
5281 ids.add(sessionId, true);
5282 }
5283 }
5284 return ids;
5285}
5286
5287AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5288{
5289 Mutex::Autolock _l(mLock);
5290 AudioStreamIn *input = mInput;
5291 mInput = NULL;
5292 return input;
5293}
5294
5295// this method must always be called either with ThreadBase mLock held or inside the thread loop
5296audio_stream_t* AudioFlinger::RecordThread::stream() const
5297{
5298 if (mInput == NULL) {
5299 return NULL;
5300 }
5301 return &mInput->stream->common;
5302}
5303
5304status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5305{
5306 // only one chain per input thread
5307 if (mEffectChains.size() != 0) {
5308 return INVALID_OPERATION;
5309 }
5310 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5311
5312 chain->setInBuffer(NULL);
5313 chain->setOutBuffer(NULL);
5314
5315 checkSuspendOnAddEffectChain_l(chain);
5316
5317 mEffectChains.add(chain);
5318
5319 return NO_ERROR;
5320}
5321
5322size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5323{
5324 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5325 ALOGW_IF(mEffectChains.size() != 1,
5326 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5327 chain.get(), mEffectChains.size(), this);
5328 if (mEffectChains.size() == 1) {
5329 mEffectChains.removeAt(0);
5330 }
5331 return 0;
5332}
5333
5334}; // namespace android