blob: aeca41e858aa93d1ed33077ff63989f677f07365 [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>
Andy Hung98ef9782014-03-04 14:46:50 -080037#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039
40// NBAIO implementations
41#include <media/nbaio/AudioStreamOutSink.h>
42#include <media/nbaio/MonoPipe.h>
43#include <media/nbaio/MonoPipeReader.h>
44#include <media/nbaio/Pipe.h>
45#include <media/nbaio/PipeReader.h>
46#include <media/nbaio/SourceAudioBufferProvider.h>
47
48#include <powermanager/PowerManager.h>
49
50#include <common_time/cc_helper.h>
51#include <common_time/local_clock.h>
52
53#include "AudioFlinger.h"
54#include "AudioMixer.h"
55#include "FastMixer.h"
56#include "ServiceUtilities.h"
57#include "SchedulingPolicyService.h"
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef DEBUG_CPU_USAGE
65#include <cpustats/CentralTendencyStatistics.h>
66#include <cpustats/ThreadCpuUsage.h>
67#endif
68
69// ----------------------------------------------------------------------------
70
71// Note: the following macro is used for extremely verbose logging message. In
72// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
73// 0; but one side effect of this is to turn all LOGV's as well. Some messages
74// are so verbose that we want to suppress them even when we have ALOG_ASSERT
75// turned on. Do not uncomment the #def below unless you really know what you
76// are doing and want to see all of the extremely verbose messages.
77//#define VERY_VERY_VERBOSE_LOGGING
78#ifdef VERY_VERY_VERBOSE_LOGGING
79#define ALOGVV ALOGV
80#else
81#define ALOGVV(a...) do { } while(0)
82#endif
83
84namespace android {
85
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95// don't warn about blocked writes or record buffer overflows more often than this
96static const nsecs_t kWarningThrottleNs = seconds(5);
97
98// RecordThread loop sleep time upon application overrun or audio HAL read error
99static const int kRecordThreadSleepUs = 5000;
100
Eric Laurent10351942014-05-08 18:49:52 -0700101// maximum time to wait in sendConfigEvent_l() for a status to be received
102static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800103
104// minimum sleep time for the mixer thread loop when tracks are active but in underrun
105static const uint32_t kMinThreadSleepTimeUs = 5000;
106// maximum divider applied to the active sleep time in the mixer thread loop
107static const uint32_t kMaxThreadSleepTimeShift = 2;
108
Andy Hung09a50072014-02-27 14:30:47 -0800109// minimum normal sink buffer size, expressed in milliseconds rather than frames
110static const uint32_t kMinNormalSinkBufferSizeMs = 20;
111// maximum normal sink buffer size
112static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800113
Eric Laurent972a1732013-09-04 09:42:59 -0700114// Offloaded output thread standby delay: allows track transition without going to standby
115static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
116
Eric Laurent81784c32012-11-19 14:55:58 -0800117// Whether to use fast mixer
118static const enum {
119 FastMixer_Never, // never initialize or use: for debugging only
120 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
121 // normal mixer multiplier is 1
122 FastMixer_Static, // initialize if needed, then use all the time if initialized,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
125 // multiplier is calculated based on min & max normal mixer buffer size
126 // FIXME for FastMixer_Dynamic:
127 // Supporting this option will require fixing HALs that can't handle large writes.
128 // For example, one HAL implementation returns an error from a large write,
129 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
130 // We could either fix the HAL implementations, or provide a wrapper that breaks
131 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
132} kUseFastMixer = FastMixer_Static;
133
134// Priorities for requestPriority
135static const int kPriorityAudioApp = 2;
136static const int kPriorityFastMixer = 3;
137
138// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
139// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800140// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
141// So for now we just assume that client is double-buffered for fast tracks.
142// FIXME It would be better for client to tell AudioFlinger the value of N,
143// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800144// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800145static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800146
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700147// See Thread::readOnlyHeap().
148// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
149// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
150// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
151static const size_t kRecordThreadReadOnlyHeapSize = 0x1000;
152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// ----------------------------------------------------------------------------
154
155#ifdef ADD_BATTERY_DATA
156// To collect the amplifier usage
157static void addBatteryData(uint32_t params) {
158 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
159 if (service == NULL) {
160 // it already logged
161 return;
162 }
163
164 service->addBatteryData(params);
165}
166#endif
167
168
169// ----------------------------------------------------------------------------
170// CPU Stats
171// ----------------------------------------------------------------------------
172
173class CpuStats {
174public:
175 CpuStats();
176 void sample(const String8 &title);
177#ifdef DEBUG_CPU_USAGE
178private:
179 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
180 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
181
182 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
183
184 int mCpuNum; // thread's current CPU number
185 int mCpukHz; // frequency of thread's current CPU in kHz
186#endif
187};
188
189CpuStats::CpuStats()
190#ifdef DEBUG_CPU_USAGE
191 : mCpuNum(-1), mCpukHz(-1)
192#endif
193{
194}
195
Glenn Kasten0f11b512014-01-31 16:18:54 -0800196void CpuStats::sample(const String8 &title
197#ifndef DEBUG_CPU_USAGE
198 __unused
199#endif
200 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800201#ifdef DEBUG_CPU_USAGE
202 // get current thread's delta CPU time in wall clock ns
203 double wcNs;
204 bool valid = mCpuUsage.sampleAndEnable(wcNs);
205
206 // record sample for wall clock statistics
207 if (valid) {
208 mWcStats.sample(wcNs);
209 }
210
211 // get the current CPU number
212 int cpuNum = sched_getcpu();
213
214 // get the current CPU frequency in kHz
215 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
216
217 // check if either CPU number or frequency changed
218 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
219 mCpuNum = cpuNum;
220 mCpukHz = cpukHz;
221 // ignore sample for purposes of cycles
222 valid = false;
223 }
224
225 // if no change in CPU number or frequency, then record sample for cycle statistics
226 if (valid && mCpukHz > 0) {
227 double cycles = wcNs * cpukHz * 0.000001;
228 mHzStats.sample(cycles);
229 }
230
231 unsigned n = mWcStats.n();
232 // mCpuUsage.elapsed() is expensive, so don't call it every loop
233 if ((n & 127) == 1) {
234 long long elapsed = mCpuUsage.elapsed();
235 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
236 double perLoop = elapsed / (double) n;
237 double perLoop100 = perLoop * 0.01;
238 double perLoop1k = perLoop * 0.001;
239 double mean = mWcStats.mean();
240 double stddev = mWcStats.stddev();
241 double minimum = mWcStats.minimum();
242 double maximum = mWcStats.maximum();
243 double meanCycles = mHzStats.mean();
244 double stddevCycles = mHzStats.stddev();
245 double minCycles = mHzStats.minimum();
246 double maxCycles = mHzStats.maximum();
247 mCpuUsage.resetElapsed();
248 mWcStats.reset();
249 mHzStats.reset();
250 ALOGD("CPU usage for %s over past %.1f secs\n"
251 " (%u mixer loops at %.1f mean ms per loop):\n"
252 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
253 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
254 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
255 title.string(),
256 elapsed * .000000001, n, perLoop * .000001,
257 mean * .001,
258 stddev * .001,
259 minimum * .001,
260 maximum * .001,
261 mean / perLoop100,
262 stddev / perLoop100,
263 minimum / perLoop100,
264 maximum / perLoop100,
265 meanCycles / perLoop1k,
266 stddevCycles / perLoop1k,
267 minCycles / perLoop1k,
268 maxCycles / perLoop1k);
269
270 }
271 }
272#endif
273};
274
275// ----------------------------------------------------------------------------
276// ThreadBase
277// ----------------------------------------------------------------------------
278
279AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
280 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
281 : Thread(false /*canCallJava*/),
282 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700283 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700284 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800285 // are set by PlaybackThread::readOutputParameters_l() or
286 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700287 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800288 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
289 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
290 // mName will be set by concrete (non-virtual) subclass
291 mDeathRecipient(new PMDeathRecipient(this))
292{
293}
294
295AudioFlinger::ThreadBase::~ThreadBase()
296{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700297 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700298 mConfigEvents.clear();
299
Eric Laurent81784c32012-11-19 14:55:58 -0800300 // do not lock the mutex in destructor
301 releaseWakeLock_l();
302 if (mPowerManager != 0) {
303 sp<IBinder> binder = mPowerManager->asBinder();
304 binder->unlinkToDeath(mDeathRecipient);
305 }
306}
307
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700308status_t AudioFlinger::ThreadBase::readyToRun()
309{
310 status_t status = initCheck();
311 if (status == NO_ERROR) {
312 ALOGI("AudioFlinger's thread %p ready to run", this);
313 } else {
314 ALOGE("No working audio driver found.");
315 }
316 return status;
317}
318
Eric Laurent81784c32012-11-19 14:55:58 -0800319void AudioFlinger::ThreadBase::exit()
320{
321 ALOGV("ThreadBase::exit");
322 // do any cleanup required for exit to succeed
323 preExit();
324 {
325 // This lock prevents the following race in thread (uniprocessor for illustration):
326 // if (!exitPending()) {
327 // // context switch from here to exit()
328 // // exit() calls requestExit(), what exitPending() observes
329 // // exit() calls signal(), which is dropped since no waiters
330 // // context switch back from exit() to here
331 // mWaitWorkCV.wait(...);
332 // // now thread is hung
333 // }
334 AutoMutex lock(mLock);
335 requestExit();
336 mWaitWorkCV.broadcast();
337 }
338 // When Thread::requestExitAndWait is made virtual and this method is renamed to
339 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
340 requestExitAndWait();
341}
342
343status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
344{
345 status_t status;
346
347 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
348 Mutex::Autolock _l(mLock);
349
Eric Laurent10351942014-05-08 18:49:52 -0700350 return sendSetParameterConfigEvent_l(keyValuePairs);
351}
352
353// sendConfigEvent_l() must be called with ThreadBase::mLock held
354// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
355status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
356{
357 status_t status = NO_ERROR;
358
359 mConfigEvents.add(event);
360 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800361 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700362 mLock.unlock();
363 {
364 Mutex::Autolock _l(event->mLock);
365 while (event->mWaitStatus) {
366 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
367 event->mStatus = TIMED_OUT;
368 event->mWaitStatus = false;
369 }
370 }
371 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800372 }
Eric Laurent10351942014-05-08 18:49:52 -0700373 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800374 return status;
375}
376
377void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
378{
379 Mutex::Autolock _l(mLock);
380 sendIoConfigEvent_l(event, param);
381}
382
383// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
384void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
385{
Eric Laurent10351942014-05-08 18:49:52 -0700386 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
387 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800388}
389
390// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
391void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
392{
Eric Laurent10351942014-05-08 18:49:52 -0700393 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
394 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800395}
396
Eric Laurent10351942014-05-08 18:49:52 -0700397// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
398status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800399{
Eric Laurent10351942014-05-08 18:49:52 -0700400 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
401 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700402}
403
Eric Laurent1c333e22014-05-20 10:48:17 -0700404status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
405 const struct audio_patch *patch,
406 audio_patch_handle_t *handle)
407{
408 Mutex::Autolock _l(mLock);
409 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
410 status_t status = sendConfigEvent_l(configEvent);
411 if (status == NO_ERROR) {
412 CreateAudioPatchConfigEventData *data =
413 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
414 *handle = data->mHandle;
415 }
416 return status;
417}
418
419status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
420 const audio_patch_handle_t handle)
421{
422 Mutex::Autolock _l(mLock);
423 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
424 return sendConfigEvent_l(configEvent);
425}
426
427
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700428// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700429void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700430{
Eric Laurent10351942014-05-08 18:49:52 -0700431 bool configChanged = false;
432
Eric Laurent81784c32012-11-19 14:55:58 -0800433 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700434 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
435 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800436 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700437 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700438 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700439 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
440 // FIXME Need to understand why this has to be done asynchronously
441 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700442 true /*asynchronous*/);
443 if (err != 0) {
444 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700445 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700446 }
447 } break;
448 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700449 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700450 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700451 } break;
452 case CFG_EVENT_SET_PARAMETER: {
453 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
454 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
455 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700456 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700457 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700458 case CFG_EVENT_CREATE_AUDIO_PATCH: {
459 CreateAudioPatchConfigEventData *data =
460 (CreateAudioPatchConfigEventData *)event->mData.get();
461 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
462 } break;
463 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
464 ReleaseAudioPatchConfigEventData *data =
465 (ReleaseAudioPatchConfigEventData *)event->mData.get();
466 event->mStatus = releaseAudioPatch_l(data->mHandle);
467 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700468 default:
Eric Laurent10351942014-05-08 18:49:52 -0700469 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700470 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800471 }
Eric Laurent10351942014-05-08 18:49:52 -0700472 {
473 Mutex::Autolock _l(event->mLock);
474 if (event->mWaitStatus) {
475 event->mWaitStatus = false;
476 event->mCond.signal();
477 }
478 }
479 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
480 }
481
482 if (configChanged) {
483 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800484 }
Eric Laurent81784c32012-11-19 14:55:58 -0800485}
486
Marco Nelissenb2208842014-02-07 14:00:50 -0800487String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
488 String8 s;
489 if (output) {
490 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
491 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
492 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
493 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
494 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
495 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
496 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
497 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
498 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
499 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
500 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
501 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
502 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
503 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
504 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
505 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
506 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
507 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
508 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
509 } else {
510 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
511 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
512 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
513 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
514 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
515 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
516 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
517 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
518 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
519 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
520 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
521 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
522 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
523 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
524 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
525 }
526 int len = s.length();
527 if (s.length() > 2) {
528 char *str = s.lockBuffer(len);
529 s.unlockBuffer(len - 2);
530 }
531 return s;
532}
533
Glenn Kasten0f11b512014-01-31 16:18:54 -0800534void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800535{
536 const size_t SIZE = 256;
537 char buffer[SIZE];
538 String8 result;
539
540 bool locked = AudioFlinger::dumpTryLock(mLock);
541 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700542 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800543 }
544
Elliott Hughes87cebad2014-05-22 10:14:43 -0700545 dprintf(fd, " I/O handle: %d\n", mId);
546 dprintf(fd, " TID: %d\n", getTid());
547 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
548 dprintf(fd, " Sample rate: %u\n", mSampleRate);
549 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
550 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
551 dprintf(fd, " Channel Count: %u\n", mChannelCount);
552 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800553 channelMaskToString(mChannelMask, mType != RECORD).string());
Elliott Hughes87cebad2014-05-22 10:14:43 -0700554 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
555 dprintf(fd, " Frame size: %zu\n", mFrameSize);
556 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800557 size_t numConfig = mConfigEvents.size();
558 if (numConfig) {
559 for (size_t i = 0; i < numConfig; i++) {
560 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700561 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800562 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700563 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800564 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700565 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800566 }
Eric Laurent81784c32012-11-19 14:55:58 -0800567
568 if (locked) {
569 mLock.unlock();
570 }
571}
572
573void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
574{
575 const size_t SIZE = 256;
576 char buffer[SIZE];
577 String8 result;
578
Marco Nelissenb2208842014-02-07 14:00:50 -0800579 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000580 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800581 write(fd, buffer, strlen(buffer));
582
Marco Nelissenb2208842014-02-07 14:00:50 -0800583 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800584 sp<EffectChain> chain = mEffectChains[i];
585 if (chain != 0) {
586 chain->dump(fd, args);
587 }
588 }
589}
590
Marco Nelissene14a5d62013-10-03 08:51:24 -0700591void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800592{
593 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700594 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800595}
596
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100597String16 AudioFlinger::ThreadBase::getWakeLockTag()
598{
599 switch (mType) {
600 case MIXER:
601 return String16("AudioMix");
602 case DIRECT:
603 return String16("AudioDirectOut");
604 case DUPLICATING:
605 return String16("AudioDup");
606 case RECORD:
607 return String16("AudioIn");
608 case OFFLOAD:
609 return String16("AudioOffload");
610 default:
611 ALOG_ASSERT(false);
612 return String16("AudioUnknown");
613 }
614}
615
Marco Nelissene14a5d62013-10-03 08:51:24 -0700616void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800617{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800618 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800619 if (mPowerManager != 0) {
620 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700621 status_t status;
622 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700623 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700624 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100625 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700626 String16("media"),
627 uid);
628 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700629 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700630 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100631 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700632 String16("media"));
633 }
Eric Laurent81784c32012-11-19 14:55:58 -0800634 if (status == NO_ERROR) {
635 mWakeLockToken = binder;
636 }
637 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
638 }
639}
640
641void AudioFlinger::ThreadBase::releaseWakeLock()
642{
643 Mutex::Autolock _l(mLock);
644 releaseWakeLock_l();
645}
646
647void AudioFlinger::ThreadBase::releaseWakeLock_l()
648{
649 if (mWakeLockToken != 0) {
650 ALOGV("releaseWakeLock_l() %s", mName);
651 if (mPowerManager != 0) {
652 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
653 }
654 mWakeLockToken.clear();
655 }
656}
657
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800658void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
659 Mutex::Autolock _l(mLock);
660 updateWakeLockUids_l(uids);
661}
662
663void AudioFlinger::ThreadBase::getPowerManager_l() {
664
665 if (mPowerManager == 0) {
666 // use checkService() to avoid blocking if power service is not up yet
667 sp<IBinder> binder =
668 defaultServiceManager()->checkService(String16("power"));
669 if (binder == 0) {
670 ALOGW("Thread %s cannot connect to the power manager service", mName);
671 } else {
672 mPowerManager = interface_cast<IPowerManager>(binder);
673 binder->linkToDeath(mDeathRecipient);
674 }
675 }
676}
677
678void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
679
680 getPowerManager_l();
681 if (mWakeLockToken == NULL) {
682 ALOGE("no wake lock to update!");
683 return;
684 }
685 if (mPowerManager != 0) {
686 sp<IBinder> binder = new BBinder();
687 status_t status;
688 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
689 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
690 }
691}
692
Eric Laurent81784c32012-11-19 14:55:58 -0800693void AudioFlinger::ThreadBase::clearPowerManager()
694{
695 Mutex::Autolock _l(mLock);
696 releaseWakeLock_l();
697 mPowerManager.clear();
698}
699
Glenn Kasten0f11b512014-01-31 16:18:54 -0800700void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800701{
702 sp<ThreadBase> thread = mThread.promote();
703 if (thread != 0) {
704 thread->clearPowerManager();
705 }
706 ALOGW("power manager service died !!!");
707}
708
709void AudioFlinger::ThreadBase::setEffectSuspended(
710 const effect_uuid_t *type, bool suspend, int sessionId)
711{
712 Mutex::Autolock _l(mLock);
713 setEffectSuspended_l(type, suspend, sessionId);
714}
715
716void AudioFlinger::ThreadBase::setEffectSuspended_l(
717 const effect_uuid_t *type, bool suspend, int sessionId)
718{
719 sp<EffectChain> chain = getEffectChain_l(sessionId);
720 if (chain != 0) {
721 if (type != NULL) {
722 chain->setEffectSuspended_l(type, suspend);
723 } else {
724 chain->setEffectSuspendedAll_l(suspend);
725 }
726 }
727
728 updateSuspendedSessions_l(type, suspend, sessionId);
729}
730
731void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
732{
733 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
734 if (index < 0) {
735 return;
736 }
737
738 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
739 mSuspendedSessions.valueAt(index);
740
741 for (size_t i = 0; i < sessionEffects.size(); i++) {
742 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
743 for (int j = 0; j < desc->mRefCount; j++) {
744 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
745 chain->setEffectSuspendedAll_l(true);
746 } else {
747 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
748 desc->mType.timeLow);
749 chain->setEffectSuspended_l(&desc->mType, true);
750 }
751 }
752 }
753}
754
755void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
756 bool suspend,
757 int sessionId)
758{
759 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
760
761 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
762
763 if (suspend) {
764 if (index >= 0) {
765 sessionEffects = mSuspendedSessions.valueAt(index);
766 } else {
767 mSuspendedSessions.add(sessionId, sessionEffects);
768 }
769 } else {
770 if (index < 0) {
771 return;
772 }
773 sessionEffects = mSuspendedSessions.valueAt(index);
774 }
775
776
777 int key = EffectChain::kKeyForSuspendAll;
778 if (type != NULL) {
779 key = type->timeLow;
780 }
781 index = sessionEffects.indexOfKey(key);
782
783 sp<SuspendedSessionDesc> desc;
784 if (suspend) {
785 if (index >= 0) {
786 desc = sessionEffects.valueAt(index);
787 } else {
788 desc = new SuspendedSessionDesc();
789 if (type != NULL) {
790 desc->mType = *type;
791 }
792 sessionEffects.add(key, desc);
793 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
794 }
795 desc->mRefCount++;
796 } else {
797 if (index < 0) {
798 return;
799 }
800 desc = sessionEffects.valueAt(index);
801 if (--desc->mRefCount == 0) {
802 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
803 sessionEffects.removeItemsAt(index);
804 if (sessionEffects.isEmpty()) {
805 ALOGV("updateSuspendedSessions_l() restore removing session %d",
806 sessionId);
807 mSuspendedSessions.removeItem(sessionId);
808 }
809 }
810 }
811 if (!sessionEffects.isEmpty()) {
812 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
813 }
814}
815
816void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
817 bool enabled,
818 int sessionId)
819{
820 Mutex::Autolock _l(mLock);
821 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
822}
823
824void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
825 bool enabled,
826 int sessionId)
827{
828 if (mType != RECORD) {
829 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
830 // another session. This gives the priority to well behaved effect control panels
831 // and applications not using global effects.
832 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
833 // global effects
834 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
835 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
836 }
837 }
838
839 sp<EffectChain> chain = getEffectChain_l(sessionId);
840 if (chain != 0) {
841 chain->checkSuspendOnEffectEnabled(effect, enabled);
842 }
843}
844
845// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
846sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
847 const sp<AudioFlinger::Client>& client,
848 const sp<IEffectClient>& effectClient,
849 int32_t priority,
850 int sessionId,
851 effect_descriptor_t *desc,
852 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700853 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800854{
855 sp<EffectModule> effect;
856 sp<EffectHandle> handle;
857 status_t lStatus;
858 sp<EffectChain> chain;
859 bool chainCreated = false;
860 bool effectCreated = false;
861 bool effectRegistered = false;
862
863 lStatus = initCheck();
864 if (lStatus != NO_ERROR) {
865 ALOGW("createEffect_l() Audio driver not initialized.");
866 goto Exit;
867 }
868
Andy Hung98ef9782014-03-04 14:46:50 -0800869 // Reject any effect on Direct output threads for now, since the format of
870 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
871 if (mType == DIRECT) {
872 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
873 desc->name, mName);
874 lStatus = BAD_VALUE;
875 goto Exit;
876 }
877
Eric Laurent5baf2af2013-09-12 17:37:00 -0700878 // Allow global effects only on offloaded and mixer threads
879 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
880 switch (mType) {
881 case MIXER:
882 case OFFLOAD:
883 break;
884 case DIRECT:
885 case DUPLICATING:
886 case RECORD:
887 default:
888 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
889 lStatus = BAD_VALUE;
890 goto Exit;
891 }
Eric Laurent81784c32012-11-19 14:55:58 -0800892 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700893
Eric Laurent81784c32012-11-19 14:55:58 -0800894 // Only Pre processor effects are allowed on input threads and only on input threads
895 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
896 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
897 desc->name, desc->flags, mType);
898 lStatus = BAD_VALUE;
899 goto Exit;
900 }
901
902 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
903
904 { // scope for mLock
905 Mutex::Autolock _l(mLock);
906
907 // check for existing effect chain with the requested audio session
908 chain = getEffectChain_l(sessionId);
909 if (chain == 0) {
910 // create a new chain for this session
911 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
912 chain = new EffectChain(this, sessionId);
913 addEffectChain_l(chain);
914 chain->setStrategy(getStrategyForSession_l(sessionId));
915 chainCreated = true;
916 } else {
917 effect = chain->getEffectFromDesc_l(desc);
918 }
919
920 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
921
922 if (effect == 0) {
923 int id = mAudioFlinger->nextUniqueId();
924 // Check CPU and memory usage
925 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
926 if (lStatus != NO_ERROR) {
927 goto Exit;
928 }
929 effectRegistered = true;
930 // create a new effect module if none present in the chain
931 effect = new EffectModule(this, chain, desc, id, sessionId);
932 lStatus = effect->status();
933 if (lStatus != NO_ERROR) {
934 goto Exit;
935 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700936 effect->setOffloaded(mType == OFFLOAD, mId);
937
Eric Laurent81784c32012-11-19 14:55:58 -0800938 lStatus = chain->addEffect_l(effect);
939 if (lStatus != NO_ERROR) {
940 goto Exit;
941 }
942 effectCreated = true;
943
944 effect->setDevice(mOutDevice);
945 effect->setDevice(mInDevice);
946 effect->setMode(mAudioFlinger->getMode());
947 effect->setAudioSource(mAudioSource);
948 }
949 // create effect handle and connect it to effect module
950 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800951 lStatus = handle->initCheck();
952 if (lStatus == OK) {
953 lStatus = effect->addHandle(handle.get());
954 }
Eric Laurent81784c32012-11-19 14:55:58 -0800955 if (enabled != NULL) {
956 *enabled = (int)effect->isEnabled();
957 }
958 }
959
960Exit:
961 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
962 Mutex::Autolock _l(mLock);
963 if (effectCreated) {
964 chain->removeEffect_l(effect);
965 }
966 if (effectRegistered) {
967 AudioSystem::unregisterEffect(effect->id());
968 }
969 if (chainCreated) {
970 removeEffectChain_l(chain);
971 }
972 handle.clear();
973 }
974
Glenn Kasten9156ef32013-08-06 15:39:08 -0700975 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800976 return handle;
977}
978
979sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
980{
981 Mutex::Autolock _l(mLock);
982 return getEffect_l(sessionId, effectId);
983}
984
985sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
986{
987 sp<EffectChain> chain = getEffectChain_l(sessionId);
988 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
989}
990
991// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
992// PlaybackThread::mLock held
993status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
994{
995 // check for existing effect chain with the requested audio session
996 int sessionId = effect->sessionId();
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 bool chainCreated = false;
999
Eric Laurent5baf2af2013-09-12 17:37:00 -07001000 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1001 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1002 this, effect->desc().name, effect->desc().flags);
1003
Eric Laurent81784c32012-11-19 14:55:58 -08001004 if (chain == 0) {
1005 // create a new chain for this session
1006 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1007 chain = new EffectChain(this, sessionId);
1008 addEffectChain_l(chain);
1009 chain->setStrategy(getStrategyForSession_l(sessionId));
1010 chainCreated = true;
1011 }
1012 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1013
1014 if (chain->getEffectFromId_l(effect->id()) != 0) {
1015 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1016 this, effect->desc().name, chain.get());
1017 return BAD_VALUE;
1018 }
1019
Eric Laurent5baf2af2013-09-12 17:37:00 -07001020 effect->setOffloaded(mType == OFFLOAD, mId);
1021
Eric Laurent81784c32012-11-19 14:55:58 -08001022 status_t status = chain->addEffect_l(effect);
1023 if (status != NO_ERROR) {
1024 if (chainCreated) {
1025 removeEffectChain_l(chain);
1026 }
1027 return status;
1028 }
1029
1030 effect->setDevice(mOutDevice);
1031 effect->setDevice(mInDevice);
1032 effect->setMode(mAudioFlinger->getMode());
1033 effect->setAudioSource(mAudioSource);
1034 return NO_ERROR;
1035}
1036
1037void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1038
1039 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1040 effect_descriptor_t desc = effect->desc();
1041 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1042 detachAuxEffect_l(effect->id());
1043 }
1044
1045 sp<EffectChain> chain = effect->chain().promote();
1046 if (chain != 0) {
1047 // remove effect chain if removing last effect
1048 if (chain->removeEffect_l(effect) == 0) {
1049 removeEffectChain_l(chain);
1050 }
1051 } else {
1052 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1053 }
1054}
1055
1056void AudioFlinger::ThreadBase::lockEffectChains_l(
1057 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1058{
1059 effectChains = mEffectChains;
1060 for (size_t i = 0; i < mEffectChains.size(); i++) {
1061 mEffectChains[i]->lock();
1062 }
1063}
1064
1065void AudioFlinger::ThreadBase::unlockEffectChains(
1066 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1067{
1068 for (size_t i = 0; i < effectChains.size(); i++) {
1069 effectChains[i]->unlock();
1070 }
1071}
1072
1073sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1074{
1075 Mutex::Autolock _l(mLock);
1076 return getEffectChain_l(sessionId);
1077}
1078
1079sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1080{
1081 size_t size = mEffectChains.size();
1082 for (size_t i = 0; i < size; i++) {
1083 if (mEffectChains[i]->sessionId() == sessionId) {
1084 return mEffectChains[i];
1085 }
1086 }
1087 return 0;
1088}
1089
1090void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1091{
1092 Mutex::Autolock _l(mLock);
1093 size_t size = mEffectChains.size();
1094 for (size_t i = 0; i < size; i++) {
1095 mEffectChains[i]->setMode_l(mode);
1096 }
1097}
1098
1099void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1100 EffectHandle *handle,
1101 bool unpinIfLast) {
1102
1103 Mutex::Autolock _l(mLock);
1104 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1105 // delete the effect module if removing last handle on it
1106 if (effect->removeHandle(handle) == 0) {
1107 if (!effect->isPinned() || unpinIfLast) {
1108 removeEffect_l(effect);
1109 AudioSystem::unregisterEffect(effect->id());
1110 }
1111 }
1112}
1113
1114// ----------------------------------------------------------------------------
1115// Playback
1116// ----------------------------------------------------------------------------
1117
1118AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1119 AudioStreamOut* output,
1120 audio_io_handle_t id,
1121 audio_devices_t device,
1122 type_t type)
1123 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001124 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001125 mMixerBufferEnabled(false),
1126 mMixerBuffer(NULL),
1127 mMixerBufferSize(0),
1128 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1129 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001130 mEffectBufferEnabled(false),
1131 mEffectBuffer(NULL),
1132 mEffectBufferSize(0),
1133 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1134 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001135 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001136 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001137 // mStreamTypes[] initialized in constructor body
1138 mOutput(output),
1139 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1140 mMixerStatus(MIXER_IDLE),
1141 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1142 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001143 mBytesRemaining(0),
1144 mCurrentWriteLength(0),
1145 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001146 mWriteAckSequence(0),
1147 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001148 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001149 mScreenState(AudioFlinger::mScreenState),
1150 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001151 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1152 // mLatchD, mLatchQ,
1153 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001154{
1155 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001156 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001157
1158 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1159 // it would be safer to explicitly pass initial masterVolume/masterMute as
1160 // parameter.
1161 //
1162 // If the HAL we are using has support for master volume or master mute,
1163 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1164 // and the mute set to false).
1165 mMasterVolume = audioFlinger->masterVolume_l();
1166 mMasterMute = audioFlinger->masterMute_l();
1167 if (mOutput && mOutput->audioHwDev) {
1168 if (mOutput->audioHwDev->canSetMasterVolume()) {
1169 mMasterVolume = 1.0;
1170 }
1171
1172 if (mOutput->audioHwDev->canSetMasterMute()) {
1173 mMasterMute = false;
1174 }
1175 }
1176
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001177 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001178
1179 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1180 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001181 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001182 stream = (audio_stream_type_t) (stream + 1)) {
1183 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1184 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1185 }
1186 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1187 // because mAudioFlinger doesn't have one to copy from
1188}
1189
1190AudioFlinger::PlaybackThread::~PlaybackThread()
1191{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001192 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001193 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001194 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001195 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001196}
1197
1198void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1199{
1200 dumpInternals(fd, args);
1201 dumpTracks(fd, args);
1202 dumpEffectChains(fd, args);
1203}
1204
Glenn Kasten0f11b512014-01-31 16:18:54 -08001205void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001206{
1207 const size_t SIZE = 256;
1208 char buffer[SIZE];
1209 String8 result;
1210
Marco Nelissenb2208842014-02-07 14:00:50 -08001211 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001212 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1213 const stream_type_t *st = &mStreamTypes[i];
1214 if (i > 0) {
1215 result.appendFormat(", ");
1216 }
1217 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1218 if (st->mute) {
1219 result.append("M");
1220 }
1221 }
1222 result.append("\n");
1223 write(fd, result.string(), result.length());
1224 result.clear();
1225
Eric Laurent81784c32012-11-19 14:55:58 -08001226 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1227 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001228 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001229 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001230
1231 size_t numtracks = mTracks.size();
1232 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001233 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001234 size_t numactiveseen = 0;
1235 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001236 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001237 Track::appendDumpHeader(result);
1238 for (size_t i = 0; i < numtracks; ++i) {
1239 sp<Track> track = mTracks[i];
1240 if (track != 0) {
1241 bool active = mActiveTracks.indexOf(track) >= 0;
1242 if (active) {
1243 numactiveseen++;
1244 }
1245 track->dump(buffer, SIZE, active);
1246 result.append(buffer);
1247 }
1248 }
1249 } else {
1250 result.append("\n");
1251 }
1252 if (numactiveseen != numactive) {
1253 // some tracks in the active list were not in the tracks list
1254 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1255 " not in the track list\n");
1256 result.append(buffer);
1257 Track::appendDumpHeader(result);
1258 for (size_t i = 0; i < numactive; ++i) {
1259 sp<Track> track = mActiveTracks[i].promote();
1260 if (track != 0 && mTracks.indexOf(track) < 0) {
1261 track->dump(buffer, SIZE, true);
1262 result.append(buffer);
1263 }
1264 }
1265 }
1266
1267 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001268}
1269
1270void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1271{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001272 dprintf(fd, "\nOutput thread %p:\n", this);
1273 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1274 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1275 dprintf(fd, " Total writes: %d\n", mNumWrites);
1276 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1277 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1278 dprintf(fd, " Suspend count: %d\n", mSuspended);
1279 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1280 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1281 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1282 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001283
1284 dumpBase(fd, args);
1285}
1286
1287// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001288
1289void AudioFlinger::PlaybackThread::onFirstRef()
1290{
1291 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1292}
1293
1294// ThreadBase virtuals
1295void AudioFlinger::PlaybackThread::preExit()
1296{
1297 ALOGV(" preExit()");
1298 // FIXME this is using hard-coded strings but in the future, this functionality will be
1299 // converted to use audio HAL extensions required to support tunneling
1300 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1301}
1302
1303// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1304sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1305 const sp<AudioFlinger::Client>& client,
1306 audio_stream_type_t streamType,
1307 uint32_t sampleRate,
1308 audio_format_t format,
1309 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001310 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001311 const sp<IMemory>& sharedBuffer,
1312 int sessionId,
1313 IAudioFlinger::track_flags_t *flags,
1314 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001315 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001316 status_t *status)
1317{
Glenn Kasten74935e42013-12-19 08:56:45 -08001318 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001319 sp<Track> track;
1320 status_t lStatus;
1321
1322 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1323
1324 // client expresses a preference for FAST, but we get the final say
1325 if (*flags & IAudioFlinger::TRACK_FAST) {
1326 if (
1327 // not timed
1328 (!isTimed) &&
1329 // either of these use cases:
1330 (
1331 // use case 1: shared buffer with any frame count
1332 (
1333 (sharedBuffer != 0)
1334 ) ||
1335 // use case 2: callback handler and frame count is default or at least as large as HAL
1336 (
1337 (tid != -1) &&
1338 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001339 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001340 )
1341 ) &&
1342 // PCM data
1343 audio_is_linear_pcm(format) &&
1344 // mono or stereo
1345 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1346 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001347 // hardware sample rate
1348 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001349 // normal mixer has an associated fast mixer
1350 hasFastMixer() &&
1351 // there are sufficient fast track slots available
1352 (mFastTrackAvailMask != 0)
1353 // FIXME test that MixerThread for this fast track has a capable output HAL
1354 // FIXME add a permission test also?
1355 ) {
1356 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1357 if (frameCount == 0) {
1358 frameCount = mFrameCount * kFastTrackMultiplier;
1359 }
1360 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1361 frameCount, mFrameCount);
1362 } else {
1363 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1364 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1365 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1366 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1367 audio_is_linear_pcm(format),
1368 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1369 *flags &= ~IAudioFlinger::TRACK_FAST;
1370 // For compatibility with AudioTrack calculation, buffer depth is forced
1371 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1372 // This is probably too conservative, but legacy application code may depend on it.
1373 // If you change this calculation, also review the start threshold which is related.
1374 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1375 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1376 if (minBufCount < 2) {
1377 minBufCount = 2;
1378 }
1379 size_t minFrameCount = mNormalFrameCount * minBufCount;
1380 if (frameCount < minFrameCount) {
1381 frameCount = minFrameCount;
1382 }
1383 }
1384 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001385 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001386
Glenn Kastenc3df8382014-03-13 15:05:25 -07001387 switch (mType) {
1388
1389 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001390 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001391 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001392 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1393 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001394 sampleRate, format, channelMask, mOutput, mFormat);
1395 lStatus = BAD_VALUE;
1396 goto Exit;
1397 }
1398 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001399 break;
1400
1401 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001402 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001403 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1404 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001405 sampleRate, format, channelMask, mOutput, mFormat);
1406 lStatus = BAD_VALUE;
1407 goto Exit;
1408 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001409 break;
1410
1411 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001412 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001413 ALOGE("createTrack_l() Bad parameter: format %#x \""
1414 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001415 format, mOutput, mFormat);
1416 lStatus = BAD_VALUE;
1417 goto Exit;
1418 }
Eric Laurent81784c32012-11-19 14:55:58 -08001419 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1420 if (sampleRate > mSampleRate*2) {
1421 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1422 lStatus = BAD_VALUE;
1423 goto Exit;
1424 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001425 break;
1426
Eric Laurent81784c32012-11-19 14:55:58 -08001427 }
1428
1429 lStatus = initCheck();
1430 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001431 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001432 goto Exit;
1433 }
1434
1435 { // scope for mLock
1436 Mutex::Autolock _l(mLock);
1437
1438 // all tracks in same audio session must share the same routing strategy otherwise
1439 // conflicts will happen when tracks are moved from one output to another by audio policy
1440 // manager
1441 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1442 for (size_t i = 0; i < mTracks.size(); ++i) {
1443 sp<Track> t = mTracks[i];
1444 if (t != 0 && !t->isOutputTrack()) {
1445 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1446 if (sessionId == t->sessionId() && strategy != actual) {
1447 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1448 strategy, actual);
1449 lStatus = BAD_VALUE;
1450 goto Exit;
1451 }
1452 }
1453 }
1454
1455 if (!isTimed) {
1456 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001457 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001458 } else {
1459 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001460 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001461 }
Glenn Kasten03003332013-08-06 15:40:54 -07001462
1463 // new Track always returns non-NULL,
1464 // but TimedTrack::create() is a factory that could fail by returning NULL
1465 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1466 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001467 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001468 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001469 goto Exit;
1470 }
1471 mTracks.add(track);
1472
1473 sp<EffectChain> chain = getEffectChain_l(sessionId);
1474 if (chain != 0) {
1475 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1476 track->setMainBuffer(chain->inBuffer());
1477 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1478 chain->incTrackCnt();
1479 }
1480
1481 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1482 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1483 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1484 // so ask activity manager to do this on our behalf
1485 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1486 }
1487 }
1488
1489 lStatus = NO_ERROR;
1490
1491Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001492 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001493 return track;
1494}
1495
1496uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1497{
1498 return latency;
1499}
1500
1501uint32_t AudioFlinger::PlaybackThread::latency() const
1502{
1503 Mutex::Autolock _l(mLock);
1504 return latency_l();
1505}
1506uint32_t AudioFlinger::PlaybackThread::latency_l() const
1507{
1508 if (initCheck() == NO_ERROR) {
1509 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1510 } else {
1511 return 0;
1512 }
1513}
1514
1515void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1516{
1517 Mutex::Autolock _l(mLock);
1518 // Don't apply master volume in SW if our HAL can do it for us.
1519 if (mOutput && mOutput->audioHwDev &&
1520 mOutput->audioHwDev->canSetMasterVolume()) {
1521 mMasterVolume = 1.0;
1522 } else {
1523 mMasterVolume = value;
1524 }
1525}
1526
1527void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1528{
1529 Mutex::Autolock _l(mLock);
1530 // Don't apply master mute in SW if our HAL can do it for us.
1531 if (mOutput && mOutput->audioHwDev &&
1532 mOutput->audioHwDev->canSetMasterMute()) {
1533 mMasterMute = false;
1534 } else {
1535 mMasterMute = muted;
1536 }
1537}
1538
1539void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1540{
1541 Mutex::Autolock _l(mLock);
1542 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001543 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001544}
1545
1546void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1547{
1548 Mutex::Autolock _l(mLock);
1549 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001550 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001551}
1552
1553float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1554{
1555 Mutex::Autolock _l(mLock);
1556 return mStreamTypes[stream].volume;
1557}
1558
1559// addTrack_l() must be called with ThreadBase::mLock held
1560status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1561{
1562 status_t status = ALREADY_EXISTS;
1563
1564 // set retry count for buffer fill
1565 track->mRetryCount = kMaxTrackStartupRetries;
1566 if (mActiveTracks.indexOf(track) < 0) {
1567 // the track is newly added, make sure it fills up all its
1568 // buffers before playing. This is to ensure the client will
1569 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001570 if (!track->isOutputTrack()) {
1571 TrackBase::track_state state = track->mState;
1572 mLock.unlock();
1573 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1574 mLock.lock();
1575 // abort track was stopped/paused while we released the lock
1576 if (state != track->mState) {
1577 if (status == NO_ERROR) {
1578 mLock.unlock();
1579 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1580 mLock.lock();
1581 }
1582 return INVALID_OPERATION;
1583 }
1584 // abort if start is rejected by audio policy manager
1585 if (status != NO_ERROR) {
1586 return PERMISSION_DENIED;
1587 }
1588#ifdef ADD_BATTERY_DATA
1589 // to track the speaker usage
1590 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1591#endif
1592 }
1593
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001594 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001595 track->mResetDone = false;
1596 track->mPresentationCompleteFrames = 0;
1597 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001598 mWakeLockUids.add(track->uid());
1599 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001600 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001601 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1602 if (chain != 0) {
1603 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1604 track->sessionId());
1605 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001606 }
1607
1608 status = NO_ERROR;
1609 }
1610
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001611 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001612 return status;
1613}
1614
Eric Laurentbfb1b832013-01-07 09:53:42 -08001615bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001616{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001617 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001618 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1620 track->mState = TrackBase::STOPPED;
1621 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001622 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001623 } else if (track->isFastTrack() || track->isOffloaded()) {
1624 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001625 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001626
1627 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001628}
1629
1630void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1631{
1632 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1633 mTracks.remove(track);
1634 deleteTrackName_l(track->name());
1635 // redundant as track is about to be destroyed, for dumpsys only
1636 track->mName = -1;
1637 if (track->isFastTrack()) {
1638 int index = track->mFastIndex;
1639 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1640 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1641 mFastTrackAvailMask |= 1 << index;
1642 // redundant as track is about to be destroyed, for dumpsys only
1643 track->mFastIndex = -1;
1644 }
1645 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1646 if (chain != 0) {
1647 chain->decTrackCnt();
1648 }
1649}
1650
Eric Laurentede6c3b2013-09-19 14:37:46 -07001651void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001652{
1653 // Thread could be blocked waiting for async
1654 // so signal it to handle state changes immediately
1655 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1656 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1657 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001658 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001659}
1660
Eric Laurent81784c32012-11-19 14:55:58 -08001661String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1662{
Eric Laurent81784c32012-11-19 14:55:58 -08001663 Mutex::Autolock _l(mLock);
1664 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001665 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001666 }
1667
Glenn Kastend8ea6992013-07-16 14:17:15 -07001668 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1669 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001670 free(s);
1671 return out_s8;
1672}
1673
Eric Laurent021cf962014-05-13 10:18:14 -07001674void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001675 AudioSystem::OutputDescriptor desc;
1676 void *param2 = NULL;
1677
Eric Laurent021cf962014-05-13 10:18:14 -07001678 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001679 param);
1680
1681 switch (event) {
1682 case AudioSystem::OUTPUT_OPENED:
1683 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001684 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001685 desc.samplingRate = mSampleRate;
1686 desc.format = mFormat;
1687 desc.frameCount = mNormalFrameCount; // FIXME see
1688 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001689 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001690 param2 = &desc;
1691 break;
1692
1693 case AudioSystem::STREAM_CONFIG_CHANGED:
1694 param2 = &param;
1695 case AudioSystem::OUTPUT_CLOSED:
1696 default:
1697 break;
1698 }
Eric Laurent021cf962014-05-13 10:18:14 -07001699 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001700}
1701
Eric Laurentbfb1b832013-01-07 09:53:42 -08001702void AudioFlinger::PlaybackThread::writeCallback()
1703{
1704 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001705 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001706}
1707
1708void AudioFlinger::PlaybackThread::drainCallback()
1709{
1710 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001711 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001712}
1713
Eric Laurent3b4529e2013-09-05 18:09:19 -07001714void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001715{
1716 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001717 // reject out of sequence requests
1718 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1719 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001720 mWaitWorkCV.signal();
1721 }
1722}
1723
Eric Laurent3b4529e2013-09-05 18:09:19 -07001724void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001725{
1726 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001727 // reject out of sequence requests
1728 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1729 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001730 mWaitWorkCV.signal();
1731 }
1732}
1733
1734// static
1735int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001736 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001737 void *cookie)
1738{
1739 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1740 ALOGV("asyncCallback() event %d", event);
1741 switch (event) {
1742 case STREAM_CBK_EVENT_WRITE_READY:
1743 me->writeCallback();
1744 break;
1745 case STREAM_CBK_EVENT_DRAIN_READY:
1746 me->drainCallback();
1747 break;
1748 default:
1749 ALOGW("asyncCallback() unknown event %d", event);
1750 break;
1751 }
1752 return 0;
1753}
1754
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001755void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001756{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001757 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001758 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1759 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001760 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001761 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001762 }
1763 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001764 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001765 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1766 }
Andy Hunge5412692014-05-16 11:25:07 -07001767 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001768 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001769 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001770 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001771 }
1772 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001773 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1774 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001775 }
Eric Laurent81784c32012-11-19 14:55:58 -08001776 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001777 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1778 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001779 if (mFrameCount & 15) {
1780 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1781 mFrameCount);
1782 }
1783
Eric Laurentbfb1b832013-01-07 09:53:42 -08001784 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1785 (mOutput->stream->set_callback != NULL)) {
1786 if (mOutput->stream->set_callback(mOutput->stream,
1787 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1788 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001789 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001790 }
1791 }
1792
Andy Hung09a50072014-02-27 14:30:47 -08001793 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001794 double multiplier = 1.0;
1795 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1796 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001797 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1798 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001799 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1800 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1801 maxNormalFrameCount = maxNormalFrameCount & ~15;
1802 if (maxNormalFrameCount < minNormalFrameCount) {
1803 maxNormalFrameCount = minNormalFrameCount;
1804 }
1805 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1806 if (multiplier <= 1.0) {
1807 multiplier = 1.0;
1808 } else if (multiplier <= 2.0) {
1809 if (2 * mFrameCount <= maxNormalFrameCount) {
1810 multiplier = 2.0;
1811 } else {
1812 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1813 }
1814 } else {
1815 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001816 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08001817 // track, but we sometimes have to do this to satisfy the maximum frame count
1818 // constraint)
1819 // FIXME this rounding up should not be done if no HAL SRC
1820 uint32_t truncMult = (uint32_t) multiplier;
1821 if ((truncMult & 1)) {
1822 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1823 ++truncMult;
1824 }
1825 }
1826 multiplier = (double) truncMult;
1827 }
1828 }
1829 mNormalFrameCount = multiplier * mFrameCount;
1830 // round up to nearest 16 frames to satisfy AudioMixer
1831 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001832 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001833 mNormalFrameCount);
1834
Andy Hung010a1a12014-03-13 13:57:33 -07001835 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1836 // Originally this was int16_t[] array, need to remove legacy implications.
1837 free(mSinkBuffer);
1838 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001839 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1840 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1841 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001842 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001843
Andy Hung69aed5f2014-02-25 17:24:40 -08001844 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1845 // drives the output.
1846 free(mMixerBuffer);
1847 mMixerBuffer = NULL;
1848 if (mMixerBufferEnabled) {
1849 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1850 mMixerBufferSize = mNormalFrameCount * mChannelCount
1851 * audio_bytes_per_sample(mMixerBufferFormat);
1852 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1853 }
Andy Hung98ef9782014-03-04 14:46:50 -08001854 free(mEffectBuffer);
1855 mEffectBuffer = NULL;
1856 if (mEffectBufferEnabled) {
1857 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1858 mEffectBufferSize = mNormalFrameCount * mChannelCount
1859 * audio_bytes_per_sample(mEffectBufferFormat);
1860 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1861 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001862
Eric Laurent81784c32012-11-19 14:55:58 -08001863 // force reconfiguration of effect chains and engines to take new buffer size and audio
1864 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001865 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001866 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1867 // matter.
1868 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1869 Vector< sp<EffectChain> > effectChains = mEffectChains;
1870 for (size_t i = 0; i < effectChains.size(); i ++) {
1871 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1872 }
1873}
1874
1875
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001876status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001877{
1878 if (halFrames == NULL || dspFrames == NULL) {
1879 return BAD_VALUE;
1880 }
1881 Mutex::Autolock _l(mLock);
1882 if (initCheck() != NO_ERROR) {
1883 return INVALID_OPERATION;
1884 }
1885 size_t framesWritten = mBytesWritten / mFrameSize;
1886 *halFrames = framesWritten;
1887
1888 if (isSuspended()) {
1889 // return an estimation of rendered frames when the output is suspended
1890 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1891 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1892 return NO_ERROR;
1893 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001894 status_t status;
1895 uint32_t frames;
1896 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1897 *dspFrames = (size_t)frames;
1898 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001899 }
1900}
1901
1902uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1903{
1904 Mutex::Autolock _l(mLock);
1905 uint32_t result = 0;
1906 if (getEffectChain_l(sessionId) != 0) {
1907 result = EFFECT_SESSION;
1908 }
1909
1910 for (size_t i = 0; i < mTracks.size(); ++i) {
1911 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001912 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001913 result |= TRACK_SESSION;
1914 break;
1915 }
1916 }
1917
1918 return result;
1919}
1920
1921uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1922{
1923 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1924 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1925 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1926 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1927 }
1928 for (size_t i = 0; i < mTracks.size(); i++) {
1929 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001930 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001931 return AudioSystem::getStrategyForStream(track->streamType());
1932 }
1933 }
1934 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1935}
1936
1937
1938AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1939{
1940 Mutex::Autolock _l(mLock);
1941 return mOutput;
1942}
1943
1944AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1945{
1946 Mutex::Autolock _l(mLock);
1947 AudioStreamOut *output = mOutput;
1948 mOutput = NULL;
1949 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1950 // must push a NULL and wait for ack
1951 mOutputSink.clear();
1952 mPipeSink.clear();
1953 mNormalSink.clear();
1954 return output;
1955}
1956
1957// this method must always be called either with ThreadBase mLock held or inside the thread loop
1958audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1959{
1960 if (mOutput == NULL) {
1961 return NULL;
1962 }
1963 return &mOutput->stream->common;
1964}
1965
1966uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1967{
1968 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1969}
1970
1971status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1972{
1973 if (!isValidSyncEvent(event)) {
1974 return BAD_VALUE;
1975 }
1976
1977 Mutex::Autolock _l(mLock);
1978
1979 for (size_t i = 0; i < mTracks.size(); ++i) {
1980 sp<Track> track = mTracks[i];
1981 if (event->triggerSession() == track->sessionId()) {
1982 (void) track->setSyncEvent(event);
1983 return NO_ERROR;
1984 }
1985 }
1986
1987 return NAME_NOT_FOUND;
1988}
1989
1990bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1991{
1992 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1993}
1994
1995void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1996 const Vector< sp<Track> >& tracksToRemove)
1997{
1998 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001999 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002000 for (size_t i = 0 ; i < count ; i++) {
2001 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002002 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002003 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002004#ifdef ADD_BATTERY_DATA
2005 // to track the speaker usage
2006 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2007#endif
2008 if (track->isTerminated()) {
2009 AudioSystem::releaseOutput(mId);
2010 }
Eric Laurent81784c32012-11-19 14:55:58 -08002011 }
2012 }
2013 }
Eric Laurent81784c32012-11-19 14:55:58 -08002014}
2015
2016void AudioFlinger::PlaybackThread::checkSilentMode_l()
2017{
2018 if (!mMasterMute) {
2019 char value[PROPERTY_VALUE_MAX];
2020 if (property_get("ro.audio.silent", value, "0") > 0) {
2021 char *endptr;
2022 unsigned long ul = strtoul(value, &endptr, 0);
2023 if (*endptr == '\0' && ul != 0) {
2024 ALOGD("Silence is golden");
2025 // The setprop command will not allow a property to be changed after
2026 // the first time it is set, so we don't have to worry about un-muting.
2027 setMasterMute_l(true);
2028 }
2029 }
2030 }
2031}
2032
2033// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002034ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002035{
2036 // FIXME rewrite to reduce number of system calls
2037 mLastWriteTime = systemTime();
2038 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002040 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002041
2042 // If an NBAIO sink is present, use it to write the normal mixer's submix
2043 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002044 const size_t count = mBytesRemaining / mFrameSize;
2045
Simon Wilson2d590962012-11-29 15:18:50 -08002046 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002047 // update the setpoint when AudioFlinger::mScreenState changes
2048 uint32_t screenState = AudioFlinger::mScreenState;
2049 if (screenState != mScreenState) {
2050 mScreenState = screenState;
2051 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2052 if (pipe != NULL) {
2053 pipe->setAvgFrames((mScreenState & 1) ?
2054 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2055 }
2056 }
Andy Hung010a1a12014-03-13 13:57:33 -07002057 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002058 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002059 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002060 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002061 } else {
2062 bytesWritten = framesWritten;
2063 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002064 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002065 if (status == NO_ERROR) {
2066 size_t totalFramesWritten = mNormalSink->framesWritten();
2067 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2068 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2069 mLatchDValid = true;
2070 }
2071 }
Eric Laurent81784c32012-11-19 14:55:58 -08002072 // otherwise use the HAL / AudioStreamOut directly
2073 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002074 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002075
Eric Laurentbfb1b832013-01-07 09:53:42 -08002076 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002077 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2078 mWriteAckSequence += 2;
2079 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002081 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002083 // FIXME We should have an implementation of timestamps for direct output threads.
2084 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002085 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002086 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002087 if (mUseAsyncWrite &&
2088 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2089 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002090 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002092 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002093 }
Eric Laurent81784c32012-11-19 14:55:58 -08002094 }
2095
Eric Laurent81784c32012-11-19 14:55:58 -08002096 mNumWrites++;
2097 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002098 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099 return bytesWritten;
2100}
2101
2102void AudioFlinger::PlaybackThread::threadLoop_drain()
2103{
2104 if (mOutput->stream->drain) {
2105 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2106 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002107 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2108 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002110 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002111 }
2112 mOutput->stream->drain(mOutput->stream,
2113 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2114 : AUDIO_DRAIN_ALL);
2115 }
2116}
2117
2118void AudioFlinger::PlaybackThread::threadLoop_exit()
2119{
2120 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002121}
2122
2123/*
2124The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002125 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002126 - activeSleepTime from activeSleepTimeUs()
2127 - idleSleepTime from idleSleepTimeUs()
2128 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2129 - maxPeriod from frame count and sample rate (MIXER only)
2130
2131The parameters that affect these derived values are:
2132 - frame count
2133 - frame size
2134 - sample rate
2135 - device type: A2DP or not
2136 - device latency
2137 - format: PCM or not
2138 - active sleep time
2139 - idle sleep time
2140*/
2141
2142void AudioFlinger::PlaybackThread::cacheParameters_l()
2143{
Andy Hung25c2dac2014-02-27 14:56:00 -08002144 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002145 activeSleepTime = activeSleepTimeUs();
2146 idleSleepTime = idleSleepTimeUs();
2147}
2148
2149void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2150{
Glenn Kasten7c027242012-12-26 14:43:16 -08002151 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002152 this, streamType, mTracks.size());
2153 Mutex::Autolock _l(mLock);
2154
2155 size_t size = mTracks.size();
2156 for (size_t i = 0; i < size; i++) {
2157 sp<Track> t = mTracks[i];
2158 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002159 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002160 }
2161 }
2162}
2163
2164status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2165{
2166 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002167 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2168 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002169 bool ownsBuffer = false;
2170
2171 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2172 if (session > 0) {
2173 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002174 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002175 if (mType != DIRECT) {
2176 size_t numSamples = mNormalFrameCount * mChannelCount;
2177 buffer = new int16_t[numSamples];
2178 memset(buffer, 0, numSamples * sizeof(int16_t));
2179 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2180 ownsBuffer = true;
2181 }
2182
2183 // Attach all tracks with same session ID to this chain.
2184 for (size_t i = 0; i < mTracks.size(); ++i) {
2185 sp<Track> track = mTracks[i];
2186 if (session == track->sessionId()) {
2187 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2188 buffer);
2189 track->setMainBuffer(buffer);
2190 chain->incTrackCnt();
2191 }
2192 }
2193
2194 // indicate all active tracks in the chain
2195 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2196 sp<Track> track = mActiveTracks[i].promote();
2197 if (track == 0) {
2198 continue;
2199 }
2200 if (session == track->sessionId()) {
2201 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2202 chain->incActiveTrackCnt();
2203 }
2204 }
2205 }
2206
2207 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002208 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2209 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002210 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2211 // chains list in order to be processed last as it contains output stage effects
2212 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2213 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2214 // after track specific effects and before output stage
2215 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2216 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2217 // Effect chain for other sessions are inserted at beginning of effect
2218 // chains list to be processed before output mix effects. Relative order between other
2219 // sessions is not important
2220 size_t size = mEffectChains.size();
2221 size_t i = 0;
2222 for (i = 0; i < size; i++) {
2223 if (mEffectChains[i]->sessionId() < session) {
2224 break;
2225 }
2226 }
2227 mEffectChains.insertAt(chain, i);
2228 checkSuspendOnAddEffectChain_l(chain);
2229
2230 return NO_ERROR;
2231}
2232
2233size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2234{
2235 int session = chain->sessionId();
2236
2237 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2238
2239 for (size_t i = 0; i < mEffectChains.size(); i++) {
2240 if (chain == mEffectChains[i]) {
2241 mEffectChains.removeAt(i);
2242 // detach all active tracks from the chain
2243 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2244 sp<Track> track = mActiveTracks[i].promote();
2245 if (track == 0) {
2246 continue;
2247 }
2248 if (session == track->sessionId()) {
2249 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2250 chain.get(), session);
2251 chain->decActiveTrackCnt();
2252 }
2253 }
2254
2255 // detach all tracks with same session ID from this chain
2256 for (size_t i = 0; i < mTracks.size(); ++i) {
2257 sp<Track> track = mTracks[i];
2258 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002259 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002260 chain->decTrackCnt();
2261 }
2262 }
2263 break;
2264 }
2265 }
2266 return mEffectChains.size();
2267}
2268
2269status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2270 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2271{
2272 Mutex::Autolock _l(mLock);
2273 return attachAuxEffect_l(track, EffectId);
2274}
2275
2276status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2277 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2278{
2279 status_t status = NO_ERROR;
2280
2281 if (EffectId == 0) {
2282 track->setAuxBuffer(0, NULL);
2283 } else {
2284 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2285 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2286 if (effect != 0) {
2287 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2288 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2289 } else {
2290 status = INVALID_OPERATION;
2291 }
2292 } else {
2293 status = BAD_VALUE;
2294 }
2295 }
2296 return status;
2297}
2298
2299void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2300{
2301 for (size_t i = 0; i < mTracks.size(); ++i) {
2302 sp<Track> track = mTracks[i];
2303 if (track->auxEffectId() == effectId) {
2304 attachAuxEffect_l(track, 0);
2305 }
2306 }
2307}
2308
2309bool AudioFlinger::PlaybackThread::threadLoop()
2310{
2311 Vector< sp<Track> > tracksToRemove;
2312
2313 standbyTime = systemTime();
2314
2315 // MIXER
2316 nsecs_t lastWarning = 0;
2317
2318 // DUPLICATING
2319 // FIXME could this be made local to while loop?
2320 writeFrames = 0;
2321
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002322 int lastGeneration = 0;
2323
Eric Laurent81784c32012-11-19 14:55:58 -08002324 cacheParameters_l();
2325 sleepTime = idleSleepTime;
2326
2327 if (mType == MIXER) {
2328 sleepTimeShift = 0;
2329 }
2330
2331 CpuStats cpuStats;
2332 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2333
2334 acquireWakeLock();
2335
Glenn Kasten9e58b552013-01-18 15:09:48 -08002336 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2337 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2338 // and then that string will be logged at the next convenient opportunity.
2339 const char *logString = NULL;
2340
Eric Laurent664539d2013-09-23 18:24:31 -07002341 checkSilentMode_l();
2342
Eric Laurent81784c32012-11-19 14:55:58 -08002343 while (!exitPending())
2344 {
2345 cpuStats.sample(myName);
2346
2347 Vector< sp<EffectChain> > effectChains;
2348
Eric Laurent81784c32012-11-19 14:55:58 -08002349 { // scope for mLock
2350
2351 Mutex::Autolock _l(mLock);
2352
Eric Laurent021cf962014-05-13 10:18:14 -07002353 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002354
Glenn Kasten9e58b552013-01-18 15:09:48 -08002355 if (logString != NULL) {
2356 mNBLogWriter->logTimestamp();
2357 mNBLogWriter->log(logString);
2358 logString = NULL;
2359 }
2360
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002361 if (mLatchDValid) {
2362 mLatchQ = mLatchD;
2363 mLatchDValid = false;
2364 mLatchQValid = true;
2365 }
2366
Eric Laurent81784c32012-11-19 14:55:58 -08002367 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368 if (mSignalPending) {
2369 // A signal was raised while we were unlocked
2370 mSignalPending = false;
2371 } else if (waitingAsyncCallback_l()) {
2372 if (exitPending()) {
2373 break;
2374 }
2375 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002376 mWakeLockUids.clear();
2377 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 ALOGV("wait async completion");
2379 mWaitWorkCV.wait(mLock);
2380 ALOGV("async completion/wake");
2381 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002382 standbyTime = systemTime() + standbyDelay;
2383 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002384
2385 continue;
2386 }
2387 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388 isSuspended()) {
2389 // put audio hardware into standby after short delay
2390 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002391
2392 threadLoop_standby();
2393
2394 mStandby = true;
2395 }
2396
2397 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2398 // we're about to wait, flush the binder command buffer
2399 IPCThreadState::self()->flushCommands();
2400
2401 clearOutputTracks();
2402
2403 if (exitPending()) {
2404 break;
2405 }
2406
2407 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002408 mWakeLockUids.clear();
2409 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002410 // wait until we have something to do...
2411 ALOGV("%s going to sleep", myName.string());
2412 mWaitWorkCV.wait(mLock);
2413 ALOGV("%s waking up", myName.string());
2414 acquireWakeLock_l();
2415
2416 mMixerStatus = MIXER_IDLE;
2417 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2418 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002419 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002420 checkSilentMode_l();
2421
2422 standbyTime = systemTime() + standbyDelay;
2423 sleepTime = idleSleepTime;
2424 if (mType == MIXER) {
2425 sleepTimeShift = 0;
2426 }
2427
2428 continue;
2429 }
2430 }
Eric Laurent81784c32012-11-19 14:55:58 -08002431 // mMixerStatusIgnoringFastTracks is also updated internally
2432 mMixerStatus = prepareTracks_l(&tracksToRemove);
2433
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002434 // compare with previously applied list
2435 if (lastGeneration != mActiveTracksGeneration) {
2436 // update wakelock
2437 updateWakeLockUids_l(mWakeLockUids);
2438 lastGeneration = mActiveTracksGeneration;
2439 }
2440
Eric Laurent81784c32012-11-19 14:55:58 -08002441 // prevent any changes in effect chain list and in each effect chain
2442 // during mixing and effect process as the audio buffers could be deleted
2443 // or modified if an effect is created or deleted
2444 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002445 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002446
Eric Laurentbfb1b832013-01-07 09:53:42 -08002447 if (mBytesRemaining == 0) {
2448 mCurrentWriteLength = 0;
2449 if (mMixerStatus == MIXER_TRACKS_READY) {
2450 // threadLoop_mix() sets mCurrentWriteLength
2451 threadLoop_mix();
2452 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2453 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2454 // threadLoop_sleepTime sets sleepTime to 0 if data
2455 // must be written to HAL
2456 threadLoop_sleepTime();
2457 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002458 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 }
2460 }
Andy Hung98ef9782014-03-04 14:46:50 -08002461 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2462 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2463 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2464 // or mSinkBuffer (if there are no effects).
2465 //
2466 // This is done pre-effects computation; if effects change to
2467 // support higher precision, this needs to move.
2468 //
2469 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2470 // TODO use sleepTime == 0 as an additional condition.
2471 if (mMixerBufferValid) {
2472 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2473 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2474
2475 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2476 mNormalFrameCount * mChannelCount);
2477 }
2478
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 mBytesRemaining = mCurrentWriteLength;
2480 if (isSuspended()) {
2481 sleepTime = suspendSleepTimeUs();
2482 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002483 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484 mBytesRemaining = 0;
2485 }
Eric Laurent81784c32012-11-19 14:55:58 -08002486
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002488 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002489 for (size_t i = 0; i < effectChains.size(); i ++) {
2490 effectChains[i]->process_l();
2491 }
Eric Laurent81784c32012-11-19 14:55:58 -08002492 }
2493 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002494 // Process effect chains for offloaded thread even if no audio
2495 // was read from audio track: process only updates effect state
2496 // and thus does have to be synchronized with audio writes but may have
2497 // to be called while waiting for async write callback
2498 if (mType == OFFLOAD) {
2499 for (size_t i = 0; i < effectChains.size(); i ++) {
2500 effectChains[i]->process_l();
2501 }
2502 }
Eric Laurent81784c32012-11-19 14:55:58 -08002503
Andy Hung98ef9782014-03-04 14:46:50 -08002504 // Only if the Effects buffer is enabled and there is data in the
2505 // Effects buffer (buffer valid), we need to
2506 // copy into the sink buffer.
2507 // TODO use sleepTime == 0 as an additional condition.
2508 if (mEffectBufferValid) {
2509 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2510 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2511 mNormalFrameCount * mChannelCount);
2512 }
2513
Eric Laurent81784c32012-11-19 14:55:58 -08002514 // enable changes in effect chain
2515 unlockEffectChains(effectChains);
2516
Eric Laurentbfb1b832013-01-07 09:53:42 -08002517 if (!waitingAsyncCallback()) {
2518 // sleepTime == 0 means we must write to audio hardware
2519 if (sleepTime == 0) {
2520 if (mBytesRemaining) {
2521 ssize_t ret = threadLoop_write();
2522 if (ret < 0) {
2523 mBytesRemaining = 0;
2524 } else {
2525 mBytesWritten += ret;
2526 mBytesRemaining -= ret;
2527 }
2528 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2529 (mMixerStatus == MIXER_DRAIN_ALL)) {
2530 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002531 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002532 if (mType == MIXER) {
2533 // write blocked detection
2534 nsecs_t now = systemTime();
2535 nsecs_t delta = now - mLastWriteTime;
2536 if (!mStandby && delta > maxPeriod) {
2537 mNumDelayedWrites++;
2538 if ((now - lastWarning) > kWarningThrottleNs) {
2539 ATRACE_NAME("underrun");
2540 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2541 ns2ms(delta), mNumDelayedWrites, this);
2542 lastWarning = now;
2543 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002544 }
2545 }
Eric Laurent81784c32012-11-19 14:55:58 -08002546
Eric Laurentbfb1b832013-01-07 09:53:42 -08002547 } else {
2548 usleep(sleepTime);
2549 }
Eric Laurent81784c32012-11-19 14:55:58 -08002550 }
2551
2552 // Finally let go of removed track(s), without the lock held
2553 // since we can't guarantee the destructors won't acquire that
2554 // same lock. This will also mutate and push a new fast mixer state.
2555 threadLoop_removeTracks(tracksToRemove);
2556 tracksToRemove.clear();
2557
2558 // FIXME I don't understand the need for this here;
2559 // it was in the original code but maybe the
2560 // assignment in saveOutputTracks() makes this unnecessary?
2561 clearOutputTracks();
2562
2563 // Effect chains will be actually deleted here if they were removed from
2564 // mEffectChains list during mixing or effects processing
2565 effectChains.clear();
2566
2567 // FIXME Note that the above .clear() is no longer necessary since effectChains
2568 // is now local to this block, but will keep it for now (at least until merge done).
2569 }
2570
Eric Laurentbfb1b832013-01-07 09:53:42 -08002571 threadLoop_exit();
2572
Eric Laurent81784c32012-11-19 14:55:58 -08002573 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002575 // put output stream into standby mode
2576 if (!mStandby) {
2577 mOutput->stream->common.standby(&mOutput->stream->common);
2578 }
2579 }
2580
2581 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002582 mWakeLockUids.clear();
2583 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002584
2585 ALOGV("Thread %p type %d exiting", this, mType);
2586 return false;
2587}
2588
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589// removeTracks_l() must be called with ThreadBase::mLock held
2590void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2591{
2592 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002593 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 for (size_t i=0 ; i<count ; i++) {
2595 const sp<Track>& track = tracksToRemove.itemAt(i);
2596 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002597 mWakeLockUids.remove(track->uid());
2598 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2600 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2601 if (chain != 0) {
2602 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2603 track->sessionId());
2604 chain->decActiveTrackCnt();
2605 }
2606 if (track->isTerminated()) {
2607 removeTrack_l(track);
2608 }
2609 }
2610 }
2611
2612}
Eric Laurent81784c32012-11-19 14:55:58 -08002613
Eric Laurentaccc1472013-09-20 09:36:34 -07002614status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2615{
2616 if (mNormalSink != 0) {
2617 return mNormalSink->getTimestamp(timestamp);
2618 }
2619 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2620 uint64_t position64;
2621 int ret = mOutput->stream->get_presentation_position(
2622 mOutput->stream, &position64, &timestamp.mTime);
2623 if (ret == 0) {
2624 timestamp.mPosition = (uint32_t)position64;
2625 return NO_ERROR;
2626 }
2627 }
2628 return INVALID_OPERATION;
2629}
Eric Laurent1c333e22014-05-20 10:48:17 -07002630
2631status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2632 audio_patch_handle_t *handle)
2633{
2634 status_t status = NO_ERROR;
2635 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2636 // store new device and send to effects
2637 audio_devices_t type = AUDIO_DEVICE_NONE;
2638 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2639 type |= patch->sinks[i].ext.device.type;
2640 }
2641 mOutDevice = type;
2642 for (size_t i = 0; i < mEffectChains.size(); i++) {
2643 mEffectChains[i]->setDevice_l(mOutDevice);
2644 }
2645
2646 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2647 status = hwDevice->create_audio_patch(hwDevice,
2648 patch->num_sources,
2649 patch->sources,
2650 patch->num_sinks,
2651 patch->sinks,
2652 handle);
2653 } else {
2654 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2655 }
2656 return status;
2657}
2658
2659status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2660{
2661 status_t status = NO_ERROR;
2662 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2663 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2664 status = hwDevice->release_audio_patch(hwDevice, handle);
2665 } else {
2666 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2667 }
2668 return status;
2669}
2670
Eric Laurent81784c32012-11-19 14:55:58 -08002671// ----------------------------------------------------------------------------
2672
2673AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2674 audio_io_handle_t id, audio_devices_t device, type_t type)
2675 : PlaybackThread(audioFlinger, output, id, device, type),
2676 // mAudioMixer below
2677 // mFastMixer below
2678 mFastMixerFutex(0)
2679 // mOutputSink below
2680 // mPipeSink below
2681 // mNormalSink below
2682{
2683 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002684 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002685 "mFrameCount=%d, mNormalFrameCount=%d",
2686 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2687 mNormalFrameCount);
2688 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2689
2690 // FIXME - Current mixer implementation only supports stereo output
2691 if (mChannelCount != FCC_2) {
2692 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2693 }
2694
2695 // create an NBAIO sink for the HAL output stream, and negotiate
2696 mOutputSink = new AudioStreamOutSink(output->stream);
2697 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002698 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002699 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2700 ALOG_ASSERT(index == 0);
2701
2702 // initialize fast mixer depending on configuration
2703 bool initFastMixer;
2704 switch (kUseFastMixer) {
2705 case FastMixer_Never:
2706 initFastMixer = false;
2707 break;
2708 case FastMixer_Always:
2709 initFastMixer = true;
2710 break;
2711 case FastMixer_Static:
2712 case FastMixer_Dynamic:
2713 initFastMixer = mFrameCount < mNormalFrameCount;
2714 break;
2715 }
2716 if (initFastMixer) {
2717
2718 // create a MonoPipe to connect our submix to FastMixer
2719 NBAIO_Format format = mOutputSink->format();
2720 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2721 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2722 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2723 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2724 const NBAIO_Format offers[1] = {format};
2725 size_t numCounterOffers = 0;
2726 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2727 ALOG_ASSERT(index == 0);
2728 monoPipe->setAvgFrames((mScreenState & 1) ?
2729 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2730 mPipeSink = monoPipe;
2731
Glenn Kasten46909e72013-02-26 09:20:22 -08002732#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002733 if (mTeeSinkOutputEnabled) {
2734 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2735 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2736 numCounterOffers = 0;
2737 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2738 ALOG_ASSERT(index == 0);
2739 mTeeSink = teeSink;
2740 PipeReader *teeSource = new PipeReader(*teeSink);
2741 numCounterOffers = 0;
2742 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2743 ALOG_ASSERT(index == 0);
2744 mTeeSource = teeSource;
2745 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002746#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002747
2748 // create fast mixer and configure it initially with just one fast track for our submix
2749 mFastMixer = new FastMixer();
2750 FastMixerStateQueue *sq = mFastMixer->sq();
2751#ifdef STATE_QUEUE_DUMP
2752 sq->setObserverDump(&mStateQueueObserverDump);
2753 sq->setMutatorDump(&mStateQueueMutatorDump);
2754#endif
2755 FastMixerState *state = sq->begin();
2756 FastTrack *fastTrack = &state->mFastTracks[0];
2757 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2758 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2759 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002760 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2761 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002762 fastTrack->mGeneration++;
2763 state->mFastTracksGen++;
2764 state->mTrackMask = 1;
2765 // fast mixer will use the HAL output sink
2766 state->mOutputSink = mOutputSink.get();
2767 state->mOutputSinkGen++;
2768 state->mFrameCount = mFrameCount;
2769 state->mCommand = FastMixerState::COLD_IDLE;
2770 // already done in constructor initialization list
2771 //mFastMixerFutex = 0;
2772 state->mColdFutexAddr = &mFastMixerFutex;
2773 state->mColdGen++;
2774 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002775#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002776 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002777#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002778 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2779 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002780 sq->end();
2781 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2782
2783 // start the fast mixer
2784 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2785 pid_t tid = mFastMixer->getTid();
2786 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2787 if (err != 0) {
2788 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2789 kPriorityFastMixer, getpid_cached, tid, err);
2790 }
2791
2792#ifdef AUDIO_WATCHDOG
2793 // create and start the watchdog
2794 mAudioWatchdog = new AudioWatchdog();
2795 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2796 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2797 tid = mAudioWatchdog->getTid();
2798 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2799 if (err != 0) {
2800 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2801 kPriorityFastMixer, getpid_cached, tid, err);
2802 }
2803#endif
2804
2805 } else {
2806 mFastMixer = NULL;
2807 }
2808
2809 switch (kUseFastMixer) {
2810 case FastMixer_Never:
2811 case FastMixer_Dynamic:
2812 mNormalSink = mOutputSink;
2813 break;
2814 case FastMixer_Always:
2815 mNormalSink = mPipeSink;
2816 break;
2817 case FastMixer_Static:
2818 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2819 break;
2820 }
2821}
2822
2823AudioFlinger::MixerThread::~MixerThread()
2824{
2825 if (mFastMixer != NULL) {
2826 FastMixerStateQueue *sq = mFastMixer->sq();
2827 FastMixerState *state = sq->begin();
2828 if (state->mCommand == FastMixerState::COLD_IDLE) {
2829 int32_t old = android_atomic_inc(&mFastMixerFutex);
2830 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002831 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002832 }
2833 }
2834 state->mCommand = FastMixerState::EXIT;
2835 sq->end();
2836 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2837 mFastMixer->join();
2838 // Though the fast mixer thread has exited, it's state queue is still valid.
2839 // We'll use that extract the final state which contains one remaining fast track
2840 // corresponding to our sub-mix.
2841 state = sq->begin();
2842 ALOG_ASSERT(state->mTrackMask == 1);
2843 FastTrack *fastTrack = &state->mFastTracks[0];
2844 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2845 delete fastTrack->mBufferProvider;
2846 sq->end(false /*didModify*/);
2847 delete mFastMixer;
2848#ifdef AUDIO_WATCHDOG
2849 if (mAudioWatchdog != 0) {
2850 mAudioWatchdog->requestExit();
2851 mAudioWatchdog->requestExitAndWait();
2852 mAudioWatchdog.clear();
2853 }
2854#endif
2855 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002856 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002857 delete mAudioMixer;
2858}
2859
2860
2861uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2862{
2863 if (mFastMixer != NULL) {
2864 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2865 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2866 }
2867 return latency;
2868}
2869
2870
2871void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2872{
2873 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2874}
2875
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002877{
2878 // FIXME we should only do one push per cycle; confirm this is true
2879 // Start the fast mixer if it's not already running
2880 if (mFastMixer != NULL) {
2881 FastMixerStateQueue *sq = mFastMixer->sq();
2882 FastMixerState *state = sq->begin();
2883 if (state->mCommand != FastMixerState::MIX_WRITE &&
2884 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2885 if (state->mCommand == FastMixerState::COLD_IDLE) {
2886 int32_t old = android_atomic_inc(&mFastMixerFutex);
2887 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002888 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002889 }
2890#ifdef AUDIO_WATCHDOG
2891 if (mAudioWatchdog != 0) {
2892 mAudioWatchdog->resume();
2893 }
2894#endif
2895 }
2896 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002897 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2898 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002899 sq->end();
2900 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2901 if (kUseFastMixer == FastMixer_Dynamic) {
2902 mNormalSink = mPipeSink;
2903 }
2904 } else {
2905 sq->end(false /*didModify*/);
2906 }
2907 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002909}
2910
2911void AudioFlinger::MixerThread::threadLoop_standby()
2912{
2913 // Idle the fast mixer if it's currently running
2914 if (mFastMixer != NULL) {
2915 FastMixerStateQueue *sq = mFastMixer->sq();
2916 FastMixerState *state = sq->begin();
2917 if (!(state->mCommand & FastMixerState::IDLE)) {
2918 state->mCommand = FastMixerState::COLD_IDLE;
2919 state->mColdFutexAddr = &mFastMixerFutex;
2920 state->mColdGen++;
2921 mFastMixerFutex = 0;
2922 sq->end();
2923 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2924 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2925 if (kUseFastMixer == FastMixer_Dynamic) {
2926 mNormalSink = mOutputSink;
2927 }
2928#ifdef AUDIO_WATCHDOG
2929 if (mAudioWatchdog != 0) {
2930 mAudioWatchdog->pause();
2931 }
2932#endif
2933 } else {
2934 sq->end(false /*didModify*/);
2935 }
2936 }
2937 PlaybackThread::threadLoop_standby();
2938}
2939
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2941{
2942 return false;
2943}
2944
2945bool AudioFlinger::PlaybackThread::shouldStandby_l()
2946{
2947 return !mStandby;
2948}
2949
2950bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2951{
2952 Mutex::Autolock _l(mLock);
2953 return waitingAsyncCallback_l();
2954}
2955
Eric Laurent81784c32012-11-19 14:55:58 -08002956// shared by MIXER and DIRECT, overridden by DUPLICATING
2957void AudioFlinger::PlaybackThread::threadLoop_standby()
2958{
2959 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2960 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002961 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002962 // discard any pending drain or write ack by incrementing sequence
2963 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2964 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002965 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002966 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2967 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968 }
Eric Laurent81784c32012-11-19 14:55:58 -08002969}
2970
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002971void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2972{
2973 ALOGV("signal playback thread");
2974 broadcast_l();
2975}
2976
Eric Laurent81784c32012-11-19 14:55:58 -08002977void AudioFlinger::MixerThread::threadLoop_mix()
2978{
2979 // obtain the presentation timestamp of the next output buffer
2980 int64_t pts;
2981 status_t status = INVALID_OPERATION;
2982
2983 if (mNormalSink != 0) {
2984 status = mNormalSink->getNextWriteTimestamp(&pts);
2985 } else {
2986 status = mOutputSink->getNextWriteTimestamp(&pts);
2987 }
2988
2989 if (status != NO_ERROR) {
2990 pts = AudioBufferProvider::kInvalidPTS;
2991 }
2992
2993 // mix buffers...
2994 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002995 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002996 // increase sleep time progressively when application underrun condition clears.
2997 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2998 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2999 // such that we would underrun the audio HAL.
3000 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3001 sleepTimeShift--;
3002 }
3003 sleepTime = 0;
3004 standbyTime = systemTime() + standbyDelay;
3005 //TODO: delay standby when effects have a tail
3006}
3007
3008void AudioFlinger::MixerThread::threadLoop_sleepTime()
3009{
3010 // If no tracks are ready, sleep once for the duration of an output
3011 // buffer size, then write 0s to the output
3012 if (sleepTime == 0) {
3013 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3014 sleepTime = activeSleepTime >> sleepTimeShift;
3015 if (sleepTime < kMinThreadSleepTimeUs) {
3016 sleepTime = kMinThreadSleepTimeUs;
3017 }
3018 // reduce sleep time in case of consecutive application underruns to avoid
3019 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3020 // duration we would end up writing less data than needed by the audio HAL if
3021 // the condition persists.
3022 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3023 sleepTimeShift++;
3024 }
3025 } else {
3026 sleepTime = idleSleepTime;
3027 }
3028 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003029 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3030 // before effects processing or output.
3031 if (mMixerBufferValid) {
3032 memset(mMixerBuffer, 0, mMixerBufferSize);
3033 } else {
3034 memset(mSinkBuffer, 0, mSinkBufferSize);
3035 }
Eric Laurent81784c32012-11-19 14:55:58 -08003036 sleepTime = 0;
3037 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3038 "anticipated start");
3039 }
3040 // TODO add standby time extension fct of effect tail
3041}
3042
3043// prepareTracks_l() must be called with ThreadBase::mLock held
3044AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3045 Vector< sp<Track> > *tracksToRemove)
3046{
3047
3048 mixer_state mixerStatus = MIXER_IDLE;
3049 // find out which tracks need to be processed
3050 size_t count = mActiveTracks.size();
3051 size_t mixedTracks = 0;
3052 size_t tracksWithEffect = 0;
3053 // counts only _active_ fast tracks
3054 size_t fastTracks = 0;
3055 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3056
3057 float masterVolume = mMasterVolume;
3058 bool masterMute = mMasterMute;
3059
3060 if (masterMute) {
3061 masterVolume = 0;
3062 }
3063 // Delegate master volume control to effect in output mix effect chain if needed
3064 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3065 if (chain != 0) {
3066 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3067 chain->setVolume_l(&v, &v);
3068 masterVolume = (float)((v + (1 << 23)) >> 24);
3069 chain.clear();
3070 }
3071
3072 // prepare a new state to push
3073 FastMixerStateQueue *sq = NULL;
3074 FastMixerState *state = NULL;
3075 bool didModify = false;
3076 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3077 if (mFastMixer != NULL) {
3078 sq = mFastMixer->sq();
3079 state = sq->begin();
3080 }
3081
Andy Hung69aed5f2014-02-25 17:24:40 -08003082 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003083 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003084
Eric Laurent81784c32012-11-19 14:55:58 -08003085 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003086 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003087 if (t == 0) {
3088 continue;
3089 }
3090
3091 // this const just means the local variable doesn't change
3092 Track* const track = t.get();
3093
3094 // process fast tracks
3095 if (track->isFastTrack()) {
3096
3097 // It's theoretically possible (though unlikely) for a fast track to be created
3098 // and then removed within the same normal mix cycle. This is not a problem, as
3099 // the track never becomes active so it's fast mixer slot is never touched.
3100 // The converse, of removing an (active) track and then creating a new track
3101 // at the identical fast mixer slot within the same normal mix cycle,
3102 // is impossible because the slot isn't marked available until the end of each cycle.
3103 int j = track->mFastIndex;
3104 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3105 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3106 FastTrack *fastTrack = &state->mFastTracks[j];
3107
3108 // Determine whether the track is currently in underrun condition,
3109 // and whether it had a recent underrun.
3110 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3111 FastTrackUnderruns underruns = ftDump->mUnderruns;
3112 uint32_t recentFull = (underruns.mBitFields.mFull -
3113 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3114 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3115 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3116 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3117 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3118 uint32_t recentUnderruns = recentPartial + recentEmpty;
3119 track->mObservedUnderruns = underruns;
3120 // don't count underruns that occur while stopping or pausing
3121 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003122 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3123 recentUnderruns > 0) {
3124 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3125 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003126 }
3127
3128 // This is similar to the state machine for normal tracks,
3129 // with a few modifications for fast tracks.
3130 bool isActive = true;
3131 switch (track->mState) {
3132 case TrackBase::STOPPING_1:
3133 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003135 track->mState = TrackBase::STOPPING_2;
3136 }
3137 break;
3138 case TrackBase::PAUSING:
3139 // ramp down is not yet implemented
3140 track->setPaused();
3141 break;
3142 case TrackBase::RESUMING:
3143 // ramp up is not yet implemented
3144 track->mState = TrackBase::ACTIVE;
3145 break;
3146 case TrackBase::ACTIVE:
3147 if (recentFull > 0 || recentPartial > 0) {
3148 // track has provided at least some frames recently: reset retry count
3149 track->mRetryCount = kMaxTrackRetries;
3150 }
3151 if (recentUnderruns == 0) {
3152 // no recent underruns: stay active
3153 break;
3154 }
3155 // there has recently been an underrun of some kind
3156 if (track->sharedBuffer() == 0) {
3157 // were any of the recent underruns "empty" (no frames available)?
3158 if (recentEmpty == 0) {
3159 // no, then ignore the partial underruns as they are allowed indefinitely
3160 break;
3161 }
3162 // there has recently been an "empty" underrun: decrement the retry counter
3163 if (--(track->mRetryCount) > 0) {
3164 break;
3165 }
3166 // indicate to client process that the track was disabled because of underrun;
3167 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003168 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003169 // remove from active list, but state remains ACTIVE [confusing but true]
3170 isActive = false;
3171 break;
3172 }
3173 // fall through
3174 case TrackBase::STOPPING_2:
3175 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003176 case TrackBase::STOPPED:
3177 case TrackBase::FLUSHED: // flush() while active
3178 // Check for presentation complete if track is inactive
3179 // We have consumed all the buffers of this track.
3180 // This would be incomplete if we auto-paused on underrun
3181 {
3182 size_t audioHALFrames =
3183 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3184 size_t framesWritten = mBytesWritten / mFrameSize;
3185 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3186 // track stays in active list until presentation is complete
3187 break;
3188 }
3189 }
3190 if (track->isStopping_2()) {
3191 track->mState = TrackBase::STOPPED;
3192 }
3193 if (track->isStopped()) {
3194 // Can't reset directly, as fast mixer is still polling this track
3195 // track->reset();
3196 // So instead mark this track as needing to be reset after push with ack
3197 resetMask |= 1 << i;
3198 }
3199 isActive = false;
3200 break;
3201 case TrackBase::IDLE:
3202 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003203 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003204 }
3205
3206 if (isActive) {
3207 // was it previously inactive?
3208 if (!(state->mTrackMask & (1 << j))) {
3209 ExtendedAudioBufferProvider *eabp = track;
3210 VolumeProvider *vp = track;
3211 fastTrack->mBufferProvider = eabp;
3212 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003213 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003214 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003215 fastTrack->mGeneration++;
3216 state->mTrackMask |= 1 << j;
3217 didModify = true;
3218 // no acknowledgement required for newly active tracks
3219 }
3220 // cache the combined master volume and stream type volume for fast mixer; this
3221 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003222 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003223 ++fastTracks;
3224 } else {
3225 // was it previously active?
3226 if (state->mTrackMask & (1 << j)) {
3227 fastTrack->mBufferProvider = NULL;
3228 fastTrack->mGeneration++;
3229 state->mTrackMask &= ~(1 << j);
3230 didModify = true;
3231 // If any fast tracks were removed, we must wait for acknowledgement
3232 // because we're about to decrement the last sp<> on those tracks.
3233 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3234 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003235 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003236 }
3237 tracksToRemove->add(track);
3238 // Avoids a misleading display in dumpsys
3239 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3240 }
3241 continue;
3242 }
3243
3244 { // local variable scope to avoid goto warning
3245
3246 audio_track_cblk_t* cblk = track->cblk();
3247
3248 // The first time a track is added we wait
3249 // for all its buffers to be filled before processing it
3250 int name = track->name();
3251 // make sure that we have enough frames to mix one full buffer.
3252 // enforce this condition only once to enable draining the buffer in case the client
3253 // app does not call stop() and relies on underrun to stop:
3254 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3255 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003256 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003257 uint32_t sr = track->sampleRate();
3258 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003259 desiredFrames = mNormalFrameCount;
3260 } else {
3261 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003262 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003263 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003264 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003265 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003266#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003267 // the minimum track buffer size is normally twice the number of frames necessary
3268 // to fill one buffer and the resampler should not leave more than one buffer worth
3269 // of unreleased frames after each pass, but just in case...
3270 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003271#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003272 }
Eric Laurent81784c32012-11-19 14:55:58 -08003273 uint32_t minFrames = 1;
3274 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3275 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003276 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003277 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003278
3279 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003280 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003281 !track->isPaused() && !track->isTerminated())
3282 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003283 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003284
3285 mixedTracks++;
3286
Andy Hung69aed5f2014-02-25 17:24:40 -08003287 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3288 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003289 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003290 if (track->mainBuffer() != mSinkBuffer &&
3291 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003292 if (mEffectBufferEnabled) {
3293 mEffectBufferValid = true; // Later can set directly.
3294 }
Eric Laurent81784c32012-11-19 14:55:58 -08003295 chain = getEffectChain_l(track->sessionId());
3296 // Delegate volume control to effect in track effect chain if needed
3297 if (chain != 0) {
3298 tracksWithEffect++;
3299 } else {
3300 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3301 "session %d",
3302 name, track->sessionId());
3303 }
3304 }
3305
3306
3307 int param = AudioMixer::VOLUME;
3308 if (track->mFillingUpStatus == Track::FS_FILLED) {
3309 // no ramp for the first volume setting
3310 track->mFillingUpStatus = Track::FS_ACTIVE;
3311 if (track->mState == TrackBase::RESUMING) {
3312 track->mState = TrackBase::ACTIVE;
3313 param = AudioMixer::RAMP_VOLUME;
3314 }
3315 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003316 // FIXME should not make a decision based on mServer
3317 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003318 // If the track is stopped before the first frame was mixed,
3319 // do not apply ramp
3320 param = AudioMixer::RAMP_VOLUME;
3321 }
3322
3323 // compute volume for this track
3324 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003325 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003326 vl = vr = va = 0;
3327 if (track->isPausing()) {
3328 track->setPaused();
3329 }
3330 } else {
3331
3332 // read original volumes with volume control
3333 float typeVolume = mStreamTypes[track->streamType()].volume;
3334 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003335 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003336 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3337 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3338 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003339 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003340 if (vlf > GAIN_FLOAT_UNITY) {
3341 ALOGV("Track left volume out of range: %.3g", vlf);
3342 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003343 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003344 if (vrf > GAIN_FLOAT_UNITY) {
3345 ALOGV("Track right volume out of range: %.3g", vrf);
3346 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003347 }
3348 // now apply the master volume and stream type volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07003349 // FIXME we're losing the wonderful dynamic range in the minifloat representation
3350 float v8_24 = v * (MAX_GAIN_INT * MAX_GAIN_INT);
3351 vl = (uint32_t) (v8_24 * vlf);
3352 vr = (uint32_t) (v8_24 * vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08003353 // assuming master volume and stream type volume each go up to 1.0,
3354 // vl and vr are now in 8.24 format
3355
Glenn Kastene3aa6592012-12-04 12:22:46 -08003356 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003357 // send level comes from shared memory and so may be corrupt
3358 if (sendLevel > MAX_GAIN_INT) {
3359 ALOGV("Track send level out of range: %04X", sendLevel);
3360 sendLevel = MAX_GAIN_INT;
3361 }
3362 va = (uint32_t)(v * sendLevel);
3363 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003364
Eric Laurent81784c32012-11-19 14:55:58 -08003365 // Delegate volume control to effect in track effect chain if needed
3366 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3367 // Do not ramp volume if volume is controlled by effect
3368 param = AudioMixer::VOLUME;
3369 track->mHasVolumeController = true;
3370 } else {
3371 // force no volume ramp when volume controller was just disabled or removed
3372 // from effect chain to avoid volume spike
3373 if (track->mHasVolumeController) {
3374 param = AudioMixer::VOLUME;
3375 }
3376 track->mHasVolumeController = false;
3377 }
3378
Glenn Kastenc56f3422014-03-21 17:53:17 -07003379 // FIXME Use float
Eric Laurent81784c32012-11-19 14:55:58 -08003380 // Convert volumes from 8.24 to 4.12 format
3381 // This additional clamping is needed in case chain->setVolume_l() overshot
3382 vl = (vl + (1 << 11)) >> 12;
3383 if (vl > MAX_GAIN_INT) {
3384 vl = MAX_GAIN_INT;
3385 }
3386 vr = (vr + (1 << 11)) >> 12;
3387 if (vr > MAX_GAIN_INT) {
3388 vr = MAX_GAIN_INT;
3389 }
3390
3391 if (va > MAX_GAIN_INT) {
3392 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3393 }
3394
3395 // XXX: these things DON'T need to be done each time
3396 mAudioMixer->setBufferProvider(name, track);
3397 mAudioMixer->enable(name);
3398
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003399 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3400 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3401 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003402 mAudioMixer->setParameter(
3403 name,
3404 AudioMixer::TRACK,
3405 AudioMixer::FORMAT, (void *)track->format());
3406 mAudioMixer->setParameter(
3407 name,
3408 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003409 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003410 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3411 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003412 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003413 if (reqSampleRate == 0) {
3414 reqSampleRate = mSampleRate;
3415 } else if (reqSampleRate > maxSampleRate) {
3416 reqSampleRate = maxSampleRate;
3417 }
Eric Laurent81784c32012-11-19 14:55:58 -08003418 mAudioMixer->setParameter(
3419 name,
3420 AudioMixer::RESAMPLE,
3421 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003422 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003423 /*
3424 * Select the appropriate output buffer for the track.
3425 *
Andy Hung98ef9782014-03-04 14:46:50 -08003426 * Tracks with effects go into their own effects chain buffer
3427 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003428 *
3429 * Other tracks can use mMixerBuffer for higher precision
3430 * channel accumulation. If this buffer is enabled
3431 * (mMixerBufferEnabled true), then selected tracks will accumulate
3432 * into it.
3433 *
3434 */
3435 if (mMixerBufferEnabled
3436 && (track->mainBuffer() == mSinkBuffer
3437 || track->mainBuffer() == mMixerBuffer)) {
3438 mAudioMixer->setParameter(
3439 name,
3440 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003441 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003442 mAudioMixer->setParameter(
3443 name,
3444 AudioMixer::TRACK,
3445 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3446 // TODO: override track->mainBuffer()?
3447 mMixerBufferValid = true;
3448 } else {
3449 mAudioMixer->setParameter(
3450 name,
3451 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003452 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003453 mAudioMixer->setParameter(
3454 name,
3455 AudioMixer::TRACK,
3456 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3457 }
Eric Laurent81784c32012-11-19 14:55:58 -08003458 mAudioMixer->setParameter(
3459 name,
3460 AudioMixer::TRACK,
3461 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3462
3463 // reset retry count
3464 track->mRetryCount = kMaxTrackRetries;
3465
3466 // If one track is ready, set the mixer ready if:
3467 // - the mixer was not ready during previous round OR
3468 // - no other track is not ready
3469 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3470 mixerStatus != MIXER_TRACKS_ENABLED) {
3471 mixerStatus = MIXER_TRACKS_READY;
3472 }
3473 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003474 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003475 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003476 }
Eric Laurent81784c32012-11-19 14:55:58 -08003477 // clear effect chain input buffer if an active track underruns to avoid sending
3478 // previous audio buffer again to effects
3479 chain = getEffectChain_l(track->sessionId());
3480 if (chain != 0) {
3481 chain->clearInputBuffer();
3482 }
3483
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003484 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003485 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3486 track->isStopped() || track->isPaused()) {
3487 // We have consumed all the buffers of this track.
3488 // Remove it from the list of active tracks.
3489 // TODO: use actual buffer filling status instead of latency when available from
3490 // audio HAL
3491 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3492 size_t framesWritten = mBytesWritten / mFrameSize;
3493 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3494 if (track->isStopped()) {
3495 track->reset();
3496 }
3497 tracksToRemove->add(track);
3498 }
3499 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003500 // No buffers for this track. Give it a few chances to
3501 // fill a buffer, then remove it from active list.
3502 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003503 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003504 tracksToRemove->add(track);
3505 // indicate to client process that the track was disabled because of underrun;
3506 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003507 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003508 // If one track is not ready, mark the mixer also not ready if:
3509 // - the mixer was ready during previous round OR
3510 // - no other track is ready
3511 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3512 mixerStatus != MIXER_TRACKS_READY) {
3513 mixerStatus = MIXER_TRACKS_ENABLED;
3514 }
3515 }
3516 mAudioMixer->disable(name);
3517 }
3518
3519 } // local variable scope to avoid goto warning
3520track_is_ready: ;
3521
3522 }
3523
3524 // Push the new FastMixer state if necessary
3525 bool pauseAudioWatchdog = false;
3526 if (didModify) {
3527 state->mFastTracksGen++;
3528 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3529 if (kUseFastMixer == FastMixer_Dynamic &&
3530 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3531 state->mCommand = FastMixerState::COLD_IDLE;
3532 state->mColdFutexAddr = &mFastMixerFutex;
3533 state->mColdGen++;
3534 mFastMixerFutex = 0;
3535 if (kUseFastMixer == FastMixer_Dynamic) {
3536 mNormalSink = mOutputSink;
3537 }
3538 // If we go into cold idle, need to wait for acknowledgement
3539 // so that fast mixer stops doing I/O.
3540 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3541 pauseAudioWatchdog = true;
3542 }
Eric Laurent81784c32012-11-19 14:55:58 -08003543 }
3544 if (sq != NULL) {
3545 sq->end(didModify);
3546 sq->push(block);
3547 }
3548#ifdef AUDIO_WATCHDOG
3549 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3550 mAudioWatchdog->pause();
3551 }
3552#endif
3553
3554 // Now perform the deferred reset on fast tracks that have stopped
3555 while (resetMask != 0) {
3556 size_t i = __builtin_ctz(resetMask);
3557 ALOG_ASSERT(i < count);
3558 resetMask &= ~(1 << i);
3559 sp<Track> t = mActiveTracks[i].promote();
3560 if (t == 0) {
3561 continue;
3562 }
3563 Track* track = t.get();
3564 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3565 track->reset();
3566 }
3567
3568 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003569 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003570
Andy Hung69aed5f2014-02-25 17:24:40 -08003571 // sink or mix buffer must be cleared if all tracks are connected to an
3572 // effect chain as in this case the mixer will not write to the sink or mix buffer
3573 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3575 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003576 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003577 if (mMixerBufferValid) {
3578 memset(mMixerBuffer, 0, mMixerBufferSize);
3579 // TODO: In testing, mSinkBuffer below need not be cleared because
3580 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3581 // after mixing.
3582 //
3583 // To enforce this guarantee:
3584 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3585 // (mixedTracks == 0 && fastTracks > 0))
3586 // must imply MIXER_TRACKS_READY.
3587 // Later, we may clear buffers regardless, and skip much of this logic.
3588 }
Andy Hung98ef9782014-03-04 14:46:50 -08003589 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3590 if (mEffectBufferValid) {
3591 memset(mEffectBuffer, 0, mEffectBufferSize);
3592 }
3593 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003594 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003595 }
3596
3597 // if any fast tracks, then status is ready
3598 mMixerStatusIgnoringFastTracks = mixerStatus;
3599 if (fastTracks > 0) {
3600 mixerStatus = MIXER_TRACKS_READY;
3601 }
3602 return mixerStatus;
3603}
3604
3605// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003606int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3607 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003608{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003609 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003610}
3611
3612// deleteTrackName_l() must be called with ThreadBase::mLock held
3613void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3614{
3615 ALOGV("remove track (%d) and delete from mixer", name);
3616 mAudioMixer->deleteTrackName(name);
3617}
3618
Eric Laurent10351942014-05-08 18:49:52 -07003619// checkForNewParameter_l() must be called with ThreadBase::mLock held
3620bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3621 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003622{
Eric Laurent81784c32012-11-19 14:55:58 -08003623 bool reconfig = false;
3624
Eric Laurent10351942014-05-08 18:49:52 -07003625 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003626
Eric Laurent10351942014-05-08 18:49:52 -07003627 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3628 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3629 if (mFastMixer != NULL) {
3630 FastMixerStateQueue *sq = mFastMixer->sq();
3631 FastMixerState *state = sq->begin();
3632 if (!(state->mCommand & FastMixerState::IDLE)) {
3633 previousCommand = state->mCommand;
3634 state->mCommand = FastMixerState::HOT_IDLE;
3635 sq->end();
3636 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3637 } else {
3638 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003639 }
Eric Laurent10351942014-05-08 18:49:52 -07003640 }
Eric Laurent81784c32012-11-19 14:55:58 -08003641
Eric Laurent10351942014-05-08 18:49:52 -07003642 AudioParameter param = AudioParameter(keyValuePair);
3643 int value;
3644 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3645 reconfig = true;
3646 }
3647 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3648 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3649 status = BAD_VALUE;
3650 } else {
3651 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003652 reconfig = true;
3653 }
Eric Laurent10351942014-05-08 18:49:52 -07003654 }
3655 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3656 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3657 status = BAD_VALUE;
3658 } else {
3659 // no need to save value, since it's constant
3660 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003661 }
Eric Laurent10351942014-05-08 18:49:52 -07003662 }
3663 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3664 // do not accept frame count changes if tracks are open as the track buffer
3665 // size depends on frame count and correct behavior would not be guaranteed
3666 // if frame count is changed after track creation
3667 if (!mTracks.isEmpty()) {
3668 status = INVALID_OPERATION;
3669 } else {
3670 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003671 }
Eric Laurent10351942014-05-08 18:49:52 -07003672 }
3673 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003674#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003675 // when changing the audio output device, call addBatteryData to notify
3676 // the change
3677 if (mOutDevice != value) {
3678 uint32_t params = 0;
3679 // check whether speaker is on
3680 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3681 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003682 }
Eric Laurent10351942014-05-08 18:49:52 -07003683
3684 audio_devices_t deviceWithoutSpeaker
3685 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3686 // check if any other device (except speaker) is on
3687 if (value & deviceWithoutSpeaker ) {
3688 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3689 }
3690
3691 if (params != 0) {
3692 addBatteryData(params);
3693 }
3694 }
Eric Laurent81784c32012-11-19 14:55:58 -08003695#endif
3696
Eric Laurent10351942014-05-08 18:49:52 -07003697 // forward device change to effects that have requested to be
3698 // aware of attached audio device.
3699 if (value != AUDIO_DEVICE_NONE) {
3700 mOutDevice = value;
3701 for (size_t i = 0; i < mEffectChains.size(); i++) {
3702 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003703 }
3704 }
Eric Laurent10351942014-05-08 18:49:52 -07003705 }
Eric Laurent81784c32012-11-19 14:55:58 -08003706
Eric Laurent10351942014-05-08 18:49:52 -07003707 if (status == NO_ERROR) {
3708 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3709 keyValuePair.string());
3710 if (!mStandby && status == INVALID_OPERATION) {
3711 mOutput->stream->common.standby(&mOutput->stream->common);
3712 mStandby = true;
3713 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003714 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003715 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003716 }
Eric Laurent10351942014-05-08 18:49:52 -07003717 if (status == NO_ERROR && reconfig) {
3718 readOutputParameters_l();
3719 delete mAudioMixer;
3720 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3721 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003722 int name = getTrackName_l(mTracks[i]->mChannelMask,
3723 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003724 if (name < 0) {
3725 break;
3726 }
3727 mTracks[i]->mName = name;
3728 }
3729 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3730 }
Eric Laurent81784c32012-11-19 14:55:58 -08003731 }
3732
3733 if (!(previousCommand & FastMixerState::IDLE)) {
3734 ALOG_ASSERT(mFastMixer != NULL);
3735 FastMixerStateQueue *sq = mFastMixer->sq();
3736 FastMixerState *state = sq->begin();
3737 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3738 state->mCommand = previousCommand;
3739 sq->end();
3740 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3741 }
3742
3743 return reconfig;
3744}
3745
3746
3747void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3748{
3749 const size_t SIZE = 256;
3750 char buffer[SIZE];
3751 String8 result;
3752
3753 PlaybackThread::dumpInternals(fd, args);
3754
Elliott Hughes87cebad2014-05-22 10:14:43 -07003755 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003756
3757 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003758 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003759 copy.dump(fd);
3760
3761#ifdef STATE_QUEUE_DUMP
3762 // Similar for state queue
3763 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3764 observerCopy.dump(fd);
3765 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3766 mutatorCopy.dump(fd);
3767#endif
3768
Glenn Kasten46909e72013-02-26 09:20:22 -08003769#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003770 // Write the tee output to a .wav file
3771 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003772#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003773
3774#ifdef AUDIO_WATCHDOG
3775 if (mAudioWatchdog != 0) {
3776 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3777 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3778 wdCopy.dump(fd);
3779 }
3780#endif
3781}
3782
3783uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3784{
3785 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3786}
3787
3788uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3789{
3790 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3791}
3792
3793void AudioFlinger::MixerThread::cacheParameters_l()
3794{
3795 PlaybackThread::cacheParameters_l();
3796
3797 // FIXME: Relaxed timing because of a certain device that can't meet latency
3798 // Should be reduced to 2x after the vendor fixes the driver issue
3799 // increase threshold again due to low power audio mode. The way this warning
3800 // threshold is calculated and its usefulness should be reconsidered anyway.
3801 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3802}
3803
3804// ----------------------------------------------------------------------------
3805
3806AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3807 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3808 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3809 // mLeftVolFloat, mRightVolFloat
3810{
3811}
3812
Eric Laurentbfb1b832013-01-07 09:53:42 -08003813AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3814 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3815 ThreadBase::type_t type)
3816 : PlaybackThread(audioFlinger, output, id, device, type)
3817 // mLeftVolFloat, mRightVolFloat
3818{
3819}
3820
Eric Laurent81784c32012-11-19 14:55:58 -08003821AudioFlinger::DirectOutputThread::~DirectOutputThread()
3822{
3823}
3824
Eric Laurentbfb1b832013-01-07 09:53:42 -08003825void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3826{
3827 audio_track_cblk_t* cblk = track->cblk();
3828 float left, right;
3829
3830 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3831 left = right = 0;
3832 } else {
3833 float typeVolume = mStreamTypes[track->streamType()].volume;
3834 float v = mMasterVolume * typeVolume;
3835 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003836 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3837 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3838 if (left > GAIN_FLOAT_UNITY) {
3839 left = GAIN_FLOAT_UNITY;
3840 }
3841 left *= v;
3842 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3843 if (right > GAIN_FLOAT_UNITY) {
3844 right = GAIN_FLOAT_UNITY;
3845 }
3846 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 }
3848
3849 if (lastTrack) {
3850 if (left != mLeftVolFloat || right != mRightVolFloat) {
3851 mLeftVolFloat = left;
3852 mRightVolFloat = right;
3853
3854 // Convert volumes from float to 8.24
3855 uint32_t vl = (uint32_t)(left * (1 << 24));
3856 uint32_t vr = (uint32_t)(right * (1 << 24));
3857
3858 // Delegate volume control to effect in track effect chain if needed
3859 // only one effect chain can be present on DirectOutputThread, so if
3860 // there is one, the track is connected to it
3861 if (!mEffectChains.isEmpty()) {
3862 mEffectChains[0]->setVolume_l(&vl, &vr);
3863 left = (float)vl / (1 << 24);
3864 right = (float)vr / (1 << 24);
3865 }
3866 if (mOutput->stream->set_volume) {
3867 mOutput->stream->set_volume(mOutput->stream, left, right);
3868 }
3869 }
3870 }
3871}
3872
3873
Eric Laurent81784c32012-11-19 14:55:58 -08003874AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3875 Vector< sp<Track> > *tracksToRemove
3876)
3877{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003878 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003879 mixer_state mixerStatus = MIXER_IDLE;
3880
3881 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003882 for (size_t i = 0; i < count; i++) {
3883 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003884 // The track died recently
3885 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003886 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003887 }
3888
3889 Track* const track = t.get();
3890 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003891 // Only consider last track started for volume and mixer state control.
3892 // In theory an older track could underrun and restart after the new one starts
3893 // but as we only care about the transition phase between two tracks on a
3894 // direct output, it is not a problem to ignore the underrun case.
3895 sp<Track> l = mLatestActiveTrack.promote();
3896 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003897
3898 // The first time a track is added we wait
3899 // for all its buffers to be filled before processing it
3900 uint32_t minFrames;
3901 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3902 minFrames = mNormalFrameCount;
3903 } else {
3904 minFrames = 1;
3905 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003906
Eric Laurent81784c32012-11-19 14:55:58 -08003907 if ((track->framesReady() >= minFrames) && track->isReady() &&
3908 !track->isPaused() && !track->isTerminated())
3909 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003910 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003911
3912 if (track->mFillingUpStatus == Track::FS_FILLED) {
3913 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003914 // make sure processVolume_l() will apply new volume even if 0
3915 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003916 if (track->mState == TrackBase::RESUMING) {
3917 track->mState = TrackBase::ACTIVE;
3918 }
3919 }
3920
3921 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922 processVolume_l(track, last);
3923 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003924 // reset retry count
3925 track->mRetryCount = kMaxTrackRetriesDirect;
3926 mActiveTrack = t;
3927 mixerStatus = MIXER_TRACKS_READY;
3928 }
Eric Laurent81784c32012-11-19 14:55:58 -08003929 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003930 // clear effect chain input buffer if the last active track started underruns
3931 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003932 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003933 mEffectChains[0]->clearInputBuffer();
3934 }
3935
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003936 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003937 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3938 track->isStopped() || track->isPaused()) {
3939 // We have consumed all the buffers of this track.
3940 // Remove it from the list of active tracks.
3941 // TODO: implement behavior for compressed audio
3942 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3943 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003944 if (mStandby || !last ||
3945 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003946 if (track->isStopped()) {
3947 track->reset();
3948 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003949 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003950 }
3951 } else {
3952 // No buffers for this track. Give it a few chances to
3953 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003954 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003955 if (--(track->mRetryCount) <= 0) {
3956 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003957 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003958 // indicate to client process that the track was disabled because of underrun;
3959 // it will then automatically call start() when data is available
3960 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003962 mixerStatus = MIXER_TRACKS_ENABLED;
3963 }
3964 }
3965 }
3966 }
3967
Eric Laurent81784c32012-11-19 14:55:58 -08003968 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003969 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003970
3971 return mixerStatus;
3972}
3973
3974void AudioFlinger::DirectOutputThread::threadLoop_mix()
3975{
Eric Laurent81784c32012-11-19 14:55:58 -08003976 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003977 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003978 // output audio to hardware
3979 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003980 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003981 buffer.frameCount = frameCount;
3982 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003983 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003984 memset(curBuf, 0, frameCount * mFrameSize);
3985 break;
3986 }
3987 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3988 frameCount -= buffer.frameCount;
3989 curBuf += buffer.frameCount * mFrameSize;
3990 mActiveTrack->releaseBuffer(&buffer);
3991 }
Andy Hung2098f272014-02-27 14:00:06 -08003992 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003993 sleepTime = 0;
3994 standbyTime = systemTime() + standbyDelay;
3995 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003996}
3997
3998void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3999{
4000 if (sleepTime == 0) {
4001 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4002 sleepTime = activeSleepTime;
4003 } else {
4004 sleepTime = idleSleepTime;
4005 }
4006 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004007 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004008 sleepTime = 0;
4009 }
4010}
4011
4012// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004013int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004014 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004015{
4016 return 0;
4017}
4018
4019// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004020void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004021{
4022}
4023
Eric Laurent10351942014-05-08 18:49:52 -07004024// checkForNewParameter_l() must be called with ThreadBase::mLock held
4025bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4026 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004027{
4028 bool reconfig = false;
4029
Eric Laurent10351942014-05-08 18:49:52 -07004030 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004031
Eric Laurent10351942014-05-08 18:49:52 -07004032 AudioParameter param = AudioParameter(keyValuePair);
4033 int value;
4034 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4035 // forward device change to effects that have requested to be
4036 // aware of attached audio device.
4037 if (value != AUDIO_DEVICE_NONE) {
4038 mOutDevice = value;
4039 for (size_t i = 0; i < mEffectChains.size(); i++) {
4040 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004041 }
4042 }
Eric Laurent81784c32012-11-19 14:55:58 -08004043 }
Eric Laurent10351942014-05-08 18:49:52 -07004044 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4045 // do not accept frame count changes if tracks are open as the track buffer
4046 // size depends on frame count and correct behavior would not be garantied
4047 // if frame count is changed after track creation
4048 if (!mTracks.isEmpty()) {
4049 status = INVALID_OPERATION;
4050 } else {
4051 reconfig = true;
4052 }
4053 }
4054 if (status == NO_ERROR) {
4055 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4056 keyValuePair.string());
4057 if (!mStandby && status == INVALID_OPERATION) {
4058 mOutput->stream->common.standby(&mOutput->stream->common);
4059 mStandby = true;
4060 mBytesWritten = 0;
4061 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4062 keyValuePair.string());
4063 }
4064 if (status == NO_ERROR && reconfig) {
4065 readOutputParameters_l();
4066 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4067 }
4068 }
4069
Eric Laurent81784c32012-11-19 14:55:58 -08004070 return reconfig;
4071}
4072
4073uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4074{
4075 uint32_t time;
4076 if (audio_is_linear_pcm(mFormat)) {
4077 time = PlaybackThread::activeSleepTimeUs();
4078 } else {
4079 time = 10000;
4080 }
4081 return time;
4082}
4083
4084uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4085{
4086 uint32_t time;
4087 if (audio_is_linear_pcm(mFormat)) {
4088 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4089 } else {
4090 time = 10000;
4091 }
4092 return time;
4093}
4094
4095uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4096{
4097 uint32_t time;
4098 if (audio_is_linear_pcm(mFormat)) {
4099 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4100 } else {
4101 time = 10000;
4102 }
4103 return time;
4104}
4105
4106void AudioFlinger::DirectOutputThread::cacheParameters_l()
4107{
4108 PlaybackThread::cacheParameters_l();
4109
4110 // use shorter standby delay as on normal output to release
4111 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004112 if (audio_is_linear_pcm(mFormat)) {
4113 standbyDelay = microseconds(activeSleepTime*2);
4114 } else {
4115 standbyDelay = kOffloadStandbyDelayNs;
4116 }
Eric Laurent81784c32012-11-19 14:55:58 -08004117}
4118
4119// ----------------------------------------------------------------------------
4120
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004122 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004124 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004125 mWriteAckSequence(0),
4126 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004127{
4128}
4129
4130AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4131{
4132}
4133
4134void AudioFlinger::AsyncCallbackThread::onFirstRef()
4135{
4136 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4137}
4138
4139bool AudioFlinger::AsyncCallbackThread::threadLoop()
4140{
4141 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004142 uint32_t writeAckSequence;
4143 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004144
4145 {
4146 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004147 while (!((mWriteAckSequence & 1) ||
4148 (mDrainSequence & 1) ||
4149 exitPending())) {
4150 mWaitWorkCV.wait(mLock);
4151 }
4152
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153 if (exitPending()) {
4154 break;
4155 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004156 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4157 mWriteAckSequence, mDrainSequence);
4158 writeAckSequence = mWriteAckSequence;
4159 mWriteAckSequence &= ~1;
4160 drainSequence = mDrainSequence;
4161 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162 }
4163 {
Eric Laurent4de95592013-09-26 15:28:21 -07004164 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4165 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004166 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004167 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004168 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004169 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004170 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 }
4172 }
4173 }
4174 }
4175 return false;
4176}
4177
4178void AudioFlinger::AsyncCallbackThread::exit()
4179{
4180 ALOGV("AsyncCallbackThread::exit");
4181 Mutex::Autolock _l(mLock);
4182 requestExit();
4183 mWaitWorkCV.broadcast();
4184}
4185
Eric Laurent3b4529e2013-09-05 18:09:19 -07004186void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187{
4188 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004189 // bit 0 is cleared
4190 mWriteAckSequence = sequence << 1;
4191}
4192
4193void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4194{
4195 Mutex::Autolock _l(mLock);
4196 // ignore unexpected callbacks
4197 if (mWriteAckSequence & 2) {
4198 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004199 mWaitWorkCV.signal();
4200 }
4201}
4202
Eric Laurent3b4529e2013-09-05 18:09:19 -07004203void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004204{
4205 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004206 // bit 0 is cleared
4207 mDrainSequence = sequence << 1;
4208}
4209
4210void AudioFlinger::AsyncCallbackThread::resetDraining()
4211{
4212 Mutex::Autolock _l(mLock);
4213 // ignore unexpected callbacks
4214 if (mDrainSequence & 2) {
4215 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 mWaitWorkCV.signal();
4217 }
4218}
4219
4220
4221// ----------------------------------------------------------------------------
4222AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4223 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4224 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4225 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004226 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004227 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004228{
Eric Laurentfd477972013-10-25 18:10:40 -07004229 //FIXME: mStandby should be set to true by ThreadBase constructor
4230 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004231}
4232
Eric Laurentbfb1b832013-01-07 09:53:42 -08004233void AudioFlinger::OffloadThread::threadLoop_exit()
4234{
4235 if (mFlushPending || mHwPaused) {
4236 // If a flush is pending or track was paused, just discard buffered data
4237 flushHw_l();
4238 } else {
4239 mMixerStatus = MIXER_DRAIN_ALL;
4240 threadLoop_drain();
4241 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004242 if (mUseAsyncWrite) {
4243 ALOG_ASSERT(mCallbackThread != 0);
4244 mCallbackThread->exit();
4245 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004246 PlaybackThread::threadLoop_exit();
4247}
4248
4249AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4250 Vector< sp<Track> > *tracksToRemove
4251)
4252{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004253 size_t count = mActiveTracks.size();
4254
4255 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004256 bool doHwPause = false;
4257 bool doHwResume = false;
4258
Eric Laurentede6c3b2013-09-19 14:37:46 -07004259 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4260
Eric Laurentbfb1b832013-01-07 09:53:42 -08004261 // find out which tracks need to be processed
4262 for (size_t i = 0; i < count; i++) {
4263 sp<Track> t = mActiveTracks[i].promote();
4264 // The track died recently
4265 if (t == 0) {
4266 continue;
4267 }
4268 Track* const track = t.get();
4269 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004270 // Only consider last track started for volume and mixer state control.
4271 // In theory an older track could underrun and restart after the new one starts
4272 // but as we only care about the transition phase between two tracks on a
4273 // direct output, it is not a problem to ignore the underrun case.
4274 sp<Track> l = mLatestActiveTrack.promote();
4275 bool last = l.get() == track;
4276
Haynes Mathew George7844f672014-01-15 12:32:55 -08004277 if (track->isInvalid()) {
4278 ALOGW("An invalidated track shouldn't be in active list");
4279 tracksToRemove->add(track);
4280 continue;
4281 }
4282
4283 if (track->mState == TrackBase::IDLE) {
4284 ALOGW("An idle track shouldn't be in active list");
4285 continue;
4286 }
4287
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288 if (track->isPausing()) {
4289 track->setPaused();
4290 if (last) {
4291 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004292 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293 mHwPaused = true;
4294 }
4295 // If we were part way through writing the mixbuffer to
4296 // the HAL we must save this until we resume
4297 // BUG - this will be wrong if a different track is made active,
4298 // in that case we want to discard the pending data in the
4299 // mixbuffer and tell the client to present it again when the
4300 // track is resumed
4301 mPausedWriteLength = mCurrentWriteLength;
4302 mPausedBytesRemaining = mBytesRemaining;
4303 mBytesRemaining = 0; // stop writing
4304 }
4305 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004306 } else if (track->isFlushPending()) {
4307 track->flushAck();
4308 if (last) {
4309 mFlushPending = true;
4310 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004311 } else if (track->isResumePending()){
4312 track->resumeAck();
4313 if (last) {
4314 if (mPausedBytesRemaining) {
4315 // Need to continue write that was interrupted
4316 mCurrentWriteLength = mPausedWriteLength;
4317 mBytesRemaining = mPausedBytesRemaining;
4318 mPausedBytesRemaining = 0;
4319 }
4320 if (mHwPaused) {
4321 doHwResume = true;
4322 mHwPaused = false;
4323 // threadLoop_mix() will handle the case that we need to
4324 // resume an interrupted write
4325 }
4326 // enable write to audio HAL
4327 sleepTime = 0;
4328
4329 // Do not handle new data in this iteration even if track->framesReady()
4330 mixerStatus = MIXER_TRACKS_ENABLED;
4331 }
4332 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004333 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004334 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004335 if (track->mFillingUpStatus == Track::FS_FILLED) {
4336 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004337 // make sure processVolume_l() will apply new volume even if 0
4338 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339 }
4340
4341 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004342 sp<Track> previousTrack = mPreviousTrack.promote();
4343 if (previousTrack != 0) {
4344 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004345 // Flush any data still being written from last track
4346 mBytesRemaining = 0;
4347 if (mPausedBytesRemaining) {
4348 // Last track was paused so we also need to flush saved
4349 // mixbuffer state and invalidate track so that it will
4350 // re-submit that unwritten data when it is next resumed
4351 mPausedBytesRemaining = 0;
4352 // Invalidate is a bit drastic - would be more efficient
4353 // to have a flag to tell client that some of the
4354 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004355 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004356 }
4357 // flush data already sent to the DSP if changing audio session as audio
4358 // comes from a different source. Also invalidate previous track to force a
4359 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004360 if (previousTrack->sessionId() != track->sessionId()) {
4361 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004362 }
4363 }
4364 }
4365 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004366 // reset retry count
4367 track->mRetryCount = kMaxTrackRetriesOffload;
4368 mActiveTrack = t;
4369 mixerStatus = MIXER_TRACKS_READY;
4370 }
4371 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004372 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004373 if (track->isStopping_1()) {
4374 // Hardware buffer can hold a large amount of audio so we must
4375 // wait for all current track's data to drain before we say
4376 // that the track is stopped.
4377 if (mBytesRemaining == 0) {
4378 // Only start draining when all data in mixbuffer
4379 // has been written
4380 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4381 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004382 // do not drain if no data was ever sent to HAL (mStandby == true)
4383 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004384 // do not modify drain sequence if we are already draining. This happens
4385 // when resuming from pause after drain.
4386 if ((mDrainSequence & 1) == 0) {
4387 sleepTime = 0;
4388 standbyTime = systemTime() + standbyDelay;
4389 mixerStatus = MIXER_DRAIN_TRACK;
4390 mDrainSequence += 2;
4391 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392 if (mHwPaused) {
4393 // It is possible to move from PAUSED to STOPPING_1 without
4394 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004395 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004396 mHwPaused = false;
4397 }
4398 }
4399 }
4400 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004401 // Drain has completed or we are in standby, signal presentation complete
4402 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 track->mState = TrackBase::STOPPED;
4404 size_t audioHALFrames =
4405 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4406 size_t framesWritten =
4407 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4408 track->presentationComplete(framesWritten, audioHALFrames);
4409 track->reset();
4410 tracksToRemove->add(track);
4411 }
4412 } else {
4413 // No buffers for this track. Give it a few chances to
4414 // fill a buffer, then remove it from active list.
4415 if (--(track->mRetryCount) <= 0) {
4416 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4417 track->name());
4418 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004419 // indicate to client process that the track was disabled because of underrun;
4420 // it will then automatically call start() when data is available
4421 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004422 } else if (last){
4423 mixerStatus = MIXER_TRACKS_ENABLED;
4424 }
4425 }
4426 }
4427 // compute volume for this track
4428 processVolume_l(track, last);
4429 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004430
Eric Laurentea0fade2013-10-04 16:23:48 -07004431 // make sure the pause/flush/resume sequence is executed in the right order.
4432 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4433 // before flush and then resume HW. This can happen in case of pause/flush/resume
4434 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004435 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004436 mOutput->stream->pause(mOutput->stream);
4437 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004438 if (mFlushPending) {
4439 flushHw_l();
4440 mFlushPending = false;
4441 }
Eric Laurentfd477972013-10-25 18:10:40 -07004442 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004443 mOutput->stream->resume(mOutput->stream);
4444 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004445
Eric Laurentbfb1b832013-01-07 09:53:42 -08004446 // remove all the tracks that need to be...
4447 removeTracks_l(*tracksToRemove);
4448
4449 return mixerStatus;
4450}
4451
Eric Laurentbfb1b832013-01-07 09:53:42 -08004452// must be called with thread mutex locked
4453bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4454{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004455 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4456 mWriteAckSequence, mDrainSequence);
4457 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004458 return true;
4459 }
4460 return false;
4461}
4462
4463// must be called with thread mutex locked
4464bool AudioFlinger::OffloadThread::shouldStandby_l()
4465{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004466 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004467
4468 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4469 // after a timeout and we will enter standby then.
4470 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004471 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004472 }
4473
Glenn Kastene6f35b12013-08-19 09:58:50 -07004474 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475}
4476
4477
4478bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4479{
4480 Mutex::Autolock _l(mLock);
4481 return waitingAsyncCallback_l();
4482}
4483
4484void AudioFlinger::OffloadThread::flushHw_l()
4485{
4486 mOutput->stream->flush(mOutput->stream);
4487 // Flush anything still waiting in the mixbuffer
4488 mCurrentWriteLength = 0;
4489 mBytesRemaining = 0;
4490 mPausedWriteLength = 0;
4491 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004492 mHwPaused = false;
4493
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004495 // discard any pending drain or write ack by incrementing sequence
4496 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4497 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004498 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004499 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4500 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004501 }
4502}
4503
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004504void AudioFlinger::OffloadThread::onAddNewTrack_l()
4505{
4506 sp<Track> previousTrack = mPreviousTrack.promote();
4507 sp<Track> latestTrack = mLatestActiveTrack.promote();
4508
4509 if (previousTrack != 0 && latestTrack != 0 &&
4510 (previousTrack->sessionId() != latestTrack->sessionId())) {
4511 mFlushPending = true;
4512 }
4513 PlaybackThread::onAddNewTrack_l();
4514}
4515
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516// ----------------------------------------------------------------------------
4517
Eric Laurent81784c32012-11-19 14:55:58 -08004518AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4519 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4520 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4521 DUPLICATING),
4522 mWaitTimeMs(UINT_MAX)
4523{
4524 addOutputTrack(mainThread);
4525}
4526
4527AudioFlinger::DuplicatingThread::~DuplicatingThread()
4528{
4529 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4530 mOutputTracks[i]->destroy();
4531 }
4532}
4533
4534void AudioFlinger::DuplicatingThread::threadLoop_mix()
4535{
4536 // mix buffers...
4537 if (outputsReady(outputTracks)) {
4538 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4539 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004540 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004541 }
4542 sleepTime = 0;
4543 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004544 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004545 standbyTime = systemTime() + standbyDelay;
4546}
4547
4548void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4549{
4550 if (sleepTime == 0) {
4551 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4552 sleepTime = activeSleepTime;
4553 } else {
4554 sleepTime = idleSleepTime;
4555 }
4556 } else if (mBytesWritten != 0) {
4557 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4558 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004559 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004560 } else {
4561 // flush remaining overflow buffers in output tracks
4562 writeFrames = 0;
4563 }
4564 sleepTime = 0;
4565 }
4566}
4567
Eric Laurentbfb1b832013-01-07 09:53:42 -08004568ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004569{
4570 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004571 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4572 // for delivery downstream as needed. This in-place conversion is safe as
4573 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4574 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4575 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4576 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4577 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4578 }
4579 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004580 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004581 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004582 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004583}
4584
4585void AudioFlinger::DuplicatingThread::threadLoop_standby()
4586{
4587 // DuplicatingThread implements standby by stopping all tracks
4588 for (size_t i = 0; i < outputTracks.size(); i++) {
4589 outputTracks[i]->stop();
4590 }
4591}
4592
4593void AudioFlinger::DuplicatingThread::saveOutputTracks()
4594{
4595 outputTracks = mOutputTracks;
4596}
4597
4598void AudioFlinger::DuplicatingThread::clearOutputTracks()
4599{
4600 outputTracks.clear();
4601}
4602
4603void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4604{
4605 Mutex::Autolock _l(mLock);
4606 // FIXME explain this formula
4607 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004608 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4609 // due to current usage case and restrictions on the AudioBufferProvider.
4610 // Actual buffer conversion is done in threadLoop_write().
4611 //
4612 // TODO: This may change in the future, depending on multichannel
4613 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004614 OutputTrack *outputTrack = new OutputTrack(thread,
4615 this,
4616 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004617 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004618 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004619 frameCount,
4620 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004621 if (outputTrack->cblk() != NULL) {
4622 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4623 mOutputTracks.add(outputTrack);
4624 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4625 updateWaitTime_l();
4626 }
4627}
4628
4629void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4630{
4631 Mutex::Autolock _l(mLock);
4632 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4633 if (mOutputTracks[i]->thread() == thread) {
4634 mOutputTracks[i]->destroy();
4635 mOutputTracks.removeAt(i);
4636 updateWaitTime_l();
4637 return;
4638 }
4639 }
4640 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4641}
4642
4643// caller must hold mLock
4644void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4645{
4646 mWaitTimeMs = UINT_MAX;
4647 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4648 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4649 if (strong != 0) {
4650 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4651 if (waitTimeMs < mWaitTimeMs) {
4652 mWaitTimeMs = waitTimeMs;
4653 }
4654 }
4655 }
4656}
4657
4658
4659bool AudioFlinger::DuplicatingThread::outputsReady(
4660 const SortedVector< sp<OutputTrack> > &outputTracks)
4661{
4662 for (size_t i = 0; i < outputTracks.size(); i++) {
4663 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4664 if (thread == 0) {
4665 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4666 outputTracks[i].get());
4667 return false;
4668 }
4669 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4670 // see note at standby() declaration
4671 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4672 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4673 thread.get());
4674 return false;
4675 }
4676 }
4677 return true;
4678}
4679
4680uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4681{
4682 return (mWaitTimeMs * 1000) / 2;
4683}
4684
4685void AudioFlinger::DuplicatingThread::cacheParameters_l()
4686{
4687 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4688 updateWaitTime_l();
4689
4690 MixerThread::cacheParameters_l();
4691}
4692
4693// ----------------------------------------------------------------------------
4694// Record
4695// ----------------------------------------------------------------------------
4696
4697AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4698 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004699 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004700 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004701 audio_devices_t inDevice
4702#ifdef TEE_SINK
4703 , const sp<NBAIO_Sink>& teeSink
4704#endif
4705 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004706 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004707 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004708 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004709 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004710#ifdef TEE_SINK
4711 , mTeeSink(teeSink)
4712#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004713 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4714 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004715{
4716 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004717 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004718
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004719 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004720}
4721
4722
4723AudioFlinger::RecordThread::~RecordThread()
4724{
Glenn Kasten481fb672013-09-30 14:39:28 -07004725 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004726 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004727}
4728
4729void AudioFlinger::RecordThread::onFirstRef()
4730{
4731 run(mName, PRIORITY_URGENT_AUDIO);
4732}
4733
Eric Laurent81784c32012-11-19 14:55:58 -08004734bool AudioFlinger::RecordThread::threadLoop()
4735{
Eric Laurent81784c32012-11-19 14:55:58 -08004736 nsecs_t lastWarning = 0;
4737
4738 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004739
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004740reacquire_wakelock:
4741 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004742 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004743 {
4744 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004745 size_t size = mActiveTracks.size();
4746 activeTracksGen = mActiveTracksGen;
4747 if (size > 0) {
4748 // FIXME an arbitrary choice
4749 activeTrack = mActiveTracks[0];
4750 acquireWakeLock_l(activeTrack->uid());
4751 if (size > 1) {
4752 SortedVector<int> tmp;
4753 for (size_t i = 0; i < size; i++) {
4754 tmp.add(mActiveTracks[i]->uid());
4755 }
4756 updateWakeLockUids_l(tmp);
4757 }
4758 } else {
4759 acquireWakeLock_l(-1);
4760 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004761 }
4762
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004763 // used to request a deferred sleep, to be executed later while mutex is unlocked
4764 uint32_t sleepUs = 0;
4765
4766 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004767 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004768 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004769
Glenn Kasten5edadd42013-08-14 16:30:49 -07004770 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004771 if (sleepUs > 0) {
4772 usleep(sleepUs);
4773 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004774 }
4775
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004776 // activeTracks accumulates a copy of a subset of mActiveTracks
4777 Vector< sp<RecordTrack> > activeTracks;
4778
Eric Laurent10351942014-05-08 18:49:52 -07004779
Eric Laurent81784c32012-11-19 14:55:58 -08004780 { // scope for mLock
4781 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004782
Eric Laurent021cf962014-05-13 10:18:14 -07004783 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004784
Eric Laurent000a4192014-01-29 15:17:32 -08004785 // check exitPending here because checkForNewParameters_l() and
4786 // checkForNewParameters_l() can temporarily release mLock
4787 if (exitPending()) {
4788 break;
4789 }
4790
Glenn Kasten2b806402013-11-20 16:37:38 -08004791 // if no active track(s), then standby and release wakelock
4792 size_t size = mActiveTracks.size();
4793 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004794 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004795 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004796 releaseWakeLock_l();
4797 ALOGV("RecordThread: loop stopping");
4798 // go to sleep
4799 mWaitWorkCV.wait(mLock);
4800 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004801 goto reacquire_wakelock;
4802 }
4803
Glenn Kasten2b806402013-11-20 16:37:38 -08004804 if (mActiveTracksGen != activeTracksGen) {
4805 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004806 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004807 for (size_t i = 0; i < size; i++) {
4808 tmp.add(mActiveTracks[i]->uid());
4809 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004810 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004811 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004812
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004813 bool doBroadcast = false;
4814 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004815
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004816 activeTrack = mActiveTracks[i];
4817 if (activeTrack->isTerminated()) {
4818 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004819 mActiveTracks.remove(activeTrack);
4820 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004821 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004822 continue;
4823 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004824
4825 TrackBase::track_state activeTrackState = activeTrack->mState;
4826 switch (activeTrackState) {
4827
4828 case TrackBase::PAUSING:
4829 mActiveTracks.remove(activeTrack);
4830 mActiveTracksGen++;
4831 doBroadcast = true;
4832 size--;
4833 continue;
4834
4835 case TrackBase::STARTING_1:
4836 sleepUs = 10000;
4837 i++;
4838 continue;
4839
4840 case TrackBase::STARTING_2:
4841 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004842 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004843 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004844 break;
4845
4846 case TrackBase::ACTIVE:
4847 break;
4848
4849 case TrackBase::IDLE:
4850 i++;
4851 continue;
4852
4853 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004854 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004855 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004856
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004857 activeTracks.add(activeTrack);
4858 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004859
Glenn Kasten9e982352013-08-14 14:39:50 -07004860 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004861 if (doBroadcast) {
4862 mStartStopCond.broadcast();
4863 }
4864
4865 // sleep if there are no active tracks to process
4866 if (activeTracks.size() == 0) {
4867 if (sleepUs == 0) {
4868 sleepUs = kRecordThreadSleepUs;
4869 }
4870 continue;
4871 }
4872 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004873
Eric Laurent81784c32012-11-19 14:55:58 -08004874 lockEffectChains_l(effectChains);
4875 }
4876
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004877 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004878
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004879 size_t size = effectChains.size();
4880 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004881 // thread mutex is not locked, but effect chain is locked
4882 effectChains[i]->process_l();
4883 }
4884
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004885 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4886 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4887 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4888 // If destination is non-contiguous, first read past the nominal end of buffer, then
4889 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004890
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004891 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4892 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4893 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4894 if (bytesRead <= 0) {
4895 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4896 // Force input into standby so that it tries to recover at next read attempt
4897 inputStandBy();
4898 sleepUs = kRecordThreadSleepUs;
4899 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004900 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004901 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4902 size_t framesRead = bytesRead / mFrameSize;
4903 ALOG_ASSERT(framesRead > 0);
4904 if (mTeeSink != 0) {
4905 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4906 }
4907 // If destination is non-contiguous, we now correct for reading past end of buffer.
4908 size_t part1 = mRsmpInFramesP2 - rear;
4909 if (framesRead > part1) {
4910 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4911 (framesRead - part1) * mFrameSize);
4912 }
4913 rear = mRsmpInRear += framesRead;
4914
4915 size = activeTracks.size();
4916 // loop over each active track
4917 for (size_t i = 0; i < size; i++) {
4918 activeTrack = activeTracks[i];
4919
4920 enum {
4921 OVERRUN_UNKNOWN,
4922 OVERRUN_TRUE,
4923 OVERRUN_FALSE
4924 } overrun = OVERRUN_UNKNOWN;
4925
4926 // loop over getNextBuffer to handle circular sink
4927 for (;;) {
4928
4929 activeTrack->mSink.frameCount = ~0;
4930 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4931 size_t framesOut = activeTrack->mSink.frameCount;
4932 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4933
4934 int32_t front = activeTrack->mRsmpInFront;
4935 ssize_t filled = rear - front;
4936 size_t framesIn;
4937
4938 if (filled < 0) {
4939 // should not happen, but treat like a massive overrun and re-sync
4940 framesIn = 0;
4941 activeTrack->mRsmpInFront = rear;
4942 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004943 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004944 framesIn = (size_t) filled;
4945 } else {
4946 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004947 framesIn = mRsmpInFrames;
4948 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004949 overrun = OVERRUN_TRUE;
4950 }
4951
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004952 if (framesOut == 0 || framesIn == 0) {
4953 break;
4954 }
4955
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004956 if (activeTrack->mResampler == NULL) {
4957 // no resampling
4958 if (framesIn > framesOut) {
4959 framesIn = framesOut;
4960 } else {
4961 framesOut = framesIn;
4962 }
4963 int8_t *dst = activeTrack->mSink.i8;
4964 while (framesIn > 0) {
4965 front &= mRsmpInFramesP2 - 1;
4966 size_t part1 = mRsmpInFramesP2 - front;
4967 if (part1 > framesIn) {
4968 part1 = framesIn;
4969 }
4970 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004971 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004972 memcpy(dst, src, part1 * mFrameSize);
4973 } else if (mChannelCount == 1) {
4974 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4975 part1);
4976 } else {
4977 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4978 part1);
4979 }
4980 dst += part1 * activeTrack->mFrameSize;
4981 front += part1;
4982 framesIn -= part1;
4983 }
4984 activeTrack->mRsmpInFront += framesOut;
4985
4986 } else {
4987 // resampling
4988 // FIXME framesInNeeded should really be part of resampler API, and should
4989 // depend on the SRC ratio
4990 // to keep mRsmpInBuffer full so resampler always has sufficient input
4991 size_t framesInNeeded;
4992 // FIXME only re-calculate when it changes, and optimize for common ratios
4993 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4994 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004995 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004996 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4997 framesInNeeded, framesOut, inOverOut);
4998 // Although we theoretically have framesIn in circular buffer, some of those are
4999 // unreleased frames, and thus must be discounted for purpose of budgeting.
5000 size_t unreleased = activeTrack->mRsmpInUnrel;
5001 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005002 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005003 ALOGV("not enough to resample: have %u frames in but need %u in to "
5004 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005005 framesIn, framesInNeeded, framesOut, inOverOut);
5006 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005007 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5008 if (newFramesOut == 0) {
5009 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005010 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005011 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
5012 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
5013 framesInNeeded, newFramesOut, outOverIn);
5014 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5015 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5016 "given in/out ratio of %.4g",
5017 framesIn, framesInNeeded, newFramesOut, inOverOut);
5018 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005019 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005020 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005021 "given in/out ratio of %.4g",
5022 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005023 }
5024
5025 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5026 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005027 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005028 delete[] activeTrack->mRsmpOutBuffer;
5029 // resampler always outputs stereo
5030 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5031 activeTrack->mRsmpOutFrameCount = framesOut;
5032 }
5033
5034 // resampler accumulates, but we only have one source track
5035 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5036 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005037 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005038 activeTrack->mResamplerBufferProvider
5039 /*this*/ /* AudioBufferProvider* */);
5040 // ditherAndClamp() works as long as all buffers returned by
5041 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005042 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005043 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005044 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5045 framesOut);
5046 // the resampler always outputs stereo samples:
5047 // do post stereo to mono conversion
5048 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
5049 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
5050 } else {
5051 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5052 activeTrack->mRsmpOutBuffer, framesOut);
5053 }
5054 // now done with mRsmpOutBuffer
5055
5056 }
5057
5058 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5059 overrun = OVERRUN_FALSE;
5060 }
5061
5062 if (activeTrack->mFramesToDrop == 0) {
5063 if (framesOut > 0) {
5064 activeTrack->mSink.frameCount = framesOut;
5065 activeTrack->releaseBuffer(&activeTrack->mSink);
5066 }
5067 } else {
5068 // FIXME could do a partial drop of framesOut
5069 if (activeTrack->mFramesToDrop > 0) {
5070 activeTrack->mFramesToDrop -= framesOut;
5071 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005072 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005073 }
5074 } else {
5075 activeTrack->mFramesToDrop += framesOut;
5076 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5077 activeTrack->mSyncStartEvent->isCancelled()) {
5078 ALOGW("Synced record %s, session %d, trigger session %d",
5079 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5080 activeTrack->sessionId(),
5081 (activeTrack->mSyncStartEvent != 0) ?
5082 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005083 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005084 }
5085 }
5086 }
5087
5088 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005089 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005090 }
5091 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005092
5093 switch (overrun) {
5094 case OVERRUN_TRUE:
5095 // client isn't retrieving buffers fast enough
5096 if (!activeTrack->setOverflow()) {
5097 nsecs_t now = systemTime();
5098 // FIXME should lastWarning per track?
5099 if ((now - lastWarning) > kWarningThrottleNs) {
5100 ALOGW("RecordThread: buffer overflow");
5101 lastWarning = now;
5102 }
5103 }
5104 break;
5105 case OVERRUN_FALSE:
5106 activeTrack->clearOverflow();
5107 break;
5108 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005109 break;
5110 }
5111
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005112 }
5113
Eric Laurent81784c32012-11-19 14:55:58 -08005114 // enable changes in effect chain
5115 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005116 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005117 }
5118
Glenn Kasten93e471f2013-08-19 08:40:07 -07005119 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005120
5121 {
5122 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005123 for (size_t i = 0; i < mTracks.size(); i++) {
5124 sp<RecordTrack> track = mTracks[i];
5125 track->invalidate();
5126 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005127 mActiveTracks.clear();
5128 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005129 mStartStopCond.broadcast();
5130 }
5131
5132 releaseWakeLock();
5133
5134 ALOGV("RecordThread %p exiting", this);
5135 return false;
5136}
5137
Glenn Kasten93e471f2013-08-19 08:40:07 -07005138void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005139{
5140 if (!mStandby) {
5141 inputStandBy();
5142 mStandby = true;
5143 }
5144}
5145
5146void AudioFlinger::RecordThread::inputStandBy()
5147{
5148 mInput->stream->common.standby(&mInput->stream->common);
5149}
5150
Glenn Kasten05997e22014-03-13 15:08:33 -07005151// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005152sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005153 const sp<AudioFlinger::Client>& client,
5154 uint32_t sampleRate,
5155 audio_format_t format,
5156 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005157 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005158 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005159 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005160 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005161 pid_t tid,
5162 status_t *status)
5163{
Glenn Kasten74935e42013-12-19 08:56:45 -08005164 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005165 sp<RecordTrack> track;
5166 status_t lStatus;
5167
Glenn Kasten90e58b12013-07-31 16:16:02 -07005168 // client expresses a preference for FAST, but we get the final say
5169 if (*flags & IAudioFlinger::TRACK_FAST) {
5170 if (
5171 // use case: callback handler and frame count is default or at least as large as HAL
5172 (
5173 (tid != -1) &&
5174 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005175 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005176 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005177 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005178 // PCM data
5179 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005180 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005181 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5182 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005183 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005184 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005185 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005186 // record thread has an associated fast capture
5187 hasFastCapture()
5188 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005189 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005190 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005191 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005192 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005193 frameCount = mFrameCount * kFastTrackMultiplier;
5194 }
5195 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5196 frameCount, mFrameCount);
5197 } else {
5198 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5199 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005200 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005201 frameCount, mFrameCount, format,
5202 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005203 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005204 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005205 // FIXME It's not clear that we need to enforce this any more, since we have a pipe.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005206 // For compatibility with AudioRecord calculation, buffer depth is forced
5207 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5208 // This is probably too conservative, but legacy application code may depend on it.
5209 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005210 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005211 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5212 size_t mNormalFrameCount = 2048; // FIXME
5213 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5214 if (minBufCount < 2) {
5215 minBufCount = 2;
5216 }
5217 size_t minFrameCount = mNormalFrameCount * minBufCount;
5218 if (frameCount < minFrameCount) {
5219 frameCount = minFrameCount;
5220 }
5221 }
5222 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005223 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005224
Glenn Kasten15e57982013-09-24 11:52:37 -07005225 lStatus = initCheck();
5226 if (lStatus != NO_ERROR) {
5227 ALOGE("createRecordTrack_l() audio driver not initialized");
5228 goto Exit;
5229 }
Eric Laurent81784c32012-11-19 14:55:58 -08005230
5231 { // scope for mLock
5232 Mutex::Autolock _l(mLock);
5233
5234 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005235 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005236 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005237
Glenn Kasten03003332013-08-06 15:40:54 -07005238 lStatus = track->initCheck();
5239 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005240 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005241 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005242 goto Exit;
5243 }
5244 mTracks.add(track);
5245
5246 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5247 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5248 mAudioFlinger->btNrecIsOff();
5249 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5250 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005251
5252 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5253 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5254 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5255 // so ask activity manager to do this on our behalf
5256 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5257 }
Eric Laurent81784c32012-11-19 14:55:58 -08005258 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005259
Eric Laurent81784c32012-11-19 14:55:58 -08005260 lStatus = NO_ERROR;
5261
5262Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005263 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005264 return track;
5265}
5266
5267status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5268 AudioSystem::sync_event_t event,
5269 int triggerSession)
5270{
5271 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5272 sp<ThreadBase> strongMe = this;
5273 status_t status = NO_ERROR;
5274
5275 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005276 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005277 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005278 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005279 triggerSession,
5280 recordTrack->sessionId(),
5281 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005282 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005283 // Sync event can be cancelled by the trigger session if the track is not in a
5284 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005285 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005286 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005287 } else {
5288 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005289 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005290 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
5292 }
5293
5294 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005295 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005296 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005297 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5298 if (recordTrack->mState == TrackBase::PAUSING) {
5299 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005300 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005301 } else {
5302 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005303 }
5304 return status;
5305 }
5306
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005307 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5308 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5309 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005310 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005311 mActiveTracks.add(recordTrack);
5312 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005313 mLock.unlock();
5314 status_t status = AudioSystem::startInput(mId);
5315 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005316 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005317 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005318 mActiveTracks.remove(recordTrack);
5319 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005320 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005321 return status;
5322 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005323 // Catch up with current buffer indices if thread is already running.
5324 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5325 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5326 // see previously buffered data before it called start(), but with greater risk of overrun.
5327
5328 recordTrack->mRsmpInFront = mRsmpInRear;
5329 recordTrack->mRsmpInUnrel = 0;
5330 // FIXME why reset?
5331 if (recordTrack->mResampler != NULL) {
5332 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005333 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005334 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005335 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005336 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005337 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005338 ALOGV("Record failed to start");
5339 status = BAD_VALUE;
5340 goto startError;
5341 }
Eric Laurent81784c32012-11-19 14:55:58 -08005342 return status;
5343 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005344
Eric Laurent81784c32012-11-19 14:55:58 -08005345startError:
5346 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005347 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005348 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005349 return status;
5350}
5351
Eric Laurent81784c32012-11-19 14:55:58 -08005352void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5353{
5354 sp<SyncEvent> strongEvent = event.promote();
5355
5356 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005357 sp<RefBase> ptr = strongEvent->cookie().promote();
5358 if (ptr != 0) {
5359 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5360 recordTrack->handleSyncStartEvent(strongEvent);
5361 }
Eric Laurent81784c32012-11-19 14:55:58 -08005362 }
5363}
5364
Glenn Kastena8356f62013-07-25 14:37:52 -07005365bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005367 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005368 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005369 return false;
5370 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005371 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005372 recordTrack->mState = TrackBase::PAUSING;
5373 // do not wait for mStartStopCond if exiting
5374 if (exitPending()) {
5375 return true;
5376 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005377 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005378 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005379 // if we have been restarted, recordTrack is in mActiveTracks here
5380 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005381 ALOGV("Record stopped OK");
5382 return true;
5383 }
5384 return false;
5385}
5386
Glenn Kasten0f11b512014-01-31 16:18:54 -08005387bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005388{
5389 return false;
5390}
5391
Glenn Kasten0f11b512014-01-31 16:18:54 -08005392status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005393{
5394#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5395 if (!isValidSyncEvent(event)) {
5396 return BAD_VALUE;
5397 }
5398
5399 int eventSession = event->triggerSession();
5400 status_t ret = NAME_NOT_FOUND;
5401
5402 Mutex::Autolock _l(mLock);
5403
5404 for (size_t i = 0; i < mTracks.size(); i++) {
5405 sp<RecordTrack> track = mTracks[i];
5406 if (eventSession == track->sessionId()) {
5407 (void) track->setSyncEvent(event);
5408 ret = NO_ERROR;
5409 }
5410 }
5411 return ret;
5412#else
5413 return BAD_VALUE;
5414#endif
5415}
5416
5417// destroyTrack_l() must be called with ThreadBase::mLock held
5418void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5419{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420 track->terminate();
5421 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005422 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005423 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005424 removeTrack_l(track);
5425 }
5426}
5427
5428void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5429{
5430 mTracks.remove(track);
5431 // need anything related to effects here?
5432}
5433
5434void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5435{
5436 dumpInternals(fd, args);
5437 dumpTracks(fd, args);
5438 dumpEffectChains(fd, args);
5439}
5440
5441void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5442{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005443 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005444
Glenn Kasten2b806402013-11-20 16:37:38 -08005445 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005446 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005447 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005448 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005449 }
5450
Eric Laurent81784c32012-11-19 14:55:58 -08005451 dumpBase(fd, args);
5452}
5453
Glenn Kasten0f11b512014-01-31 16:18:54 -08005454void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005455{
5456 const size_t SIZE = 256;
5457 char buffer[SIZE];
5458 String8 result;
5459
Marco Nelissenb2208842014-02-07 14:00:50 -08005460 size_t numtracks = mTracks.size();
5461 size_t numactive = mActiveTracks.size();
5462 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005463 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005464 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005465 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005466 RecordTrack::appendDumpHeader(result);
5467 for (size_t i = 0; i < numtracks ; ++i) {
5468 sp<RecordTrack> track = mTracks[i];
5469 if (track != 0) {
5470 bool active = mActiveTracks.indexOf(track) >= 0;
5471 if (active) {
5472 numactiveseen++;
5473 }
5474 track->dump(buffer, SIZE, active);
5475 result.append(buffer);
5476 }
Eric Laurent81784c32012-11-19 14:55:58 -08005477 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005478 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005479 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005480 }
5481
Marco Nelissenb2208842014-02-07 14:00:50 -08005482 if (numactiveseen != numactive) {
5483 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5484 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005485 result.append(buffer);
5486 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005487 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005488 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005489 if (mTracks.indexOf(track) < 0) {
5490 track->dump(buffer, SIZE, true);
5491 result.append(buffer);
5492 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005493 }
Eric Laurent81784c32012-11-19 14:55:58 -08005494
5495 }
5496 write(fd, result.string(), result.size());
5497}
5498
5499// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005500status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5501 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005502{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005503 RecordTrack *activeTrack = mRecordTrack;
5504 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5505 if (threadBase == 0) {
5506 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005507 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005508 return NOT_ENOUGH_DATA;
5509 }
5510 RecordThread *recordThread = (RecordThread *) threadBase.get();
5511 int32_t rear = recordThread->mRsmpInRear;
5512 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005513 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005514 // FIXME should not be P2 (don't want to increase latency)
5515 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005516 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005517 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005518 front &= recordThread->mRsmpInFramesP2 - 1;
5519 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005520 if (part1 > (size_t) filled) {
5521 part1 = filled;
5522 }
5523 size_t ask = buffer->frameCount;
5524 ALOG_ASSERT(ask > 0);
5525 if (part1 > ask) {
5526 part1 = ask;
5527 }
5528 if (part1 == 0) {
5529 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005530 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005531 buffer->raw = NULL;
5532 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005533 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005534 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 }
5536
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005537 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005538 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005540 return NO_ERROR;
5541}
5542
5543// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005544void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5545 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005546{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005547 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005548 size_t stepCount = buffer->frameCount;
5549 if (stepCount == 0) {
5550 return;
5551 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005552 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5553 activeTrack->mRsmpInUnrel -= stepCount;
5554 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005555 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005556 buffer->frameCount = 0;
5557}
5558
Eric Laurent10351942014-05-08 18:49:52 -07005559bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5560 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005561{
5562 bool reconfig = false;
5563
Eric Laurent10351942014-05-08 18:49:52 -07005564 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005565
Eric Laurent10351942014-05-08 18:49:52 -07005566 audio_format_t reqFormat = mFormat;
5567 uint32_t samplingRate = mSampleRate;
5568 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5569
5570 AudioParameter param = AudioParameter(keyValuePair);
5571 int value;
5572 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5573 // channel count change can be requested. Do we mandate the first client defines the
5574 // HAL sampling rate and channel count or do we allow changes on the fly?
5575 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5576 samplingRate = value;
5577 reconfig = true;
5578 }
5579 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5580 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5581 status = BAD_VALUE;
5582 } else {
5583 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 reconfig = true;
5585 }
Eric Laurent10351942014-05-08 18:49:52 -07005586 }
5587 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5588 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5589 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5590 status = BAD_VALUE;
5591 } else {
5592 channelMask = mask;
5593 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 }
Eric Laurent10351942014-05-08 18:49:52 -07005595 }
5596 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5597 // do not accept frame count changes if tracks are open as the track buffer
5598 // size depends on frame count and correct behavior would not be guaranteed
5599 // if frame count is changed after track creation
5600 if (mActiveTracks.size() > 0) {
5601 status = INVALID_OPERATION;
5602 } else {
5603 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005604 }
Eric Laurent10351942014-05-08 18:49:52 -07005605 }
5606 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5607 // forward device change to effects that have requested to be
5608 // aware of attached audio device.
5609 for (size_t i = 0; i < mEffectChains.size(); i++) {
5610 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005611 }
Eric Laurent81784c32012-11-19 14:55:58 -08005612
Eric Laurent10351942014-05-08 18:49:52 -07005613 // store input device and output device but do not forward output device to audio HAL.
5614 // Note that status is ignored by the caller for output device
5615 // (see AudioFlinger::setParameters()
5616 if (audio_is_output_devices(value)) {
5617 mOutDevice = value;
5618 status = BAD_VALUE;
5619 } else {
5620 mInDevice = value;
5621 // disable AEC and NS if the device is a BT SCO headset supporting those
5622 // pre processings
5623 if (mTracks.size() > 0) {
5624 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5625 mAudioFlinger->btNrecIsOff();
5626 for (size_t i = 0; i < mTracks.size(); i++) {
5627 sp<RecordTrack> track = mTracks[i];
5628 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5629 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005630 }
5631 }
5632 }
Eric Laurent10351942014-05-08 18:49:52 -07005633 }
5634 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5635 mAudioSource != (audio_source_t)value) {
5636 // forward device change to effects that have requested to be
5637 // aware of attached audio device.
5638 for (size_t i = 0; i < mEffectChains.size(); i++) {
5639 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005640 }
Eric Laurent10351942014-05-08 18:49:52 -07005641 mAudioSource = (audio_source_t)value;
5642 }
Glenn Kastene198c362013-08-13 09:13:36 -07005643
Eric Laurent10351942014-05-08 18:49:52 -07005644 if (status == NO_ERROR) {
5645 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5646 keyValuePair.string());
5647 if (status == INVALID_OPERATION) {
5648 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005649 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5650 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005651 }
5652 if (reconfig) {
5653 if (status == BAD_VALUE &&
5654 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5655 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5656 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5657 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005658 audio_channel_count_from_in_mask(
5659 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005660 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5661 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5662 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005663 }
Eric Laurent10351942014-05-08 18:49:52 -07005664 if (status == NO_ERROR) {
5665 readInputParameters_l();
5666 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005667 }
5668 }
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
Eric Laurent10351942014-05-08 18:49:52 -07005670
Eric Laurent81784c32012-11-19 14:55:58 -08005671 return reconfig;
5672}
5673
5674String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5675{
Eric Laurent81784c32012-11-19 14:55:58 -08005676 Mutex::Autolock _l(mLock);
5677 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005678 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005679 }
5680
Glenn Kastend8ea6992013-07-16 14:17:15 -07005681 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5682 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005683 free(s);
5684 return out_s8;
5685}
5686
Eric Laurent021cf962014-05-13 10:18:14 -07005687void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005688 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005689 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005690
5691 switch (event) {
5692 case AudioSystem::INPUT_OPENED:
5693 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005694 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005695 desc.samplingRate = mSampleRate;
5696 desc.format = mFormat;
5697 desc.frameCount = mFrameCount;
5698 desc.latency = 0;
5699 param2 = &desc;
5700 break;
5701
5702 case AudioSystem::INPUT_CLOSED:
5703 default:
5704 break;
5705 }
Eric Laurent021cf962014-05-13 10:18:14 -07005706 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005707}
5708
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005709void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005710{
Eric Laurent81784c32012-11-19 14:55:58 -08005711 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5712 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07005713 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005714 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005715 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005716 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005717 }
Eric Laurent81784c32012-11-19 14:55:58 -08005718 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005719 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5720 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005721 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005722 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07005723 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005724 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005725 // A larger value should allow more old data to be read after a track calls start(),
5726 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005727 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005728 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005729 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005730 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5731 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005732
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005733 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5734 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005735}
5736
Glenn Kasten5f972c02014-01-13 09:59:31 -08005737uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005738{
5739 Mutex::Autolock _l(mLock);
5740 if (initCheck() != NO_ERROR) {
5741 return 0;
5742 }
5743
5744 return mInput->stream->get_input_frames_lost(mInput->stream);
5745}
5746
5747uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5748{
5749 Mutex::Autolock _l(mLock);
5750 uint32_t result = 0;
5751 if (getEffectChain_l(sessionId) != 0) {
5752 result = EFFECT_SESSION;
5753 }
5754
5755 for (size_t i = 0; i < mTracks.size(); ++i) {
5756 if (sessionId == mTracks[i]->sessionId()) {
5757 result |= TRACK_SESSION;
5758 break;
5759 }
5760 }
5761
5762 return result;
5763}
5764
5765KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5766{
5767 KeyedVector<int, bool> ids;
5768 Mutex::Autolock _l(mLock);
5769 for (size_t j = 0; j < mTracks.size(); ++j) {
5770 sp<RecordThread::RecordTrack> track = mTracks[j];
5771 int sessionId = track->sessionId();
5772 if (ids.indexOfKey(sessionId) < 0) {
5773 ids.add(sessionId, true);
5774 }
5775 }
5776 return ids;
5777}
5778
5779AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5780{
5781 Mutex::Autolock _l(mLock);
5782 AudioStreamIn *input = mInput;
5783 mInput = NULL;
5784 return input;
5785}
5786
5787// this method must always be called either with ThreadBase mLock held or inside the thread loop
5788audio_stream_t* AudioFlinger::RecordThread::stream() const
5789{
5790 if (mInput == NULL) {
5791 return NULL;
5792 }
5793 return &mInput->stream->common;
5794}
5795
5796status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5797{
5798 // only one chain per input thread
5799 if (mEffectChains.size() != 0) {
5800 return INVALID_OPERATION;
5801 }
5802 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5803
5804 chain->setInBuffer(NULL);
5805 chain->setOutBuffer(NULL);
5806
5807 checkSuspendOnAddEffectChain_l(chain);
5808
5809 mEffectChains.add(chain);
5810
5811 return NO_ERROR;
5812}
5813
5814size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5815{
5816 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5817 ALOGW_IF(mEffectChains.size() != 1,
5818 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5819 chain.get(), mEffectChains.size(), this);
5820 if (mEffectChains.size() == 1) {
5821 mEffectChains.removeAt(0);
5822 }
5823 return 0;
5824}
5825
Eric Laurent1c333e22014-05-20 10:48:17 -07005826status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
5827 audio_patch_handle_t *handle)
5828{
5829 status_t status = NO_ERROR;
5830 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
5831 // store new device and send to effects
5832 mInDevice = patch->sources[0].ext.device.type;
5833 for (size_t i = 0; i < mEffectChains.size(); i++) {
5834 mEffectChains[i]->setDevice_l(mInDevice);
5835 }
5836
5837 // disable AEC and NS if the device is a BT SCO headset supporting those
5838 // pre processings
5839 if (mTracks.size() > 0) {
5840 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5841 mAudioFlinger->btNrecIsOff();
5842 for (size_t i = 0; i < mTracks.size(); i++) {
5843 sp<RecordTrack> track = mTracks[i];
5844 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5845 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5846 }
5847 }
5848
5849 // store new source and send to effects
5850 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
5851 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
5852 for (size_t i = 0; i < mEffectChains.size(); i++) {
5853 mEffectChains[i]->setAudioSource_l(mAudioSource);
5854 }
5855 }
5856
5857 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
5858 status = hwDevice->create_audio_patch(hwDevice,
5859 patch->num_sources,
5860 patch->sources,
5861 patch->num_sinks,
5862 patch->sinks,
5863 handle);
5864 } else {
5865 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
5866 }
5867 return status;
5868}
5869
5870status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
5871{
5872 status_t status = NO_ERROR;
5873 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
5874 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
5875 status = hwDevice->release_audio_patch(hwDevice, handle);
5876 } else {
5877 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
5878 }
5879 return status;
5880}
5881
5882
Eric Laurent81784c32012-11-19 14:55:58 -08005883}; // namespace android