blob: 4972c7a8fb6e3f67aecf1daf2354ed8c097b2932 [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 Laurent951f4552014-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 Laurent951f4552014-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) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800542 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800543 }
544
Marco Nelissenb2208842014-02-07 14:00:50 -0800545 fdprintf(fd, " I/O handle: %d\n", mId);
546 fdprintf(fd, " TID: %d\n", getTid());
547 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
548 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000549 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800550 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
551 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
552 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
553 channelMaskToString(mChannelMask, mType != RECORD).string());
554 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000555 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800556 fdprintf(fd, " Pending config events:");
557 size_t numConfig = mConfigEvents.size();
558 if (numConfig) {
559 for (size_t i = 0; i < numConfig; i++) {
560 mConfigEvents[i]->dump(buffer, SIZE);
561 fdprintf(fd, "\n %s", buffer);
562 }
563 fdprintf(fd, "\n");
564 } else {
565 fdprintf(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);
Marco Nelissenb2208842014-02-07 14:00:50 -08001228 fdprintf(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();
1233 fdprintf(fd, " %d Tracks", numtracks);
1234 size_t numactiveseen = 0;
1235 if (numtracks) {
1236 fdprintf(fd, " of which %d are active\n", numactive);
1237 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());
1268
Eric Laurent81784c32012-11-19 14:55:58 -08001269}
1270
1271void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1272{
Marco Nelissenb2208842014-02-07 14:00:50 -08001273 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001274 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001275 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1276 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1277 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1278 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1279 fdprintf(fd, " Suspend count: %d\n", mSuspended);
Andy Hung2098f272014-02-27 14:00:06 -08001280 fdprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001281 fdprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001282 fdprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001283 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001284
1285 dumpBase(fd, args);
1286}
1287
1288// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001289
1290void AudioFlinger::PlaybackThread::onFirstRef()
1291{
1292 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1293}
1294
1295// ThreadBase virtuals
1296void AudioFlinger::PlaybackThread::preExit()
1297{
1298 ALOGV(" preExit()");
1299 // FIXME this is using hard-coded strings but in the future, this functionality will be
1300 // converted to use audio HAL extensions required to support tunneling
1301 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1302}
1303
1304// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1305sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1306 const sp<AudioFlinger::Client>& client,
1307 audio_stream_type_t streamType,
1308 uint32_t sampleRate,
1309 audio_format_t format,
1310 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001311 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001312 const sp<IMemory>& sharedBuffer,
1313 int sessionId,
1314 IAudioFlinger::track_flags_t *flags,
1315 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001316 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001317 status_t *status)
1318{
Glenn Kasten74935e42013-12-19 08:56:45 -08001319 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001320 sp<Track> track;
1321 status_t lStatus;
1322
1323 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1324
1325 // client expresses a preference for FAST, but we get the final say
1326 if (*flags & IAudioFlinger::TRACK_FAST) {
1327 if (
1328 // not timed
1329 (!isTimed) &&
1330 // either of these use cases:
1331 (
1332 // use case 1: shared buffer with any frame count
1333 (
1334 (sharedBuffer != 0)
1335 ) ||
1336 // use case 2: callback handler and frame count is default or at least as large as HAL
1337 (
1338 (tid != -1) &&
1339 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001340 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001341 )
1342 ) &&
1343 // PCM data
1344 audio_is_linear_pcm(format) &&
1345 // mono or stereo
1346 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1347 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001348 // hardware sample rate
1349 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001350 // normal mixer has an associated fast mixer
1351 hasFastMixer() &&
1352 // there are sufficient fast track slots available
1353 (mFastTrackAvailMask != 0)
1354 // FIXME test that MixerThread for this fast track has a capable output HAL
1355 // FIXME add a permission test also?
1356 ) {
1357 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1358 if (frameCount == 0) {
1359 frameCount = mFrameCount * kFastTrackMultiplier;
1360 }
1361 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1362 frameCount, mFrameCount);
1363 } else {
1364 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1365 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1366 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1367 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1368 audio_is_linear_pcm(format),
1369 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1370 *flags &= ~IAudioFlinger::TRACK_FAST;
1371 // For compatibility with AudioTrack calculation, buffer depth is forced
1372 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1373 // This is probably too conservative, but legacy application code may depend on it.
1374 // If you change this calculation, also review the start threshold which is related.
1375 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1376 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1377 if (minBufCount < 2) {
1378 minBufCount = 2;
1379 }
1380 size_t minFrameCount = mNormalFrameCount * minBufCount;
1381 if (frameCount < minFrameCount) {
1382 frameCount = minFrameCount;
1383 }
1384 }
1385 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001386 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001387
Glenn Kastenc3df8382014-03-13 15:05:25 -07001388 switch (mType) {
1389
1390 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001391 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001393 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1394 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001395 sampleRate, format, channelMask, mOutput, mFormat);
1396 lStatus = BAD_VALUE;
1397 goto Exit;
1398 }
1399 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001400 break;
1401
1402 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001403 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001404 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1405 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001406 sampleRate, format, channelMask, mOutput, mFormat);
1407 lStatus = BAD_VALUE;
1408 goto Exit;
1409 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001410 break;
1411
1412 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001413 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001414 ALOGE("createTrack_l() Bad parameter: format %#x \""
1415 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001416 format, mOutput, mFormat);
1417 lStatus = BAD_VALUE;
1418 goto Exit;
1419 }
Eric Laurent81784c32012-11-19 14:55:58 -08001420 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1421 if (sampleRate > mSampleRate*2) {
1422 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1423 lStatus = BAD_VALUE;
1424 goto Exit;
1425 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001426 break;
1427
Eric Laurent81784c32012-11-19 14:55:58 -08001428 }
1429
1430 lStatus = initCheck();
1431 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001432 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001433 goto Exit;
1434 }
1435
1436 { // scope for mLock
1437 Mutex::Autolock _l(mLock);
1438
1439 // all tracks in same audio session must share the same routing strategy otherwise
1440 // conflicts will happen when tracks are moved from one output to another by audio policy
1441 // manager
1442 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1443 for (size_t i = 0; i < mTracks.size(); ++i) {
1444 sp<Track> t = mTracks[i];
1445 if (t != 0 && !t->isOutputTrack()) {
1446 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1447 if (sessionId == t->sessionId() && strategy != actual) {
1448 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1449 strategy, actual);
1450 lStatus = BAD_VALUE;
1451 goto Exit;
1452 }
1453 }
1454 }
1455
1456 if (!isTimed) {
1457 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001458 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001459 } else {
1460 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001461 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001462 }
Glenn Kasten03003332013-08-06 15:40:54 -07001463
1464 // new Track always returns non-NULL,
1465 // but TimedTrack::create() is a factory that could fail by returning NULL
1466 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1467 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001468 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001469 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001470 goto Exit;
1471 }
1472 mTracks.add(track);
1473
1474 sp<EffectChain> chain = getEffectChain_l(sessionId);
1475 if (chain != 0) {
1476 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1477 track->setMainBuffer(chain->inBuffer());
1478 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1479 chain->incTrackCnt();
1480 }
1481
1482 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1483 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1484 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1485 // so ask activity manager to do this on our behalf
1486 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1487 }
1488 }
1489
1490 lStatus = NO_ERROR;
1491
1492Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001493 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001494 return track;
1495}
1496
1497uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1498{
1499 return latency;
1500}
1501
1502uint32_t AudioFlinger::PlaybackThread::latency() const
1503{
1504 Mutex::Autolock _l(mLock);
1505 return latency_l();
1506}
1507uint32_t AudioFlinger::PlaybackThread::latency_l() const
1508{
1509 if (initCheck() == NO_ERROR) {
1510 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1511 } else {
1512 return 0;
1513 }
1514}
1515
1516void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1517{
1518 Mutex::Autolock _l(mLock);
1519 // Don't apply master volume in SW if our HAL can do it for us.
1520 if (mOutput && mOutput->audioHwDev &&
1521 mOutput->audioHwDev->canSetMasterVolume()) {
1522 mMasterVolume = 1.0;
1523 } else {
1524 mMasterVolume = value;
1525 }
1526}
1527
1528void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1529{
1530 Mutex::Autolock _l(mLock);
1531 // Don't apply master mute in SW if our HAL can do it for us.
1532 if (mOutput && mOutput->audioHwDev &&
1533 mOutput->audioHwDev->canSetMasterMute()) {
1534 mMasterMute = false;
1535 } else {
1536 mMasterMute = muted;
1537 }
1538}
1539
1540void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1541{
1542 Mutex::Autolock _l(mLock);
1543 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001544 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001545}
1546
1547void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1548{
1549 Mutex::Autolock _l(mLock);
1550 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001551 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001552}
1553
1554float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1555{
1556 Mutex::Autolock _l(mLock);
1557 return mStreamTypes[stream].volume;
1558}
1559
1560// addTrack_l() must be called with ThreadBase::mLock held
1561status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1562{
1563 status_t status = ALREADY_EXISTS;
1564
1565 // set retry count for buffer fill
1566 track->mRetryCount = kMaxTrackStartupRetries;
1567 if (mActiveTracks.indexOf(track) < 0) {
1568 // the track is newly added, make sure it fills up all its
1569 // buffers before playing. This is to ensure the client will
1570 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001571 if (!track->isOutputTrack()) {
1572 TrackBase::track_state state = track->mState;
1573 mLock.unlock();
1574 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1575 mLock.lock();
1576 // abort track was stopped/paused while we released the lock
1577 if (state != track->mState) {
1578 if (status == NO_ERROR) {
1579 mLock.unlock();
1580 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1581 mLock.lock();
1582 }
1583 return INVALID_OPERATION;
1584 }
1585 // abort if start is rejected by audio policy manager
1586 if (status != NO_ERROR) {
1587 return PERMISSION_DENIED;
1588 }
1589#ifdef ADD_BATTERY_DATA
1590 // to track the speaker usage
1591 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1592#endif
1593 }
1594
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001595 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001596 track->mResetDone = false;
1597 track->mPresentationCompleteFrames = 0;
1598 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001599 mWakeLockUids.add(track->uid());
1600 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001601 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001602 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1603 if (chain != 0) {
1604 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1605 track->sessionId());
1606 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001607 }
1608
1609 status = NO_ERROR;
1610 }
1611
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001612 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001613 return status;
1614}
1615
Eric Laurentbfb1b832013-01-07 09:53:42 -08001616bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001617{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001618 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001619 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001620 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1621 track->mState = TrackBase::STOPPED;
1622 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001623 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001624 } else if (track->isFastTrack() || track->isOffloaded()) {
1625 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001626 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001627
1628 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001629}
1630
1631void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1632{
1633 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1634 mTracks.remove(track);
1635 deleteTrackName_l(track->name());
1636 // redundant as track is about to be destroyed, for dumpsys only
1637 track->mName = -1;
1638 if (track->isFastTrack()) {
1639 int index = track->mFastIndex;
1640 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1641 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1642 mFastTrackAvailMask |= 1 << index;
1643 // redundant as track is about to be destroyed, for dumpsys only
1644 track->mFastIndex = -1;
1645 }
1646 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1647 if (chain != 0) {
1648 chain->decTrackCnt();
1649 }
1650}
1651
Eric Laurentede6c3b2013-09-19 14:37:46 -07001652void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001653{
1654 // Thread could be blocked waiting for async
1655 // so signal it to handle state changes immediately
1656 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1657 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1658 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001659 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001660}
1661
Eric Laurent81784c32012-11-19 14:55:58 -08001662String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1663{
Eric Laurent81784c32012-11-19 14:55:58 -08001664 Mutex::Autolock _l(mLock);
1665 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001666 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001667 }
1668
Glenn Kastend8ea6992013-07-16 14:17:15 -07001669 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1670 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001671 free(s);
1672 return out_s8;
1673}
1674
Eric Laurent021cf962014-05-13 10:18:14 -07001675void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001676 AudioSystem::OutputDescriptor desc;
1677 void *param2 = NULL;
1678
Eric Laurent021cf962014-05-13 10:18:14 -07001679 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001680 param);
1681
1682 switch (event) {
1683 case AudioSystem::OUTPUT_OPENED:
1684 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001685 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001686 desc.samplingRate = mSampleRate;
1687 desc.format = mFormat;
1688 desc.frameCount = mNormalFrameCount; // FIXME see
1689 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001690 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001691 param2 = &desc;
1692 break;
1693
1694 case AudioSystem::STREAM_CONFIG_CHANGED:
1695 param2 = &param;
1696 case AudioSystem::OUTPUT_CLOSED:
1697 default:
1698 break;
1699 }
Eric Laurent021cf962014-05-13 10:18:14 -07001700 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001701}
1702
Eric Laurentbfb1b832013-01-07 09:53:42 -08001703void AudioFlinger::PlaybackThread::writeCallback()
1704{
1705 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001706 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001707}
1708
1709void AudioFlinger::PlaybackThread::drainCallback()
1710{
1711 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001712 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001713}
1714
Eric Laurent3b4529e2013-09-05 18:09:19 -07001715void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001716{
1717 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001718 // reject out of sequence requests
1719 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1720 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001721 mWaitWorkCV.signal();
1722 }
1723}
1724
Eric Laurent3b4529e2013-09-05 18:09:19 -07001725void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001726{
1727 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001728 // reject out of sequence requests
1729 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1730 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001731 mWaitWorkCV.signal();
1732 }
1733}
1734
1735// static
1736int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001737 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001738 void *cookie)
1739{
1740 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1741 ALOGV("asyncCallback() event %d", event);
1742 switch (event) {
1743 case STREAM_CBK_EVENT_WRITE_READY:
1744 me->writeCallback();
1745 break;
1746 case STREAM_CBK_EVENT_DRAIN_READY:
1747 me->drainCallback();
1748 break;
1749 default:
1750 ALOGW("asyncCallback() unknown event %d", event);
1751 break;
1752 }
1753 return 0;
1754}
1755
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001756void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001757{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001758 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001759 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1760 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001761 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001762 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001763 }
1764 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001765 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001766 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1767 }
Andy Hunge5412692014-05-16 11:25:07 -07001768 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001769 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001770 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001771 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001772 }
1773 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001774 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1775 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001776 }
Eric Laurent81784c32012-11-19 14:55:58 -08001777 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001778 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1779 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001780 if (mFrameCount & 15) {
1781 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1782 mFrameCount);
1783 }
1784
Eric Laurentbfb1b832013-01-07 09:53:42 -08001785 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1786 (mOutput->stream->set_callback != NULL)) {
1787 if (mOutput->stream->set_callback(mOutput->stream,
1788 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1789 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001790 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001791 }
1792 }
1793
Andy Hung09a50072014-02-27 14:30:47 -08001794 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001795 double multiplier = 1.0;
1796 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1797 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001798 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1799 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001800 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1801 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1802 maxNormalFrameCount = maxNormalFrameCount & ~15;
1803 if (maxNormalFrameCount < minNormalFrameCount) {
1804 maxNormalFrameCount = minNormalFrameCount;
1805 }
1806 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1807 if (multiplier <= 1.0) {
1808 multiplier = 1.0;
1809 } else if (multiplier <= 2.0) {
1810 if (2 * mFrameCount <= maxNormalFrameCount) {
1811 multiplier = 2.0;
1812 } else {
1813 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1814 }
1815 } else {
1816 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001817 // 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 -08001818 // track, but we sometimes have to do this to satisfy the maximum frame count
1819 // constraint)
1820 // FIXME this rounding up should not be done if no HAL SRC
1821 uint32_t truncMult = (uint32_t) multiplier;
1822 if ((truncMult & 1)) {
1823 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1824 ++truncMult;
1825 }
1826 }
1827 multiplier = (double) truncMult;
1828 }
1829 }
1830 mNormalFrameCount = multiplier * mFrameCount;
1831 // round up to nearest 16 frames to satisfy AudioMixer
1832 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001833 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001834 mNormalFrameCount);
1835
Andy Hung010a1a12014-03-13 13:57:33 -07001836 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1837 // Originally this was int16_t[] array, need to remove legacy implications.
1838 free(mSinkBuffer);
1839 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001840 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1841 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1842 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001843 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001844
Andy Hung69aed5f2014-02-25 17:24:40 -08001845 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1846 // drives the output.
1847 free(mMixerBuffer);
1848 mMixerBuffer = NULL;
1849 if (mMixerBufferEnabled) {
1850 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1851 mMixerBufferSize = mNormalFrameCount * mChannelCount
1852 * audio_bytes_per_sample(mMixerBufferFormat);
1853 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1854 }
Andy Hung98ef9782014-03-04 14:46:50 -08001855 free(mEffectBuffer);
1856 mEffectBuffer = NULL;
1857 if (mEffectBufferEnabled) {
1858 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1859 mEffectBufferSize = mNormalFrameCount * mChannelCount
1860 * audio_bytes_per_sample(mEffectBufferFormat);
1861 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1862 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001863
Eric Laurent81784c32012-11-19 14:55:58 -08001864 // force reconfiguration of effect chains and engines to take new buffer size and audio
1865 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001866 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001867 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1868 // matter.
1869 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1870 Vector< sp<EffectChain> > effectChains = mEffectChains;
1871 for (size_t i = 0; i < effectChains.size(); i ++) {
1872 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1873 }
1874}
1875
1876
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001877status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001878{
1879 if (halFrames == NULL || dspFrames == NULL) {
1880 return BAD_VALUE;
1881 }
1882 Mutex::Autolock _l(mLock);
1883 if (initCheck() != NO_ERROR) {
1884 return INVALID_OPERATION;
1885 }
1886 size_t framesWritten = mBytesWritten / mFrameSize;
1887 *halFrames = framesWritten;
1888
1889 if (isSuspended()) {
1890 // return an estimation of rendered frames when the output is suspended
1891 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1892 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1893 return NO_ERROR;
1894 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001895 status_t status;
1896 uint32_t frames;
1897 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1898 *dspFrames = (size_t)frames;
1899 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001900 }
1901}
1902
1903uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1904{
1905 Mutex::Autolock _l(mLock);
1906 uint32_t result = 0;
1907 if (getEffectChain_l(sessionId) != 0) {
1908 result = EFFECT_SESSION;
1909 }
1910
1911 for (size_t i = 0; i < mTracks.size(); ++i) {
1912 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001913 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001914 result |= TRACK_SESSION;
1915 break;
1916 }
1917 }
1918
1919 return result;
1920}
1921
1922uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1923{
1924 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1925 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1926 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1927 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1928 }
1929 for (size_t i = 0; i < mTracks.size(); i++) {
1930 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001931 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001932 return AudioSystem::getStrategyForStream(track->streamType());
1933 }
1934 }
1935 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1936}
1937
1938
1939AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1940{
1941 Mutex::Autolock _l(mLock);
1942 return mOutput;
1943}
1944
1945AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1946{
1947 Mutex::Autolock _l(mLock);
1948 AudioStreamOut *output = mOutput;
1949 mOutput = NULL;
1950 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1951 // must push a NULL and wait for ack
1952 mOutputSink.clear();
1953 mPipeSink.clear();
1954 mNormalSink.clear();
1955 return output;
1956}
1957
1958// this method must always be called either with ThreadBase mLock held or inside the thread loop
1959audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1960{
1961 if (mOutput == NULL) {
1962 return NULL;
1963 }
1964 return &mOutput->stream->common;
1965}
1966
1967uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1968{
1969 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1970}
1971
1972status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1973{
1974 if (!isValidSyncEvent(event)) {
1975 return BAD_VALUE;
1976 }
1977
1978 Mutex::Autolock _l(mLock);
1979
1980 for (size_t i = 0; i < mTracks.size(); ++i) {
1981 sp<Track> track = mTracks[i];
1982 if (event->triggerSession() == track->sessionId()) {
1983 (void) track->setSyncEvent(event);
1984 return NO_ERROR;
1985 }
1986 }
1987
1988 return NAME_NOT_FOUND;
1989}
1990
1991bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1992{
1993 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1994}
1995
1996void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1997 const Vector< sp<Track> >& tracksToRemove)
1998{
1999 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002000 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002001 for (size_t i = 0 ; i < count ; i++) {
2002 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002003 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002004 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002005#ifdef ADD_BATTERY_DATA
2006 // to track the speaker usage
2007 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2008#endif
2009 if (track->isTerminated()) {
2010 AudioSystem::releaseOutput(mId);
2011 }
Eric Laurent81784c32012-11-19 14:55:58 -08002012 }
2013 }
2014 }
Eric Laurent81784c32012-11-19 14:55:58 -08002015}
2016
2017void AudioFlinger::PlaybackThread::checkSilentMode_l()
2018{
2019 if (!mMasterMute) {
2020 char value[PROPERTY_VALUE_MAX];
2021 if (property_get("ro.audio.silent", value, "0") > 0) {
2022 char *endptr;
2023 unsigned long ul = strtoul(value, &endptr, 0);
2024 if (*endptr == '\0' && ul != 0) {
2025 ALOGD("Silence is golden");
2026 // The setprop command will not allow a property to be changed after
2027 // the first time it is set, so we don't have to worry about un-muting.
2028 setMasterMute_l(true);
2029 }
2030 }
2031 }
2032}
2033
2034// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002036{
2037 // FIXME rewrite to reduce number of system calls
2038 mLastWriteTime = systemTime();
2039 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002041 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002042
2043 // If an NBAIO sink is present, use it to write the normal mixer's submix
2044 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002045 const size_t count = mBytesRemaining / mFrameSize;
2046
Simon Wilson2d590962012-11-29 15:18:50 -08002047 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002048 // update the setpoint when AudioFlinger::mScreenState changes
2049 uint32_t screenState = AudioFlinger::mScreenState;
2050 if (screenState != mScreenState) {
2051 mScreenState = screenState;
2052 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2053 if (pipe != NULL) {
2054 pipe->setAvgFrames((mScreenState & 1) ?
2055 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2056 }
2057 }
Andy Hung010a1a12014-03-13 13:57:33 -07002058 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002059 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002060 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002061 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002062 } else {
2063 bytesWritten = framesWritten;
2064 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002065 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002066 if (status == NO_ERROR) {
2067 size_t totalFramesWritten = mNormalSink->framesWritten();
2068 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2069 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2070 mLatchDValid = true;
2071 }
2072 }
Eric Laurent81784c32012-11-19 14:55:58 -08002073 // otherwise use the HAL / AudioStreamOut directly
2074 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002075 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002076
Eric Laurentbfb1b832013-01-07 09:53:42 -08002077 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002078 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2079 mWriteAckSequence += 2;
2080 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002081 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002082 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002083 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002084 // FIXME We should have an implementation of timestamps for direct output threads.
2085 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002086 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002087 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002088 if (mUseAsyncWrite &&
2089 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2090 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002091 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002092 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002093 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002094 }
Eric Laurent81784c32012-11-19 14:55:58 -08002095 }
2096
Eric Laurent81784c32012-11-19 14:55:58 -08002097 mNumWrites++;
2098 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002099 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002100 return bytesWritten;
2101}
2102
2103void AudioFlinger::PlaybackThread::threadLoop_drain()
2104{
2105 if (mOutput->stream->drain) {
2106 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2107 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002108 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2109 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002111 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 }
2113 mOutput->stream->drain(mOutput->stream,
2114 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2115 : AUDIO_DRAIN_ALL);
2116 }
2117}
2118
2119void AudioFlinger::PlaybackThread::threadLoop_exit()
2120{
2121 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
2124/*
2125The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002126 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002127 - activeSleepTime from activeSleepTimeUs()
2128 - idleSleepTime from idleSleepTimeUs()
2129 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2130 - maxPeriod from frame count and sample rate (MIXER only)
2131
2132The parameters that affect these derived values are:
2133 - frame count
2134 - frame size
2135 - sample rate
2136 - device type: A2DP or not
2137 - device latency
2138 - format: PCM or not
2139 - active sleep time
2140 - idle sleep time
2141*/
2142
2143void AudioFlinger::PlaybackThread::cacheParameters_l()
2144{
Andy Hung25c2dac2014-02-27 14:56:00 -08002145 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002146 activeSleepTime = activeSleepTimeUs();
2147 idleSleepTime = idleSleepTimeUs();
2148}
2149
2150void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2151{
Glenn Kasten7c027242012-12-26 14:43:16 -08002152 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002153 this, streamType, mTracks.size());
2154 Mutex::Autolock _l(mLock);
2155
2156 size_t size = mTracks.size();
2157 for (size_t i = 0; i < size; i++) {
2158 sp<Track> t = mTracks[i];
2159 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002160 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002161 }
2162 }
2163}
2164
2165status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2166{
2167 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002168 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2169 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002170 bool ownsBuffer = false;
2171
2172 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2173 if (session > 0) {
2174 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002175 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002176 if (mType != DIRECT) {
2177 size_t numSamples = mNormalFrameCount * mChannelCount;
2178 buffer = new int16_t[numSamples];
2179 memset(buffer, 0, numSamples * sizeof(int16_t));
2180 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2181 ownsBuffer = true;
2182 }
2183
2184 // Attach all tracks with same session ID to this chain.
2185 for (size_t i = 0; i < mTracks.size(); ++i) {
2186 sp<Track> track = mTracks[i];
2187 if (session == track->sessionId()) {
2188 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2189 buffer);
2190 track->setMainBuffer(buffer);
2191 chain->incTrackCnt();
2192 }
2193 }
2194
2195 // indicate all active tracks in the chain
2196 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2197 sp<Track> track = mActiveTracks[i].promote();
2198 if (track == 0) {
2199 continue;
2200 }
2201 if (session == track->sessionId()) {
2202 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2203 chain->incActiveTrackCnt();
2204 }
2205 }
2206 }
2207
2208 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002209 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2210 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002211 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2212 // chains list in order to be processed last as it contains output stage effects
2213 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2214 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2215 // after track specific effects and before output stage
2216 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2217 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2218 // Effect chain for other sessions are inserted at beginning of effect
2219 // chains list to be processed before output mix effects. Relative order between other
2220 // sessions is not important
2221 size_t size = mEffectChains.size();
2222 size_t i = 0;
2223 for (i = 0; i < size; i++) {
2224 if (mEffectChains[i]->sessionId() < session) {
2225 break;
2226 }
2227 }
2228 mEffectChains.insertAt(chain, i);
2229 checkSuspendOnAddEffectChain_l(chain);
2230
2231 return NO_ERROR;
2232}
2233
2234size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2235{
2236 int session = chain->sessionId();
2237
2238 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2239
2240 for (size_t i = 0; i < mEffectChains.size(); i++) {
2241 if (chain == mEffectChains[i]) {
2242 mEffectChains.removeAt(i);
2243 // detach all active tracks from the chain
2244 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2245 sp<Track> track = mActiveTracks[i].promote();
2246 if (track == 0) {
2247 continue;
2248 }
2249 if (session == track->sessionId()) {
2250 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2251 chain.get(), session);
2252 chain->decActiveTrackCnt();
2253 }
2254 }
2255
2256 // detach all tracks with same session ID from this chain
2257 for (size_t i = 0; i < mTracks.size(); ++i) {
2258 sp<Track> track = mTracks[i];
2259 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002260 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002261 chain->decTrackCnt();
2262 }
2263 }
2264 break;
2265 }
2266 }
2267 return mEffectChains.size();
2268}
2269
2270status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2271 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2272{
2273 Mutex::Autolock _l(mLock);
2274 return attachAuxEffect_l(track, EffectId);
2275}
2276
2277status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2278 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2279{
2280 status_t status = NO_ERROR;
2281
2282 if (EffectId == 0) {
2283 track->setAuxBuffer(0, NULL);
2284 } else {
2285 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2286 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2287 if (effect != 0) {
2288 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2289 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2290 } else {
2291 status = INVALID_OPERATION;
2292 }
2293 } else {
2294 status = BAD_VALUE;
2295 }
2296 }
2297 return status;
2298}
2299
2300void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2301{
2302 for (size_t i = 0; i < mTracks.size(); ++i) {
2303 sp<Track> track = mTracks[i];
2304 if (track->auxEffectId() == effectId) {
2305 attachAuxEffect_l(track, 0);
2306 }
2307 }
2308}
2309
2310bool AudioFlinger::PlaybackThread::threadLoop()
2311{
2312 Vector< sp<Track> > tracksToRemove;
2313
2314 standbyTime = systemTime();
2315
2316 // MIXER
2317 nsecs_t lastWarning = 0;
2318
2319 // DUPLICATING
2320 // FIXME could this be made local to while loop?
2321 writeFrames = 0;
2322
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002323 int lastGeneration = 0;
2324
Eric Laurent81784c32012-11-19 14:55:58 -08002325 cacheParameters_l();
2326 sleepTime = idleSleepTime;
2327
2328 if (mType == MIXER) {
2329 sleepTimeShift = 0;
2330 }
2331
2332 CpuStats cpuStats;
2333 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2334
2335 acquireWakeLock();
2336
Glenn Kasten9e58b552013-01-18 15:09:48 -08002337 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2338 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2339 // and then that string will be logged at the next convenient opportunity.
2340 const char *logString = NULL;
2341
Eric Laurent664539d2013-09-23 18:24:31 -07002342 checkSilentMode_l();
2343
Eric Laurent81784c32012-11-19 14:55:58 -08002344 while (!exitPending())
2345 {
2346 cpuStats.sample(myName);
2347
2348 Vector< sp<EffectChain> > effectChains;
2349
Eric Laurent81784c32012-11-19 14:55:58 -08002350 { // scope for mLock
2351
2352 Mutex::Autolock _l(mLock);
2353
Eric Laurent021cf962014-05-13 10:18:14 -07002354 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002355
Glenn Kasten9e58b552013-01-18 15:09:48 -08002356 if (logString != NULL) {
2357 mNBLogWriter->logTimestamp();
2358 mNBLogWriter->log(logString);
2359 logString = NULL;
2360 }
2361
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002362 if (mLatchDValid) {
2363 mLatchQ = mLatchD;
2364 mLatchDValid = false;
2365 mLatchQValid = true;
2366 }
2367
Eric Laurent81784c32012-11-19 14:55:58 -08002368 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002369 if (mSignalPending) {
2370 // A signal was raised while we were unlocked
2371 mSignalPending = false;
2372 } else if (waitingAsyncCallback_l()) {
2373 if (exitPending()) {
2374 break;
2375 }
2376 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002377 mWakeLockUids.clear();
2378 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379 ALOGV("wait async completion");
2380 mWaitWorkCV.wait(mLock);
2381 ALOGV("async completion/wake");
2382 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002383 standbyTime = systemTime() + standbyDelay;
2384 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002385
2386 continue;
2387 }
2388 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 isSuspended()) {
2390 // put audio hardware into standby after short delay
2391 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002392
2393 threadLoop_standby();
2394
2395 mStandby = true;
2396 }
2397
2398 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2399 // we're about to wait, flush the binder command buffer
2400 IPCThreadState::self()->flushCommands();
2401
2402 clearOutputTracks();
2403
2404 if (exitPending()) {
2405 break;
2406 }
2407
2408 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002409 mWakeLockUids.clear();
2410 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002411 // wait until we have something to do...
2412 ALOGV("%s going to sleep", myName.string());
2413 mWaitWorkCV.wait(mLock);
2414 ALOGV("%s waking up", myName.string());
2415 acquireWakeLock_l();
2416
2417 mMixerStatus = MIXER_IDLE;
2418 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2419 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002421 checkSilentMode_l();
2422
2423 standbyTime = systemTime() + standbyDelay;
2424 sleepTime = idleSleepTime;
2425 if (mType == MIXER) {
2426 sleepTimeShift = 0;
2427 }
2428
2429 continue;
2430 }
2431 }
Eric Laurent81784c32012-11-19 14:55:58 -08002432 // mMixerStatusIgnoringFastTracks is also updated internally
2433 mMixerStatus = prepareTracks_l(&tracksToRemove);
2434
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002435 // compare with previously applied list
2436 if (lastGeneration != mActiveTracksGeneration) {
2437 // update wakelock
2438 updateWakeLockUids_l(mWakeLockUids);
2439 lastGeneration = mActiveTracksGeneration;
2440 }
2441
Eric Laurent81784c32012-11-19 14:55:58 -08002442 // prevent any changes in effect chain list and in each effect chain
2443 // during mixing and effect process as the audio buffers could be deleted
2444 // or modified if an effect is created or deleted
2445 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002446 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002447
Eric Laurentbfb1b832013-01-07 09:53:42 -08002448 if (mBytesRemaining == 0) {
2449 mCurrentWriteLength = 0;
2450 if (mMixerStatus == MIXER_TRACKS_READY) {
2451 // threadLoop_mix() sets mCurrentWriteLength
2452 threadLoop_mix();
2453 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2454 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2455 // threadLoop_sleepTime sets sleepTime to 0 if data
2456 // must be written to HAL
2457 threadLoop_sleepTime();
2458 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002459 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002460 }
2461 }
Andy Hung98ef9782014-03-04 14:46:50 -08002462 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2463 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2464 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2465 // or mSinkBuffer (if there are no effects).
2466 //
2467 // This is done pre-effects computation; if effects change to
2468 // support higher precision, this needs to move.
2469 //
2470 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2471 // TODO use sleepTime == 0 as an additional condition.
2472 if (mMixerBufferValid) {
2473 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2474 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2475
2476 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2477 mNormalFrameCount * mChannelCount);
2478 }
2479
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480 mBytesRemaining = mCurrentWriteLength;
2481 if (isSuspended()) {
2482 sleepTime = suspendSleepTimeUs();
2483 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002484 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485 mBytesRemaining = 0;
2486 }
Eric Laurent81784c32012-11-19 14:55:58 -08002487
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002489 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 for (size_t i = 0; i < effectChains.size(); i ++) {
2491 effectChains[i]->process_l();
2492 }
Eric Laurent81784c32012-11-19 14:55:58 -08002493 }
2494 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002495 // Process effect chains for offloaded thread even if no audio
2496 // was read from audio track: process only updates effect state
2497 // and thus does have to be synchronized with audio writes but may have
2498 // to be called while waiting for async write callback
2499 if (mType == OFFLOAD) {
2500 for (size_t i = 0; i < effectChains.size(); i ++) {
2501 effectChains[i]->process_l();
2502 }
2503 }
Eric Laurent81784c32012-11-19 14:55:58 -08002504
Andy Hung98ef9782014-03-04 14:46:50 -08002505 // Only if the Effects buffer is enabled and there is data in the
2506 // Effects buffer (buffer valid), we need to
2507 // copy into the sink buffer.
2508 // TODO use sleepTime == 0 as an additional condition.
2509 if (mEffectBufferValid) {
2510 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2511 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2512 mNormalFrameCount * mChannelCount);
2513 }
2514
Eric Laurent81784c32012-11-19 14:55:58 -08002515 // enable changes in effect chain
2516 unlockEffectChains(effectChains);
2517
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 if (!waitingAsyncCallback()) {
2519 // sleepTime == 0 means we must write to audio hardware
2520 if (sleepTime == 0) {
2521 if (mBytesRemaining) {
2522 ssize_t ret = threadLoop_write();
2523 if (ret < 0) {
2524 mBytesRemaining = 0;
2525 } else {
2526 mBytesWritten += ret;
2527 mBytesRemaining -= ret;
2528 }
2529 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2530 (mMixerStatus == MIXER_DRAIN_ALL)) {
2531 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002532 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002533 if (mType == MIXER) {
2534 // write blocked detection
2535 nsecs_t now = systemTime();
2536 nsecs_t delta = now - mLastWriteTime;
2537 if (!mStandby && delta > maxPeriod) {
2538 mNumDelayedWrites++;
2539 if ((now - lastWarning) > kWarningThrottleNs) {
2540 ATRACE_NAME("underrun");
2541 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2542 ns2ms(delta), mNumDelayedWrites, this);
2543 lastWarning = now;
2544 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002545 }
2546 }
Eric Laurent81784c32012-11-19 14:55:58 -08002547
Eric Laurentbfb1b832013-01-07 09:53:42 -08002548 } else {
2549 usleep(sleepTime);
2550 }
Eric Laurent81784c32012-11-19 14:55:58 -08002551 }
2552
2553 // Finally let go of removed track(s), without the lock held
2554 // since we can't guarantee the destructors won't acquire that
2555 // same lock. This will also mutate and push a new fast mixer state.
2556 threadLoop_removeTracks(tracksToRemove);
2557 tracksToRemove.clear();
2558
2559 // FIXME I don't understand the need for this here;
2560 // it was in the original code but maybe the
2561 // assignment in saveOutputTracks() makes this unnecessary?
2562 clearOutputTracks();
2563
2564 // Effect chains will be actually deleted here if they were removed from
2565 // mEffectChains list during mixing or effects processing
2566 effectChains.clear();
2567
2568 // FIXME Note that the above .clear() is no longer necessary since effectChains
2569 // is now local to this block, but will keep it for now (at least until merge done).
2570 }
2571
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572 threadLoop_exit();
2573
Eric Laurent81784c32012-11-19 14:55:58 -08002574 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002576 // put output stream into standby mode
2577 if (!mStandby) {
2578 mOutput->stream->common.standby(&mOutput->stream->common);
2579 }
2580 }
2581
2582 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002583 mWakeLockUids.clear();
2584 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002585
2586 ALOGV("Thread %p type %d exiting", this, mType);
2587 return false;
2588}
2589
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590// removeTracks_l() must be called with ThreadBase::mLock held
2591void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2592{
2593 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002594 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 for (size_t i=0 ; i<count ; i++) {
2596 const sp<Track>& track = tracksToRemove.itemAt(i);
2597 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002598 mWakeLockUids.remove(track->uid());
2599 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2601 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2602 if (chain != 0) {
2603 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2604 track->sessionId());
2605 chain->decActiveTrackCnt();
2606 }
2607 if (track->isTerminated()) {
2608 removeTrack_l(track);
2609 }
2610 }
2611 }
2612
2613}
Eric Laurent81784c32012-11-19 14:55:58 -08002614
Eric Laurentaccc1472013-09-20 09:36:34 -07002615status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2616{
2617 if (mNormalSink != 0) {
2618 return mNormalSink->getTimestamp(timestamp);
2619 }
2620 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2621 uint64_t position64;
2622 int ret = mOutput->stream->get_presentation_position(
2623 mOutput->stream, &position64, &timestamp.mTime);
2624 if (ret == 0) {
2625 timestamp.mPosition = (uint32_t)position64;
2626 return NO_ERROR;
2627 }
2628 }
2629 return INVALID_OPERATION;
2630}
Eric Laurent951f4552014-05-20 10:48:17 -07002631
2632status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2633 audio_patch_handle_t *handle)
2634{
2635 status_t status = NO_ERROR;
2636 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2637 // store new device and send to effects
2638 audio_devices_t type = AUDIO_DEVICE_NONE;
2639 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2640 type |= patch->sinks[i].ext.device.type;
2641 }
2642 mOutDevice = type;
2643 for (size_t i = 0; i < mEffectChains.size(); i++) {
2644 mEffectChains[i]->setDevice_l(mOutDevice);
2645 }
2646
2647 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2648 status = hwDevice->create_audio_patch(hwDevice,
2649 patch->num_sources,
2650 patch->sources,
2651 patch->num_sinks,
2652 patch->sinks,
2653 handle);
2654 } else {
2655 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2656 }
2657 return status;
2658}
2659
2660status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2661{
2662 status_t status = NO_ERROR;
2663 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2664 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2665 status = hwDevice->release_audio_patch(hwDevice, handle);
2666 } else {
2667 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2668 }
2669 return status;
2670}
2671
Eric Laurent81784c32012-11-19 14:55:58 -08002672// ----------------------------------------------------------------------------
2673
2674AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2675 audio_io_handle_t id, audio_devices_t device, type_t type)
2676 : PlaybackThread(audioFlinger, output, id, device, type),
2677 // mAudioMixer below
2678 // mFastMixer below
2679 mFastMixerFutex(0)
2680 // mOutputSink below
2681 // mPipeSink below
2682 // mNormalSink below
2683{
2684 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002685 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002686 "mFrameCount=%d, mNormalFrameCount=%d",
2687 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2688 mNormalFrameCount);
2689 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2690
2691 // FIXME - Current mixer implementation only supports stereo output
2692 if (mChannelCount != FCC_2) {
2693 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2694 }
2695
2696 // create an NBAIO sink for the HAL output stream, and negotiate
2697 mOutputSink = new AudioStreamOutSink(output->stream);
2698 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002699 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002700 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2701 ALOG_ASSERT(index == 0);
2702
2703 // initialize fast mixer depending on configuration
2704 bool initFastMixer;
2705 switch (kUseFastMixer) {
2706 case FastMixer_Never:
2707 initFastMixer = false;
2708 break;
2709 case FastMixer_Always:
2710 initFastMixer = true;
2711 break;
2712 case FastMixer_Static:
2713 case FastMixer_Dynamic:
2714 initFastMixer = mFrameCount < mNormalFrameCount;
2715 break;
2716 }
2717 if (initFastMixer) {
2718
2719 // create a MonoPipe to connect our submix to FastMixer
2720 NBAIO_Format format = mOutputSink->format();
2721 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2722 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2723 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2724 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2725 const NBAIO_Format offers[1] = {format};
2726 size_t numCounterOffers = 0;
2727 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2728 ALOG_ASSERT(index == 0);
2729 monoPipe->setAvgFrames((mScreenState & 1) ?
2730 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2731 mPipeSink = monoPipe;
2732
Glenn Kasten46909e72013-02-26 09:20:22 -08002733#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002734 if (mTeeSinkOutputEnabled) {
2735 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2736 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2737 numCounterOffers = 0;
2738 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2739 ALOG_ASSERT(index == 0);
2740 mTeeSink = teeSink;
2741 PipeReader *teeSource = new PipeReader(*teeSink);
2742 numCounterOffers = 0;
2743 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2744 ALOG_ASSERT(index == 0);
2745 mTeeSource = teeSource;
2746 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002747#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002748
2749 // create fast mixer and configure it initially with just one fast track for our submix
2750 mFastMixer = new FastMixer();
2751 FastMixerStateQueue *sq = mFastMixer->sq();
2752#ifdef STATE_QUEUE_DUMP
2753 sq->setObserverDump(&mStateQueueObserverDump);
2754 sq->setMutatorDump(&mStateQueueMutatorDump);
2755#endif
2756 FastMixerState *state = sq->begin();
2757 FastTrack *fastTrack = &state->mFastTracks[0];
2758 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2759 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2760 fastTrack->mVolumeProvider = NULL;
2761 fastTrack->mGeneration++;
2762 state->mFastTracksGen++;
2763 state->mTrackMask = 1;
2764 // fast mixer will use the HAL output sink
2765 state->mOutputSink = mOutputSink.get();
2766 state->mOutputSinkGen++;
2767 state->mFrameCount = mFrameCount;
2768 state->mCommand = FastMixerState::COLD_IDLE;
2769 // already done in constructor initialization list
2770 //mFastMixerFutex = 0;
2771 state->mColdFutexAddr = &mFastMixerFutex;
2772 state->mColdGen++;
2773 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002774#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002775 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002776#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002777 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2778 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002779 sq->end();
2780 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2781
2782 // start the fast mixer
2783 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2784 pid_t tid = mFastMixer->getTid();
2785 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2786 if (err != 0) {
2787 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2788 kPriorityFastMixer, getpid_cached, tid, err);
2789 }
2790
2791#ifdef AUDIO_WATCHDOG
2792 // create and start the watchdog
2793 mAudioWatchdog = new AudioWatchdog();
2794 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2795 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2796 tid = mAudioWatchdog->getTid();
2797 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2798 if (err != 0) {
2799 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2800 kPriorityFastMixer, getpid_cached, tid, err);
2801 }
2802#endif
2803
2804 } else {
2805 mFastMixer = NULL;
2806 }
2807
2808 switch (kUseFastMixer) {
2809 case FastMixer_Never:
2810 case FastMixer_Dynamic:
2811 mNormalSink = mOutputSink;
2812 break;
2813 case FastMixer_Always:
2814 mNormalSink = mPipeSink;
2815 break;
2816 case FastMixer_Static:
2817 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2818 break;
2819 }
2820}
2821
2822AudioFlinger::MixerThread::~MixerThread()
2823{
2824 if (mFastMixer != NULL) {
2825 FastMixerStateQueue *sq = mFastMixer->sq();
2826 FastMixerState *state = sq->begin();
2827 if (state->mCommand == FastMixerState::COLD_IDLE) {
2828 int32_t old = android_atomic_inc(&mFastMixerFutex);
2829 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002830 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002831 }
2832 }
2833 state->mCommand = FastMixerState::EXIT;
2834 sq->end();
2835 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2836 mFastMixer->join();
2837 // Though the fast mixer thread has exited, it's state queue is still valid.
2838 // We'll use that extract the final state which contains one remaining fast track
2839 // corresponding to our sub-mix.
2840 state = sq->begin();
2841 ALOG_ASSERT(state->mTrackMask == 1);
2842 FastTrack *fastTrack = &state->mFastTracks[0];
2843 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2844 delete fastTrack->mBufferProvider;
2845 sq->end(false /*didModify*/);
2846 delete mFastMixer;
2847#ifdef AUDIO_WATCHDOG
2848 if (mAudioWatchdog != 0) {
2849 mAudioWatchdog->requestExit();
2850 mAudioWatchdog->requestExitAndWait();
2851 mAudioWatchdog.clear();
2852 }
2853#endif
2854 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002855 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002856 delete mAudioMixer;
2857}
2858
2859
2860uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2861{
2862 if (mFastMixer != NULL) {
2863 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2864 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2865 }
2866 return latency;
2867}
2868
2869
2870void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2871{
2872 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2873}
2874
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002876{
2877 // FIXME we should only do one push per cycle; confirm this is true
2878 // Start the fast mixer if it's not already running
2879 if (mFastMixer != NULL) {
2880 FastMixerStateQueue *sq = mFastMixer->sq();
2881 FastMixerState *state = sq->begin();
2882 if (state->mCommand != FastMixerState::MIX_WRITE &&
2883 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2884 if (state->mCommand == FastMixerState::COLD_IDLE) {
2885 int32_t old = android_atomic_inc(&mFastMixerFutex);
2886 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002887 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002888 }
2889#ifdef AUDIO_WATCHDOG
2890 if (mAudioWatchdog != 0) {
2891 mAudioWatchdog->resume();
2892 }
2893#endif
2894 }
2895 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002896 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2897 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002898 sq->end();
2899 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2900 if (kUseFastMixer == FastMixer_Dynamic) {
2901 mNormalSink = mPipeSink;
2902 }
2903 } else {
2904 sq->end(false /*didModify*/);
2905 }
2906 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002908}
2909
2910void AudioFlinger::MixerThread::threadLoop_standby()
2911{
2912 // Idle the fast mixer if it's currently running
2913 if (mFastMixer != NULL) {
2914 FastMixerStateQueue *sq = mFastMixer->sq();
2915 FastMixerState *state = sq->begin();
2916 if (!(state->mCommand & FastMixerState::IDLE)) {
2917 state->mCommand = FastMixerState::COLD_IDLE;
2918 state->mColdFutexAddr = &mFastMixerFutex;
2919 state->mColdGen++;
2920 mFastMixerFutex = 0;
2921 sq->end();
2922 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2923 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2924 if (kUseFastMixer == FastMixer_Dynamic) {
2925 mNormalSink = mOutputSink;
2926 }
2927#ifdef AUDIO_WATCHDOG
2928 if (mAudioWatchdog != 0) {
2929 mAudioWatchdog->pause();
2930 }
2931#endif
2932 } else {
2933 sq->end(false /*didModify*/);
2934 }
2935 }
2936 PlaybackThread::threadLoop_standby();
2937}
2938
Eric Laurentbfb1b832013-01-07 09:53:42 -08002939bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2940{
2941 return false;
2942}
2943
2944bool AudioFlinger::PlaybackThread::shouldStandby_l()
2945{
2946 return !mStandby;
2947}
2948
2949bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2950{
2951 Mutex::Autolock _l(mLock);
2952 return waitingAsyncCallback_l();
2953}
2954
Eric Laurent81784c32012-11-19 14:55:58 -08002955// shared by MIXER and DIRECT, overridden by DUPLICATING
2956void AudioFlinger::PlaybackThread::threadLoop_standby()
2957{
2958 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2959 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002961 // discard any pending drain or write ack by incrementing sequence
2962 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2963 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002964 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002965 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2966 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002967 }
Eric Laurent81784c32012-11-19 14:55:58 -08002968}
2969
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002970void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2971{
2972 ALOGV("signal playback thread");
2973 broadcast_l();
2974}
2975
Eric Laurent81784c32012-11-19 14:55:58 -08002976void AudioFlinger::MixerThread::threadLoop_mix()
2977{
2978 // obtain the presentation timestamp of the next output buffer
2979 int64_t pts;
2980 status_t status = INVALID_OPERATION;
2981
2982 if (mNormalSink != 0) {
2983 status = mNormalSink->getNextWriteTimestamp(&pts);
2984 } else {
2985 status = mOutputSink->getNextWriteTimestamp(&pts);
2986 }
2987
2988 if (status != NO_ERROR) {
2989 pts = AudioBufferProvider::kInvalidPTS;
2990 }
2991
2992 // mix buffers...
2993 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002994 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002995 // increase sleep time progressively when application underrun condition clears.
2996 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2997 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2998 // such that we would underrun the audio HAL.
2999 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3000 sleepTimeShift--;
3001 }
3002 sleepTime = 0;
3003 standbyTime = systemTime() + standbyDelay;
3004 //TODO: delay standby when effects have a tail
3005}
3006
3007void AudioFlinger::MixerThread::threadLoop_sleepTime()
3008{
3009 // If no tracks are ready, sleep once for the duration of an output
3010 // buffer size, then write 0s to the output
3011 if (sleepTime == 0) {
3012 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3013 sleepTime = activeSleepTime >> sleepTimeShift;
3014 if (sleepTime < kMinThreadSleepTimeUs) {
3015 sleepTime = kMinThreadSleepTimeUs;
3016 }
3017 // reduce sleep time in case of consecutive application underruns to avoid
3018 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3019 // duration we would end up writing less data than needed by the audio HAL if
3020 // the condition persists.
3021 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3022 sleepTimeShift++;
3023 }
3024 } else {
3025 sleepTime = idleSleepTime;
3026 }
3027 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003028 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3029 // before effects processing or output.
3030 if (mMixerBufferValid) {
3031 memset(mMixerBuffer, 0, mMixerBufferSize);
3032 } else {
3033 memset(mSinkBuffer, 0, mSinkBufferSize);
3034 }
Eric Laurent81784c32012-11-19 14:55:58 -08003035 sleepTime = 0;
3036 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3037 "anticipated start");
3038 }
3039 // TODO add standby time extension fct of effect tail
3040}
3041
3042// prepareTracks_l() must be called with ThreadBase::mLock held
3043AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3044 Vector< sp<Track> > *tracksToRemove)
3045{
3046
3047 mixer_state mixerStatus = MIXER_IDLE;
3048 // find out which tracks need to be processed
3049 size_t count = mActiveTracks.size();
3050 size_t mixedTracks = 0;
3051 size_t tracksWithEffect = 0;
3052 // counts only _active_ fast tracks
3053 size_t fastTracks = 0;
3054 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3055
3056 float masterVolume = mMasterVolume;
3057 bool masterMute = mMasterMute;
3058
3059 if (masterMute) {
3060 masterVolume = 0;
3061 }
3062 // Delegate master volume control to effect in output mix effect chain if needed
3063 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3064 if (chain != 0) {
3065 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3066 chain->setVolume_l(&v, &v);
3067 masterVolume = (float)((v + (1 << 23)) >> 24);
3068 chain.clear();
3069 }
3070
3071 // prepare a new state to push
3072 FastMixerStateQueue *sq = NULL;
3073 FastMixerState *state = NULL;
3074 bool didModify = false;
3075 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3076 if (mFastMixer != NULL) {
3077 sq = mFastMixer->sq();
3078 state = sq->begin();
3079 }
3080
Andy Hung69aed5f2014-02-25 17:24:40 -08003081 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003082 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003083
Eric Laurent81784c32012-11-19 14:55:58 -08003084 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003085 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003086 if (t == 0) {
3087 continue;
3088 }
3089
3090 // this const just means the local variable doesn't change
3091 Track* const track = t.get();
3092
3093 // process fast tracks
3094 if (track->isFastTrack()) {
3095
3096 // It's theoretically possible (though unlikely) for a fast track to be created
3097 // and then removed within the same normal mix cycle. This is not a problem, as
3098 // the track never becomes active so it's fast mixer slot is never touched.
3099 // The converse, of removing an (active) track and then creating a new track
3100 // at the identical fast mixer slot within the same normal mix cycle,
3101 // is impossible because the slot isn't marked available until the end of each cycle.
3102 int j = track->mFastIndex;
3103 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3104 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3105 FastTrack *fastTrack = &state->mFastTracks[j];
3106
3107 // Determine whether the track is currently in underrun condition,
3108 // and whether it had a recent underrun.
3109 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3110 FastTrackUnderruns underruns = ftDump->mUnderruns;
3111 uint32_t recentFull = (underruns.mBitFields.mFull -
3112 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3113 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3114 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3115 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3116 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3117 uint32_t recentUnderruns = recentPartial + recentEmpty;
3118 track->mObservedUnderruns = underruns;
3119 // don't count underruns that occur while stopping or pausing
3120 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003121 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3122 recentUnderruns > 0) {
3123 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3124 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003125 }
3126
3127 // This is similar to the state machine for normal tracks,
3128 // with a few modifications for fast tracks.
3129 bool isActive = true;
3130 switch (track->mState) {
3131 case TrackBase::STOPPING_1:
3132 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003134 track->mState = TrackBase::STOPPING_2;
3135 }
3136 break;
3137 case TrackBase::PAUSING:
3138 // ramp down is not yet implemented
3139 track->setPaused();
3140 break;
3141 case TrackBase::RESUMING:
3142 // ramp up is not yet implemented
3143 track->mState = TrackBase::ACTIVE;
3144 break;
3145 case TrackBase::ACTIVE:
3146 if (recentFull > 0 || recentPartial > 0) {
3147 // track has provided at least some frames recently: reset retry count
3148 track->mRetryCount = kMaxTrackRetries;
3149 }
3150 if (recentUnderruns == 0) {
3151 // no recent underruns: stay active
3152 break;
3153 }
3154 // there has recently been an underrun of some kind
3155 if (track->sharedBuffer() == 0) {
3156 // were any of the recent underruns "empty" (no frames available)?
3157 if (recentEmpty == 0) {
3158 // no, then ignore the partial underruns as they are allowed indefinitely
3159 break;
3160 }
3161 // there has recently been an "empty" underrun: decrement the retry counter
3162 if (--(track->mRetryCount) > 0) {
3163 break;
3164 }
3165 // indicate to client process that the track was disabled because of underrun;
3166 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003167 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003168 // remove from active list, but state remains ACTIVE [confusing but true]
3169 isActive = false;
3170 break;
3171 }
3172 // fall through
3173 case TrackBase::STOPPING_2:
3174 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003175 case TrackBase::STOPPED:
3176 case TrackBase::FLUSHED: // flush() while active
3177 // Check for presentation complete if track is inactive
3178 // We have consumed all the buffers of this track.
3179 // This would be incomplete if we auto-paused on underrun
3180 {
3181 size_t audioHALFrames =
3182 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3183 size_t framesWritten = mBytesWritten / mFrameSize;
3184 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3185 // track stays in active list until presentation is complete
3186 break;
3187 }
3188 }
3189 if (track->isStopping_2()) {
3190 track->mState = TrackBase::STOPPED;
3191 }
3192 if (track->isStopped()) {
3193 // Can't reset directly, as fast mixer is still polling this track
3194 // track->reset();
3195 // So instead mark this track as needing to be reset after push with ack
3196 resetMask |= 1 << i;
3197 }
3198 isActive = false;
3199 break;
3200 case TrackBase::IDLE:
3201 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003202 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003203 }
3204
3205 if (isActive) {
3206 // was it previously inactive?
3207 if (!(state->mTrackMask & (1 << j))) {
3208 ExtendedAudioBufferProvider *eabp = track;
3209 VolumeProvider *vp = track;
3210 fastTrack->mBufferProvider = eabp;
3211 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003212 fastTrack->mChannelMask = track->mChannelMask;
3213 fastTrack->mGeneration++;
3214 state->mTrackMask |= 1 << j;
3215 didModify = true;
3216 // no acknowledgement required for newly active tracks
3217 }
3218 // cache the combined master volume and stream type volume for fast mixer; this
3219 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003220 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003221 ++fastTracks;
3222 } else {
3223 // was it previously active?
3224 if (state->mTrackMask & (1 << j)) {
3225 fastTrack->mBufferProvider = NULL;
3226 fastTrack->mGeneration++;
3227 state->mTrackMask &= ~(1 << j);
3228 didModify = true;
3229 // If any fast tracks were removed, we must wait for acknowledgement
3230 // because we're about to decrement the last sp<> on those tracks.
3231 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3232 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003233 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003234 }
3235 tracksToRemove->add(track);
3236 // Avoids a misleading display in dumpsys
3237 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3238 }
3239 continue;
3240 }
3241
3242 { // local variable scope to avoid goto warning
3243
3244 audio_track_cblk_t* cblk = track->cblk();
3245
3246 // The first time a track is added we wait
3247 // for all its buffers to be filled before processing it
3248 int name = track->name();
3249 // make sure that we have enough frames to mix one full buffer.
3250 // enforce this condition only once to enable draining the buffer in case the client
3251 // app does not call stop() and relies on underrun to stop:
3252 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3253 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003254 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003255 uint32_t sr = track->sampleRate();
3256 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003257 desiredFrames = mNormalFrameCount;
3258 } else {
3259 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003260 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003261 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003262 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003263 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003264#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003265 // the minimum track buffer size is normally twice the number of frames necessary
3266 // to fill one buffer and the resampler should not leave more than one buffer worth
3267 // of unreleased frames after each pass, but just in case...
3268 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003269#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003270 }
Eric Laurent81784c32012-11-19 14:55:58 -08003271 uint32_t minFrames = 1;
3272 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3273 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003274 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003275 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003276
3277 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003278 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003279 !track->isPaused() && !track->isTerminated())
3280 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003281 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003282
3283 mixedTracks++;
3284
Andy Hung69aed5f2014-02-25 17:24:40 -08003285 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3286 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003287 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003288 if (track->mainBuffer() != mSinkBuffer &&
3289 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003290 if (mEffectBufferEnabled) {
3291 mEffectBufferValid = true; // Later can set directly.
3292 }
Eric Laurent81784c32012-11-19 14:55:58 -08003293 chain = getEffectChain_l(track->sessionId());
3294 // Delegate volume control to effect in track effect chain if needed
3295 if (chain != 0) {
3296 tracksWithEffect++;
3297 } else {
3298 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3299 "session %d",
3300 name, track->sessionId());
3301 }
3302 }
3303
3304
3305 int param = AudioMixer::VOLUME;
3306 if (track->mFillingUpStatus == Track::FS_FILLED) {
3307 // no ramp for the first volume setting
3308 track->mFillingUpStatus = Track::FS_ACTIVE;
3309 if (track->mState == TrackBase::RESUMING) {
3310 track->mState = TrackBase::ACTIVE;
3311 param = AudioMixer::RAMP_VOLUME;
3312 }
3313 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003314 // FIXME should not make a decision based on mServer
3315 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003316 // If the track is stopped before the first frame was mixed,
3317 // do not apply ramp
3318 param = AudioMixer::RAMP_VOLUME;
3319 }
3320
3321 // compute volume for this track
3322 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003323 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003324 vl = vr = va = 0;
3325 if (track->isPausing()) {
3326 track->setPaused();
3327 }
3328 } else {
3329
3330 // read original volumes with volume control
3331 float typeVolume = mStreamTypes[track->streamType()].volume;
3332 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003333 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003334 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3335 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3336 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003337 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003338 if (vlf > GAIN_FLOAT_UNITY) {
3339 ALOGV("Track left volume out of range: %.3g", vlf);
3340 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003341 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003342 if (vrf > GAIN_FLOAT_UNITY) {
3343 ALOGV("Track right volume out of range: %.3g", vrf);
3344 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003345 }
3346 // now apply the master volume and stream type volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07003347 // FIXME we're losing the wonderful dynamic range in the minifloat representation
3348 float v8_24 = v * (MAX_GAIN_INT * MAX_GAIN_INT);
3349 vl = (uint32_t) (v8_24 * vlf);
3350 vr = (uint32_t) (v8_24 * vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08003351 // assuming master volume and stream type volume each go up to 1.0,
3352 // vl and vr are now in 8.24 format
3353
Glenn Kastene3aa6592012-12-04 12:22:46 -08003354 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003355 // send level comes from shared memory and so may be corrupt
3356 if (sendLevel > MAX_GAIN_INT) {
3357 ALOGV("Track send level out of range: %04X", sendLevel);
3358 sendLevel = MAX_GAIN_INT;
3359 }
3360 va = (uint32_t)(v * sendLevel);
3361 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003362
Eric Laurent81784c32012-11-19 14:55:58 -08003363 // Delegate volume control to effect in track effect chain if needed
3364 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3365 // Do not ramp volume if volume is controlled by effect
3366 param = AudioMixer::VOLUME;
3367 track->mHasVolumeController = true;
3368 } else {
3369 // force no volume ramp when volume controller was just disabled or removed
3370 // from effect chain to avoid volume spike
3371 if (track->mHasVolumeController) {
3372 param = AudioMixer::VOLUME;
3373 }
3374 track->mHasVolumeController = false;
3375 }
3376
Glenn Kastenc56f3422014-03-21 17:53:17 -07003377 // FIXME Use float
Eric Laurent81784c32012-11-19 14:55:58 -08003378 // Convert volumes from 8.24 to 4.12 format
3379 // This additional clamping is needed in case chain->setVolume_l() overshot
3380 vl = (vl + (1 << 11)) >> 12;
3381 if (vl > MAX_GAIN_INT) {
3382 vl = MAX_GAIN_INT;
3383 }
3384 vr = (vr + (1 << 11)) >> 12;
3385 if (vr > MAX_GAIN_INT) {
3386 vr = MAX_GAIN_INT;
3387 }
3388
3389 if (va > MAX_GAIN_INT) {
3390 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3391 }
3392
3393 // XXX: these things DON'T need to be done each time
3394 mAudioMixer->setBufferProvider(name, track);
3395 mAudioMixer->enable(name);
3396
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003397 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3398 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3399 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003400 mAudioMixer->setParameter(
3401 name,
3402 AudioMixer::TRACK,
3403 AudioMixer::FORMAT, (void *)track->format());
3404 mAudioMixer->setParameter(
3405 name,
3406 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003407 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003408 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3409 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003410 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003411 if (reqSampleRate == 0) {
3412 reqSampleRate = mSampleRate;
3413 } else if (reqSampleRate > maxSampleRate) {
3414 reqSampleRate = maxSampleRate;
3415 }
Eric Laurent81784c32012-11-19 14:55:58 -08003416 mAudioMixer->setParameter(
3417 name,
3418 AudioMixer::RESAMPLE,
3419 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003420 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003421 /*
3422 * Select the appropriate output buffer for the track.
3423 *
Andy Hung98ef9782014-03-04 14:46:50 -08003424 * Tracks with effects go into their own effects chain buffer
3425 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003426 *
3427 * Other tracks can use mMixerBuffer for higher precision
3428 * channel accumulation. If this buffer is enabled
3429 * (mMixerBufferEnabled true), then selected tracks will accumulate
3430 * into it.
3431 *
3432 */
3433 if (mMixerBufferEnabled
3434 && (track->mainBuffer() == mSinkBuffer
3435 || track->mainBuffer() == mMixerBuffer)) {
3436 mAudioMixer->setParameter(
3437 name,
3438 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003439 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003440 mAudioMixer->setParameter(
3441 name,
3442 AudioMixer::TRACK,
3443 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3444 // TODO: override track->mainBuffer()?
3445 mMixerBufferValid = true;
3446 } else {
3447 mAudioMixer->setParameter(
3448 name,
3449 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003450 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003451 mAudioMixer->setParameter(
3452 name,
3453 AudioMixer::TRACK,
3454 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3455 }
Eric Laurent81784c32012-11-19 14:55:58 -08003456 mAudioMixer->setParameter(
3457 name,
3458 AudioMixer::TRACK,
3459 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3460
3461 // reset retry count
3462 track->mRetryCount = kMaxTrackRetries;
3463
3464 // If one track is ready, set the mixer ready if:
3465 // - the mixer was not ready during previous round OR
3466 // - no other track is not ready
3467 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3468 mixerStatus != MIXER_TRACKS_ENABLED) {
3469 mixerStatus = MIXER_TRACKS_READY;
3470 }
3471 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003472 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003473 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003474 }
Eric Laurent81784c32012-11-19 14:55:58 -08003475 // clear effect chain input buffer if an active track underruns to avoid sending
3476 // previous audio buffer again to effects
3477 chain = getEffectChain_l(track->sessionId());
3478 if (chain != 0) {
3479 chain->clearInputBuffer();
3480 }
3481
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003482 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3484 track->isStopped() || track->isPaused()) {
3485 // We have consumed all the buffers of this track.
3486 // Remove it from the list of active tracks.
3487 // TODO: use actual buffer filling status instead of latency when available from
3488 // audio HAL
3489 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3490 size_t framesWritten = mBytesWritten / mFrameSize;
3491 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3492 if (track->isStopped()) {
3493 track->reset();
3494 }
3495 tracksToRemove->add(track);
3496 }
3497 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003498 // No buffers for this track. Give it a few chances to
3499 // fill a buffer, then remove it from active list.
3500 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003501 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003502 tracksToRemove->add(track);
3503 // indicate to client process that the track was disabled because of underrun;
3504 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003505 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003506 // If one track is not ready, mark the mixer also not ready if:
3507 // - the mixer was ready during previous round OR
3508 // - no other track is ready
3509 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3510 mixerStatus != MIXER_TRACKS_READY) {
3511 mixerStatus = MIXER_TRACKS_ENABLED;
3512 }
3513 }
3514 mAudioMixer->disable(name);
3515 }
3516
3517 } // local variable scope to avoid goto warning
3518track_is_ready: ;
3519
3520 }
3521
3522 // Push the new FastMixer state if necessary
3523 bool pauseAudioWatchdog = false;
3524 if (didModify) {
3525 state->mFastTracksGen++;
3526 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3527 if (kUseFastMixer == FastMixer_Dynamic &&
3528 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3529 state->mCommand = FastMixerState::COLD_IDLE;
3530 state->mColdFutexAddr = &mFastMixerFutex;
3531 state->mColdGen++;
3532 mFastMixerFutex = 0;
3533 if (kUseFastMixer == FastMixer_Dynamic) {
3534 mNormalSink = mOutputSink;
3535 }
3536 // If we go into cold idle, need to wait for acknowledgement
3537 // so that fast mixer stops doing I/O.
3538 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3539 pauseAudioWatchdog = true;
3540 }
Eric Laurent81784c32012-11-19 14:55:58 -08003541 }
3542 if (sq != NULL) {
3543 sq->end(didModify);
3544 sq->push(block);
3545 }
3546#ifdef AUDIO_WATCHDOG
3547 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3548 mAudioWatchdog->pause();
3549 }
3550#endif
3551
3552 // Now perform the deferred reset on fast tracks that have stopped
3553 while (resetMask != 0) {
3554 size_t i = __builtin_ctz(resetMask);
3555 ALOG_ASSERT(i < count);
3556 resetMask &= ~(1 << i);
3557 sp<Track> t = mActiveTracks[i].promote();
3558 if (t == 0) {
3559 continue;
3560 }
3561 Track* track = t.get();
3562 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3563 track->reset();
3564 }
3565
3566 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003567 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003568
Andy Hung69aed5f2014-02-25 17:24:40 -08003569 // sink or mix buffer must be cleared if all tracks are connected to an
3570 // effect chain as in this case the mixer will not write to the sink or mix buffer
3571 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003572 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3573 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003574 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003575 if (mMixerBufferValid) {
3576 memset(mMixerBuffer, 0, mMixerBufferSize);
3577 // TODO: In testing, mSinkBuffer below need not be cleared because
3578 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3579 // after mixing.
3580 //
3581 // To enforce this guarantee:
3582 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3583 // (mixedTracks == 0 && fastTracks > 0))
3584 // must imply MIXER_TRACKS_READY.
3585 // Later, we may clear buffers regardless, and skip much of this logic.
3586 }
Andy Hung98ef9782014-03-04 14:46:50 -08003587 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3588 if (mEffectBufferValid) {
3589 memset(mEffectBuffer, 0, mEffectBufferSize);
3590 }
3591 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003592 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003593 }
3594
3595 // if any fast tracks, then status is ready
3596 mMixerStatusIgnoringFastTracks = mixerStatus;
3597 if (fastTracks > 0) {
3598 mixerStatus = MIXER_TRACKS_READY;
3599 }
3600 return mixerStatus;
3601}
3602
3603// getTrackName_l() must be called with ThreadBase::mLock held
3604int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3605{
3606 return mAudioMixer->getTrackName(channelMask, sessionId);
3607}
3608
3609// deleteTrackName_l() must be called with ThreadBase::mLock held
3610void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3611{
3612 ALOGV("remove track (%d) and delete from mixer", name);
3613 mAudioMixer->deleteTrackName(name);
3614}
3615
Eric Laurent10351942014-05-08 18:49:52 -07003616// checkForNewParameter_l() must be called with ThreadBase::mLock held
3617bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3618 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003619{
Eric Laurent81784c32012-11-19 14:55:58 -08003620 bool reconfig = false;
3621
Eric Laurent10351942014-05-08 18:49:52 -07003622 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003623
Eric Laurent10351942014-05-08 18:49:52 -07003624 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3625 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3626 if (mFastMixer != NULL) {
3627 FastMixerStateQueue *sq = mFastMixer->sq();
3628 FastMixerState *state = sq->begin();
3629 if (!(state->mCommand & FastMixerState::IDLE)) {
3630 previousCommand = state->mCommand;
3631 state->mCommand = FastMixerState::HOT_IDLE;
3632 sq->end();
3633 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3634 } else {
3635 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003636 }
Eric Laurent10351942014-05-08 18:49:52 -07003637 }
Eric Laurent81784c32012-11-19 14:55:58 -08003638
Eric Laurent10351942014-05-08 18:49:52 -07003639 AudioParameter param = AudioParameter(keyValuePair);
3640 int value;
3641 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3642 reconfig = true;
3643 }
3644 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3645 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3646 status = BAD_VALUE;
3647 } else {
3648 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003649 reconfig = true;
3650 }
Eric Laurent10351942014-05-08 18:49:52 -07003651 }
3652 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3653 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3654 status = BAD_VALUE;
3655 } else {
3656 // no need to save value, since it's constant
3657 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003658 }
Eric Laurent10351942014-05-08 18:49:52 -07003659 }
3660 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3661 // do not accept frame count changes if tracks are open as the track buffer
3662 // size depends on frame count and correct behavior would not be guaranteed
3663 // if frame count is changed after track creation
3664 if (!mTracks.isEmpty()) {
3665 status = INVALID_OPERATION;
3666 } else {
3667 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003668 }
Eric Laurent10351942014-05-08 18:49:52 -07003669 }
3670 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003671#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003672 // when changing the audio output device, call addBatteryData to notify
3673 // the change
3674 if (mOutDevice != value) {
3675 uint32_t params = 0;
3676 // check whether speaker is on
3677 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3678 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003679 }
Eric Laurent10351942014-05-08 18:49:52 -07003680
3681 audio_devices_t deviceWithoutSpeaker
3682 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3683 // check if any other device (except speaker) is on
3684 if (value & deviceWithoutSpeaker ) {
3685 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3686 }
3687
3688 if (params != 0) {
3689 addBatteryData(params);
3690 }
3691 }
Eric Laurent81784c32012-11-19 14:55:58 -08003692#endif
3693
Eric Laurent10351942014-05-08 18:49:52 -07003694 // forward device change to effects that have requested to be
3695 // aware of attached audio device.
3696 if (value != AUDIO_DEVICE_NONE) {
3697 mOutDevice = value;
3698 for (size_t i = 0; i < mEffectChains.size(); i++) {
3699 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003700 }
3701 }
Eric Laurent10351942014-05-08 18:49:52 -07003702 }
Eric Laurent81784c32012-11-19 14:55:58 -08003703
Eric Laurent10351942014-05-08 18:49:52 -07003704 if (status == NO_ERROR) {
3705 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3706 keyValuePair.string());
3707 if (!mStandby && status == INVALID_OPERATION) {
3708 mOutput->stream->common.standby(&mOutput->stream->common);
3709 mStandby = true;
3710 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003711 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003712 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003713 }
Eric Laurent10351942014-05-08 18:49:52 -07003714 if (status == NO_ERROR && reconfig) {
3715 readOutputParameters_l();
3716 delete mAudioMixer;
3717 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3718 for (size_t i = 0; i < mTracks.size() ; i++) {
3719 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3720 if (name < 0) {
3721 break;
3722 }
3723 mTracks[i]->mName = name;
3724 }
3725 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3726 }
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
3728
3729 if (!(previousCommand & FastMixerState::IDLE)) {
3730 ALOG_ASSERT(mFastMixer != NULL);
3731 FastMixerStateQueue *sq = mFastMixer->sq();
3732 FastMixerState *state = sq->begin();
3733 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3734 state->mCommand = previousCommand;
3735 sq->end();
3736 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3737 }
3738
3739 return reconfig;
3740}
3741
3742
3743void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3744{
3745 const size_t SIZE = 256;
3746 char buffer[SIZE];
3747 String8 result;
3748
3749 PlaybackThread::dumpInternals(fd, args);
3750
Marco Nelissenb2208842014-02-07 14:00:50 -08003751 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003752
3753 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003754 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003755 copy.dump(fd);
3756
3757#ifdef STATE_QUEUE_DUMP
3758 // Similar for state queue
3759 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3760 observerCopy.dump(fd);
3761 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3762 mutatorCopy.dump(fd);
3763#endif
3764
Glenn Kasten46909e72013-02-26 09:20:22 -08003765#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003766 // Write the tee output to a .wav file
3767 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003768#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003769
3770#ifdef AUDIO_WATCHDOG
3771 if (mAudioWatchdog != 0) {
3772 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3773 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3774 wdCopy.dump(fd);
3775 }
3776#endif
3777}
3778
3779uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3780{
3781 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3782}
3783
3784uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3785{
3786 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3787}
3788
3789void AudioFlinger::MixerThread::cacheParameters_l()
3790{
3791 PlaybackThread::cacheParameters_l();
3792
3793 // FIXME: Relaxed timing because of a certain device that can't meet latency
3794 // Should be reduced to 2x after the vendor fixes the driver issue
3795 // increase threshold again due to low power audio mode. The way this warning
3796 // threshold is calculated and its usefulness should be reconsidered anyway.
3797 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3798}
3799
3800// ----------------------------------------------------------------------------
3801
3802AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3803 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3804 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3805 // mLeftVolFloat, mRightVolFloat
3806{
3807}
3808
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3810 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3811 ThreadBase::type_t type)
3812 : PlaybackThread(audioFlinger, output, id, device, type)
3813 // mLeftVolFloat, mRightVolFloat
3814{
3815}
3816
Eric Laurent81784c32012-11-19 14:55:58 -08003817AudioFlinger::DirectOutputThread::~DirectOutputThread()
3818{
3819}
3820
Eric Laurentbfb1b832013-01-07 09:53:42 -08003821void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3822{
3823 audio_track_cblk_t* cblk = track->cblk();
3824 float left, right;
3825
3826 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3827 left = right = 0;
3828 } else {
3829 float typeVolume = mStreamTypes[track->streamType()].volume;
3830 float v = mMasterVolume * typeVolume;
3831 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003832 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3833 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3834 if (left > GAIN_FLOAT_UNITY) {
3835 left = GAIN_FLOAT_UNITY;
3836 }
3837 left *= v;
3838 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3839 if (right > GAIN_FLOAT_UNITY) {
3840 right = GAIN_FLOAT_UNITY;
3841 }
3842 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003843 }
3844
3845 if (lastTrack) {
3846 if (left != mLeftVolFloat || right != mRightVolFloat) {
3847 mLeftVolFloat = left;
3848 mRightVolFloat = right;
3849
3850 // Convert volumes from float to 8.24
3851 uint32_t vl = (uint32_t)(left * (1 << 24));
3852 uint32_t vr = (uint32_t)(right * (1 << 24));
3853
3854 // Delegate volume control to effect in track effect chain if needed
3855 // only one effect chain can be present on DirectOutputThread, so if
3856 // there is one, the track is connected to it
3857 if (!mEffectChains.isEmpty()) {
3858 mEffectChains[0]->setVolume_l(&vl, &vr);
3859 left = (float)vl / (1 << 24);
3860 right = (float)vr / (1 << 24);
3861 }
3862 if (mOutput->stream->set_volume) {
3863 mOutput->stream->set_volume(mOutput->stream, left, right);
3864 }
3865 }
3866 }
3867}
3868
3869
Eric Laurent81784c32012-11-19 14:55:58 -08003870AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3871 Vector< sp<Track> > *tracksToRemove
3872)
3873{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003874 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003875 mixer_state mixerStatus = MIXER_IDLE;
3876
3877 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003878 for (size_t i = 0; i < count; i++) {
3879 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003880 // The track died recently
3881 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003882 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003883 }
3884
3885 Track* const track = t.get();
3886 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003887 // Only consider last track started for volume and mixer state control.
3888 // In theory an older track could underrun and restart after the new one starts
3889 // but as we only care about the transition phase between two tracks on a
3890 // direct output, it is not a problem to ignore the underrun case.
3891 sp<Track> l = mLatestActiveTrack.promote();
3892 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003893
3894 // The first time a track is added we wait
3895 // for all its buffers to be filled before processing it
3896 uint32_t minFrames;
3897 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3898 minFrames = mNormalFrameCount;
3899 } else {
3900 minFrames = 1;
3901 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003902
Eric Laurent81784c32012-11-19 14:55:58 -08003903 if ((track->framesReady() >= minFrames) && track->isReady() &&
3904 !track->isPaused() && !track->isTerminated())
3905 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003906 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003907
3908 if (track->mFillingUpStatus == Track::FS_FILLED) {
3909 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003910 // make sure processVolume_l() will apply new volume even if 0
3911 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003912 if (track->mState == TrackBase::RESUMING) {
3913 track->mState = TrackBase::ACTIVE;
3914 }
3915 }
3916
3917 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 processVolume_l(track, last);
3919 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003920 // reset retry count
3921 track->mRetryCount = kMaxTrackRetriesDirect;
3922 mActiveTrack = t;
3923 mixerStatus = MIXER_TRACKS_READY;
3924 }
Eric Laurent81784c32012-11-19 14:55:58 -08003925 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003926 // clear effect chain input buffer if the last active track started underruns
3927 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003928 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003929 mEffectChains[0]->clearInputBuffer();
3930 }
3931
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003932 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003933 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3934 track->isStopped() || track->isPaused()) {
3935 // We have consumed all the buffers of this track.
3936 // Remove it from the list of active tracks.
3937 // TODO: implement behavior for compressed audio
3938 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3939 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003940 if (mStandby || !last ||
3941 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003942 if (track->isStopped()) {
3943 track->reset();
3944 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003945 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003946 }
3947 } else {
3948 // No buffers for this track. Give it a few chances to
3949 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003950 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003951 if (--(track->mRetryCount) <= 0) {
3952 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003953 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003954 // indicate to client process that the track was disabled because of underrun;
3955 // it will then automatically call start() when data is available
3956 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003958 mixerStatus = MIXER_TRACKS_ENABLED;
3959 }
3960 }
3961 }
3962 }
3963
Eric Laurent81784c32012-11-19 14:55:58 -08003964 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003966
3967 return mixerStatus;
3968}
3969
3970void AudioFlinger::DirectOutputThread::threadLoop_mix()
3971{
Eric Laurent81784c32012-11-19 14:55:58 -08003972 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003973 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003974 // output audio to hardware
3975 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003976 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003977 buffer.frameCount = frameCount;
3978 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003979 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003980 memset(curBuf, 0, frameCount * mFrameSize);
3981 break;
3982 }
3983 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3984 frameCount -= buffer.frameCount;
3985 curBuf += buffer.frameCount * mFrameSize;
3986 mActiveTrack->releaseBuffer(&buffer);
3987 }
Andy Hung2098f272014-02-27 14:00:06 -08003988 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003989 sleepTime = 0;
3990 standbyTime = systemTime() + standbyDelay;
3991 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003992}
3993
3994void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3995{
3996 if (sleepTime == 0) {
3997 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3998 sleepTime = activeSleepTime;
3999 } else {
4000 sleepTime = idleSleepTime;
4001 }
4002 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004003 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004004 sleepTime = 0;
4005 }
4006}
4007
4008// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004009int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
4010 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004011{
4012 return 0;
4013}
4014
4015// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004016void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004017{
4018}
4019
Eric Laurent10351942014-05-08 18:49:52 -07004020// checkForNewParameter_l() must be called with ThreadBase::mLock held
4021bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4022 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004023{
4024 bool reconfig = false;
4025
Eric Laurent10351942014-05-08 18:49:52 -07004026 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004027
Eric Laurent10351942014-05-08 18:49:52 -07004028 AudioParameter param = AudioParameter(keyValuePair);
4029 int value;
4030 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4031 // forward device change to effects that have requested to be
4032 // aware of attached audio device.
4033 if (value != AUDIO_DEVICE_NONE) {
4034 mOutDevice = value;
4035 for (size_t i = 0; i < mEffectChains.size(); i++) {
4036 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004037 }
4038 }
Eric Laurent81784c32012-11-19 14:55:58 -08004039 }
Eric Laurent10351942014-05-08 18:49:52 -07004040 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4041 // do not accept frame count changes if tracks are open as the track buffer
4042 // size depends on frame count and correct behavior would not be garantied
4043 // if frame count is changed after track creation
4044 if (!mTracks.isEmpty()) {
4045 status = INVALID_OPERATION;
4046 } else {
4047 reconfig = true;
4048 }
4049 }
4050 if (status == NO_ERROR) {
4051 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4052 keyValuePair.string());
4053 if (!mStandby && status == INVALID_OPERATION) {
4054 mOutput->stream->common.standby(&mOutput->stream->common);
4055 mStandby = true;
4056 mBytesWritten = 0;
4057 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4058 keyValuePair.string());
4059 }
4060 if (status == NO_ERROR && reconfig) {
4061 readOutputParameters_l();
4062 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4063 }
4064 }
4065
Eric Laurent81784c32012-11-19 14:55:58 -08004066 return reconfig;
4067}
4068
4069uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4070{
4071 uint32_t time;
4072 if (audio_is_linear_pcm(mFormat)) {
4073 time = PlaybackThread::activeSleepTimeUs();
4074 } else {
4075 time = 10000;
4076 }
4077 return time;
4078}
4079
4080uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4081{
4082 uint32_t time;
4083 if (audio_is_linear_pcm(mFormat)) {
4084 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4085 } else {
4086 time = 10000;
4087 }
4088 return time;
4089}
4090
4091uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4092{
4093 uint32_t time;
4094 if (audio_is_linear_pcm(mFormat)) {
4095 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4096 } else {
4097 time = 10000;
4098 }
4099 return time;
4100}
4101
4102void AudioFlinger::DirectOutputThread::cacheParameters_l()
4103{
4104 PlaybackThread::cacheParameters_l();
4105
4106 // use shorter standby delay as on normal output to release
4107 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004108 if (audio_is_linear_pcm(mFormat)) {
4109 standbyDelay = microseconds(activeSleepTime*2);
4110 } else {
4111 standbyDelay = kOffloadStandbyDelayNs;
4112 }
Eric Laurent81784c32012-11-19 14:55:58 -08004113}
4114
4115// ----------------------------------------------------------------------------
4116
Eric Laurentbfb1b832013-01-07 09:53:42 -08004117AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004118 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004119 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004120 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004121 mWriteAckSequence(0),
4122 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123{
4124}
4125
4126AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4127{
4128}
4129
4130void AudioFlinger::AsyncCallbackThread::onFirstRef()
4131{
4132 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4133}
4134
4135bool AudioFlinger::AsyncCallbackThread::threadLoop()
4136{
4137 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004138 uint32_t writeAckSequence;
4139 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004140
4141 {
4142 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004143 while (!((mWriteAckSequence & 1) ||
4144 (mDrainSequence & 1) ||
4145 exitPending())) {
4146 mWaitWorkCV.wait(mLock);
4147 }
4148
Eric Laurentbfb1b832013-01-07 09:53:42 -08004149 if (exitPending()) {
4150 break;
4151 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004152 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4153 mWriteAckSequence, mDrainSequence);
4154 writeAckSequence = mWriteAckSequence;
4155 mWriteAckSequence &= ~1;
4156 drainSequence = mDrainSequence;
4157 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004158 }
4159 {
Eric Laurent4de95592013-09-26 15:28:21 -07004160 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4161 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004162 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004163 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004164 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004165 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004166 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 }
4168 }
4169 }
4170 }
4171 return false;
4172}
4173
4174void AudioFlinger::AsyncCallbackThread::exit()
4175{
4176 ALOGV("AsyncCallbackThread::exit");
4177 Mutex::Autolock _l(mLock);
4178 requestExit();
4179 mWaitWorkCV.broadcast();
4180}
4181
Eric Laurent3b4529e2013-09-05 18:09:19 -07004182void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004183{
4184 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004185 // bit 0 is cleared
4186 mWriteAckSequence = sequence << 1;
4187}
4188
4189void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4190{
4191 Mutex::Autolock _l(mLock);
4192 // ignore unexpected callbacks
4193 if (mWriteAckSequence & 2) {
4194 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195 mWaitWorkCV.signal();
4196 }
4197}
4198
Eric Laurent3b4529e2013-09-05 18:09:19 -07004199void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200{
4201 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004202 // bit 0 is cleared
4203 mDrainSequence = sequence << 1;
4204}
4205
4206void AudioFlinger::AsyncCallbackThread::resetDraining()
4207{
4208 Mutex::Autolock _l(mLock);
4209 // ignore unexpected callbacks
4210 if (mDrainSequence & 2) {
4211 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004212 mWaitWorkCV.signal();
4213 }
4214}
4215
4216
4217// ----------------------------------------------------------------------------
4218AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4219 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4220 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4221 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004222 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004223 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004224{
Eric Laurentfd477972013-10-25 18:10:40 -07004225 //FIXME: mStandby should be set to true by ThreadBase constructor
4226 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227}
4228
Eric Laurentbfb1b832013-01-07 09:53:42 -08004229void AudioFlinger::OffloadThread::threadLoop_exit()
4230{
4231 if (mFlushPending || mHwPaused) {
4232 // If a flush is pending or track was paused, just discard buffered data
4233 flushHw_l();
4234 } else {
4235 mMixerStatus = MIXER_DRAIN_ALL;
4236 threadLoop_drain();
4237 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004238 if (mUseAsyncWrite) {
4239 ALOG_ASSERT(mCallbackThread != 0);
4240 mCallbackThread->exit();
4241 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004242 PlaybackThread::threadLoop_exit();
4243}
4244
4245AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4246 Vector< sp<Track> > *tracksToRemove
4247)
4248{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249 size_t count = mActiveTracks.size();
4250
4251 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004252 bool doHwPause = false;
4253 bool doHwResume = false;
4254
Eric Laurentede6c3b2013-09-19 14:37:46 -07004255 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4256
Eric Laurentbfb1b832013-01-07 09:53:42 -08004257 // find out which tracks need to be processed
4258 for (size_t i = 0; i < count; i++) {
4259 sp<Track> t = mActiveTracks[i].promote();
4260 // The track died recently
4261 if (t == 0) {
4262 continue;
4263 }
4264 Track* const track = t.get();
4265 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004266 // Only consider last track started for volume and mixer state control.
4267 // In theory an older track could underrun and restart after the new one starts
4268 // but as we only care about the transition phase between two tracks on a
4269 // direct output, it is not a problem to ignore the underrun case.
4270 sp<Track> l = mLatestActiveTrack.promote();
4271 bool last = l.get() == track;
4272
Haynes Mathew George7844f672014-01-15 12:32:55 -08004273 if (track->isInvalid()) {
4274 ALOGW("An invalidated track shouldn't be in active list");
4275 tracksToRemove->add(track);
4276 continue;
4277 }
4278
4279 if (track->mState == TrackBase::IDLE) {
4280 ALOGW("An idle track shouldn't be in active list");
4281 continue;
4282 }
4283
Eric Laurentbfb1b832013-01-07 09:53:42 -08004284 if (track->isPausing()) {
4285 track->setPaused();
4286 if (last) {
4287 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004288 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004289 mHwPaused = true;
4290 }
4291 // If we were part way through writing the mixbuffer to
4292 // the HAL we must save this until we resume
4293 // BUG - this will be wrong if a different track is made active,
4294 // in that case we want to discard the pending data in the
4295 // mixbuffer and tell the client to present it again when the
4296 // track is resumed
4297 mPausedWriteLength = mCurrentWriteLength;
4298 mPausedBytesRemaining = mBytesRemaining;
4299 mBytesRemaining = 0; // stop writing
4300 }
4301 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004302 } else if (track->isFlushPending()) {
4303 track->flushAck();
4304 if (last) {
4305 mFlushPending = true;
4306 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004307 } else if (track->isResumePending()){
4308 track->resumeAck();
4309 if (last) {
4310 if (mPausedBytesRemaining) {
4311 // Need to continue write that was interrupted
4312 mCurrentWriteLength = mPausedWriteLength;
4313 mBytesRemaining = mPausedBytesRemaining;
4314 mPausedBytesRemaining = 0;
4315 }
4316 if (mHwPaused) {
4317 doHwResume = true;
4318 mHwPaused = false;
4319 // threadLoop_mix() will handle the case that we need to
4320 // resume an interrupted write
4321 }
4322 // enable write to audio HAL
4323 sleepTime = 0;
4324
4325 // Do not handle new data in this iteration even if track->framesReady()
4326 mixerStatus = MIXER_TRACKS_ENABLED;
4327 }
4328 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004329 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004330 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004331 if (track->mFillingUpStatus == Track::FS_FILLED) {
4332 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004333 // make sure processVolume_l() will apply new volume even if 0
4334 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004335 }
4336
4337 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004338 sp<Track> previousTrack = mPreviousTrack.promote();
4339 if (previousTrack != 0) {
4340 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004341 // Flush any data still being written from last track
4342 mBytesRemaining = 0;
4343 if (mPausedBytesRemaining) {
4344 // Last track was paused so we also need to flush saved
4345 // mixbuffer state and invalidate track so that it will
4346 // re-submit that unwritten data when it is next resumed
4347 mPausedBytesRemaining = 0;
4348 // Invalidate is a bit drastic - would be more efficient
4349 // to have a flag to tell client that some of the
4350 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004351 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004352 }
4353 // flush data already sent to the DSP if changing audio session as audio
4354 // comes from a different source. Also invalidate previous track to force a
4355 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004356 if (previousTrack->sessionId() != track->sessionId()) {
4357 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004358 }
4359 }
4360 }
4361 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004362 // reset retry count
4363 track->mRetryCount = kMaxTrackRetriesOffload;
4364 mActiveTrack = t;
4365 mixerStatus = MIXER_TRACKS_READY;
4366 }
4367 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004368 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004369 if (track->isStopping_1()) {
4370 // Hardware buffer can hold a large amount of audio so we must
4371 // wait for all current track's data to drain before we say
4372 // that the track is stopped.
4373 if (mBytesRemaining == 0) {
4374 // Only start draining when all data in mixbuffer
4375 // has been written
4376 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4377 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004378 // do not drain if no data was ever sent to HAL (mStandby == true)
4379 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004380 // do not modify drain sequence if we are already draining. This happens
4381 // when resuming from pause after drain.
4382 if ((mDrainSequence & 1) == 0) {
4383 sleepTime = 0;
4384 standbyTime = systemTime() + standbyDelay;
4385 mixerStatus = MIXER_DRAIN_TRACK;
4386 mDrainSequence += 2;
4387 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388 if (mHwPaused) {
4389 // It is possible to move from PAUSED to STOPPING_1 without
4390 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004391 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392 mHwPaused = false;
4393 }
4394 }
4395 }
4396 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004397 // Drain has completed or we are in standby, signal presentation complete
4398 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 track->mState = TrackBase::STOPPED;
4400 size_t audioHALFrames =
4401 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4402 size_t framesWritten =
4403 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4404 track->presentationComplete(framesWritten, audioHALFrames);
4405 track->reset();
4406 tracksToRemove->add(track);
4407 }
4408 } else {
4409 // No buffers for this track. Give it a few chances to
4410 // fill a buffer, then remove it from active list.
4411 if (--(track->mRetryCount) <= 0) {
4412 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4413 track->name());
4414 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004415 // indicate to client process that the track was disabled because of underrun;
4416 // it will then automatically call start() when data is available
4417 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004418 } else if (last){
4419 mixerStatus = MIXER_TRACKS_ENABLED;
4420 }
4421 }
4422 }
4423 // compute volume for this track
4424 processVolume_l(track, last);
4425 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004426
Eric Laurentea0fade2013-10-04 16:23:48 -07004427 // make sure the pause/flush/resume sequence is executed in the right order.
4428 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4429 // before flush and then resume HW. This can happen in case of pause/flush/resume
4430 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004431 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004432 mOutput->stream->pause(mOutput->stream);
4433 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004434 if (mFlushPending) {
4435 flushHw_l();
4436 mFlushPending = false;
4437 }
Eric Laurentfd477972013-10-25 18:10:40 -07004438 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004439 mOutput->stream->resume(mOutput->stream);
4440 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004441
Eric Laurentbfb1b832013-01-07 09:53:42 -08004442 // remove all the tracks that need to be...
4443 removeTracks_l(*tracksToRemove);
4444
4445 return mixerStatus;
4446}
4447
Eric Laurentbfb1b832013-01-07 09:53:42 -08004448// must be called with thread mutex locked
4449bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4450{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004451 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4452 mWriteAckSequence, mDrainSequence);
4453 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004454 return true;
4455 }
4456 return false;
4457}
4458
4459// must be called with thread mutex locked
4460bool AudioFlinger::OffloadThread::shouldStandby_l()
4461{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004462 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004463
4464 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4465 // after a timeout and we will enter standby then.
4466 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004467 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004468 }
4469
Glenn Kastene6f35b12013-08-19 09:58:50 -07004470 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471}
4472
4473
4474bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4475{
4476 Mutex::Autolock _l(mLock);
4477 return waitingAsyncCallback_l();
4478}
4479
4480void AudioFlinger::OffloadThread::flushHw_l()
4481{
4482 mOutput->stream->flush(mOutput->stream);
4483 // Flush anything still waiting in the mixbuffer
4484 mCurrentWriteLength = 0;
4485 mBytesRemaining = 0;
4486 mPausedWriteLength = 0;
4487 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004488 mHwPaused = false;
4489
Eric Laurentbfb1b832013-01-07 09:53:42 -08004490 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004491 // discard any pending drain or write ack by incrementing sequence
4492 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4493 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004495 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4496 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004497 }
4498}
4499
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004500void AudioFlinger::OffloadThread::onAddNewTrack_l()
4501{
4502 sp<Track> previousTrack = mPreviousTrack.promote();
4503 sp<Track> latestTrack = mLatestActiveTrack.promote();
4504
4505 if (previousTrack != 0 && latestTrack != 0 &&
4506 (previousTrack->sessionId() != latestTrack->sessionId())) {
4507 mFlushPending = true;
4508 }
4509 PlaybackThread::onAddNewTrack_l();
4510}
4511
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512// ----------------------------------------------------------------------------
4513
Eric Laurent81784c32012-11-19 14:55:58 -08004514AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4515 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4516 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4517 DUPLICATING),
4518 mWaitTimeMs(UINT_MAX)
4519{
4520 addOutputTrack(mainThread);
4521}
4522
4523AudioFlinger::DuplicatingThread::~DuplicatingThread()
4524{
4525 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4526 mOutputTracks[i]->destroy();
4527 }
4528}
4529
4530void AudioFlinger::DuplicatingThread::threadLoop_mix()
4531{
4532 // mix buffers...
4533 if (outputsReady(outputTracks)) {
4534 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4535 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004536 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004537 }
4538 sleepTime = 0;
4539 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004540 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004541 standbyTime = systemTime() + standbyDelay;
4542}
4543
4544void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4545{
4546 if (sleepTime == 0) {
4547 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4548 sleepTime = activeSleepTime;
4549 } else {
4550 sleepTime = idleSleepTime;
4551 }
4552 } else if (mBytesWritten != 0) {
4553 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4554 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004555 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004556 } else {
4557 // flush remaining overflow buffers in output tracks
4558 writeFrames = 0;
4559 }
4560 sleepTime = 0;
4561 }
4562}
4563
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004565{
4566 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004567 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4568 // for delivery downstream as needed. This in-place conversion is safe as
4569 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4570 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4571 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4572 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4573 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4574 }
4575 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004576 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004577 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004578 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004579}
4580
4581void AudioFlinger::DuplicatingThread::threadLoop_standby()
4582{
4583 // DuplicatingThread implements standby by stopping all tracks
4584 for (size_t i = 0; i < outputTracks.size(); i++) {
4585 outputTracks[i]->stop();
4586 }
4587}
4588
4589void AudioFlinger::DuplicatingThread::saveOutputTracks()
4590{
4591 outputTracks = mOutputTracks;
4592}
4593
4594void AudioFlinger::DuplicatingThread::clearOutputTracks()
4595{
4596 outputTracks.clear();
4597}
4598
4599void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4600{
4601 Mutex::Autolock _l(mLock);
4602 // FIXME explain this formula
4603 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004604 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4605 // due to current usage case and restrictions on the AudioBufferProvider.
4606 // Actual buffer conversion is done in threadLoop_write().
4607 //
4608 // TODO: This may change in the future, depending on multichannel
4609 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004610 OutputTrack *outputTrack = new OutputTrack(thread,
4611 this,
4612 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004613 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004614 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004615 frameCount,
4616 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004617 if (outputTrack->cblk() != NULL) {
4618 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4619 mOutputTracks.add(outputTrack);
4620 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4621 updateWaitTime_l();
4622 }
4623}
4624
4625void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4626{
4627 Mutex::Autolock _l(mLock);
4628 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4629 if (mOutputTracks[i]->thread() == thread) {
4630 mOutputTracks[i]->destroy();
4631 mOutputTracks.removeAt(i);
4632 updateWaitTime_l();
4633 return;
4634 }
4635 }
4636 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4637}
4638
4639// caller must hold mLock
4640void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4641{
4642 mWaitTimeMs = UINT_MAX;
4643 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4644 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4645 if (strong != 0) {
4646 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4647 if (waitTimeMs < mWaitTimeMs) {
4648 mWaitTimeMs = waitTimeMs;
4649 }
4650 }
4651 }
4652}
4653
4654
4655bool AudioFlinger::DuplicatingThread::outputsReady(
4656 const SortedVector< sp<OutputTrack> > &outputTracks)
4657{
4658 for (size_t i = 0; i < outputTracks.size(); i++) {
4659 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4660 if (thread == 0) {
4661 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4662 outputTracks[i].get());
4663 return false;
4664 }
4665 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4666 // see note at standby() declaration
4667 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4668 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4669 thread.get());
4670 return false;
4671 }
4672 }
4673 return true;
4674}
4675
4676uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4677{
4678 return (mWaitTimeMs * 1000) / 2;
4679}
4680
4681void AudioFlinger::DuplicatingThread::cacheParameters_l()
4682{
4683 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4684 updateWaitTime_l();
4685
4686 MixerThread::cacheParameters_l();
4687}
4688
4689// ----------------------------------------------------------------------------
4690// Record
4691// ----------------------------------------------------------------------------
4692
4693AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4694 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004695 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004696 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004697 audio_devices_t inDevice
4698#ifdef TEE_SINK
4699 , const sp<NBAIO_Sink>& teeSink
4700#endif
4701 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004702 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004703 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004704 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004705 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004706#ifdef TEE_SINK
4707 , mTeeSink(teeSink)
4708#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004709 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4710 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004711{
4712 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004713 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004714
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004715 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004716}
4717
4718
4719AudioFlinger::RecordThread::~RecordThread()
4720{
Glenn Kasten481fb672013-09-30 14:39:28 -07004721 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004722 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004723}
4724
4725void AudioFlinger::RecordThread::onFirstRef()
4726{
4727 run(mName, PRIORITY_URGENT_AUDIO);
4728}
4729
Eric Laurent81784c32012-11-19 14:55:58 -08004730bool AudioFlinger::RecordThread::threadLoop()
4731{
Eric Laurent81784c32012-11-19 14:55:58 -08004732 nsecs_t lastWarning = 0;
4733
4734 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004735
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004736reacquire_wakelock:
4737 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004738 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004739 {
4740 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004741 size_t size = mActiveTracks.size();
4742 activeTracksGen = mActiveTracksGen;
4743 if (size > 0) {
4744 // FIXME an arbitrary choice
4745 activeTrack = mActiveTracks[0];
4746 acquireWakeLock_l(activeTrack->uid());
4747 if (size > 1) {
4748 SortedVector<int> tmp;
4749 for (size_t i = 0; i < size; i++) {
4750 tmp.add(mActiveTracks[i]->uid());
4751 }
4752 updateWakeLockUids_l(tmp);
4753 }
4754 } else {
4755 acquireWakeLock_l(-1);
4756 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004757 }
4758
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004759 // used to request a deferred sleep, to be executed later while mutex is unlocked
4760 uint32_t sleepUs = 0;
4761
4762 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004763 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004764 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004765
Glenn Kasten5edadd42013-08-14 16:30:49 -07004766 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004767 if (sleepUs > 0) {
4768 usleep(sleepUs);
4769 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004770 }
4771
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004772 // activeTracks accumulates a copy of a subset of mActiveTracks
4773 Vector< sp<RecordTrack> > activeTracks;
4774
Eric Laurent10351942014-05-08 18:49:52 -07004775
Eric Laurent81784c32012-11-19 14:55:58 -08004776 { // scope for mLock
4777 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004778
Eric Laurent021cf962014-05-13 10:18:14 -07004779 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004780
Eric Laurent000a4192014-01-29 15:17:32 -08004781 // check exitPending here because checkForNewParameters_l() and
4782 // checkForNewParameters_l() can temporarily release mLock
4783 if (exitPending()) {
4784 break;
4785 }
4786
Glenn Kasten2b806402013-11-20 16:37:38 -08004787 // if no active track(s), then standby and release wakelock
4788 size_t size = mActiveTracks.size();
4789 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004790 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004791 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004792 releaseWakeLock_l();
4793 ALOGV("RecordThread: loop stopping");
4794 // go to sleep
4795 mWaitWorkCV.wait(mLock);
4796 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004797 goto reacquire_wakelock;
4798 }
4799
Glenn Kasten2b806402013-11-20 16:37:38 -08004800 if (mActiveTracksGen != activeTracksGen) {
4801 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004802 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004803 for (size_t i = 0; i < size; i++) {
4804 tmp.add(mActiveTracks[i]->uid());
4805 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004806 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004807 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004808
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004809 bool doBroadcast = false;
4810 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004811
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004812 activeTrack = mActiveTracks[i];
4813 if (activeTrack->isTerminated()) {
4814 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004815 mActiveTracks.remove(activeTrack);
4816 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004817 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004818 continue;
4819 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004820
4821 TrackBase::track_state activeTrackState = activeTrack->mState;
4822 switch (activeTrackState) {
4823
4824 case TrackBase::PAUSING:
4825 mActiveTracks.remove(activeTrack);
4826 mActiveTracksGen++;
4827 doBroadcast = true;
4828 size--;
4829 continue;
4830
4831 case TrackBase::STARTING_1:
4832 sleepUs = 10000;
4833 i++;
4834 continue;
4835
4836 case TrackBase::STARTING_2:
4837 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004838 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004839 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004840 break;
4841
4842 case TrackBase::ACTIVE:
4843 break;
4844
4845 case TrackBase::IDLE:
4846 i++;
4847 continue;
4848
4849 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004850 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004851 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004852
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004853 activeTracks.add(activeTrack);
4854 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004855
Glenn Kasten9e982352013-08-14 14:39:50 -07004856 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004857 if (doBroadcast) {
4858 mStartStopCond.broadcast();
4859 }
4860
4861 // sleep if there are no active tracks to process
4862 if (activeTracks.size() == 0) {
4863 if (sleepUs == 0) {
4864 sleepUs = kRecordThreadSleepUs;
4865 }
4866 continue;
4867 }
4868 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004869
Eric Laurent81784c32012-11-19 14:55:58 -08004870 lockEffectChains_l(effectChains);
4871 }
4872
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004873 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004874
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004875 size_t size = effectChains.size();
4876 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004877 // thread mutex is not locked, but effect chain is locked
4878 effectChains[i]->process_l();
4879 }
4880
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004881 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4882 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4883 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4884 // If destination is non-contiguous, first read past the nominal end of buffer, then
4885 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004887 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4888 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4889 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4890 if (bytesRead <= 0) {
4891 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4892 // Force input into standby so that it tries to recover at next read attempt
4893 inputStandBy();
4894 sleepUs = kRecordThreadSleepUs;
4895 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004896 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004897 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4898 size_t framesRead = bytesRead / mFrameSize;
4899 ALOG_ASSERT(framesRead > 0);
4900 if (mTeeSink != 0) {
4901 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4902 }
4903 // If destination is non-contiguous, we now correct for reading past end of buffer.
4904 size_t part1 = mRsmpInFramesP2 - rear;
4905 if (framesRead > part1) {
4906 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4907 (framesRead - part1) * mFrameSize);
4908 }
4909 rear = mRsmpInRear += framesRead;
4910
4911 size = activeTracks.size();
4912 // loop over each active track
4913 for (size_t i = 0; i < size; i++) {
4914 activeTrack = activeTracks[i];
4915
4916 enum {
4917 OVERRUN_UNKNOWN,
4918 OVERRUN_TRUE,
4919 OVERRUN_FALSE
4920 } overrun = OVERRUN_UNKNOWN;
4921
4922 // loop over getNextBuffer to handle circular sink
4923 for (;;) {
4924
4925 activeTrack->mSink.frameCount = ~0;
4926 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4927 size_t framesOut = activeTrack->mSink.frameCount;
4928 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4929
4930 int32_t front = activeTrack->mRsmpInFront;
4931 ssize_t filled = rear - front;
4932 size_t framesIn;
4933
4934 if (filled < 0) {
4935 // should not happen, but treat like a massive overrun and re-sync
4936 framesIn = 0;
4937 activeTrack->mRsmpInFront = rear;
4938 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004939 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004940 framesIn = (size_t) filled;
4941 } else {
4942 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004943 framesIn = mRsmpInFrames;
4944 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004945 overrun = OVERRUN_TRUE;
4946 }
4947
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004948 if (framesOut == 0 || framesIn == 0) {
4949 break;
4950 }
4951
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004952 if (activeTrack->mResampler == NULL) {
4953 // no resampling
4954 if (framesIn > framesOut) {
4955 framesIn = framesOut;
4956 } else {
4957 framesOut = framesIn;
4958 }
4959 int8_t *dst = activeTrack->mSink.i8;
4960 while (framesIn > 0) {
4961 front &= mRsmpInFramesP2 - 1;
4962 size_t part1 = mRsmpInFramesP2 - front;
4963 if (part1 > framesIn) {
4964 part1 = framesIn;
4965 }
4966 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004967 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004968 memcpy(dst, src, part1 * mFrameSize);
4969 } else if (mChannelCount == 1) {
4970 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4971 part1);
4972 } else {
4973 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4974 part1);
4975 }
4976 dst += part1 * activeTrack->mFrameSize;
4977 front += part1;
4978 framesIn -= part1;
4979 }
4980 activeTrack->mRsmpInFront += framesOut;
4981
4982 } else {
4983 // resampling
4984 // FIXME framesInNeeded should really be part of resampler API, and should
4985 // depend on the SRC ratio
4986 // to keep mRsmpInBuffer full so resampler always has sufficient input
4987 size_t framesInNeeded;
4988 // FIXME only re-calculate when it changes, and optimize for common ratios
4989 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4990 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004991 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004992 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4993 framesInNeeded, framesOut, inOverOut);
4994 // Although we theoretically have framesIn in circular buffer, some of those are
4995 // unreleased frames, and thus must be discounted for purpose of budgeting.
4996 size_t unreleased = activeTrack->mRsmpInUnrel;
4997 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004998 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004999 ALOGV("not enough to resample: have %u frames in but need %u in to "
5000 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005001 framesIn, framesInNeeded, framesOut, inOverOut);
5002 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005003 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5004 if (newFramesOut == 0) {
5005 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005006 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005007 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
5008 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
5009 framesInNeeded, newFramesOut, outOverIn);
5010 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5011 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5012 "given in/out ratio of %.4g",
5013 framesIn, framesInNeeded, newFramesOut, inOverOut);
5014 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005015 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005016 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005017 "given in/out ratio of %.4g",
5018 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005019 }
5020
5021 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5022 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005023 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005024 delete[] activeTrack->mRsmpOutBuffer;
5025 // resampler always outputs stereo
5026 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5027 activeTrack->mRsmpOutFrameCount = framesOut;
5028 }
5029
5030 // resampler accumulates, but we only have one source track
5031 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5032 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005033 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005034 activeTrack->mResamplerBufferProvider
5035 /*this*/ /* AudioBufferProvider* */);
5036 // ditherAndClamp() works as long as all buffers returned by
5037 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005038 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005039 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005040 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5041 framesOut);
5042 // the resampler always outputs stereo samples:
5043 // do post stereo to mono conversion
5044 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
5045 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
5046 } else {
5047 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5048 activeTrack->mRsmpOutBuffer, framesOut);
5049 }
5050 // now done with mRsmpOutBuffer
5051
5052 }
5053
5054 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5055 overrun = OVERRUN_FALSE;
5056 }
5057
5058 if (activeTrack->mFramesToDrop == 0) {
5059 if (framesOut > 0) {
5060 activeTrack->mSink.frameCount = framesOut;
5061 activeTrack->releaseBuffer(&activeTrack->mSink);
5062 }
5063 } else {
5064 // FIXME could do a partial drop of framesOut
5065 if (activeTrack->mFramesToDrop > 0) {
5066 activeTrack->mFramesToDrop -= framesOut;
5067 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005068 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005069 }
5070 } else {
5071 activeTrack->mFramesToDrop += framesOut;
5072 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5073 activeTrack->mSyncStartEvent->isCancelled()) {
5074 ALOGW("Synced record %s, session %d, trigger session %d",
5075 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5076 activeTrack->sessionId(),
5077 (activeTrack->mSyncStartEvent != 0) ?
5078 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005079 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005080 }
5081 }
5082 }
5083
5084 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005085 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005086 }
5087 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005088
5089 switch (overrun) {
5090 case OVERRUN_TRUE:
5091 // client isn't retrieving buffers fast enough
5092 if (!activeTrack->setOverflow()) {
5093 nsecs_t now = systemTime();
5094 // FIXME should lastWarning per track?
5095 if ((now - lastWarning) > kWarningThrottleNs) {
5096 ALOGW("RecordThread: buffer overflow");
5097 lastWarning = now;
5098 }
5099 }
5100 break;
5101 case OVERRUN_FALSE:
5102 activeTrack->clearOverflow();
5103 break;
5104 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005105 break;
5106 }
5107
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005108 }
5109
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // enable changes in effect chain
5111 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005112 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005113 }
5114
Glenn Kasten93e471f2013-08-19 08:40:07 -07005115 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005116
5117 {
5118 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005119 for (size_t i = 0; i < mTracks.size(); i++) {
5120 sp<RecordTrack> track = mTracks[i];
5121 track->invalidate();
5122 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005123 mActiveTracks.clear();
5124 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005125 mStartStopCond.broadcast();
5126 }
5127
5128 releaseWakeLock();
5129
5130 ALOGV("RecordThread %p exiting", this);
5131 return false;
5132}
5133
Glenn Kasten93e471f2013-08-19 08:40:07 -07005134void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005135{
5136 if (!mStandby) {
5137 inputStandBy();
5138 mStandby = true;
5139 }
5140}
5141
5142void AudioFlinger::RecordThread::inputStandBy()
5143{
5144 mInput->stream->common.standby(&mInput->stream->common);
5145}
5146
Glenn Kasten05997e22014-03-13 15:08:33 -07005147// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005148sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005149 const sp<AudioFlinger::Client>& client,
5150 uint32_t sampleRate,
5151 audio_format_t format,
5152 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005153 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005154 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005155 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005156 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005157 pid_t tid,
5158 status_t *status)
5159{
Glenn Kasten74935e42013-12-19 08:56:45 -08005160 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005161 sp<RecordTrack> track;
5162 status_t lStatus;
5163
Glenn Kasten90e58b12013-07-31 16:16:02 -07005164 // client expresses a preference for FAST, but we get the final say
5165 if (*flags & IAudioFlinger::TRACK_FAST) {
5166 if (
5167 // use case: callback handler and frame count is default or at least as large as HAL
5168 (
5169 (tid != -1) &&
5170 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005171 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005172 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005173 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005174 // PCM data
5175 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005176 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005177 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5178 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005179 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005180 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005181 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005182 // record thread has an associated fast capture
5183 hasFastCapture()
5184 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005185 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005186 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005187 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005188 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005189 frameCount = mFrameCount * kFastTrackMultiplier;
5190 }
5191 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5192 frameCount, mFrameCount);
5193 } else {
5194 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5195 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005196 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005197 frameCount, mFrameCount, format,
5198 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005199 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005200 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005201 // 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 -07005202 // For compatibility with AudioRecord calculation, buffer depth is forced
5203 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5204 // This is probably too conservative, but legacy application code may depend on it.
5205 // If you change this calculation, also review the start threshold which is related.
5206 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5207 size_t mNormalFrameCount = 2048; // FIXME
5208 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5209 if (minBufCount < 2) {
5210 minBufCount = 2;
5211 }
5212 size_t minFrameCount = mNormalFrameCount * minBufCount;
5213 if (frameCount < minFrameCount) {
5214 frameCount = minFrameCount;
5215 }
5216 }
5217 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005218 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005219
Glenn Kasten15e57982013-09-24 11:52:37 -07005220 lStatus = initCheck();
5221 if (lStatus != NO_ERROR) {
5222 ALOGE("createRecordTrack_l() audio driver not initialized");
5223 goto Exit;
5224 }
Eric Laurent81784c32012-11-19 14:55:58 -08005225
5226 { // scope for mLock
5227 Mutex::Autolock _l(mLock);
5228
5229 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005230 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005231 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005232
Glenn Kasten03003332013-08-06 15:40:54 -07005233 lStatus = track->initCheck();
5234 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005235 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005236 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005237 goto Exit;
5238 }
5239 mTracks.add(track);
5240
5241 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5242 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5243 mAudioFlinger->btNrecIsOff();
5244 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5245 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005246
5247 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5248 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5249 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5250 // so ask activity manager to do this on our behalf
5251 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5252 }
Eric Laurent81784c32012-11-19 14:55:58 -08005253 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005254
Eric Laurent81784c32012-11-19 14:55:58 -08005255 lStatus = NO_ERROR;
5256
5257Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005258 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005259 return track;
5260}
5261
5262status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5263 AudioSystem::sync_event_t event,
5264 int triggerSession)
5265{
5266 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5267 sp<ThreadBase> strongMe = this;
5268 status_t status = NO_ERROR;
5269
5270 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005271 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005272 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005273 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005274 triggerSession,
5275 recordTrack->sessionId(),
5276 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005277 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005278 // Sync event can be cancelled by the trigger session if the track is not in a
5279 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005280 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005281 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005282 } else {
5283 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005284 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005285 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005286 }
5287 }
5288
5289 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005290 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005291 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005292 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5293 if (recordTrack->mState == TrackBase::PAUSING) {
5294 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005295 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005296 } else {
5297 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005298 }
5299 return status;
5300 }
5301
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005302 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5303 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5304 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005305 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005306 mActiveTracks.add(recordTrack);
5307 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005308 mLock.unlock();
5309 status_t status = AudioSystem::startInput(mId);
5310 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005311 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005312 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005313 mActiveTracks.remove(recordTrack);
5314 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005315 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005316 return status;
5317 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005318 // Catch up with current buffer indices if thread is already running.
5319 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5320 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5321 // see previously buffered data before it called start(), but with greater risk of overrun.
5322
5323 recordTrack->mRsmpInFront = mRsmpInRear;
5324 recordTrack->mRsmpInUnrel = 0;
5325 // FIXME why reset?
5326 if (recordTrack->mResampler != NULL) {
5327 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005328 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005329 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005330 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005331 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005332 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005333 ALOGV("Record failed to start");
5334 status = BAD_VALUE;
5335 goto startError;
5336 }
Eric Laurent81784c32012-11-19 14:55:58 -08005337 return status;
5338 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005339
Eric Laurent81784c32012-11-19 14:55:58 -08005340startError:
5341 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005342 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005343 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005344 return status;
5345}
5346
Eric Laurent81784c32012-11-19 14:55:58 -08005347void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5348{
5349 sp<SyncEvent> strongEvent = event.promote();
5350
5351 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005352 sp<RefBase> ptr = strongEvent->cookie().promote();
5353 if (ptr != 0) {
5354 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5355 recordTrack->handleSyncStartEvent(strongEvent);
5356 }
Eric Laurent81784c32012-11-19 14:55:58 -08005357 }
5358}
5359
Glenn Kastena8356f62013-07-25 14:37:52 -07005360bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005361 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005362 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005363 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005364 return false;
5365 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005366 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005367 recordTrack->mState = TrackBase::PAUSING;
5368 // do not wait for mStartStopCond if exiting
5369 if (exitPending()) {
5370 return true;
5371 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005372 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005373 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005374 // if we have been restarted, recordTrack is in mActiveTracks here
5375 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005376 ALOGV("Record stopped OK");
5377 return true;
5378 }
5379 return false;
5380}
5381
Glenn Kasten0f11b512014-01-31 16:18:54 -08005382bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005383{
5384 return false;
5385}
5386
Glenn Kasten0f11b512014-01-31 16:18:54 -08005387status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005388{
5389#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5390 if (!isValidSyncEvent(event)) {
5391 return BAD_VALUE;
5392 }
5393
5394 int eventSession = event->triggerSession();
5395 status_t ret = NAME_NOT_FOUND;
5396
5397 Mutex::Autolock _l(mLock);
5398
5399 for (size_t i = 0; i < mTracks.size(); i++) {
5400 sp<RecordTrack> track = mTracks[i];
5401 if (eventSession == track->sessionId()) {
5402 (void) track->setSyncEvent(event);
5403 ret = NO_ERROR;
5404 }
5405 }
5406 return ret;
5407#else
5408 return BAD_VALUE;
5409#endif
5410}
5411
5412// destroyTrack_l() must be called with ThreadBase::mLock held
5413void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5414{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005415 track->terminate();
5416 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005417 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005418 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005419 removeTrack_l(track);
5420 }
5421}
5422
5423void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5424{
5425 mTracks.remove(track);
5426 // need anything related to effects here?
5427}
5428
5429void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5430{
5431 dumpInternals(fd, args);
5432 dumpTracks(fd, args);
5433 dumpEffectChains(fd, args);
5434}
5435
5436void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5437{
Marco Nelissenb2208842014-02-07 14:00:50 -08005438 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005439
Glenn Kasten2b806402013-11-20 16:37:38 -08005440 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005441 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005442 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005443 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005444 }
5445
Eric Laurent81784c32012-11-19 14:55:58 -08005446 dumpBase(fd, args);
5447}
5448
Glenn Kasten0f11b512014-01-31 16:18:54 -08005449void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005450{
5451 const size_t SIZE = 256;
5452 char buffer[SIZE];
5453 String8 result;
5454
Marco Nelissenb2208842014-02-07 14:00:50 -08005455 size_t numtracks = mTracks.size();
5456 size_t numactive = mActiveTracks.size();
5457 size_t numactiveseen = 0;
5458 fdprintf(fd, " %d Tracks", numtracks);
5459 if (numtracks) {
5460 fdprintf(fd, " of which %d are active\n", numactive);
5461 RecordTrack::appendDumpHeader(result);
5462 for (size_t i = 0; i < numtracks ; ++i) {
5463 sp<RecordTrack> track = mTracks[i];
5464 if (track != 0) {
5465 bool active = mActiveTracks.indexOf(track) >= 0;
5466 if (active) {
5467 numactiveseen++;
5468 }
5469 track->dump(buffer, SIZE, active);
5470 result.append(buffer);
5471 }
Eric Laurent81784c32012-11-19 14:55:58 -08005472 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005473 } else {
5474 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005475 }
5476
Marco Nelissenb2208842014-02-07 14:00:50 -08005477 if (numactiveseen != numactive) {
5478 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5479 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005480 result.append(buffer);
5481 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005482 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005483 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005484 if (mTracks.indexOf(track) < 0) {
5485 track->dump(buffer, SIZE, true);
5486 result.append(buffer);
5487 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005488 }
Eric Laurent81784c32012-11-19 14:55:58 -08005489
5490 }
5491 write(fd, result.string(), result.size());
5492}
5493
5494// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005495status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5496 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005497{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005498 RecordTrack *activeTrack = mRecordTrack;
5499 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5500 if (threadBase == 0) {
5501 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005502 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005503 return NOT_ENOUGH_DATA;
5504 }
5505 RecordThread *recordThread = (RecordThread *) threadBase.get();
5506 int32_t rear = recordThread->mRsmpInRear;
5507 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005508 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005509 // FIXME should not be P2 (don't want to increase latency)
5510 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005511 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005512 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005513 front &= recordThread->mRsmpInFramesP2 - 1;
5514 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005515 if (part1 > (size_t) filled) {
5516 part1 = filled;
5517 }
5518 size_t ask = buffer->frameCount;
5519 ALOG_ASSERT(ask > 0);
5520 if (part1 > ask) {
5521 part1 = ask;
5522 }
5523 if (part1 == 0) {
5524 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005525 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005526 buffer->raw = NULL;
5527 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005528 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005529 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005530 }
5531
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005532 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005533 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005534 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 return NO_ERROR;
5536}
5537
5538// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5540 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005541{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005542 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005543 size_t stepCount = buffer->frameCount;
5544 if (stepCount == 0) {
5545 return;
5546 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005547 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5548 activeTrack->mRsmpInUnrel -= stepCount;
5549 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005550 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005551 buffer->frameCount = 0;
5552}
5553
Eric Laurent10351942014-05-08 18:49:52 -07005554bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5555 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005556{
5557 bool reconfig = false;
5558
Eric Laurent10351942014-05-08 18:49:52 -07005559 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005560
Eric Laurent10351942014-05-08 18:49:52 -07005561 audio_format_t reqFormat = mFormat;
5562 uint32_t samplingRate = mSampleRate;
5563 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5564
5565 AudioParameter param = AudioParameter(keyValuePair);
5566 int value;
5567 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5568 // channel count change can be requested. Do we mandate the first client defines the
5569 // HAL sampling rate and channel count or do we allow changes on the fly?
5570 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5571 samplingRate = value;
5572 reconfig = true;
5573 }
5574 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5575 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5576 status = BAD_VALUE;
5577 } else {
5578 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005579 reconfig = true;
5580 }
Eric Laurent10351942014-05-08 18:49:52 -07005581 }
5582 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5583 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5584 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5585 status = BAD_VALUE;
5586 } else {
5587 channelMask = mask;
5588 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005589 }
Eric Laurent10351942014-05-08 18:49:52 -07005590 }
5591 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5592 // do not accept frame count changes if tracks are open as the track buffer
5593 // size depends on frame count and correct behavior would not be guaranteed
5594 // if frame count is changed after track creation
5595 if (mActiveTracks.size() > 0) {
5596 status = INVALID_OPERATION;
5597 } else {
5598 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005599 }
Eric Laurent10351942014-05-08 18:49:52 -07005600 }
5601 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5602 // forward device change to effects that have requested to be
5603 // aware of attached audio device.
5604 for (size_t i = 0; i < mEffectChains.size(); i++) {
5605 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005606 }
Eric Laurent81784c32012-11-19 14:55:58 -08005607
Eric Laurent10351942014-05-08 18:49:52 -07005608 // store input device and output device but do not forward output device to audio HAL.
5609 // Note that status is ignored by the caller for output device
5610 // (see AudioFlinger::setParameters()
5611 if (audio_is_output_devices(value)) {
5612 mOutDevice = value;
5613 status = BAD_VALUE;
5614 } else {
5615 mInDevice = value;
5616 // disable AEC and NS if the device is a BT SCO headset supporting those
5617 // pre processings
5618 if (mTracks.size() > 0) {
5619 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5620 mAudioFlinger->btNrecIsOff();
5621 for (size_t i = 0; i < mTracks.size(); i++) {
5622 sp<RecordTrack> track = mTracks[i];
5623 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5624 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005625 }
5626 }
5627 }
Eric Laurent10351942014-05-08 18:49:52 -07005628 }
5629 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5630 mAudioSource != (audio_source_t)value) {
5631 // forward device change to effects that have requested to be
5632 // aware of attached audio device.
5633 for (size_t i = 0; i < mEffectChains.size(); i++) {
5634 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005635 }
Eric Laurent10351942014-05-08 18:49:52 -07005636 mAudioSource = (audio_source_t)value;
5637 }
Glenn Kastene198c362013-08-13 09:13:36 -07005638
Eric Laurent10351942014-05-08 18:49:52 -07005639 if (status == NO_ERROR) {
5640 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5641 keyValuePair.string());
5642 if (status == INVALID_OPERATION) {
5643 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005644 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5645 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005646 }
5647 if (reconfig) {
5648 if (status == BAD_VALUE &&
5649 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5650 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5651 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5652 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005653 audio_channel_count_from_in_mask(
5654 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005655 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5656 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5657 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005658 }
Eric Laurent10351942014-05-08 18:49:52 -07005659 if (status == NO_ERROR) {
5660 readInputParameters_l();
5661 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005662 }
5663 }
Eric Laurent81784c32012-11-19 14:55:58 -08005664 }
Eric Laurent10351942014-05-08 18:49:52 -07005665
Eric Laurent81784c32012-11-19 14:55:58 -08005666 return reconfig;
5667}
5668
5669String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5670{
Eric Laurent81784c32012-11-19 14:55:58 -08005671 Mutex::Autolock _l(mLock);
5672 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005673 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005674 }
5675
Glenn Kastend8ea6992013-07-16 14:17:15 -07005676 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5677 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005678 free(s);
5679 return out_s8;
5680}
5681
Eric Laurent021cf962014-05-13 10:18:14 -07005682void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005683 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005684 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005685
5686 switch (event) {
5687 case AudioSystem::INPUT_OPENED:
5688 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005689 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005690 desc.samplingRate = mSampleRate;
5691 desc.format = mFormat;
5692 desc.frameCount = mFrameCount;
5693 desc.latency = 0;
5694 param2 = &desc;
5695 break;
5696
5697 case AudioSystem::INPUT_CLOSED:
5698 default:
5699 break;
5700 }
Eric Laurent021cf962014-05-13 10:18:14 -07005701 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005702}
5703
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005704void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005705{
Eric Laurent81784c32012-11-19 14:55:58 -08005706 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5707 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07005708 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005709 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005710 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005711 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005712 }
Eric Laurent81784c32012-11-19 14:55:58 -08005713 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005714 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5715 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005716 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005717 // 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 -07005718 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005719 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005720 // A larger value should allow more old data to be read after a track calls start(),
5721 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005722 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005723 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005724 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005725 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5726 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005727
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005728 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5729 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005730}
5731
Glenn Kasten5f972c02014-01-13 09:59:31 -08005732uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005733{
5734 Mutex::Autolock _l(mLock);
5735 if (initCheck() != NO_ERROR) {
5736 return 0;
5737 }
5738
5739 return mInput->stream->get_input_frames_lost(mInput->stream);
5740}
5741
5742uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5743{
5744 Mutex::Autolock _l(mLock);
5745 uint32_t result = 0;
5746 if (getEffectChain_l(sessionId) != 0) {
5747 result = EFFECT_SESSION;
5748 }
5749
5750 for (size_t i = 0; i < mTracks.size(); ++i) {
5751 if (sessionId == mTracks[i]->sessionId()) {
5752 result |= TRACK_SESSION;
5753 break;
5754 }
5755 }
5756
5757 return result;
5758}
5759
5760KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5761{
5762 KeyedVector<int, bool> ids;
5763 Mutex::Autolock _l(mLock);
5764 for (size_t j = 0; j < mTracks.size(); ++j) {
5765 sp<RecordThread::RecordTrack> track = mTracks[j];
5766 int sessionId = track->sessionId();
5767 if (ids.indexOfKey(sessionId) < 0) {
5768 ids.add(sessionId, true);
5769 }
5770 }
5771 return ids;
5772}
5773
5774AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5775{
5776 Mutex::Autolock _l(mLock);
5777 AudioStreamIn *input = mInput;
5778 mInput = NULL;
5779 return input;
5780}
5781
5782// this method must always be called either with ThreadBase mLock held or inside the thread loop
5783audio_stream_t* AudioFlinger::RecordThread::stream() const
5784{
5785 if (mInput == NULL) {
5786 return NULL;
5787 }
5788 return &mInput->stream->common;
5789}
5790
5791status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5792{
5793 // only one chain per input thread
5794 if (mEffectChains.size() != 0) {
5795 return INVALID_OPERATION;
5796 }
5797 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5798
5799 chain->setInBuffer(NULL);
5800 chain->setOutBuffer(NULL);
5801
5802 checkSuspendOnAddEffectChain_l(chain);
5803
5804 mEffectChains.add(chain);
5805
5806 return NO_ERROR;
5807}
5808
5809size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5810{
5811 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5812 ALOGW_IF(mEffectChains.size() != 1,
5813 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5814 chain.get(), mEffectChains.size(), this);
5815 if (mEffectChains.size() == 1) {
5816 mEffectChains.removeAt(0);
5817 }
5818 return 0;
5819}
5820
Eric Laurent951f4552014-05-20 10:48:17 -07005821status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
5822 audio_patch_handle_t *handle)
5823{
5824 status_t status = NO_ERROR;
5825 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
5826 // store new device and send to effects
5827 mInDevice = patch->sources[0].ext.device.type;
5828 for (size_t i = 0; i < mEffectChains.size(); i++) {
5829 mEffectChains[i]->setDevice_l(mInDevice);
5830 }
5831
5832 // disable AEC and NS if the device is a BT SCO headset supporting those
5833 // pre processings
5834 if (mTracks.size() > 0) {
5835 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5836 mAudioFlinger->btNrecIsOff();
5837 for (size_t i = 0; i < mTracks.size(); i++) {
5838 sp<RecordTrack> track = mTracks[i];
5839 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5840 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5841 }
5842 }
5843
5844 // store new source and send to effects
5845 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
5846 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
5847 for (size_t i = 0; i < mEffectChains.size(); i++) {
5848 mEffectChains[i]->setAudioSource_l(mAudioSource);
5849 }
5850 }
5851
5852 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
5853 status = hwDevice->create_audio_patch(hwDevice,
5854 patch->num_sources,
5855 patch->sources,
5856 patch->num_sinks,
5857 patch->sinks,
5858 handle);
5859 } else {
5860 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
5861 }
5862 return status;
5863}
5864
5865status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
5866{
5867 status_t status = NO_ERROR;
5868 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
5869 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
5870 status = hwDevice->release_audio_patch(hwDevice, handle);
5871 } else {
5872 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
5873 }
5874 return status;
5875}
5876
5877
Eric Laurent81784c32012-11-19 14:55:58 -08005878}; // namespace android