blob: cd66b1638a6486aa865f17196b84f47bb707c57b [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 Kasten03490092014-05-27 12:30:54 -0700145
146// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800147static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800148
Glenn Kasten03490092014-05-27 12:30:54 -0700149// The minimum and maximum allowed values
150static const int kFastTrackMultiplierMin = 1;
151static const int kFastTrackMultiplierMax = 2;
152
153// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
154static int sFastTrackMultiplier = kFastTrackMultiplier;
155
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700156// See Thread::readOnlyHeap().
157// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
158// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
159// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
160static const size_t kRecordThreadReadOnlyHeapSize = 0x1000;
161
Eric Laurent81784c32012-11-19 14:55:58 -0800162// ----------------------------------------------------------------------------
163
Glenn Kasten03490092014-05-27 12:30:54 -0700164static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
165
166static void sFastTrackMultiplierInit()
167{
168 char value[PROPERTY_VALUE_MAX];
169 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
170 char *endptr;
171 unsigned long ul = strtoul(value, &endptr, 0);
172 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
173 sFastTrackMultiplier = (int) ul;
174 }
175 }
176}
177
178// ----------------------------------------------------------------------------
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180#ifdef ADD_BATTERY_DATA
181// To collect the amplifier usage
182static void addBatteryData(uint32_t params) {
183 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
184 if (service == NULL) {
185 // it already logged
186 return;
187 }
188
189 service->addBatteryData(params);
190}
191#endif
192
193
194// ----------------------------------------------------------------------------
195// CPU Stats
196// ----------------------------------------------------------------------------
197
198class CpuStats {
199public:
200 CpuStats();
201 void sample(const String8 &title);
202#ifdef DEBUG_CPU_USAGE
203private:
204 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
205 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
206
207 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
208
209 int mCpuNum; // thread's current CPU number
210 int mCpukHz; // frequency of thread's current CPU in kHz
211#endif
212};
213
214CpuStats::CpuStats()
215#ifdef DEBUG_CPU_USAGE
216 : mCpuNum(-1), mCpukHz(-1)
217#endif
218{
219}
220
Glenn Kasten0f11b512014-01-31 16:18:54 -0800221void CpuStats::sample(const String8 &title
222#ifndef DEBUG_CPU_USAGE
223 __unused
224#endif
225 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800226#ifdef DEBUG_CPU_USAGE
227 // get current thread's delta CPU time in wall clock ns
228 double wcNs;
229 bool valid = mCpuUsage.sampleAndEnable(wcNs);
230
231 // record sample for wall clock statistics
232 if (valid) {
233 mWcStats.sample(wcNs);
234 }
235
236 // get the current CPU number
237 int cpuNum = sched_getcpu();
238
239 // get the current CPU frequency in kHz
240 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
241
242 // check if either CPU number or frequency changed
243 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
244 mCpuNum = cpuNum;
245 mCpukHz = cpukHz;
246 // ignore sample for purposes of cycles
247 valid = false;
248 }
249
250 // if no change in CPU number or frequency, then record sample for cycle statistics
251 if (valid && mCpukHz > 0) {
252 double cycles = wcNs * cpukHz * 0.000001;
253 mHzStats.sample(cycles);
254 }
255
256 unsigned n = mWcStats.n();
257 // mCpuUsage.elapsed() is expensive, so don't call it every loop
258 if ((n & 127) == 1) {
259 long long elapsed = mCpuUsage.elapsed();
260 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
261 double perLoop = elapsed / (double) n;
262 double perLoop100 = perLoop * 0.01;
263 double perLoop1k = perLoop * 0.001;
264 double mean = mWcStats.mean();
265 double stddev = mWcStats.stddev();
266 double minimum = mWcStats.minimum();
267 double maximum = mWcStats.maximum();
268 double meanCycles = mHzStats.mean();
269 double stddevCycles = mHzStats.stddev();
270 double minCycles = mHzStats.minimum();
271 double maxCycles = mHzStats.maximum();
272 mCpuUsage.resetElapsed();
273 mWcStats.reset();
274 mHzStats.reset();
275 ALOGD("CPU usage for %s over past %.1f secs\n"
276 " (%u mixer loops at %.1f mean ms per loop):\n"
277 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
278 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
279 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
280 title.string(),
281 elapsed * .000000001, n, perLoop * .000001,
282 mean * .001,
283 stddev * .001,
284 minimum * .001,
285 maximum * .001,
286 mean / perLoop100,
287 stddev / perLoop100,
288 minimum / perLoop100,
289 maximum / perLoop100,
290 meanCycles / perLoop1k,
291 stddevCycles / perLoop1k,
292 minCycles / perLoop1k,
293 maxCycles / perLoop1k);
294
295 }
296 }
297#endif
298};
299
300// ----------------------------------------------------------------------------
301// ThreadBase
302// ----------------------------------------------------------------------------
303
304AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
305 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
306 : Thread(false /*canCallJava*/),
307 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700308 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700309 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800310 // are set by PlaybackThread::readOutputParameters_l() or
311 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700312 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800313 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
314 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
315 // mName will be set by concrete (non-virtual) subclass
316 mDeathRecipient(new PMDeathRecipient(this))
317{
318}
319
320AudioFlinger::ThreadBase::~ThreadBase()
321{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700322 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700323 mConfigEvents.clear();
324
Eric Laurent81784c32012-11-19 14:55:58 -0800325 // do not lock the mutex in destructor
326 releaseWakeLock_l();
327 if (mPowerManager != 0) {
328 sp<IBinder> binder = mPowerManager->asBinder();
329 binder->unlinkToDeath(mDeathRecipient);
330 }
331}
332
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700333status_t AudioFlinger::ThreadBase::readyToRun()
334{
335 status_t status = initCheck();
336 if (status == NO_ERROR) {
337 ALOGI("AudioFlinger's thread %p ready to run", this);
338 } else {
339 ALOGE("No working audio driver found.");
340 }
341 return status;
342}
343
Eric Laurent81784c32012-11-19 14:55:58 -0800344void AudioFlinger::ThreadBase::exit()
345{
346 ALOGV("ThreadBase::exit");
347 // do any cleanup required for exit to succeed
348 preExit();
349 {
350 // This lock prevents the following race in thread (uniprocessor for illustration):
351 // if (!exitPending()) {
352 // // context switch from here to exit()
353 // // exit() calls requestExit(), what exitPending() observes
354 // // exit() calls signal(), which is dropped since no waiters
355 // // context switch back from exit() to here
356 // mWaitWorkCV.wait(...);
357 // // now thread is hung
358 // }
359 AutoMutex lock(mLock);
360 requestExit();
361 mWaitWorkCV.broadcast();
362 }
363 // When Thread::requestExitAndWait is made virtual and this method is renamed to
364 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
365 requestExitAndWait();
366}
367
368status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
369{
370 status_t status;
371
372 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
373 Mutex::Autolock _l(mLock);
374
Eric Laurent10351942014-05-08 18:49:52 -0700375 return sendSetParameterConfigEvent_l(keyValuePairs);
376}
377
378// sendConfigEvent_l() must be called with ThreadBase::mLock held
379// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
380status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
381{
382 status_t status = NO_ERROR;
383
384 mConfigEvents.add(event);
385 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800386 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700387 mLock.unlock();
388 {
389 Mutex::Autolock _l(event->mLock);
390 while (event->mWaitStatus) {
391 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
392 event->mStatus = TIMED_OUT;
393 event->mWaitStatus = false;
394 }
395 }
396 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800397 }
Eric Laurent10351942014-05-08 18:49:52 -0700398 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800399 return status;
400}
401
402void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
403{
404 Mutex::Autolock _l(mLock);
405 sendIoConfigEvent_l(event, param);
406}
407
408// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
409void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
410{
Eric Laurent10351942014-05-08 18:49:52 -0700411 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
412 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800413}
414
415// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
416void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
417{
Eric Laurent10351942014-05-08 18:49:52 -0700418 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
419 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800420}
421
Eric Laurent10351942014-05-08 18:49:52 -0700422// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
423status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800424{
Eric Laurent10351942014-05-08 18:49:52 -0700425 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
426 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700427}
428
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700429// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700430void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700431{
Eric Laurent10351942014-05-08 18:49:52 -0700432 bool configChanged = false;
433
Eric Laurent81784c32012-11-19 14:55:58 -0800434 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700435 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
436 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800437 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700438 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700439 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700440 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
441 // FIXME Need to understand why this has to be done asynchronously
442 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700443 true /*asynchronous*/);
444 if (err != 0) {
445 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700446 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700447 }
448 } break;
449 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700450 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700451 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700452 } break;
453 case CFG_EVENT_SET_PARAMETER: {
454 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
455 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
456 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700457 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700458 } break;
459 default:
Eric Laurent10351942014-05-08 18:49:52 -0700460 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700461 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800462 }
Eric Laurent10351942014-05-08 18:49:52 -0700463 {
464 Mutex::Autolock _l(event->mLock);
465 if (event->mWaitStatus) {
466 event->mWaitStatus = false;
467 event->mCond.signal();
468 }
469 }
470 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
471 }
472
473 if (configChanged) {
474 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800475 }
Eric Laurent81784c32012-11-19 14:55:58 -0800476}
477
Marco Nelissenb2208842014-02-07 14:00:50 -0800478String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
479 String8 s;
480 if (output) {
481 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
482 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
483 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
484 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
485 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
486 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
487 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
488 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
489 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
490 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
491 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
492 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
493 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
494 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
495 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
496 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
497 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
498 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
499 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
500 } else {
501 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
502 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
503 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
504 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
505 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
506 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
507 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
508 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
509 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
510 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
511 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
512 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
513 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
514 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
515 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
516 }
517 int len = s.length();
518 if (s.length() > 2) {
519 char *str = s.lockBuffer(len);
520 s.unlockBuffer(len - 2);
521 }
522 return s;
523}
524
Glenn Kasten0f11b512014-01-31 16:18:54 -0800525void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800526{
527 const size_t SIZE = 256;
528 char buffer[SIZE];
529 String8 result;
530
531 bool locked = AudioFlinger::dumpTryLock(mLock);
532 if (!locked) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700533 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800534 }
535
Elliott Hughes87cebad2014-05-22 10:14:43 -0700536 dprintf(fd, " I/O handle: %d\n", mId);
537 dprintf(fd, " TID: %d\n", getTid());
538 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
539 dprintf(fd, " Sample rate: %u\n", mSampleRate);
540 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
541 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
542 dprintf(fd, " Channel Count: %u\n", mChannelCount);
543 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800544 channelMaskToString(mChannelMask, mType != RECORD).string());
Elliott Hughes87cebad2014-05-22 10:14:43 -0700545 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
546 dprintf(fd, " Frame size: %zu\n", mFrameSize);
547 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800548 size_t numConfig = mConfigEvents.size();
549 if (numConfig) {
550 for (size_t i = 0; i < numConfig; i++) {
551 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700552 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800553 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700554 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800555 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700556 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800557 }
Eric Laurent81784c32012-11-19 14:55:58 -0800558
559 if (locked) {
560 mLock.unlock();
561 }
562}
563
564void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
565{
566 const size_t SIZE = 256;
567 char buffer[SIZE];
568 String8 result;
569
Marco Nelissenb2208842014-02-07 14:00:50 -0800570 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000571 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800572 write(fd, buffer, strlen(buffer));
573
Marco Nelissenb2208842014-02-07 14:00:50 -0800574 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800575 sp<EffectChain> chain = mEffectChains[i];
576 if (chain != 0) {
577 chain->dump(fd, args);
578 }
579 }
580}
581
Marco Nelissene14a5d62013-10-03 08:51:24 -0700582void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800583{
584 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700585 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800586}
587
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100588String16 AudioFlinger::ThreadBase::getWakeLockTag()
589{
590 switch (mType) {
591 case MIXER:
592 return String16("AudioMix");
593 case DIRECT:
594 return String16("AudioDirectOut");
595 case DUPLICATING:
596 return String16("AudioDup");
597 case RECORD:
598 return String16("AudioIn");
599 case OFFLOAD:
600 return String16("AudioOffload");
601 default:
602 ALOG_ASSERT(false);
603 return String16("AudioUnknown");
604 }
605}
606
Marco Nelissene14a5d62013-10-03 08:51:24 -0700607void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800608{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800609 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800610 if (mPowerManager != 0) {
611 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700612 status_t status;
613 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700614 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700615 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100616 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700617 String16("media"),
618 uid);
619 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700620 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700621 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100622 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700623 String16("media"));
624 }
Eric Laurent81784c32012-11-19 14:55:58 -0800625 if (status == NO_ERROR) {
626 mWakeLockToken = binder;
627 }
628 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
629 }
630}
631
632void AudioFlinger::ThreadBase::releaseWakeLock()
633{
634 Mutex::Autolock _l(mLock);
635 releaseWakeLock_l();
636}
637
638void AudioFlinger::ThreadBase::releaseWakeLock_l()
639{
640 if (mWakeLockToken != 0) {
641 ALOGV("releaseWakeLock_l() %s", mName);
642 if (mPowerManager != 0) {
643 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
644 }
645 mWakeLockToken.clear();
646 }
647}
648
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800649void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
650 Mutex::Autolock _l(mLock);
651 updateWakeLockUids_l(uids);
652}
653
654void AudioFlinger::ThreadBase::getPowerManager_l() {
655
656 if (mPowerManager == 0) {
657 // use checkService() to avoid blocking if power service is not up yet
658 sp<IBinder> binder =
659 defaultServiceManager()->checkService(String16("power"));
660 if (binder == 0) {
661 ALOGW("Thread %s cannot connect to the power manager service", mName);
662 } else {
663 mPowerManager = interface_cast<IPowerManager>(binder);
664 binder->linkToDeath(mDeathRecipient);
665 }
666 }
667}
668
669void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
670
671 getPowerManager_l();
672 if (mWakeLockToken == NULL) {
673 ALOGE("no wake lock to update!");
674 return;
675 }
676 if (mPowerManager != 0) {
677 sp<IBinder> binder = new BBinder();
678 status_t status;
679 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
680 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
681 }
682}
683
Eric Laurent81784c32012-11-19 14:55:58 -0800684void AudioFlinger::ThreadBase::clearPowerManager()
685{
686 Mutex::Autolock _l(mLock);
687 releaseWakeLock_l();
688 mPowerManager.clear();
689}
690
Glenn Kasten0f11b512014-01-31 16:18:54 -0800691void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800692{
693 sp<ThreadBase> thread = mThread.promote();
694 if (thread != 0) {
695 thread->clearPowerManager();
696 }
697 ALOGW("power manager service died !!!");
698}
699
700void AudioFlinger::ThreadBase::setEffectSuspended(
701 const effect_uuid_t *type, bool suspend, int sessionId)
702{
703 Mutex::Autolock _l(mLock);
704 setEffectSuspended_l(type, suspend, sessionId);
705}
706
707void AudioFlinger::ThreadBase::setEffectSuspended_l(
708 const effect_uuid_t *type, bool suspend, int sessionId)
709{
710 sp<EffectChain> chain = getEffectChain_l(sessionId);
711 if (chain != 0) {
712 if (type != NULL) {
713 chain->setEffectSuspended_l(type, suspend);
714 } else {
715 chain->setEffectSuspendedAll_l(suspend);
716 }
717 }
718
719 updateSuspendedSessions_l(type, suspend, sessionId);
720}
721
722void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
723{
724 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
725 if (index < 0) {
726 return;
727 }
728
729 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
730 mSuspendedSessions.valueAt(index);
731
732 for (size_t i = 0; i < sessionEffects.size(); i++) {
733 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
734 for (int j = 0; j < desc->mRefCount; j++) {
735 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
736 chain->setEffectSuspendedAll_l(true);
737 } else {
738 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
739 desc->mType.timeLow);
740 chain->setEffectSuspended_l(&desc->mType, true);
741 }
742 }
743 }
744}
745
746void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
747 bool suspend,
748 int sessionId)
749{
750 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
751
752 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
753
754 if (suspend) {
755 if (index >= 0) {
756 sessionEffects = mSuspendedSessions.valueAt(index);
757 } else {
758 mSuspendedSessions.add(sessionId, sessionEffects);
759 }
760 } else {
761 if (index < 0) {
762 return;
763 }
764 sessionEffects = mSuspendedSessions.valueAt(index);
765 }
766
767
768 int key = EffectChain::kKeyForSuspendAll;
769 if (type != NULL) {
770 key = type->timeLow;
771 }
772 index = sessionEffects.indexOfKey(key);
773
774 sp<SuspendedSessionDesc> desc;
775 if (suspend) {
776 if (index >= 0) {
777 desc = sessionEffects.valueAt(index);
778 } else {
779 desc = new SuspendedSessionDesc();
780 if (type != NULL) {
781 desc->mType = *type;
782 }
783 sessionEffects.add(key, desc);
784 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
785 }
786 desc->mRefCount++;
787 } else {
788 if (index < 0) {
789 return;
790 }
791 desc = sessionEffects.valueAt(index);
792 if (--desc->mRefCount == 0) {
793 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
794 sessionEffects.removeItemsAt(index);
795 if (sessionEffects.isEmpty()) {
796 ALOGV("updateSuspendedSessions_l() restore removing session %d",
797 sessionId);
798 mSuspendedSessions.removeItem(sessionId);
799 }
800 }
801 }
802 if (!sessionEffects.isEmpty()) {
803 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
804 }
805}
806
807void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
808 bool enabled,
809 int sessionId)
810{
811 Mutex::Autolock _l(mLock);
812 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
813}
814
815void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
816 bool enabled,
817 int sessionId)
818{
819 if (mType != RECORD) {
820 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
821 // another session. This gives the priority to well behaved effect control panels
822 // and applications not using global effects.
823 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
824 // global effects
825 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
826 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
827 }
828 }
829
830 sp<EffectChain> chain = getEffectChain_l(sessionId);
831 if (chain != 0) {
832 chain->checkSuspendOnEffectEnabled(effect, enabled);
833 }
834}
835
836// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
837sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
838 const sp<AudioFlinger::Client>& client,
839 const sp<IEffectClient>& effectClient,
840 int32_t priority,
841 int sessionId,
842 effect_descriptor_t *desc,
843 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700844 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800845{
846 sp<EffectModule> effect;
847 sp<EffectHandle> handle;
848 status_t lStatus;
849 sp<EffectChain> chain;
850 bool chainCreated = false;
851 bool effectCreated = false;
852 bool effectRegistered = false;
853
854 lStatus = initCheck();
855 if (lStatus != NO_ERROR) {
856 ALOGW("createEffect_l() Audio driver not initialized.");
857 goto Exit;
858 }
859
Andy Hung98ef9782014-03-04 14:46:50 -0800860 // Reject any effect on Direct output threads for now, since the format of
861 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
862 if (mType == DIRECT) {
863 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
864 desc->name, mName);
865 lStatus = BAD_VALUE;
866 goto Exit;
867 }
868
Eric Laurent5baf2af2013-09-12 17:37:00 -0700869 // Allow global effects only on offloaded and mixer threads
870 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
871 switch (mType) {
872 case MIXER:
873 case OFFLOAD:
874 break;
875 case DIRECT:
876 case DUPLICATING:
877 case RECORD:
878 default:
879 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
880 lStatus = BAD_VALUE;
881 goto Exit;
882 }
Eric Laurent81784c32012-11-19 14:55:58 -0800883 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700884
Eric Laurent81784c32012-11-19 14:55:58 -0800885 // Only Pre processor effects are allowed on input threads and only on input threads
886 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
887 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
888 desc->name, desc->flags, mType);
889 lStatus = BAD_VALUE;
890 goto Exit;
891 }
892
893 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
894
895 { // scope for mLock
896 Mutex::Autolock _l(mLock);
897
898 // check for existing effect chain with the requested audio session
899 chain = getEffectChain_l(sessionId);
900 if (chain == 0) {
901 // create a new chain for this session
902 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
903 chain = new EffectChain(this, sessionId);
904 addEffectChain_l(chain);
905 chain->setStrategy(getStrategyForSession_l(sessionId));
906 chainCreated = true;
907 } else {
908 effect = chain->getEffectFromDesc_l(desc);
909 }
910
911 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
912
913 if (effect == 0) {
914 int id = mAudioFlinger->nextUniqueId();
915 // Check CPU and memory usage
916 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
917 if (lStatus != NO_ERROR) {
918 goto Exit;
919 }
920 effectRegistered = true;
921 // create a new effect module if none present in the chain
922 effect = new EffectModule(this, chain, desc, id, sessionId);
923 lStatus = effect->status();
924 if (lStatus != NO_ERROR) {
925 goto Exit;
926 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700927 effect->setOffloaded(mType == OFFLOAD, mId);
928
Eric Laurent81784c32012-11-19 14:55:58 -0800929 lStatus = chain->addEffect_l(effect);
930 if (lStatus != NO_ERROR) {
931 goto Exit;
932 }
933 effectCreated = true;
934
935 effect->setDevice(mOutDevice);
936 effect->setDevice(mInDevice);
937 effect->setMode(mAudioFlinger->getMode());
938 effect->setAudioSource(mAudioSource);
939 }
940 // create effect handle and connect it to effect module
941 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800942 lStatus = handle->initCheck();
943 if (lStatus == OK) {
944 lStatus = effect->addHandle(handle.get());
945 }
Eric Laurent81784c32012-11-19 14:55:58 -0800946 if (enabled != NULL) {
947 *enabled = (int)effect->isEnabled();
948 }
949 }
950
951Exit:
952 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
953 Mutex::Autolock _l(mLock);
954 if (effectCreated) {
955 chain->removeEffect_l(effect);
956 }
957 if (effectRegistered) {
958 AudioSystem::unregisterEffect(effect->id());
959 }
960 if (chainCreated) {
961 removeEffectChain_l(chain);
962 }
963 handle.clear();
964 }
965
Glenn Kasten9156ef32013-08-06 15:39:08 -0700966 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800967 return handle;
968}
969
970sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
971{
972 Mutex::Autolock _l(mLock);
973 return getEffect_l(sessionId, effectId);
974}
975
976sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
977{
978 sp<EffectChain> chain = getEffectChain_l(sessionId);
979 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
980}
981
982// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
983// PlaybackThread::mLock held
984status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
985{
986 // check for existing effect chain with the requested audio session
987 int sessionId = effect->sessionId();
988 sp<EffectChain> chain = getEffectChain_l(sessionId);
989 bool chainCreated = false;
990
Eric Laurent5baf2af2013-09-12 17:37:00 -0700991 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
992 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
993 this, effect->desc().name, effect->desc().flags);
994
Eric Laurent81784c32012-11-19 14:55:58 -0800995 if (chain == 0) {
996 // create a new chain for this session
997 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
998 chain = new EffectChain(this, sessionId);
999 addEffectChain_l(chain);
1000 chain->setStrategy(getStrategyForSession_l(sessionId));
1001 chainCreated = true;
1002 }
1003 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1004
1005 if (chain->getEffectFromId_l(effect->id()) != 0) {
1006 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1007 this, effect->desc().name, chain.get());
1008 return BAD_VALUE;
1009 }
1010
Eric Laurent5baf2af2013-09-12 17:37:00 -07001011 effect->setOffloaded(mType == OFFLOAD, mId);
1012
Eric Laurent81784c32012-11-19 14:55:58 -08001013 status_t status = chain->addEffect_l(effect);
1014 if (status != NO_ERROR) {
1015 if (chainCreated) {
1016 removeEffectChain_l(chain);
1017 }
1018 return status;
1019 }
1020
1021 effect->setDevice(mOutDevice);
1022 effect->setDevice(mInDevice);
1023 effect->setMode(mAudioFlinger->getMode());
1024 effect->setAudioSource(mAudioSource);
1025 return NO_ERROR;
1026}
1027
1028void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1029
1030 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1031 effect_descriptor_t desc = effect->desc();
1032 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1033 detachAuxEffect_l(effect->id());
1034 }
1035
1036 sp<EffectChain> chain = effect->chain().promote();
1037 if (chain != 0) {
1038 // remove effect chain if removing last effect
1039 if (chain->removeEffect_l(effect) == 0) {
1040 removeEffectChain_l(chain);
1041 }
1042 } else {
1043 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1044 }
1045}
1046
1047void AudioFlinger::ThreadBase::lockEffectChains_l(
1048 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1049{
1050 effectChains = mEffectChains;
1051 for (size_t i = 0; i < mEffectChains.size(); i++) {
1052 mEffectChains[i]->lock();
1053 }
1054}
1055
1056void AudioFlinger::ThreadBase::unlockEffectChains(
1057 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1058{
1059 for (size_t i = 0; i < effectChains.size(); i++) {
1060 effectChains[i]->unlock();
1061 }
1062}
1063
1064sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1065{
1066 Mutex::Autolock _l(mLock);
1067 return getEffectChain_l(sessionId);
1068}
1069
1070sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1071{
1072 size_t size = mEffectChains.size();
1073 for (size_t i = 0; i < size; i++) {
1074 if (mEffectChains[i]->sessionId() == sessionId) {
1075 return mEffectChains[i];
1076 }
1077 }
1078 return 0;
1079}
1080
1081void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1082{
1083 Mutex::Autolock _l(mLock);
1084 size_t size = mEffectChains.size();
1085 for (size_t i = 0; i < size; i++) {
1086 mEffectChains[i]->setMode_l(mode);
1087 }
1088}
1089
1090void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1091 EffectHandle *handle,
1092 bool unpinIfLast) {
1093
1094 Mutex::Autolock _l(mLock);
1095 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1096 // delete the effect module if removing last handle on it
1097 if (effect->removeHandle(handle) == 0) {
1098 if (!effect->isPinned() || unpinIfLast) {
1099 removeEffect_l(effect);
1100 AudioSystem::unregisterEffect(effect->id());
1101 }
1102 }
1103}
1104
1105// ----------------------------------------------------------------------------
1106// Playback
1107// ----------------------------------------------------------------------------
1108
1109AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1110 AudioStreamOut* output,
1111 audio_io_handle_t id,
1112 audio_devices_t device,
1113 type_t type)
1114 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001115 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001116 mMixerBufferEnabled(false),
1117 mMixerBuffer(NULL),
1118 mMixerBufferSize(0),
1119 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1120 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001121 mEffectBufferEnabled(false),
1122 mEffectBuffer(NULL),
1123 mEffectBufferSize(0),
1124 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1125 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001126 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001127 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001128 // mStreamTypes[] initialized in constructor body
1129 mOutput(output),
1130 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1131 mMixerStatus(MIXER_IDLE),
1132 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1133 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001134 mBytesRemaining(0),
1135 mCurrentWriteLength(0),
1136 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001137 mWriteAckSequence(0),
1138 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001139 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001140 mScreenState(AudioFlinger::mScreenState),
1141 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001142 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1143 // mLatchD, mLatchQ,
1144 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001147 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001148
1149 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1150 // it would be safer to explicitly pass initial masterVolume/masterMute as
1151 // parameter.
1152 //
1153 // If the HAL we are using has support for master volume or master mute,
1154 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1155 // and the mute set to false).
1156 mMasterVolume = audioFlinger->masterVolume_l();
1157 mMasterMute = audioFlinger->masterMute_l();
1158 if (mOutput && mOutput->audioHwDev) {
1159 if (mOutput->audioHwDev->canSetMasterVolume()) {
1160 mMasterVolume = 1.0;
1161 }
1162
1163 if (mOutput->audioHwDev->canSetMasterMute()) {
1164 mMasterMute = false;
1165 }
1166 }
1167
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001168 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001169
1170 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1171 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001172 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001173 stream = (audio_stream_type_t) (stream + 1)) {
1174 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1175 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1176 }
1177 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1178 // because mAudioFlinger doesn't have one to copy from
1179}
1180
1181AudioFlinger::PlaybackThread::~PlaybackThread()
1182{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001183 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001184 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001185 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001186 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001187}
1188
1189void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1190{
1191 dumpInternals(fd, args);
1192 dumpTracks(fd, args);
1193 dumpEffectChains(fd, args);
1194}
1195
Glenn Kasten0f11b512014-01-31 16:18:54 -08001196void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001197{
1198 const size_t SIZE = 256;
1199 char buffer[SIZE];
1200 String8 result;
1201
Marco Nelissenb2208842014-02-07 14:00:50 -08001202 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001203 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1204 const stream_type_t *st = &mStreamTypes[i];
1205 if (i > 0) {
1206 result.appendFormat(", ");
1207 }
1208 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1209 if (st->mute) {
1210 result.append("M");
1211 }
1212 }
1213 result.append("\n");
1214 write(fd, result.string(), result.length());
1215 result.clear();
1216
Eric Laurent81784c32012-11-19 14:55:58 -08001217 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1218 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001219 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001220 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001221
1222 size_t numtracks = mTracks.size();
1223 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001224 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001225 size_t numactiveseen = 0;
1226 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001227 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001228 Track::appendDumpHeader(result);
1229 for (size_t i = 0; i < numtracks; ++i) {
1230 sp<Track> track = mTracks[i];
1231 if (track != 0) {
1232 bool active = mActiveTracks.indexOf(track) >= 0;
1233 if (active) {
1234 numactiveseen++;
1235 }
1236 track->dump(buffer, SIZE, active);
1237 result.append(buffer);
1238 }
1239 }
1240 } else {
1241 result.append("\n");
1242 }
1243 if (numactiveseen != numactive) {
1244 // some tracks in the active list were not in the tracks list
1245 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1246 " not in the track list\n");
1247 result.append(buffer);
1248 Track::appendDumpHeader(result);
1249 for (size_t i = 0; i < numactive; ++i) {
1250 sp<Track> track = mActiveTracks[i].promote();
1251 if (track != 0 && mTracks.indexOf(track) < 0) {
1252 track->dump(buffer, SIZE, true);
1253 result.append(buffer);
1254 }
1255 }
1256 }
1257
1258 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001259}
1260
1261void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1262{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001263 dprintf(fd, "\nOutput thread %p:\n", this);
1264 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1265 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1266 dprintf(fd, " Total writes: %d\n", mNumWrites);
1267 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1268 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1269 dprintf(fd, " Suspend count: %d\n", mSuspended);
1270 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1271 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1272 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1273 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001274
1275 dumpBase(fd, args);
1276}
1277
1278// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001279
1280void AudioFlinger::PlaybackThread::onFirstRef()
1281{
1282 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1283}
1284
1285// ThreadBase virtuals
1286void AudioFlinger::PlaybackThread::preExit()
1287{
1288 ALOGV(" preExit()");
1289 // FIXME this is using hard-coded strings but in the future, this functionality will be
1290 // converted to use audio HAL extensions required to support tunneling
1291 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1292}
1293
1294// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1295sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1296 const sp<AudioFlinger::Client>& client,
1297 audio_stream_type_t streamType,
1298 uint32_t sampleRate,
1299 audio_format_t format,
1300 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001301 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001302 const sp<IMemory>& sharedBuffer,
1303 int sessionId,
1304 IAudioFlinger::track_flags_t *flags,
1305 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001306 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001307 status_t *status)
1308{
Glenn Kasten74935e42013-12-19 08:56:45 -08001309 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001310 sp<Track> track;
1311 status_t lStatus;
1312
1313 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1314
1315 // client expresses a preference for FAST, but we get the final say
1316 if (*flags & IAudioFlinger::TRACK_FAST) {
1317 if (
1318 // not timed
1319 (!isTimed) &&
1320 // either of these use cases:
1321 (
1322 // use case 1: shared buffer with any frame count
1323 (
1324 (sharedBuffer != 0)
1325 ) ||
1326 // use case 2: callback handler and frame count is default or at least as large as HAL
1327 (
1328 (tid != -1) &&
1329 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001330 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001331 )
1332 ) &&
1333 // PCM data
1334 audio_is_linear_pcm(format) &&
1335 // mono or stereo
1336 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1337 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001338 // hardware sample rate
1339 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001340 // normal mixer has an associated fast mixer
1341 hasFastMixer() &&
1342 // there are sufficient fast track slots available
1343 (mFastTrackAvailMask != 0)
1344 // FIXME test that MixerThread for this fast track has a capable output HAL
1345 // FIXME add a permission test also?
1346 ) {
1347 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1348 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001349 // read the fast track multiplier property the first time it is needed
1350 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1351 if (ok != 0) {
1352 ALOGE("%s pthread_once failed: %d", __func__, ok);
1353 }
1354 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001355 }
1356 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1357 frameCount, mFrameCount);
1358 } else {
1359 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1360 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1361 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1362 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1363 audio_is_linear_pcm(format),
1364 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1365 *flags &= ~IAudioFlinger::TRACK_FAST;
1366 // For compatibility with AudioTrack calculation, buffer depth is forced
1367 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1368 // This is probably too conservative, but legacy application code may depend on it.
1369 // If you change this calculation, also review the start threshold which is related.
1370 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1371 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1372 if (minBufCount < 2) {
1373 minBufCount = 2;
1374 }
1375 size_t minFrameCount = mNormalFrameCount * minBufCount;
1376 if (frameCount < minFrameCount) {
1377 frameCount = minFrameCount;
1378 }
1379 }
1380 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001381 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001382
Glenn Kastenc3df8382014-03-13 15:05:25 -07001383 switch (mType) {
1384
1385 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001386 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001387 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001388 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1389 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001390 sampleRate, format, channelMask, mOutput, mFormat);
1391 lStatus = BAD_VALUE;
1392 goto Exit;
1393 }
1394 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001395 break;
1396
1397 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001398 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001399 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1400 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001401 sampleRate, format, channelMask, mOutput, mFormat);
1402 lStatus = BAD_VALUE;
1403 goto Exit;
1404 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001405 break;
1406
1407 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001408 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001409 ALOGE("createTrack_l() Bad parameter: format %#x \""
1410 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001411 format, mOutput, mFormat);
1412 lStatus = BAD_VALUE;
1413 goto Exit;
1414 }
Eric Laurent81784c32012-11-19 14:55:58 -08001415 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1416 if (sampleRate > mSampleRate*2) {
1417 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1418 lStatus = BAD_VALUE;
1419 goto Exit;
1420 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001421 break;
1422
Eric Laurent81784c32012-11-19 14:55:58 -08001423 }
1424
1425 lStatus = initCheck();
1426 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001427 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001428 goto Exit;
1429 }
1430
1431 { // scope for mLock
1432 Mutex::Autolock _l(mLock);
1433
1434 // all tracks in same audio session must share the same routing strategy otherwise
1435 // conflicts will happen when tracks are moved from one output to another by audio policy
1436 // manager
1437 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1438 for (size_t i = 0; i < mTracks.size(); ++i) {
1439 sp<Track> t = mTracks[i];
1440 if (t != 0 && !t->isOutputTrack()) {
1441 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1442 if (sessionId == t->sessionId() && strategy != actual) {
1443 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1444 strategy, actual);
1445 lStatus = BAD_VALUE;
1446 goto Exit;
1447 }
1448 }
1449 }
1450
1451 if (!isTimed) {
1452 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001453 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001454 } else {
1455 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001456 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001457 }
Glenn Kasten03003332013-08-06 15:40:54 -07001458
1459 // new Track always returns non-NULL,
1460 // but TimedTrack::create() is a factory that could fail by returning NULL
1461 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1462 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001463 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001464 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001465 goto Exit;
1466 }
1467 mTracks.add(track);
1468
1469 sp<EffectChain> chain = getEffectChain_l(sessionId);
1470 if (chain != 0) {
1471 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1472 track->setMainBuffer(chain->inBuffer());
1473 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1474 chain->incTrackCnt();
1475 }
1476
1477 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1478 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1479 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1480 // so ask activity manager to do this on our behalf
1481 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1482 }
1483 }
1484
1485 lStatus = NO_ERROR;
1486
1487Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001488 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001489 return track;
1490}
1491
1492uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1493{
1494 return latency;
1495}
1496
1497uint32_t AudioFlinger::PlaybackThread::latency() const
1498{
1499 Mutex::Autolock _l(mLock);
1500 return latency_l();
1501}
1502uint32_t AudioFlinger::PlaybackThread::latency_l() const
1503{
1504 if (initCheck() == NO_ERROR) {
1505 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1506 } else {
1507 return 0;
1508 }
1509}
1510
1511void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1512{
1513 Mutex::Autolock _l(mLock);
1514 // Don't apply master volume in SW if our HAL can do it for us.
1515 if (mOutput && mOutput->audioHwDev &&
1516 mOutput->audioHwDev->canSetMasterVolume()) {
1517 mMasterVolume = 1.0;
1518 } else {
1519 mMasterVolume = value;
1520 }
1521}
1522
1523void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1524{
1525 Mutex::Autolock _l(mLock);
1526 // Don't apply master mute in SW if our HAL can do it for us.
1527 if (mOutput && mOutput->audioHwDev &&
1528 mOutput->audioHwDev->canSetMasterMute()) {
1529 mMasterMute = false;
1530 } else {
1531 mMasterMute = muted;
1532 }
1533}
1534
1535void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1536{
1537 Mutex::Autolock _l(mLock);
1538 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001539 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001540}
1541
1542void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1543{
1544 Mutex::Autolock _l(mLock);
1545 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001546 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001547}
1548
1549float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1550{
1551 Mutex::Autolock _l(mLock);
1552 return mStreamTypes[stream].volume;
1553}
1554
1555// addTrack_l() must be called with ThreadBase::mLock held
1556status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1557{
1558 status_t status = ALREADY_EXISTS;
1559
1560 // set retry count for buffer fill
1561 track->mRetryCount = kMaxTrackStartupRetries;
1562 if (mActiveTracks.indexOf(track) < 0) {
1563 // the track is newly added, make sure it fills up all its
1564 // buffers before playing. This is to ensure the client will
1565 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001566 if (!track->isOutputTrack()) {
1567 TrackBase::track_state state = track->mState;
1568 mLock.unlock();
1569 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1570 mLock.lock();
1571 // abort track was stopped/paused while we released the lock
1572 if (state != track->mState) {
1573 if (status == NO_ERROR) {
1574 mLock.unlock();
1575 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1576 mLock.lock();
1577 }
1578 return INVALID_OPERATION;
1579 }
1580 // abort if start is rejected by audio policy manager
1581 if (status != NO_ERROR) {
1582 return PERMISSION_DENIED;
1583 }
1584#ifdef ADD_BATTERY_DATA
1585 // to track the speaker usage
1586 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1587#endif
1588 }
1589
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001590 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001591 track->mResetDone = false;
1592 track->mPresentationCompleteFrames = 0;
1593 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001594 mWakeLockUids.add(track->uid());
1595 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001596 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001597 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1598 if (chain != 0) {
1599 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1600 track->sessionId());
1601 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001602 }
1603
1604 status = NO_ERROR;
1605 }
1606
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001607 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001608 return status;
1609}
1610
Eric Laurentbfb1b832013-01-07 09:53:42 -08001611bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001612{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001613 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001614 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001615 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1616 track->mState = TrackBase::STOPPED;
1617 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001618 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619 } else if (track->isFastTrack() || track->isOffloaded()) {
1620 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001621 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001622
1623 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001624}
1625
1626void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1627{
1628 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1629 mTracks.remove(track);
1630 deleteTrackName_l(track->name());
1631 // redundant as track is about to be destroyed, for dumpsys only
1632 track->mName = -1;
1633 if (track->isFastTrack()) {
1634 int index = track->mFastIndex;
1635 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1636 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1637 mFastTrackAvailMask |= 1 << index;
1638 // redundant as track is about to be destroyed, for dumpsys only
1639 track->mFastIndex = -1;
1640 }
1641 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1642 if (chain != 0) {
1643 chain->decTrackCnt();
1644 }
1645}
1646
Eric Laurentede6c3b2013-09-19 14:37:46 -07001647void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001648{
1649 // Thread could be blocked waiting for async
1650 // so signal it to handle state changes immediately
1651 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1652 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1653 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001654 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655}
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1658{
Eric Laurent81784c32012-11-19 14:55:58 -08001659 Mutex::Autolock _l(mLock);
1660 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001661 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001662 }
1663
Glenn Kastend8ea6992013-07-16 14:17:15 -07001664 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1665 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001666 free(s);
1667 return out_s8;
1668}
1669
Eric Laurent021cf962014-05-13 10:18:14 -07001670void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001671 AudioSystem::OutputDescriptor desc;
1672 void *param2 = NULL;
1673
Eric Laurent021cf962014-05-13 10:18:14 -07001674 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001675 param);
1676
1677 switch (event) {
1678 case AudioSystem::OUTPUT_OPENED:
1679 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001680 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001681 desc.samplingRate = mSampleRate;
1682 desc.format = mFormat;
1683 desc.frameCount = mNormalFrameCount; // FIXME see
1684 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001685 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001686 param2 = &desc;
1687 break;
1688
1689 case AudioSystem::STREAM_CONFIG_CHANGED:
1690 param2 = &param;
1691 case AudioSystem::OUTPUT_CLOSED:
1692 default:
1693 break;
1694 }
Eric Laurent021cf962014-05-13 10:18:14 -07001695 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001696}
1697
Eric Laurentbfb1b832013-01-07 09:53:42 -08001698void AudioFlinger::PlaybackThread::writeCallback()
1699{
1700 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001701 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001702}
1703
1704void AudioFlinger::PlaybackThread::drainCallback()
1705{
1706 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001707 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001708}
1709
Eric Laurent3b4529e2013-09-05 18:09:19 -07001710void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001711{
1712 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001713 // reject out of sequence requests
1714 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1715 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001716 mWaitWorkCV.signal();
1717 }
1718}
1719
Eric Laurent3b4529e2013-09-05 18:09:19 -07001720void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001721{
1722 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001723 // reject out of sequence requests
1724 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1725 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001726 mWaitWorkCV.signal();
1727 }
1728}
1729
1730// static
1731int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001732 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001733 void *cookie)
1734{
1735 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1736 ALOGV("asyncCallback() event %d", event);
1737 switch (event) {
1738 case STREAM_CBK_EVENT_WRITE_READY:
1739 me->writeCallback();
1740 break;
1741 case STREAM_CBK_EVENT_DRAIN_READY:
1742 me->drainCallback();
1743 break;
1744 default:
1745 ALOGW("asyncCallback() unknown event %d", event);
1746 break;
1747 }
1748 return 0;
1749}
1750
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001751void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001752{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001753 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001754 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1755 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001756 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001757 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001758 }
1759 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001760 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001761 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1762 }
Andy Hunge5412692014-05-16 11:25:07 -07001763 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001764 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001765 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001766 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001767 }
1768 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001769 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1770 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001771 }
Eric Laurent81784c32012-11-19 14:55:58 -08001772 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001773 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1774 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001775 if (mFrameCount & 15) {
1776 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1777 mFrameCount);
1778 }
1779
Eric Laurentbfb1b832013-01-07 09:53:42 -08001780 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1781 (mOutput->stream->set_callback != NULL)) {
1782 if (mOutput->stream->set_callback(mOutput->stream,
1783 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1784 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001785 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001786 }
1787 }
1788
Andy Hung09a50072014-02-27 14:30:47 -08001789 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001790 double multiplier = 1.0;
1791 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1792 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001793 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1794 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001795 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1796 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1797 maxNormalFrameCount = maxNormalFrameCount & ~15;
1798 if (maxNormalFrameCount < minNormalFrameCount) {
1799 maxNormalFrameCount = minNormalFrameCount;
1800 }
1801 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1802 if (multiplier <= 1.0) {
1803 multiplier = 1.0;
1804 } else if (multiplier <= 2.0) {
1805 if (2 * mFrameCount <= maxNormalFrameCount) {
1806 multiplier = 2.0;
1807 } else {
1808 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1809 }
1810 } else {
1811 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001812 // 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 -08001813 // track, but we sometimes have to do this to satisfy the maximum frame count
1814 // constraint)
1815 // FIXME this rounding up should not be done if no HAL SRC
1816 uint32_t truncMult = (uint32_t) multiplier;
1817 if ((truncMult & 1)) {
1818 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1819 ++truncMult;
1820 }
1821 }
1822 multiplier = (double) truncMult;
1823 }
1824 }
1825 mNormalFrameCount = multiplier * mFrameCount;
1826 // round up to nearest 16 frames to satisfy AudioMixer
1827 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001828 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001829 mNormalFrameCount);
1830
Andy Hung010a1a12014-03-13 13:57:33 -07001831 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1832 // Originally this was int16_t[] array, need to remove legacy implications.
1833 free(mSinkBuffer);
1834 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001835 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1836 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1837 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001838 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001839
Andy Hung69aed5f2014-02-25 17:24:40 -08001840 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1841 // drives the output.
1842 free(mMixerBuffer);
1843 mMixerBuffer = NULL;
1844 if (mMixerBufferEnabled) {
1845 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1846 mMixerBufferSize = mNormalFrameCount * mChannelCount
1847 * audio_bytes_per_sample(mMixerBufferFormat);
1848 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1849 }
Andy Hung98ef9782014-03-04 14:46:50 -08001850 free(mEffectBuffer);
1851 mEffectBuffer = NULL;
1852 if (mEffectBufferEnabled) {
1853 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1854 mEffectBufferSize = mNormalFrameCount * mChannelCount
1855 * audio_bytes_per_sample(mEffectBufferFormat);
1856 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1857 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001858
Eric Laurent81784c32012-11-19 14:55:58 -08001859 // force reconfiguration of effect chains and engines to take new buffer size and audio
1860 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001861 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001862 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1863 // matter.
1864 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1865 Vector< sp<EffectChain> > effectChains = mEffectChains;
1866 for (size_t i = 0; i < effectChains.size(); i ++) {
1867 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1868 }
1869}
1870
1871
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001872status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001873{
1874 if (halFrames == NULL || dspFrames == NULL) {
1875 return BAD_VALUE;
1876 }
1877 Mutex::Autolock _l(mLock);
1878 if (initCheck() != NO_ERROR) {
1879 return INVALID_OPERATION;
1880 }
1881 size_t framesWritten = mBytesWritten / mFrameSize;
1882 *halFrames = framesWritten;
1883
1884 if (isSuspended()) {
1885 // return an estimation of rendered frames when the output is suspended
1886 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1887 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1888 return NO_ERROR;
1889 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001890 status_t status;
1891 uint32_t frames;
1892 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1893 *dspFrames = (size_t)frames;
1894 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001895 }
1896}
1897
1898uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1899{
1900 Mutex::Autolock _l(mLock);
1901 uint32_t result = 0;
1902 if (getEffectChain_l(sessionId) != 0) {
1903 result = EFFECT_SESSION;
1904 }
1905
1906 for (size_t i = 0; i < mTracks.size(); ++i) {
1907 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001908 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001909 result |= TRACK_SESSION;
1910 break;
1911 }
1912 }
1913
1914 return result;
1915}
1916
1917uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1918{
1919 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1920 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1921 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1922 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1923 }
1924 for (size_t i = 0; i < mTracks.size(); i++) {
1925 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001926 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001927 return AudioSystem::getStrategyForStream(track->streamType());
1928 }
1929 }
1930 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1931}
1932
1933
1934AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1935{
1936 Mutex::Autolock _l(mLock);
1937 return mOutput;
1938}
1939
1940AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1941{
1942 Mutex::Autolock _l(mLock);
1943 AudioStreamOut *output = mOutput;
1944 mOutput = NULL;
1945 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1946 // must push a NULL and wait for ack
1947 mOutputSink.clear();
1948 mPipeSink.clear();
1949 mNormalSink.clear();
1950 return output;
1951}
1952
1953// this method must always be called either with ThreadBase mLock held or inside the thread loop
1954audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1955{
1956 if (mOutput == NULL) {
1957 return NULL;
1958 }
1959 return &mOutput->stream->common;
1960}
1961
1962uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1963{
1964 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1965}
1966
1967status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1968{
1969 if (!isValidSyncEvent(event)) {
1970 return BAD_VALUE;
1971 }
1972
1973 Mutex::Autolock _l(mLock);
1974
1975 for (size_t i = 0; i < mTracks.size(); ++i) {
1976 sp<Track> track = mTracks[i];
1977 if (event->triggerSession() == track->sessionId()) {
1978 (void) track->setSyncEvent(event);
1979 return NO_ERROR;
1980 }
1981 }
1982
1983 return NAME_NOT_FOUND;
1984}
1985
1986bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1987{
1988 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1989}
1990
1991void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1992 const Vector< sp<Track> >& tracksToRemove)
1993{
1994 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001995 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001996 for (size_t i = 0 ; i < count ; i++) {
1997 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001998 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001999 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002000#ifdef ADD_BATTERY_DATA
2001 // to track the speaker usage
2002 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2003#endif
2004 if (track->isTerminated()) {
2005 AudioSystem::releaseOutput(mId);
2006 }
Eric Laurent81784c32012-11-19 14:55:58 -08002007 }
2008 }
2009 }
Eric Laurent81784c32012-11-19 14:55:58 -08002010}
2011
2012void AudioFlinger::PlaybackThread::checkSilentMode_l()
2013{
2014 if (!mMasterMute) {
2015 char value[PROPERTY_VALUE_MAX];
2016 if (property_get("ro.audio.silent", value, "0") > 0) {
2017 char *endptr;
2018 unsigned long ul = strtoul(value, &endptr, 0);
2019 if (*endptr == '\0' && ul != 0) {
2020 ALOGD("Silence is golden");
2021 // The setprop command will not allow a property to be changed after
2022 // the first time it is set, so we don't have to worry about un-muting.
2023 setMasterMute_l(true);
2024 }
2025 }
2026 }
2027}
2028
2029// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002030ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002031{
2032 // FIXME rewrite to reduce number of system calls
2033 mLastWriteTime = systemTime();
2034 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002036 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002037
2038 // If an NBAIO sink is present, use it to write the normal mixer's submix
2039 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002040 const size_t count = mBytesRemaining / mFrameSize;
2041
Simon Wilson2d590962012-11-29 15:18:50 -08002042 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002043 // update the setpoint when AudioFlinger::mScreenState changes
2044 uint32_t screenState = AudioFlinger::mScreenState;
2045 if (screenState != mScreenState) {
2046 mScreenState = screenState;
2047 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2048 if (pipe != NULL) {
2049 pipe->setAvgFrames((mScreenState & 1) ?
2050 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2051 }
2052 }
Andy Hung010a1a12014-03-13 13:57:33 -07002053 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002054 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002055 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002056 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002057 } else {
2058 bytesWritten = framesWritten;
2059 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002060 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002061 if (status == NO_ERROR) {
2062 size_t totalFramesWritten = mNormalSink->framesWritten();
2063 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2064 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2065 mLatchDValid = true;
2066 }
2067 }
Eric Laurent81784c32012-11-19 14:55:58 -08002068 // otherwise use the HAL / AudioStreamOut directly
2069 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002070 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002071
Eric Laurentbfb1b832013-01-07 09:53:42 -08002072 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002073 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2074 mWriteAckSequence += 2;
2075 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002076 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002077 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002079 // FIXME We should have an implementation of timestamps for direct output threads.
2080 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002081 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002082 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002083 if (mUseAsyncWrite &&
2084 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2085 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002086 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002087 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002088 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089 }
Eric Laurent81784c32012-11-19 14:55:58 -08002090 }
2091
Eric Laurent81784c32012-11-19 14:55:58 -08002092 mNumWrites++;
2093 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002094 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002095 return bytesWritten;
2096}
2097
2098void AudioFlinger::PlaybackThread::threadLoop_drain()
2099{
2100 if (mOutput->stream->drain) {
2101 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2102 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002103 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2104 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002106 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002107 }
2108 mOutput->stream->drain(mOutput->stream,
2109 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2110 : AUDIO_DRAIN_ALL);
2111 }
2112}
2113
2114void AudioFlinger::PlaybackThread::threadLoop_exit()
2115{
2116 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002117}
2118
2119/*
2120The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002121 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002122 - activeSleepTime from activeSleepTimeUs()
2123 - idleSleepTime from idleSleepTimeUs()
2124 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2125 - maxPeriod from frame count and sample rate (MIXER only)
2126
2127The parameters that affect these derived values are:
2128 - frame count
2129 - frame size
2130 - sample rate
2131 - device type: A2DP or not
2132 - device latency
2133 - format: PCM or not
2134 - active sleep time
2135 - idle sleep time
2136*/
2137
2138void AudioFlinger::PlaybackThread::cacheParameters_l()
2139{
Andy Hung25c2dac2014-02-27 14:56:00 -08002140 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002141 activeSleepTime = activeSleepTimeUs();
2142 idleSleepTime = idleSleepTimeUs();
2143}
2144
2145void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2146{
Glenn Kasten7c027242012-12-26 14:43:16 -08002147 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002148 this, streamType, mTracks.size());
2149 Mutex::Autolock _l(mLock);
2150
2151 size_t size = mTracks.size();
2152 for (size_t i = 0; i < size; i++) {
2153 sp<Track> t = mTracks[i];
2154 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002155 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002156 }
2157 }
2158}
2159
2160status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2161{
2162 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002163 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2164 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002165 bool ownsBuffer = false;
2166
2167 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2168 if (session > 0) {
2169 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002170 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002171 if (mType != DIRECT) {
2172 size_t numSamples = mNormalFrameCount * mChannelCount;
2173 buffer = new int16_t[numSamples];
2174 memset(buffer, 0, numSamples * sizeof(int16_t));
2175 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2176 ownsBuffer = true;
2177 }
2178
2179 // Attach all tracks with same session ID to this chain.
2180 for (size_t i = 0; i < mTracks.size(); ++i) {
2181 sp<Track> track = mTracks[i];
2182 if (session == track->sessionId()) {
2183 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2184 buffer);
2185 track->setMainBuffer(buffer);
2186 chain->incTrackCnt();
2187 }
2188 }
2189
2190 // indicate all active tracks in the chain
2191 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2192 sp<Track> track = mActiveTracks[i].promote();
2193 if (track == 0) {
2194 continue;
2195 }
2196 if (session == track->sessionId()) {
2197 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2198 chain->incActiveTrackCnt();
2199 }
2200 }
2201 }
2202
2203 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002204 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2205 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002206 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2207 // chains list in order to be processed last as it contains output stage effects
2208 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2209 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2210 // after track specific effects and before output stage
2211 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2212 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2213 // Effect chain for other sessions are inserted at beginning of effect
2214 // chains list to be processed before output mix effects. Relative order between other
2215 // sessions is not important
2216 size_t size = mEffectChains.size();
2217 size_t i = 0;
2218 for (i = 0; i < size; i++) {
2219 if (mEffectChains[i]->sessionId() < session) {
2220 break;
2221 }
2222 }
2223 mEffectChains.insertAt(chain, i);
2224 checkSuspendOnAddEffectChain_l(chain);
2225
2226 return NO_ERROR;
2227}
2228
2229size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2230{
2231 int session = chain->sessionId();
2232
2233 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2234
2235 for (size_t i = 0; i < mEffectChains.size(); i++) {
2236 if (chain == mEffectChains[i]) {
2237 mEffectChains.removeAt(i);
2238 // detach all active tracks from the chain
2239 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2240 sp<Track> track = mActiveTracks[i].promote();
2241 if (track == 0) {
2242 continue;
2243 }
2244 if (session == track->sessionId()) {
2245 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2246 chain.get(), session);
2247 chain->decActiveTrackCnt();
2248 }
2249 }
2250
2251 // detach all tracks with same session ID from this chain
2252 for (size_t i = 0; i < mTracks.size(); ++i) {
2253 sp<Track> track = mTracks[i];
2254 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002255 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002256 chain->decTrackCnt();
2257 }
2258 }
2259 break;
2260 }
2261 }
2262 return mEffectChains.size();
2263}
2264
2265status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2266 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2267{
2268 Mutex::Autolock _l(mLock);
2269 return attachAuxEffect_l(track, EffectId);
2270}
2271
2272status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2273 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2274{
2275 status_t status = NO_ERROR;
2276
2277 if (EffectId == 0) {
2278 track->setAuxBuffer(0, NULL);
2279 } else {
2280 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2281 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2282 if (effect != 0) {
2283 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2284 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2285 } else {
2286 status = INVALID_OPERATION;
2287 }
2288 } else {
2289 status = BAD_VALUE;
2290 }
2291 }
2292 return status;
2293}
2294
2295void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2296{
2297 for (size_t i = 0; i < mTracks.size(); ++i) {
2298 sp<Track> track = mTracks[i];
2299 if (track->auxEffectId() == effectId) {
2300 attachAuxEffect_l(track, 0);
2301 }
2302 }
2303}
2304
2305bool AudioFlinger::PlaybackThread::threadLoop()
2306{
2307 Vector< sp<Track> > tracksToRemove;
2308
2309 standbyTime = systemTime();
2310
2311 // MIXER
2312 nsecs_t lastWarning = 0;
2313
2314 // DUPLICATING
2315 // FIXME could this be made local to while loop?
2316 writeFrames = 0;
2317
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002318 int lastGeneration = 0;
2319
Eric Laurent81784c32012-11-19 14:55:58 -08002320 cacheParameters_l();
2321 sleepTime = idleSleepTime;
2322
2323 if (mType == MIXER) {
2324 sleepTimeShift = 0;
2325 }
2326
2327 CpuStats cpuStats;
2328 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2329
2330 acquireWakeLock();
2331
Glenn Kasten9e58b552013-01-18 15:09:48 -08002332 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2333 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2334 // and then that string will be logged at the next convenient opportunity.
2335 const char *logString = NULL;
2336
Eric Laurent664539d2013-09-23 18:24:31 -07002337 checkSilentMode_l();
2338
Eric Laurent81784c32012-11-19 14:55:58 -08002339 while (!exitPending())
2340 {
2341 cpuStats.sample(myName);
2342
2343 Vector< sp<EffectChain> > effectChains;
2344
Eric Laurent81784c32012-11-19 14:55:58 -08002345 { // scope for mLock
2346
2347 Mutex::Autolock _l(mLock);
2348
Eric Laurent021cf962014-05-13 10:18:14 -07002349 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002350
Glenn Kasten9e58b552013-01-18 15:09:48 -08002351 if (logString != NULL) {
2352 mNBLogWriter->logTimestamp();
2353 mNBLogWriter->log(logString);
2354 logString = NULL;
2355 }
2356
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002357 if (mLatchDValid) {
2358 mLatchQ = mLatchD;
2359 mLatchDValid = false;
2360 mLatchQValid = true;
2361 }
2362
Eric Laurent81784c32012-11-19 14:55:58 -08002363 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 if (mSignalPending) {
2365 // A signal was raised while we were unlocked
2366 mSignalPending = false;
2367 } else if (waitingAsyncCallback_l()) {
2368 if (exitPending()) {
2369 break;
2370 }
2371 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002372 mWakeLockUids.clear();
2373 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374 ALOGV("wait async completion");
2375 mWaitWorkCV.wait(mLock);
2376 ALOGV("async completion/wake");
2377 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002378 standbyTime = systemTime() + standbyDelay;
2379 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002380
2381 continue;
2382 }
2383 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002384 isSuspended()) {
2385 // put audio hardware into standby after short delay
2386 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002387
2388 threadLoop_standby();
2389
2390 mStandby = true;
2391 }
2392
2393 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2394 // we're about to wait, flush the binder command buffer
2395 IPCThreadState::self()->flushCommands();
2396
2397 clearOutputTracks();
2398
2399 if (exitPending()) {
2400 break;
2401 }
2402
2403 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002404 mWakeLockUids.clear();
2405 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002406 // wait until we have something to do...
2407 ALOGV("%s going to sleep", myName.string());
2408 mWaitWorkCV.wait(mLock);
2409 ALOGV("%s waking up", myName.string());
2410 acquireWakeLock_l();
2411
2412 mMixerStatus = MIXER_IDLE;
2413 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2414 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002415 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002416 checkSilentMode_l();
2417
2418 standbyTime = systemTime() + standbyDelay;
2419 sleepTime = idleSleepTime;
2420 if (mType == MIXER) {
2421 sleepTimeShift = 0;
2422 }
2423
2424 continue;
2425 }
2426 }
Eric Laurent81784c32012-11-19 14:55:58 -08002427 // mMixerStatusIgnoringFastTracks is also updated internally
2428 mMixerStatus = prepareTracks_l(&tracksToRemove);
2429
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002430 // compare with previously applied list
2431 if (lastGeneration != mActiveTracksGeneration) {
2432 // update wakelock
2433 updateWakeLockUids_l(mWakeLockUids);
2434 lastGeneration = mActiveTracksGeneration;
2435 }
2436
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // prevent any changes in effect chain list and in each effect chain
2438 // during mixing and effect process as the audio buffers could be deleted
2439 // or modified if an effect is created or deleted
2440 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002441 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002442
Eric Laurentbfb1b832013-01-07 09:53:42 -08002443 if (mBytesRemaining == 0) {
2444 mCurrentWriteLength = 0;
2445 if (mMixerStatus == MIXER_TRACKS_READY) {
2446 // threadLoop_mix() sets mCurrentWriteLength
2447 threadLoop_mix();
2448 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2449 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2450 // threadLoop_sleepTime sets sleepTime to 0 if data
2451 // must be written to HAL
2452 threadLoop_sleepTime();
2453 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002454 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 }
2456 }
Andy Hung98ef9782014-03-04 14:46:50 -08002457 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2458 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2459 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2460 // or mSinkBuffer (if there are no effects).
2461 //
2462 // This is done pre-effects computation; if effects change to
2463 // support higher precision, this needs to move.
2464 //
2465 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2466 // TODO use sleepTime == 0 as an additional condition.
2467 if (mMixerBufferValid) {
2468 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2469 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2470
2471 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2472 mNormalFrameCount * mChannelCount);
2473 }
2474
Eric Laurentbfb1b832013-01-07 09:53:42 -08002475 mBytesRemaining = mCurrentWriteLength;
2476 if (isSuspended()) {
2477 sleepTime = suspendSleepTimeUs();
2478 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002479 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480 mBytesRemaining = 0;
2481 }
Eric Laurent81784c32012-11-19 14:55:58 -08002482
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002484 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485 for (size_t i = 0; i < effectChains.size(); i ++) {
2486 effectChains[i]->process_l();
2487 }
Eric Laurent81784c32012-11-19 14:55:58 -08002488 }
2489 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002490 // Process effect chains for offloaded thread even if no audio
2491 // was read from audio track: process only updates effect state
2492 // and thus does have to be synchronized with audio writes but may have
2493 // to be called while waiting for async write callback
2494 if (mType == OFFLOAD) {
2495 for (size_t i = 0; i < effectChains.size(); i ++) {
2496 effectChains[i]->process_l();
2497 }
2498 }
Eric Laurent81784c32012-11-19 14:55:58 -08002499
Andy Hung98ef9782014-03-04 14:46:50 -08002500 // Only if the Effects buffer is enabled and there is data in the
2501 // Effects buffer (buffer valid), we need to
2502 // copy into the sink buffer.
2503 // TODO use sleepTime == 0 as an additional condition.
2504 if (mEffectBufferValid) {
2505 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2506 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2507 mNormalFrameCount * mChannelCount);
2508 }
2509
Eric Laurent81784c32012-11-19 14:55:58 -08002510 // enable changes in effect chain
2511 unlockEffectChains(effectChains);
2512
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 if (!waitingAsyncCallback()) {
2514 // sleepTime == 0 means we must write to audio hardware
2515 if (sleepTime == 0) {
2516 if (mBytesRemaining) {
2517 ssize_t ret = threadLoop_write();
2518 if (ret < 0) {
2519 mBytesRemaining = 0;
2520 } else {
2521 mBytesWritten += ret;
2522 mBytesRemaining -= ret;
2523 }
2524 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2525 (mMixerStatus == MIXER_DRAIN_ALL)) {
2526 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002527 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002528 if (mType == MIXER) {
2529 // write blocked detection
2530 nsecs_t now = systemTime();
2531 nsecs_t delta = now - mLastWriteTime;
2532 if (!mStandby && delta > maxPeriod) {
2533 mNumDelayedWrites++;
2534 if ((now - lastWarning) > kWarningThrottleNs) {
2535 ATRACE_NAME("underrun");
2536 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2537 ns2ms(delta), mNumDelayedWrites, this);
2538 lastWarning = now;
2539 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 }
2541 }
Eric Laurent81784c32012-11-19 14:55:58 -08002542
Eric Laurentbfb1b832013-01-07 09:53:42 -08002543 } else {
2544 usleep(sleepTime);
2545 }
Eric Laurent81784c32012-11-19 14:55:58 -08002546 }
2547
2548 // Finally let go of removed track(s), without the lock held
2549 // since we can't guarantee the destructors won't acquire that
2550 // same lock. This will also mutate and push a new fast mixer state.
2551 threadLoop_removeTracks(tracksToRemove);
2552 tracksToRemove.clear();
2553
2554 // FIXME I don't understand the need for this here;
2555 // it was in the original code but maybe the
2556 // assignment in saveOutputTracks() makes this unnecessary?
2557 clearOutputTracks();
2558
2559 // Effect chains will be actually deleted here if they were removed from
2560 // mEffectChains list during mixing or effects processing
2561 effectChains.clear();
2562
2563 // FIXME Note that the above .clear() is no longer necessary since effectChains
2564 // is now local to this block, but will keep it for now (at least until merge done).
2565 }
2566
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567 threadLoop_exit();
2568
Eric Laurent81784c32012-11-19 14:55:58 -08002569 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002571 // put output stream into standby mode
2572 if (!mStandby) {
2573 mOutput->stream->common.standby(&mOutput->stream->common);
2574 }
2575 }
2576
2577 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002578 mWakeLockUids.clear();
2579 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002580
2581 ALOGV("Thread %p type %d exiting", this, mType);
2582 return false;
2583}
2584
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585// removeTracks_l() must be called with ThreadBase::mLock held
2586void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2587{
2588 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002589 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590 for (size_t i=0 ; i<count ; i++) {
2591 const sp<Track>& track = tracksToRemove.itemAt(i);
2592 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002593 mWakeLockUids.remove(track->uid());
2594 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2596 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2597 if (chain != 0) {
2598 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2599 track->sessionId());
2600 chain->decActiveTrackCnt();
2601 }
2602 if (track->isTerminated()) {
2603 removeTrack_l(track);
2604 }
2605 }
2606 }
2607
2608}
Eric Laurent81784c32012-11-19 14:55:58 -08002609
Eric Laurentaccc1472013-09-20 09:36:34 -07002610status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2611{
2612 if (mNormalSink != 0) {
2613 return mNormalSink->getTimestamp(timestamp);
2614 }
2615 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2616 uint64_t position64;
2617 int ret = mOutput->stream->get_presentation_position(
2618 mOutput->stream, &position64, &timestamp.mTime);
2619 if (ret == 0) {
2620 timestamp.mPosition = (uint32_t)position64;
2621 return NO_ERROR;
2622 }
2623 }
2624 return INVALID_OPERATION;
2625}
Eric Laurent81784c32012-11-19 14:55:58 -08002626// ----------------------------------------------------------------------------
2627
2628AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2629 audio_io_handle_t id, audio_devices_t device, type_t type)
2630 : PlaybackThread(audioFlinger, output, id, device, type),
2631 // mAudioMixer below
2632 // mFastMixer below
2633 mFastMixerFutex(0)
2634 // mOutputSink below
2635 // mPipeSink below
2636 // mNormalSink below
2637{
2638 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002639 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002640 "mFrameCount=%d, mNormalFrameCount=%d",
2641 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2642 mNormalFrameCount);
2643 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2644
2645 // FIXME - Current mixer implementation only supports stereo output
2646 if (mChannelCount != FCC_2) {
2647 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2648 }
2649
2650 // create an NBAIO sink for the HAL output stream, and negotiate
2651 mOutputSink = new AudioStreamOutSink(output->stream);
2652 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002653 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002654 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2655 ALOG_ASSERT(index == 0);
2656
2657 // initialize fast mixer depending on configuration
2658 bool initFastMixer;
2659 switch (kUseFastMixer) {
2660 case FastMixer_Never:
2661 initFastMixer = false;
2662 break;
2663 case FastMixer_Always:
2664 initFastMixer = true;
2665 break;
2666 case FastMixer_Static:
2667 case FastMixer_Dynamic:
2668 initFastMixer = mFrameCount < mNormalFrameCount;
2669 break;
2670 }
2671 if (initFastMixer) {
2672
2673 // create a MonoPipe to connect our submix to FastMixer
2674 NBAIO_Format format = mOutputSink->format();
2675 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2676 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2677 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2678 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2679 const NBAIO_Format offers[1] = {format};
2680 size_t numCounterOffers = 0;
2681 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2682 ALOG_ASSERT(index == 0);
2683 monoPipe->setAvgFrames((mScreenState & 1) ?
2684 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2685 mPipeSink = monoPipe;
2686
Glenn Kasten46909e72013-02-26 09:20:22 -08002687#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002688 if (mTeeSinkOutputEnabled) {
2689 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2690 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2691 numCounterOffers = 0;
2692 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2693 ALOG_ASSERT(index == 0);
2694 mTeeSink = teeSink;
2695 PipeReader *teeSource = new PipeReader(*teeSink);
2696 numCounterOffers = 0;
2697 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2698 ALOG_ASSERT(index == 0);
2699 mTeeSource = teeSource;
2700 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002701#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002702
2703 // create fast mixer and configure it initially with just one fast track for our submix
2704 mFastMixer = new FastMixer();
2705 FastMixerStateQueue *sq = mFastMixer->sq();
2706#ifdef STATE_QUEUE_DUMP
2707 sq->setObserverDump(&mStateQueueObserverDump);
2708 sq->setMutatorDump(&mStateQueueMutatorDump);
2709#endif
2710 FastMixerState *state = sq->begin();
2711 FastTrack *fastTrack = &state->mFastTracks[0];
2712 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2713 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2714 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002715 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2716 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002717 fastTrack->mGeneration++;
2718 state->mFastTracksGen++;
2719 state->mTrackMask = 1;
2720 // fast mixer will use the HAL output sink
2721 state->mOutputSink = mOutputSink.get();
2722 state->mOutputSinkGen++;
2723 state->mFrameCount = mFrameCount;
2724 state->mCommand = FastMixerState::COLD_IDLE;
2725 // already done in constructor initialization list
2726 //mFastMixerFutex = 0;
2727 state->mColdFutexAddr = &mFastMixerFutex;
2728 state->mColdGen++;
2729 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002730#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002731 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002732#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002733 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2734 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002735 sq->end();
2736 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2737
2738 // start the fast mixer
2739 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2740 pid_t tid = mFastMixer->getTid();
2741 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2742 if (err != 0) {
2743 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2744 kPriorityFastMixer, getpid_cached, tid, err);
2745 }
2746
2747#ifdef AUDIO_WATCHDOG
2748 // create and start the watchdog
2749 mAudioWatchdog = new AudioWatchdog();
2750 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2751 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2752 tid = mAudioWatchdog->getTid();
2753 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2754 if (err != 0) {
2755 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2756 kPriorityFastMixer, getpid_cached, tid, err);
2757 }
2758#endif
2759
2760 } else {
2761 mFastMixer = NULL;
2762 }
2763
2764 switch (kUseFastMixer) {
2765 case FastMixer_Never:
2766 case FastMixer_Dynamic:
2767 mNormalSink = mOutputSink;
2768 break;
2769 case FastMixer_Always:
2770 mNormalSink = mPipeSink;
2771 break;
2772 case FastMixer_Static:
2773 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2774 break;
2775 }
2776}
2777
2778AudioFlinger::MixerThread::~MixerThread()
2779{
2780 if (mFastMixer != NULL) {
2781 FastMixerStateQueue *sq = mFastMixer->sq();
2782 FastMixerState *state = sq->begin();
2783 if (state->mCommand == FastMixerState::COLD_IDLE) {
2784 int32_t old = android_atomic_inc(&mFastMixerFutex);
2785 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002786 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002787 }
2788 }
2789 state->mCommand = FastMixerState::EXIT;
2790 sq->end();
2791 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2792 mFastMixer->join();
2793 // Though the fast mixer thread has exited, it's state queue is still valid.
2794 // We'll use that extract the final state which contains one remaining fast track
2795 // corresponding to our sub-mix.
2796 state = sq->begin();
2797 ALOG_ASSERT(state->mTrackMask == 1);
2798 FastTrack *fastTrack = &state->mFastTracks[0];
2799 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2800 delete fastTrack->mBufferProvider;
2801 sq->end(false /*didModify*/);
2802 delete mFastMixer;
2803#ifdef AUDIO_WATCHDOG
2804 if (mAudioWatchdog != 0) {
2805 mAudioWatchdog->requestExit();
2806 mAudioWatchdog->requestExitAndWait();
2807 mAudioWatchdog.clear();
2808 }
2809#endif
2810 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002811 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 delete mAudioMixer;
2813}
2814
2815
2816uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2817{
2818 if (mFastMixer != NULL) {
2819 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2820 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2821 }
2822 return latency;
2823}
2824
2825
2826void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2827{
2828 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2829}
2830
Eric Laurentbfb1b832013-01-07 09:53:42 -08002831ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002832{
2833 // FIXME we should only do one push per cycle; confirm this is true
2834 // Start the fast mixer if it's not already running
2835 if (mFastMixer != NULL) {
2836 FastMixerStateQueue *sq = mFastMixer->sq();
2837 FastMixerState *state = sq->begin();
2838 if (state->mCommand != FastMixerState::MIX_WRITE &&
2839 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2840 if (state->mCommand == FastMixerState::COLD_IDLE) {
2841 int32_t old = android_atomic_inc(&mFastMixerFutex);
2842 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002843 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002844 }
2845#ifdef AUDIO_WATCHDOG
2846 if (mAudioWatchdog != 0) {
2847 mAudioWatchdog->resume();
2848 }
2849#endif
2850 }
2851 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002852 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2853 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002854 sq->end();
2855 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2856 if (kUseFastMixer == FastMixer_Dynamic) {
2857 mNormalSink = mPipeSink;
2858 }
2859 } else {
2860 sq->end(false /*didModify*/);
2861 }
2862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002864}
2865
2866void AudioFlinger::MixerThread::threadLoop_standby()
2867{
2868 // Idle the fast mixer if it's currently running
2869 if (mFastMixer != NULL) {
2870 FastMixerStateQueue *sq = mFastMixer->sq();
2871 FastMixerState *state = sq->begin();
2872 if (!(state->mCommand & FastMixerState::IDLE)) {
2873 state->mCommand = FastMixerState::COLD_IDLE;
2874 state->mColdFutexAddr = &mFastMixerFutex;
2875 state->mColdGen++;
2876 mFastMixerFutex = 0;
2877 sq->end();
2878 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2879 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2880 if (kUseFastMixer == FastMixer_Dynamic) {
2881 mNormalSink = mOutputSink;
2882 }
2883#ifdef AUDIO_WATCHDOG
2884 if (mAudioWatchdog != 0) {
2885 mAudioWatchdog->pause();
2886 }
2887#endif
2888 } else {
2889 sq->end(false /*didModify*/);
2890 }
2891 }
2892 PlaybackThread::threadLoop_standby();
2893}
2894
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2896{
2897 return false;
2898}
2899
2900bool AudioFlinger::PlaybackThread::shouldStandby_l()
2901{
2902 return !mStandby;
2903}
2904
2905bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2906{
2907 Mutex::Autolock _l(mLock);
2908 return waitingAsyncCallback_l();
2909}
2910
Eric Laurent81784c32012-11-19 14:55:58 -08002911// shared by MIXER and DIRECT, overridden by DUPLICATING
2912void AudioFlinger::PlaybackThread::threadLoop_standby()
2913{
2914 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2915 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002917 // discard any pending drain or write ack by incrementing sequence
2918 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2919 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002920 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002921 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2922 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 }
Eric Laurent81784c32012-11-19 14:55:58 -08002924}
2925
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002926void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2927{
2928 ALOGV("signal playback thread");
2929 broadcast_l();
2930}
2931
Eric Laurent81784c32012-11-19 14:55:58 -08002932void AudioFlinger::MixerThread::threadLoop_mix()
2933{
2934 // obtain the presentation timestamp of the next output buffer
2935 int64_t pts;
2936 status_t status = INVALID_OPERATION;
2937
2938 if (mNormalSink != 0) {
2939 status = mNormalSink->getNextWriteTimestamp(&pts);
2940 } else {
2941 status = mOutputSink->getNextWriteTimestamp(&pts);
2942 }
2943
2944 if (status != NO_ERROR) {
2945 pts = AudioBufferProvider::kInvalidPTS;
2946 }
2947
2948 // mix buffers...
2949 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002950 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002951 // increase sleep time progressively when application underrun condition clears.
2952 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2953 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2954 // such that we would underrun the audio HAL.
2955 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2956 sleepTimeShift--;
2957 }
2958 sleepTime = 0;
2959 standbyTime = systemTime() + standbyDelay;
2960 //TODO: delay standby when effects have a tail
2961}
2962
2963void AudioFlinger::MixerThread::threadLoop_sleepTime()
2964{
2965 // If no tracks are ready, sleep once for the duration of an output
2966 // buffer size, then write 0s to the output
2967 if (sleepTime == 0) {
2968 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2969 sleepTime = activeSleepTime >> sleepTimeShift;
2970 if (sleepTime < kMinThreadSleepTimeUs) {
2971 sleepTime = kMinThreadSleepTimeUs;
2972 }
2973 // reduce sleep time in case of consecutive application underruns to avoid
2974 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2975 // duration we would end up writing less data than needed by the audio HAL if
2976 // the condition persists.
2977 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2978 sleepTimeShift++;
2979 }
2980 } else {
2981 sleepTime = idleSleepTime;
2982 }
2983 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002984 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2985 // before effects processing or output.
2986 if (mMixerBufferValid) {
2987 memset(mMixerBuffer, 0, mMixerBufferSize);
2988 } else {
2989 memset(mSinkBuffer, 0, mSinkBufferSize);
2990 }
Eric Laurent81784c32012-11-19 14:55:58 -08002991 sleepTime = 0;
2992 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2993 "anticipated start");
2994 }
2995 // TODO add standby time extension fct of effect tail
2996}
2997
2998// prepareTracks_l() must be called with ThreadBase::mLock held
2999AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3000 Vector< sp<Track> > *tracksToRemove)
3001{
3002
3003 mixer_state mixerStatus = MIXER_IDLE;
3004 // find out which tracks need to be processed
3005 size_t count = mActiveTracks.size();
3006 size_t mixedTracks = 0;
3007 size_t tracksWithEffect = 0;
3008 // counts only _active_ fast tracks
3009 size_t fastTracks = 0;
3010 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3011
3012 float masterVolume = mMasterVolume;
3013 bool masterMute = mMasterMute;
3014
3015 if (masterMute) {
3016 masterVolume = 0;
3017 }
3018 // Delegate master volume control to effect in output mix effect chain if needed
3019 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3020 if (chain != 0) {
3021 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3022 chain->setVolume_l(&v, &v);
3023 masterVolume = (float)((v + (1 << 23)) >> 24);
3024 chain.clear();
3025 }
3026
3027 // prepare a new state to push
3028 FastMixerStateQueue *sq = NULL;
3029 FastMixerState *state = NULL;
3030 bool didModify = false;
3031 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3032 if (mFastMixer != NULL) {
3033 sq = mFastMixer->sq();
3034 state = sq->begin();
3035 }
3036
Andy Hung69aed5f2014-02-25 17:24:40 -08003037 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003038 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003039
Eric Laurent81784c32012-11-19 14:55:58 -08003040 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003041 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003042 if (t == 0) {
3043 continue;
3044 }
3045
3046 // this const just means the local variable doesn't change
3047 Track* const track = t.get();
3048
3049 // process fast tracks
3050 if (track->isFastTrack()) {
3051
3052 // It's theoretically possible (though unlikely) for a fast track to be created
3053 // and then removed within the same normal mix cycle. This is not a problem, as
3054 // the track never becomes active so it's fast mixer slot is never touched.
3055 // The converse, of removing an (active) track and then creating a new track
3056 // at the identical fast mixer slot within the same normal mix cycle,
3057 // is impossible because the slot isn't marked available until the end of each cycle.
3058 int j = track->mFastIndex;
3059 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3060 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3061 FastTrack *fastTrack = &state->mFastTracks[j];
3062
3063 // Determine whether the track is currently in underrun condition,
3064 // and whether it had a recent underrun.
3065 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3066 FastTrackUnderruns underruns = ftDump->mUnderruns;
3067 uint32_t recentFull = (underruns.mBitFields.mFull -
3068 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3069 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3070 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3071 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3072 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3073 uint32_t recentUnderruns = recentPartial + recentEmpty;
3074 track->mObservedUnderruns = underruns;
3075 // don't count underruns that occur while stopping or pausing
3076 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003077 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3078 recentUnderruns > 0) {
3079 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3080 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003081 }
3082
3083 // This is similar to the state machine for normal tracks,
3084 // with a few modifications for fast tracks.
3085 bool isActive = true;
3086 switch (track->mState) {
3087 case TrackBase::STOPPING_1:
3088 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003090 track->mState = TrackBase::STOPPING_2;
3091 }
3092 break;
3093 case TrackBase::PAUSING:
3094 // ramp down is not yet implemented
3095 track->setPaused();
3096 break;
3097 case TrackBase::RESUMING:
3098 // ramp up is not yet implemented
3099 track->mState = TrackBase::ACTIVE;
3100 break;
3101 case TrackBase::ACTIVE:
3102 if (recentFull > 0 || recentPartial > 0) {
3103 // track has provided at least some frames recently: reset retry count
3104 track->mRetryCount = kMaxTrackRetries;
3105 }
3106 if (recentUnderruns == 0) {
3107 // no recent underruns: stay active
3108 break;
3109 }
3110 // there has recently been an underrun of some kind
3111 if (track->sharedBuffer() == 0) {
3112 // were any of the recent underruns "empty" (no frames available)?
3113 if (recentEmpty == 0) {
3114 // no, then ignore the partial underruns as they are allowed indefinitely
3115 break;
3116 }
3117 // there has recently been an "empty" underrun: decrement the retry counter
3118 if (--(track->mRetryCount) > 0) {
3119 break;
3120 }
3121 // indicate to client process that the track was disabled because of underrun;
3122 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003123 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // remove from active list, but state remains ACTIVE [confusing but true]
3125 isActive = false;
3126 break;
3127 }
3128 // fall through
3129 case TrackBase::STOPPING_2:
3130 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003131 case TrackBase::STOPPED:
3132 case TrackBase::FLUSHED: // flush() while active
3133 // Check for presentation complete if track is inactive
3134 // We have consumed all the buffers of this track.
3135 // This would be incomplete if we auto-paused on underrun
3136 {
3137 size_t audioHALFrames =
3138 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3139 size_t framesWritten = mBytesWritten / mFrameSize;
3140 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3141 // track stays in active list until presentation is complete
3142 break;
3143 }
3144 }
3145 if (track->isStopping_2()) {
3146 track->mState = TrackBase::STOPPED;
3147 }
3148 if (track->isStopped()) {
3149 // Can't reset directly, as fast mixer is still polling this track
3150 // track->reset();
3151 // So instead mark this track as needing to be reset after push with ack
3152 resetMask |= 1 << i;
3153 }
3154 isActive = false;
3155 break;
3156 case TrackBase::IDLE:
3157 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003158 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003159 }
3160
3161 if (isActive) {
3162 // was it previously inactive?
3163 if (!(state->mTrackMask & (1 << j))) {
3164 ExtendedAudioBufferProvider *eabp = track;
3165 VolumeProvider *vp = track;
3166 fastTrack->mBufferProvider = eabp;
3167 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003168 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003169 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003170 fastTrack->mGeneration++;
3171 state->mTrackMask |= 1 << j;
3172 didModify = true;
3173 // no acknowledgement required for newly active tracks
3174 }
3175 // cache the combined master volume and stream type volume for fast mixer; this
3176 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003177 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003178 ++fastTracks;
3179 } else {
3180 // was it previously active?
3181 if (state->mTrackMask & (1 << j)) {
3182 fastTrack->mBufferProvider = NULL;
3183 fastTrack->mGeneration++;
3184 state->mTrackMask &= ~(1 << j);
3185 didModify = true;
3186 // If any fast tracks were removed, we must wait for acknowledgement
3187 // because we're about to decrement the last sp<> on those tracks.
3188 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3189 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003190 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003191 }
3192 tracksToRemove->add(track);
3193 // Avoids a misleading display in dumpsys
3194 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3195 }
3196 continue;
3197 }
3198
3199 { // local variable scope to avoid goto warning
3200
3201 audio_track_cblk_t* cblk = track->cblk();
3202
3203 // The first time a track is added we wait
3204 // for all its buffers to be filled before processing it
3205 int name = track->name();
3206 // make sure that we have enough frames to mix one full buffer.
3207 // enforce this condition only once to enable draining the buffer in case the client
3208 // app does not call stop() and relies on underrun to stop:
3209 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3210 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003211 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003212 uint32_t sr = track->sampleRate();
3213 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003214 desiredFrames = mNormalFrameCount;
3215 } else {
3216 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003217 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003218 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003219 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003220 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003221#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003222 // the minimum track buffer size is normally twice the number of frames necessary
3223 // to fill one buffer and the resampler should not leave more than one buffer worth
3224 // of unreleased frames after each pass, but just in case...
3225 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003226#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003227 }
Eric Laurent81784c32012-11-19 14:55:58 -08003228 uint32_t minFrames = 1;
3229 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3230 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003231 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003232 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003233
3234 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003235 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003236 !track->isPaused() && !track->isTerminated())
3237 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003238 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003239
3240 mixedTracks++;
3241
Andy Hung69aed5f2014-02-25 17:24:40 -08003242 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3243 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003244 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003245 if (track->mainBuffer() != mSinkBuffer &&
3246 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003247 if (mEffectBufferEnabled) {
3248 mEffectBufferValid = true; // Later can set directly.
3249 }
Eric Laurent81784c32012-11-19 14:55:58 -08003250 chain = getEffectChain_l(track->sessionId());
3251 // Delegate volume control to effect in track effect chain if needed
3252 if (chain != 0) {
3253 tracksWithEffect++;
3254 } else {
3255 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3256 "session %d",
3257 name, track->sessionId());
3258 }
3259 }
3260
3261
3262 int param = AudioMixer::VOLUME;
3263 if (track->mFillingUpStatus == Track::FS_FILLED) {
3264 // no ramp for the first volume setting
3265 track->mFillingUpStatus = Track::FS_ACTIVE;
3266 if (track->mState == TrackBase::RESUMING) {
3267 track->mState = TrackBase::ACTIVE;
3268 param = AudioMixer::RAMP_VOLUME;
3269 }
3270 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003271 // FIXME should not make a decision based on mServer
3272 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003273 // If the track is stopped before the first frame was mixed,
3274 // do not apply ramp
3275 param = AudioMixer::RAMP_VOLUME;
3276 }
3277
3278 // compute volume for this track
3279 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003280 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003281 vl = vr = va = 0;
3282 if (track->isPausing()) {
3283 track->setPaused();
3284 }
3285 } else {
3286
3287 // read original volumes with volume control
3288 float typeVolume = mStreamTypes[track->streamType()].volume;
3289 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003290 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003291 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3292 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3293 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003294 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003295 if (vlf > GAIN_FLOAT_UNITY) {
3296 ALOGV("Track left volume out of range: %.3g", vlf);
3297 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003299 if (vrf > GAIN_FLOAT_UNITY) {
3300 ALOGV("Track right volume out of range: %.3g", vrf);
3301 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003302 }
3303 // now apply the master volume and stream type volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07003304 // FIXME we're losing the wonderful dynamic range in the minifloat representation
3305 float v8_24 = v * (MAX_GAIN_INT * MAX_GAIN_INT);
3306 vl = (uint32_t) (v8_24 * vlf);
3307 vr = (uint32_t) (v8_24 * vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08003308 // assuming master volume and stream type volume each go up to 1.0,
3309 // vl and vr are now in 8.24 format
3310
Glenn Kastene3aa6592012-12-04 12:22:46 -08003311 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003312 // send level comes from shared memory and so may be corrupt
3313 if (sendLevel > MAX_GAIN_INT) {
3314 ALOGV("Track send level out of range: %04X", sendLevel);
3315 sendLevel = MAX_GAIN_INT;
3316 }
3317 va = (uint32_t)(v * sendLevel);
3318 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003319
Eric Laurent81784c32012-11-19 14:55:58 -08003320 // Delegate volume control to effect in track effect chain if needed
3321 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3322 // Do not ramp volume if volume is controlled by effect
3323 param = AudioMixer::VOLUME;
3324 track->mHasVolumeController = true;
3325 } else {
3326 // force no volume ramp when volume controller was just disabled or removed
3327 // from effect chain to avoid volume spike
3328 if (track->mHasVolumeController) {
3329 param = AudioMixer::VOLUME;
3330 }
3331 track->mHasVolumeController = false;
3332 }
3333
Glenn Kastenc56f3422014-03-21 17:53:17 -07003334 // FIXME Use float
Eric Laurent81784c32012-11-19 14:55:58 -08003335 // Convert volumes from 8.24 to 4.12 format
3336 // This additional clamping is needed in case chain->setVolume_l() overshot
3337 vl = (vl + (1 << 11)) >> 12;
3338 if (vl > MAX_GAIN_INT) {
3339 vl = MAX_GAIN_INT;
3340 }
3341 vr = (vr + (1 << 11)) >> 12;
3342 if (vr > MAX_GAIN_INT) {
3343 vr = MAX_GAIN_INT;
3344 }
3345
3346 if (va > MAX_GAIN_INT) {
3347 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3348 }
3349
3350 // XXX: these things DON'T need to be done each time
3351 mAudioMixer->setBufferProvider(name, track);
3352 mAudioMixer->enable(name);
3353
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003354 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3355 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3356 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003357 mAudioMixer->setParameter(
3358 name,
3359 AudioMixer::TRACK,
3360 AudioMixer::FORMAT, (void *)track->format());
3361 mAudioMixer->setParameter(
3362 name,
3363 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003364 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003365 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3366 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003367 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003368 if (reqSampleRate == 0) {
3369 reqSampleRate = mSampleRate;
3370 } else if (reqSampleRate > maxSampleRate) {
3371 reqSampleRate = maxSampleRate;
3372 }
Eric Laurent81784c32012-11-19 14:55:58 -08003373 mAudioMixer->setParameter(
3374 name,
3375 AudioMixer::RESAMPLE,
3376 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003377 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003378 /*
3379 * Select the appropriate output buffer for the track.
3380 *
Andy Hung98ef9782014-03-04 14:46:50 -08003381 * Tracks with effects go into their own effects chain buffer
3382 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003383 *
3384 * Other tracks can use mMixerBuffer for higher precision
3385 * channel accumulation. If this buffer is enabled
3386 * (mMixerBufferEnabled true), then selected tracks will accumulate
3387 * into it.
3388 *
3389 */
3390 if (mMixerBufferEnabled
3391 && (track->mainBuffer() == mSinkBuffer
3392 || track->mainBuffer() == mMixerBuffer)) {
3393 mAudioMixer->setParameter(
3394 name,
3395 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003396 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003397 mAudioMixer->setParameter(
3398 name,
3399 AudioMixer::TRACK,
3400 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3401 // TODO: override track->mainBuffer()?
3402 mMixerBufferValid = true;
3403 } else {
3404 mAudioMixer->setParameter(
3405 name,
3406 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003407 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003408 mAudioMixer->setParameter(
3409 name,
3410 AudioMixer::TRACK,
3411 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3412 }
Eric Laurent81784c32012-11-19 14:55:58 -08003413 mAudioMixer->setParameter(
3414 name,
3415 AudioMixer::TRACK,
3416 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3417
3418 // reset retry count
3419 track->mRetryCount = kMaxTrackRetries;
3420
3421 // If one track is ready, set the mixer ready if:
3422 // - the mixer was not ready during previous round OR
3423 // - no other track is not ready
3424 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3425 mixerStatus != MIXER_TRACKS_ENABLED) {
3426 mixerStatus = MIXER_TRACKS_READY;
3427 }
3428 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003429 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003430 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003431 }
Eric Laurent81784c32012-11-19 14:55:58 -08003432 // clear effect chain input buffer if an active track underruns to avoid sending
3433 // previous audio buffer again to effects
3434 chain = getEffectChain_l(track->sessionId());
3435 if (chain != 0) {
3436 chain->clearInputBuffer();
3437 }
3438
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003439 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003440 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3441 track->isStopped() || track->isPaused()) {
3442 // We have consumed all the buffers of this track.
3443 // Remove it from the list of active tracks.
3444 // TODO: use actual buffer filling status instead of latency when available from
3445 // audio HAL
3446 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3447 size_t framesWritten = mBytesWritten / mFrameSize;
3448 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3449 if (track->isStopped()) {
3450 track->reset();
3451 }
3452 tracksToRemove->add(track);
3453 }
3454 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003455 // No buffers for this track. Give it a few chances to
3456 // fill a buffer, then remove it from active list.
3457 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003458 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003459 tracksToRemove->add(track);
3460 // indicate to client process that the track was disabled because of underrun;
3461 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003462 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003463 // If one track is not ready, mark the mixer also not ready if:
3464 // - the mixer was ready during previous round OR
3465 // - no other track is ready
3466 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3467 mixerStatus != MIXER_TRACKS_READY) {
3468 mixerStatus = MIXER_TRACKS_ENABLED;
3469 }
3470 }
3471 mAudioMixer->disable(name);
3472 }
3473
3474 } // local variable scope to avoid goto warning
3475track_is_ready: ;
3476
3477 }
3478
3479 // Push the new FastMixer state if necessary
3480 bool pauseAudioWatchdog = false;
3481 if (didModify) {
3482 state->mFastTracksGen++;
3483 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3484 if (kUseFastMixer == FastMixer_Dynamic &&
3485 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3486 state->mCommand = FastMixerState::COLD_IDLE;
3487 state->mColdFutexAddr = &mFastMixerFutex;
3488 state->mColdGen++;
3489 mFastMixerFutex = 0;
3490 if (kUseFastMixer == FastMixer_Dynamic) {
3491 mNormalSink = mOutputSink;
3492 }
3493 // If we go into cold idle, need to wait for acknowledgement
3494 // so that fast mixer stops doing I/O.
3495 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3496 pauseAudioWatchdog = true;
3497 }
Eric Laurent81784c32012-11-19 14:55:58 -08003498 }
3499 if (sq != NULL) {
3500 sq->end(didModify);
3501 sq->push(block);
3502 }
3503#ifdef AUDIO_WATCHDOG
3504 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3505 mAudioWatchdog->pause();
3506 }
3507#endif
3508
3509 // Now perform the deferred reset on fast tracks that have stopped
3510 while (resetMask != 0) {
3511 size_t i = __builtin_ctz(resetMask);
3512 ALOG_ASSERT(i < count);
3513 resetMask &= ~(1 << i);
3514 sp<Track> t = mActiveTracks[i].promote();
3515 if (t == 0) {
3516 continue;
3517 }
3518 Track* track = t.get();
3519 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3520 track->reset();
3521 }
3522
3523 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003524 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003525
Andy Hung69aed5f2014-02-25 17:24:40 -08003526 // sink or mix buffer must be cleared if all tracks are connected to an
3527 // effect chain as in this case the mixer will not write to the sink or mix buffer
3528 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3530 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003531 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003532 if (mMixerBufferValid) {
3533 memset(mMixerBuffer, 0, mMixerBufferSize);
3534 // TODO: In testing, mSinkBuffer below need not be cleared because
3535 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3536 // after mixing.
3537 //
3538 // To enforce this guarantee:
3539 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3540 // (mixedTracks == 0 && fastTracks > 0))
3541 // must imply MIXER_TRACKS_READY.
3542 // Later, we may clear buffers regardless, and skip much of this logic.
3543 }
Andy Hung98ef9782014-03-04 14:46:50 -08003544 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3545 if (mEffectBufferValid) {
3546 memset(mEffectBuffer, 0, mEffectBufferSize);
3547 }
3548 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003549 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003550 }
3551
3552 // if any fast tracks, then status is ready
3553 mMixerStatusIgnoringFastTracks = mixerStatus;
3554 if (fastTracks > 0) {
3555 mixerStatus = MIXER_TRACKS_READY;
3556 }
3557 return mixerStatus;
3558}
3559
3560// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003561int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3562 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003563{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003564 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003565}
3566
3567// deleteTrackName_l() must be called with ThreadBase::mLock held
3568void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3569{
3570 ALOGV("remove track (%d) and delete from mixer", name);
3571 mAudioMixer->deleteTrackName(name);
3572}
3573
Eric Laurent10351942014-05-08 18:49:52 -07003574// checkForNewParameter_l() must be called with ThreadBase::mLock held
3575bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3576 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003577{
Eric Laurent81784c32012-11-19 14:55:58 -08003578 bool reconfig = false;
3579
Eric Laurent10351942014-05-08 18:49:52 -07003580 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Eric Laurent10351942014-05-08 18:49:52 -07003582 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3583 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3584 if (mFastMixer != NULL) {
3585 FastMixerStateQueue *sq = mFastMixer->sq();
3586 FastMixerState *state = sq->begin();
3587 if (!(state->mCommand & FastMixerState::IDLE)) {
3588 previousCommand = state->mCommand;
3589 state->mCommand = FastMixerState::HOT_IDLE;
3590 sq->end();
3591 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3592 } else {
3593 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003594 }
Eric Laurent10351942014-05-08 18:49:52 -07003595 }
Eric Laurent81784c32012-11-19 14:55:58 -08003596
Eric Laurent10351942014-05-08 18:49:52 -07003597 AudioParameter param = AudioParameter(keyValuePair);
3598 int value;
3599 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3600 reconfig = true;
3601 }
3602 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3603 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3604 status = BAD_VALUE;
3605 } else {
3606 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003607 reconfig = true;
3608 }
Eric Laurent10351942014-05-08 18:49:52 -07003609 }
3610 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3611 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3612 status = BAD_VALUE;
3613 } else {
3614 // no need to save value, since it's constant
3615 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003616 }
Eric Laurent10351942014-05-08 18:49:52 -07003617 }
3618 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3619 // do not accept frame count changes if tracks are open as the track buffer
3620 // size depends on frame count and correct behavior would not be guaranteed
3621 // if frame count is changed after track creation
3622 if (!mTracks.isEmpty()) {
3623 status = INVALID_OPERATION;
3624 } else {
3625 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003626 }
Eric Laurent10351942014-05-08 18:49:52 -07003627 }
3628 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003629#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003630 // when changing the audio output device, call addBatteryData to notify
3631 // the change
3632 if (mOutDevice != value) {
3633 uint32_t params = 0;
3634 // check whether speaker is on
3635 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3636 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003637 }
Eric Laurent10351942014-05-08 18:49:52 -07003638
3639 audio_devices_t deviceWithoutSpeaker
3640 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3641 // check if any other device (except speaker) is on
3642 if (value & deviceWithoutSpeaker ) {
3643 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3644 }
3645
3646 if (params != 0) {
3647 addBatteryData(params);
3648 }
3649 }
Eric Laurent81784c32012-11-19 14:55:58 -08003650#endif
3651
Eric Laurent10351942014-05-08 18:49:52 -07003652 // forward device change to effects that have requested to be
3653 // aware of attached audio device.
3654 if (value != AUDIO_DEVICE_NONE) {
3655 mOutDevice = value;
3656 for (size_t i = 0; i < mEffectChains.size(); i++) {
3657 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003658 }
3659 }
Eric Laurent10351942014-05-08 18:49:52 -07003660 }
Eric Laurent81784c32012-11-19 14:55:58 -08003661
Eric Laurent10351942014-05-08 18:49:52 -07003662 if (status == NO_ERROR) {
3663 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3664 keyValuePair.string());
3665 if (!mStandby && status == INVALID_OPERATION) {
3666 mOutput->stream->common.standby(&mOutput->stream->common);
3667 mStandby = true;
3668 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003669 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003670 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003671 }
Eric Laurent10351942014-05-08 18:49:52 -07003672 if (status == NO_ERROR && reconfig) {
3673 readOutputParameters_l();
3674 delete mAudioMixer;
3675 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3676 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003677 int name = getTrackName_l(mTracks[i]->mChannelMask,
3678 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003679 if (name < 0) {
3680 break;
3681 }
3682 mTracks[i]->mName = name;
3683 }
3684 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3685 }
Eric Laurent81784c32012-11-19 14:55:58 -08003686 }
3687
3688 if (!(previousCommand & FastMixerState::IDLE)) {
3689 ALOG_ASSERT(mFastMixer != NULL);
3690 FastMixerStateQueue *sq = mFastMixer->sq();
3691 FastMixerState *state = sq->begin();
3692 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3693 state->mCommand = previousCommand;
3694 sq->end();
3695 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3696 }
3697
3698 return reconfig;
3699}
3700
3701
3702void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3703{
3704 const size_t SIZE = 256;
3705 char buffer[SIZE];
3706 String8 result;
3707
3708 PlaybackThread::dumpInternals(fd, args);
3709
Elliott Hughes87cebad2014-05-22 10:14:43 -07003710 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003711
3712 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003713 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003714 copy.dump(fd);
3715
3716#ifdef STATE_QUEUE_DUMP
3717 // Similar for state queue
3718 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3719 observerCopy.dump(fd);
3720 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3721 mutatorCopy.dump(fd);
3722#endif
3723
Glenn Kasten46909e72013-02-26 09:20:22 -08003724#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003725 // Write the tee output to a .wav file
3726 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003727#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003728
3729#ifdef AUDIO_WATCHDOG
3730 if (mAudioWatchdog != 0) {
3731 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3732 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3733 wdCopy.dump(fd);
3734 }
3735#endif
3736}
3737
3738uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3739{
3740 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3741}
3742
3743uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3744{
3745 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3746}
3747
3748void AudioFlinger::MixerThread::cacheParameters_l()
3749{
3750 PlaybackThread::cacheParameters_l();
3751
3752 // FIXME: Relaxed timing because of a certain device that can't meet latency
3753 // Should be reduced to 2x after the vendor fixes the driver issue
3754 // increase threshold again due to low power audio mode. The way this warning
3755 // threshold is calculated and its usefulness should be reconsidered anyway.
3756 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3757}
3758
3759// ----------------------------------------------------------------------------
3760
3761AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3762 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3763 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3764 // mLeftVolFloat, mRightVolFloat
3765{
3766}
3767
Eric Laurentbfb1b832013-01-07 09:53:42 -08003768AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3769 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3770 ThreadBase::type_t type)
3771 : PlaybackThread(audioFlinger, output, id, device, type)
3772 // mLeftVolFloat, mRightVolFloat
3773{
3774}
3775
Eric Laurent81784c32012-11-19 14:55:58 -08003776AudioFlinger::DirectOutputThread::~DirectOutputThread()
3777{
3778}
3779
Eric Laurentbfb1b832013-01-07 09:53:42 -08003780void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3781{
3782 audio_track_cblk_t* cblk = track->cblk();
3783 float left, right;
3784
3785 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3786 left = right = 0;
3787 } else {
3788 float typeVolume = mStreamTypes[track->streamType()].volume;
3789 float v = mMasterVolume * typeVolume;
3790 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003791 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3792 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3793 if (left > GAIN_FLOAT_UNITY) {
3794 left = GAIN_FLOAT_UNITY;
3795 }
3796 left *= v;
3797 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3798 if (right > GAIN_FLOAT_UNITY) {
3799 right = GAIN_FLOAT_UNITY;
3800 }
3801 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003802 }
3803
3804 if (lastTrack) {
3805 if (left != mLeftVolFloat || right != mRightVolFloat) {
3806 mLeftVolFloat = left;
3807 mRightVolFloat = right;
3808
3809 // Convert volumes from float to 8.24
3810 uint32_t vl = (uint32_t)(left * (1 << 24));
3811 uint32_t vr = (uint32_t)(right * (1 << 24));
3812
3813 // Delegate volume control to effect in track effect chain if needed
3814 // only one effect chain can be present on DirectOutputThread, so if
3815 // there is one, the track is connected to it
3816 if (!mEffectChains.isEmpty()) {
3817 mEffectChains[0]->setVolume_l(&vl, &vr);
3818 left = (float)vl / (1 << 24);
3819 right = (float)vr / (1 << 24);
3820 }
3821 if (mOutput->stream->set_volume) {
3822 mOutput->stream->set_volume(mOutput->stream, left, right);
3823 }
3824 }
3825 }
3826}
3827
3828
Eric Laurent81784c32012-11-19 14:55:58 -08003829AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3830 Vector< sp<Track> > *tracksToRemove
3831)
3832{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003833 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003834 mixer_state mixerStatus = MIXER_IDLE;
3835
3836 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003837 for (size_t i = 0; i < count; i++) {
3838 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003839 // The track died recently
3840 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003841 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003842 }
3843
3844 Track* const track = t.get();
3845 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003846 // Only consider last track started for volume and mixer state control.
3847 // In theory an older track could underrun and restart after the new one starts
3848 // but as we only care about the transition phase between two tracks on a
3849 // direct output, it is not a problem to ignore the underrun case.
3850 sp<Track> l = mLatestActiveTrack.promote();
3851 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003852
3853 // The first time a track is added we wait
3854 // for all its buffers to be filled before processing it
3855 uint32_t minFrames;
3856 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3857 minFrames = mNormalFrameCount;
3858 } else {
3859 minFrames = 1;
3860 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861
Eric Laurent81784c32012-11-19 14:55:58 -08003862 if ((track->framesReady() >= minFrames) && track->isReady() &&
3863 !track->isPaused() && !track->isTerminated())
3864 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003865 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003866
3867 if (track->mFillingUpStatus == Track::FS_FILLED) {
3868 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003869 // make sure processVolume_l() will apply new volume even if 0
3870 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003871 if (track->mState == TrackBase::RESUMING) {
3872 track->mState = TrackBase::ACTIVE;
3873 }
3874 }
3875
3876 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003877 processVolume_l(track, last);
3878 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003879 // reset retry count
3880 track->mRetryCount = kMaxTrackRetriesDirect;
3881 mActiveTrack = t;
3882 mixerStatus = MIXER_TRACKS_READY;
3883 }
Eric Laurent81784c32012-11-19 14:55:58 -08003884 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003885 // clear effect chain input buffer if the last active track started underruns
3886 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003887 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003888 mEffectChains[0]->clearInputBuffer();
3889 }
3890
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003891 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003892 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3893 track->isStopped() || track->isPaused()) {
3894 // We have consumed all the buffers of this track.
3895 // Remove it from the list of active tracks.
3896 // TODO: implement behavior for compressed audio
3897 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3898 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003899 if (mStandby || !last ||
3900 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003901 if (track->isStopped()) {
3902 track->reset();
3903 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003904 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003905 }
3906 } else {
3907 // No buffers for this track. Give it a few chances to
3908 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003909 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003910 if (--(track->mRetryCount) <= 0) {
3911 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003912 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003913 // indicate to client process that the track was disabled because of underrun;
3914 // it will then automatically call start() when data is available
3915 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003916 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003917 mixerStatus = MIXER_TRACKS_ENABLED;
3918 }
3919 }
3920 }
3921 }
3922
Eric Laurent81784c32012-11-19 14:55:58 -08003923 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003924 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003925
3926 return mixerStatus;
3927}
3928
3929void AudioFlinger::DirectOutputThread::threadLoop_mix()
3930{
Eric Laurent81784c32012-11-19 14:55:58 -08003931 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003932 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003933 // output audio to hardware
3934 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003935 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003936 buffer.frameCount = frameCount;
3937 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003938 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003939 memset(curBuf, 0, frameCount * mFrameSize);
3940 break;
3941 }
3942 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3943 frameCount -= buffer.frameCount;
3944 curBuf += buffer.frameCount * mFrameSize;
3945 mActiveTrack->releaseBuffer(&buffer);
3946 }
Andy Hung2098f272014-02-27 14:00:06 -08003947 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003948 sleepTime = 0;
3949 standbyTime = systemTime() + standbyDelay;
3950 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003951}
3952
3953void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3954{
3955 if (sleepTime == 0) {
3956 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3957 sleepTime = activeSleepTime;
3958 } else {
3959 sleepTime = idleSleepTime;
3960 }
3961 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003962 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003963 sleepTime = 0;
3964 }
3965}
3966
3967// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003968int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07003969 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003970{
3971 return 0;
3972}
3973
3974// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003975void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003976{
3977}
3978
Eric Laurent10351942014-05-08 18:49:52 -07003979// checkForNewParameter_l() must be called with ThreadBase::mLock held
3980bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
3981 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003982{
3983 bool reconfig = false;
3984
Eric Laurent10351942014-05-08 18:49:52 -07003985 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003986
Eric Laurent10351942014-05-08 18:49:52 -07003987 AudioParameter param = AudioParameter(keyValuePair);
3988 int value;
3989 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3990 // forward device change to effects that have requested to be
3991 // aware of attached audio device.
3992 if (value != AUDIO_DEVICE_NONE) {
3993 mOutDevice = value;
3994 for (size_t i = 0; i < mEffectChains.size(); i++) {
3995 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07003996 }
3997 }
Eric Laurent81784c32012-11-19 14:55:58 -08003998 }
Eric Laurent10351942014-05-08 18:49:52 -07003999 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4000 // do not accept frame count changes if tracks are open as the track buffer
4001 // size depends on frame count and correct behavior would not be garantied
4002 // if frame count is changed after track creation
4003 if (!mTracks.isEmpty()) {
4004 status = INVALID_OPERATION;
4005 } else {
4006 reconfig = true;
4007 }
4008 }
4009 if (status == NO_ERROR) {
4010 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4011 keyValuePair.string());
4012 if (!mStandby && status == INVALID_OPERATION) {
4013 mOutput->stream->common.standby(&mOutput->stream->common);
4014 mStandby = true;
4015 mBytesWritten = 0;
4016 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4017 keyValuePair.string());
4018 }
4019 if (status == NO_ERROR && reconfig) {
4020 readOutputParameters_l();
4021 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4022 }
4023 }
4024
Eric Laurent81784c32012-11-19 14:55:58 -08004025 return reconfig;
4026}
4027
4028uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4029{
4030 uint32_t time;
4031 if (audio_is_linear_pcm(mFormat)) {
4032 time = PlaybackThread::activeSleepTimeUs();
4033 } else {
4034 time = 10000;
4035 }
4036 return time;
4037}
4038
4039uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4040{
4041 uint32_t time;
4042 if (audio_is_linear_pcm(mFormat)) {
4043 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4044 } else {
4045 time = 10000;
4046 }
4047 return time;
4048}
4049
4050uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4051{
4052 uint32_t time;
4053 if (audio_is_linear_pcm(mFormat)) {
4054 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4055 } else {
4056 time = 10000;
4057 }
4058 return time;
4059}
4060
4061void AudioFlinger::DirectOutputThread::cacheParameters_l()
4062{
4063 PlaybackThread::cacheParameters_l();
4064
4065 // use shorter standby delay as on normal output to release
4066 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004067 if (audio_is_linear_pcm(mFormat)) {
4068 standbyDelay = microseconds(activeSleepTime*2);
4069 } else {
4070 standbyDelay = kOffloadStandbyDelayNs;
4071 }
Eric Laurent81784c32012-11-19 14:55:58 -08004072}
4073
4074// ----------------------------------------------------------------------------
4075
Eric Laurentbfb1b832013-01-07 09:53:42 -08004076AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004077 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004079 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004080 mWriteAckSequence(0),
4081 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082{
4083}
4084
4085AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4086{
4087}
4088
4089void AudioFlinger::AsyncCallbackThread::onFirstRef()
4090{
4091 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4092}
4093
4094bool AudioFlinger::AsyncCallbackThread::threadLoop()
4095{
4096 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004097 uint32_t writeAckSequence;
4098 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099
4100 {
4101 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004102 while (!((mWriteAckSequence & 1) ||
4103 (mDrainSequence & 1) ||
4104 exitPending())) {
4105 mWaitWorkCV.wait(mLock);
4106 }
4107
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 if (exitPending()) {
4109 break;
4110 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004111 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4112 mWriteAckSequence, mDrainSequence);
4113 writeAckSequence = mWriteAckSequence;
4114 mWriteAckSequence &= ~1;
4115 drainSequence = mDrainSequence;
4116 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004117 }
4118 {
Eric Laurent4de95592013-09-26 15:28:21 -07004119 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4120 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004121 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004122 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004124 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004125 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004126 }
4127 }
4128 }
4129 }
4130 return false;
4131}
4132
4133void AudioFlinger::AsyncCallbackThread::exit()
4134{
4135 ALOGV("AsyncCallbackThread::exit");
4136 Mutex::Autolock _l(mLock);
4137 requestExit();
4138 mWaitWorkCV.broadcast();
4139}
4140
Eric Laurent3b4529e2013-09-05 18:09:19 -07004141void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004142{
4143 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004144 // bit 0 is cleared
4145 mWriteAckSequence = sequence << 1;
4146}
4147
4148void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4149{
4150 Mutex::Autolock _l(mLock);
4151 // ignore unexpected callbacks
4152 if (mWriteAckSequence & 2) {
4153 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 mWaitWorkCV.signal();
4155 }
4156}
4157
Eric Laurent3b4529e2013-09-05 18:09:19 -07004158void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004159{
4160 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004161 // bit 0 is cleared
4162 mDrainSequence = sequence << 1;
4163}
4164
4165void AudioFlinger::AsyncCallbackThread::resetDraining()
4166{
4167 Mutex::Autolock _l(mLock);
4168 // ignore unexpected callbacks
4169 if (mDrainSequence & 2) {
4170 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 mWaitWorkCV.signal();
4172 }
4173}
4174
4175
4176// ----------------------------------------------------------------------------
4177AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4178 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4179 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4180 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004181 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004182 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004183{
Eric Laurentfd477972013-10-25 18:10:40 -07004184 //FIXME: mStandby should be set to true by ThreadBase constructor
4185 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004186}
4187
Eric Laurentbfb1b832013-01-07 09:53:42 -08004188void AudioFlinger::OffloadThread::threadLoop_exit()
4189{
4190 if (mFlushPending || mHwPaused) {
4191 // If a flush is pending or track was paused, just discard buffered data
4192 flushHw_l();
4193 } else {
4194 mMixerStatus = MIXER_DRAIN_ALL;
4195 threadLoop_drain();
4196 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004197 if (mUseAsyncWrite) {
4198 ALOG_ASSERT(mCallbackThread != 0);
4199 mCallbackThread->exit();
4200 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 PlaybackThread::threadLoop_exit();
4202}
4203
4204AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4205 Vector< sp<Track> > *tracksToRemove
4206)
4207{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004208 size_t count = mActiveTracks.size();
4209
4210 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004211 bool doHwPause = false;
4212 bool doHwResume = false;
4213
Eric Laurentede6c3b2013-09-19 14:37:46 -07004214 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4215
Eric Laurentbfb1b832013-01-07 09:53:42 -08004216 // find out which tracks need to be processed
4217 for (size_t i = 0; i < count; i++) {
4218 sp<Track> t = mActiveTracks[i].promote();
4219 // The track died recently
4220 if (t == 0) {
4221 continue;
4222 }
4223 Track* const track = t.get();
4224 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004225 // Only consider last track started for volume and mixer state control.
4226 // In theory an older track could underrun and restart after the new one starts
4227 // but as we only care about the transition phase between two tracks on a
4228 // direct output, it is not a problem to ignore the underrun case.
4229 sp<Track> l = mLatestActiveTrack.promote();
4230 bool last = l.get() == track;
4231
Haynes Mathew George7844f672014-01-15 12:32:55 -08004232 if (track->isInvalid()) {
4233 ALOGW("An invalidated track shouldn't be in active list");
4234 tracksToRemove->add(track);
4235 continue;
4236 }
4237
4238 if (track->mState == TrackBase::IDLE) {
4239 ALOGW("An idle track shouldn't be in active list");
4240 continue;
4241 }
4242
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243 if (track->isPausing()) {
4244 track->setPaused();
4245 if (last) {
4246 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004247 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004248 mHwPaused = true;
4249 }
4250 // If we were part way through writing the mixbuffer to
4251 // the HAL we must save this until we resume
4252 // BUG - this will be wrong if a different track is made active,
4253 // in that case we want to discard the pending data in the
4254 // mixbuffer and tell the client to present it again when the
4255 // track is resumed
4256 mPausedWriteLength = mCurrentWriteLength;
4257 mPausedBytesRemaining = mBytesRemaining;
4258 mBytesRemaining = 0; // stop writing
4259 }
4260 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004261 } else if (track->isFlushPending()) {
4262 track->flushAck();
4263 if (last) {
4264 mFlushPending = true;
4265 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004266 } else if (track->isResumePending()){
4267 track->resumeAck();
4268 if (last) {
4269 if (mPausedBytesRemaining) {
4270 // Need to continue write that was interrupted
4271 mCurrentWriteLength = mPausedWriteLength;
4272 mBytesRemaining = mPausedBytesRemaining;
4273 mPausedBytesRemaining = 0;
4274 }
4275 if (mHwPaused) {
4276 doHwResume = true;
4277 mHwPaused = false;
4278 // threadLoop_mix() will handle the case that we need to
4279 // resume an interrupted write
4280 }
4281 // enable write to audio HAL
4282 sleepTime = 0;
4283
4284 // Do not handle new data in this iteration even if track->framesReady()
4285 mixerStatus = MIXER_TRACKS_ENABLED;
4286 }
4287 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004288 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004289 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004290 if (track->mFillingUpStatus == Track::FS_FILLED) {
4291 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004292 // make sure processVolume_l() will apply new volume even if 0
4293 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 }
4295
4296 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004297 sp<Track> previousTrack = mPreviousTrack.promote();
4298 if (previousTrack != 0) {
4299 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004300 // Flush any data still being written from last track
4301 mBytesRemaining = 0;
4302 if (mPausedBytesRemaining) {
4303 // Last track was paused so we also need to flush saved
4304 // mixbuffer state and invalidate track so that it will
4305 // re-submit that unwritten data when it is next resumed
4306 mPausedBytesRemaining = 0;
4307 // Invalidate is a bit drastic - would be more efficient
4308 // to have a flag to tell client that some of the
4309 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004310 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004311 }
4312 // flush data already sent to the DSP if changing audio session as audio
4313 // comes from a different source. Also invalidate previous track to force a
4314 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004315 if (previousTrack->sessionId() != track->sessionId()) {
4316 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004317 }
4318 }
4319 }
4320 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321 // reset retry count
4322 track->mRetryCount = kMaxTrackRetriesOffload;
4323 mActiveTrack = t;
4324 mixerStatus = MIXER_TRACKS_READY;
4325 }
4326 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004327 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328 if (track->isStopping_1()) {
4329 // Hardware buffer can hold a large amount of audio so we must
4330 // wait for all current track's data to drain before we say
4331 // that the track is stopped.
4332 if (mBytesRemaining == 0) {
4333 // Only start draining when all data in mixbuffer
4334 // has been written
4335 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4336 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004337 // do not drain if no data was ever sent to HAL (mStandby == true)
4338 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004339 // do not modify drain sequence if we are already draining. This happens
4340 // when resuming from pause after drain.
4341 if ((mDrainSequence & 1) == 0) {
4342 sleepTime = 0;
4343 standbyTime = systemTime() + standbyDelay;
4344 mixerStatus = MIXER_DRAIN_TRACK;
4345 mDrainSequence += 2;
4346 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004347 if (mHwPaused) {
4348 // It is possible to move from PAUSED to STOPPING_1 without
4349 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004350 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351 mHwPaused = false;
4352 }
4353 }
4354 }
4355 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004356 // Drain has completed or we are in standby, signal presentation complete
4357 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004358 track->mState = TrackBase::STOPPED;
4359 size_t audioHALFrames =
4360 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4361 size_t framesWritten =
4362 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4363 track->presentationComplete(framesWritten, audioHALFrames);
4364 track->reset();
4365 tracksToRemove->add(track);
4366 }
4367 } else {
4368 // No buffers for this track. Give it a few chances to
4369 // fill a buffer, then remove it from active list.
4370 if (--(track->mRetryCount) <= 0) {
4371 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4372 track->name());
4373 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004374 // indicate to client process that the track was disabled because of underrun;
4375 // it will then automatically call start() when data is available
4376 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 } else if (last){
4378 mixerStatus = MIXER_TRACKS_ENABLED;
4379 }
4380 }
4381 }
4382 // compute volume for this track
4383 processVolume_l(track, last);
4384 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004385
Eric Laurentea0fade2013-10-04 16:23:48 -07004386 // make sure the pause/flush/resume sequence is executed in the right order.
4387 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4388 // before flush and then resume HW. This can happen in case of pause/flush/resume
4389 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004390 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004391 mOutput->stream->pause(mOutput->stream);
4392 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004393 if (mFlushPending) {
4394 flushHw_l();
4395 mFlushPending = false;
4396 }
Eric Laurentfd477972013-10-25 18:10:40 -07004397 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004398 mOutput->stream->resume(mOutput->stream);
4399 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004400
Eric Laurentbfb1b832013-01-07 09:53:42 -08004401 // remove all the tracks that need to be...
4402 removeTracks_l(*tracksToRemove);
4403
4404 return mixerStatus;
4405}
4406
Eric Laurentbfb1b832013-01-07 09:53:42 -08004407// must be called with thread mutex locked
4408bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4409{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004410 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4411 mWriteAckSequence, mDrainSequence);
4412 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004413 return true;
4414 }
4415 return false;
4416}
4417
4418// must be called with thread mutex locked
4419bool AudioFlinger::OffloadThread::shouldStandby_l()
4420{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004421 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004422
4423 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4424 // after a timeout and we will enter standby then.
4425 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004426 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004427 }
4428
Glenn Kastene6f35b12013-08-19 09:58:50 -07004429 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004430}
4431
4432
4433bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4434{
4435 Mutex::Autolock _l(mLock);
4436 return waitingAsyncCallback_l();
4437}
4438
4439void AudioFlinger::OffloadThread::flushHw_l()
4440{
4441 mOutput->stream->flush(mOutput->stream);
4442 // Flush anything still waiting in the mixbuffer
4443 mCurrentWriteLength = 0;
4444 mBytesRemaining = 0;
4445 mPausedWriteLength = 0;
4446 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004447 mHwPaused = false;
4448
Eric Laurentbfb1b832013-01-07 09:53:42 -08004449 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004450 // discard any pending drain or write ack by incrementing sequence
4451 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4452 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004453 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004454 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4455 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 }
4457}
4458
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004459void AudioFlinger::OffloadThread::onAddNewTrack_l()
4460{
4461 sp<Track> previousTrack = mPreviousTrack.promote();
4462 sp<Track> latestTrack = mLatestActiveTrack.promote();
4463
4464 if (previousTrack != 0 && latestTrack != 0 &&
4465 (previousTrack->sessionId() != latestTrack->sessionId())) {
4466 mFlushPending = true;
4467 }
4468 PlaybackThread::onAddNewTrack_l();
4469}
4470
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471// ----------------------------------------------------------------------------
4472
Eric Laurent81784c32012-11-19 14:55:58 -08004473AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4474 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4475 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4476 DUPLICATING),
4477 mWaitTimeMs(UINT_MAX)
4478{
4479 addOutputTrack(mainThread);
4480}
4481
4482AudioFlinger::DuplicatingThread::~DuplicatingThread()
4483{
4484 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4485 mOutputTracks[i]->destroy();
4486 }
4487}
4488
4489void AudioFlinger::DuplicatingThread::threadLoop_mix()
4490{
4491 // mix buffers...
4492 if (outputsReady(outputTracks)) {
4493 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4494 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004495 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004496 }
4497 sleepTime = 0;
4498 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004499 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004500 standbyTime = systemTime() + standbyDelay;
4501}
4502
4503void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4504{
4505 if (sleepTime == 0) {
4506 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4507 sleepTime = activeSleepTime;
4508 } else {
4509 sleepTime = idleSleepTime;
4510 }
4511 } else if (mBytesWritten != 0) {
4512 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4513 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004514 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004515 } else {
4516 // flush remaining overflow buffers in output tracks
4517 writeFrames = 0;
4518 }
4519 sleepTime = 0;
4520 }
4521}
4522
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004524{
4525 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004526 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4527 // for delivery downstream as needed. This in-place conversion is safe as
4528 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4529 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4530 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4531 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4532 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4533 }
4534 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004535 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004536 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004537 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004538}
4539
4540void AudioFlinger::DuplicatingThread::threadLoop_standby()
4541{
4542 // DuplicatingThread implements standby by stopping all tracks
4543 for (size_t i = 0; i < outputTracks.size(); i++) {
4544 outputTracks[i]->stop();
4545 }
4546}
4547
4548void AudioFlinger::DuplicatingThread::saveOutputTracks()
4549{
4550 outputTracks = mOutputTracks;
4551}
4552
4553void AudioFlinger::DuplicatingThread::clearOutputTracks()
4554{
4555 outputTracks.clear();
4556}
4557
4558void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4559{
4560 Mutex::Autolock _l(mLock);
4561 // FIXME explain this formula
4562 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004563 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4564 // due to current usage case and restrictions on the AudioBufferProvider.
4565 // Actual buffer conversion is done in threadLoop_write().
4566 //
4567 // TODO: This may change in the future, depending on multichannel
4568 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004569 OutputTrack *outputTrack = new OutputTrack(thread,
4570 this,
4571 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004572 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004573 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004574 frameCount,
4575 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004576 if (outputTrack->cblk() != NULL) {
4577 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4578 mOutputTracks.add(outputTrack);
4579 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4580 updateWaitTime_l();
4581 }
4582}
4583
4584void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4585{
4586 Mutex::Autolock _l(mLock);
4587 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4588 if (mOutputTracks[i]->thread() == thread) {
4589 mOutputTracks[i]->destroy();
4590 mOutputTracks.removeAt(i);
4591 updateWaitTime_l();
4592 return;
4593 }
4594 }
4595 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4596}
4597
4598// caller must hold mLock
4599void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4600{
4601 mWaitTimeMs = UINT_MAX;
4602 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4603 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4604 if (strong != 0) {
4605 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4606 if (waitTimeMs < mWaitTimeMs) {
4607 mWaitTimeMs = waitTimeMs;
4608 }
4609 }
4610 }
4611}
4612
4613
4614bool AudioFlinger::DuplicatingThread::outputsReady(
4615 const SortedVector< sp<OutputTrack> > &outputTracks)
4616{
4617 for (size_t i = 0; i < outputTracks.size(); i++) {
4618 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4619 if (thread == 0) {
4620 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4621 outputTracks[i].get());
4622 return false;
4623 }
4624 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4625 // see note at standby() declaration
4626 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4627 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4628 thread.get());
4629 return false;
4630 }
4631 }
4632 return true;
4633}
4634
4635uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4636{
4637 return (mWaitTimeMs * 1000) / 2;
4638}
4639
4640void AudioFlinger::DuplicatingThread::cacheParameters_l()
4641{
4642 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4643 updateWaitTime_l();
4644
4645 MixerThread::cacheParameters_l();
4646}
4647
4648// ----------------------------------------------------------------------------
4649// Record
4650// ----------------------------------------------------------------------------
4651
4652AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4653 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004654 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004655 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004656 audio_devices_t inDevice
4657#ifdef TEE_SINK
4658 , const sp<NBAIO_Sink>& teeSink
4659#endif
4660 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004661 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004662 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004663 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004664 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004665#ifdef TEE_SINK
4666 , mTeeSink(teeSink)
4667#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004668 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4669 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004670{
4671 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004672 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004673
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004674 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004675}
4676
4677
4678AudioFlinger::RecordThread::~RecordThread()
4679{
Glenn Kasten481fb672013-09-30 14:39:28 -07004680 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004681 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004682}
4683
4684void AudioFlinger::RecordThread::onFirstRef()
4685{
4686 run(mName, PRIORITY_URGENT_AUDIO);
4687}
4688
Eric Laurent81784c32012-11-19 14:55:58 -08004689bool AudioFlinger::RecordThread::threadLoop()
4690{
Eric Laurent81784c32012-11-19 14:55:58 -08004691 nsecs_t lastWarning = 0;
4692
4693 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004694
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004695reacquire_wakelock:
4696 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004697 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004698 {
4699 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004700 size_t size = mActiveTracks.size();
4701 activeTracksGen = mActiveTracksGen;
4702 if (size > 0) {
4703 // FIXME an arbitrary choice
4704 activeTrack = mActiveTracks[0];
4705 acquireWakeLock_l(activeTrack->uid());
4706 if (size > 1) {
4707 SortedVector<int> tmp;
4708 for (size_t i = 0; i < size; i++) {
4709 tmp.add(mActiveTracks[i]->uid());
4710 }
4711 updateWakeLockUids_l(tmp);
4712 }
4713 } else {
4714 acquireWakeLock_l(-1);
4715 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004716 }
4717
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004718 // used to request a deferred sleep, to be executed later while mutex is unlocked
4719 uint32_t sleepUs = 0;
4720
4721 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004722 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004723 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004724
Glenn Kasten5edadd42013-08-14 16:30:49 -07004725 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004726 if (sleepUs > 0) {
4727 usleep(sleepUs);
4728 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004729 }
4730
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004731 // activeTracks accumulates a copy of a subset of mActiveTracks
4732 Vector< sp<RecordTrack> > activeTracks;
4733
Eric Laurent10351942014-05-08 18:49:52 -07004734
Eric Laurent81784c32012-11-19 14:55:58 -08004735 { // scope for mLock
4736 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004737
Eric Laurent021cf962014-05-13 10:18:14 -07004738 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004739
Eric Laurent000a4192014-01-29 15:17:32 -08004740 // check exitPending here because checkForNewParameters_l() and
4741 // checkForNewParameters_l() can temporarily release mLock
4742 if (exitPending()) {
4743 break;
4744 }
4745
Glenn Kasten2b806402013-11-20 16:37:38 -08004746 // if no active track(s), then standby and release wakelock
4747 size_t size = mActiveTracks.size();
4748 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004749 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004750 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004751 releaseWakeLock_l();
4752 ALOGV("RecordThread: loop stopping");
4753 // go to sleep
4754 mWaitWorkCV.wait(mLock);
4755 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004756 goto reacquire_wakelock;
4757 }
4758
Glenn Kasten2b806402013-11-20 16:37:38 -08004759 if (mActiveTracksGen != activeTracksGen) {
4760 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004761 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004762 for (size_t i = 0; i < size; i++) {
4763 tmp.add(mActiveTracks[i]->uid());
4764 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004765 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004766 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004767
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004768 bool doBroadcast = false;
4769 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004770
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004771 activeTrack = mActiveTracks[i];
4772 if (activeTrack->isTerminated()) {
4773 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004774 mActiveTracks.remove(activeTrack);
4775 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004776 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004777 continue;
4778 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004779
4780 TrackBase::track_state activeTrackState = activeTrack->mState;
4781 switch (activeTrackState) {
4782
4783 case TrackBase::PAUSING:
4784 mActiveTracks.remove(activeTrack);
4785 mActiveTracksGen++;
4786 doBroadcast = true;
4787 size--;
4788 continue;
4789
4790 case TrackBase::STARTING_1:
4791 sleepUs = 10000;
4792 i++;
4793 continue;
4794
4795 case TrackBase::STARTING_2:
4796 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004797 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004798 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004799 break;
4800
4801 case TrackBase::ACTIVE:
4802 break;
4803
4804 case TrackBase::IDLE:
4805 i++;
4806 continue;
4807
4808 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004809 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004810 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004811
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004812 activeTracks.add(activeTrack);
4813 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004814
Glenn Kasten9e982352013-08-14 14:39:50 -07004815 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004816 if (doBroadcast) {
4817 mStartStopCond.broadcast();
4818 }
4819
4820 // sleep if there are no active tracks to process
4821 if (activeTracks.size() == 0) {
4822 if (sleepUs == 0) {
4823 sleepUs = kRecordThreadSleepUs;
4824 }
4825 continue;
4826 }
4827 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004828
Eric Laurent81784c32012-11-19 14:55:58 -08004829 lockEffectChains_l(effectChains);
4830 }
4831
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004832 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004833
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004834 size_t size = effectChains.size();
4835 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004836 // thread mutex is not locked, but effect chain is locked
4837 effectChains[i]->process_l();
4838 }
4839
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004840 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4841 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4842 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4843 // If destination is non-contiguous, first read past the nominal end of buffer, then
4844 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004845
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004846 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4847 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4848 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4849 if (bytesRead <= 0) {
4850 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4851 // Force input into standby so that it tries to recover at next read attempt
4852 inputStandBy();
4853 sleepUs = kRecordThreadSleepUs;
4854 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004855 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004856 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4857 size_t framesRead = bytesRead / mFrameSize;
4858 ALOG_ASSERT(framesRead > 0);
4859 if (mTeeSink != 0) {
4860 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4861 }
4862 // If destination is non-contiguous, we now correct for reading past end of buffer.
4863 size_t part1 = mRsmpInFramesP2 - rear;
4864 if (framesRead > part1) {
4865 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4866 (framesRead - part1) * mFrameSize);
4867 }
4868 rear = mRsmpInRear += framesRead;
4869
4870 size = activeTracks.size();
4871 // loop over each active track
4872 for (size_t i = 0; i < size; i++) {
4873 activeTrack = activeTracks[i];
4874
4875 enum {
4876 OVERRUN_UNKNOWN,
4877 OVERRUN_TRUE,
4878 OVERRUN_FALSE
4879 } overrun = OVERRUN_UNKNOWN;
4880
4881 // loop over getNextBuffer to handle circular sink
4882 for (;;) {
4883
4884 activeTrack->mSink.frameCount = ~0;
4885 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4886 size_t framesOut = activeTrack->mSink.frameCount;
4887 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4888
4889 int32_t front = activeTrack->mRsmpInFront;
4890 ssize_t filled = rear - front;
4891 size_t framesIn;
4892
4893 if (filled < 0) {
4894 // should not happen, but treat like a massive overrun and re-sync
4895 framesIn = 0;
4896 activeTrack->mRsmpInFront = rear;
4897 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004898 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004899 framesIn = (size_t) filled;
4900 } else {
4901 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004902 framesIn = mRsmpInFrames;
4903 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004904 overrun = OVERRUN_TRUE;
4905 }
4906
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004907 if (framesOut == 0 || framesIn == 0) {
4908 break;
4909 }
4910
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004911 if (activeTrack->mResampler == NULL) {
4912 // no resampling
4913 if (framesIn > framesOut) {
4914 framesIn = framesOut;
4915 } else {
4916 framesOut = framesIn;
4917 }
4918 int8_t *dst = activeTrack->mSink.i8;
4919 while (framesIn > 0) {
4920 front &= mRsmpInFramesP2 - 1;
4921 size_t part1 = mRsmpInFramesP2 - front;
4922 if (part1 > framesIn) {
4923 part1 = framesIn;
4924 }
4925 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004926 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004927 memcpy(dst, src, part1 * mFrameSize);
4928 } else if (mChannelCount == 1) {
4929 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4930 part1);
4931 } else {
4932 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4933 part1);
4934 }
4935 dst += part1 * activeTrack->mFrameSize;
4936 front += part1;
4937 framesIn -= part1;
4938 }
4939 activeTrack->mRsmpInFront += framesOut;
4940
4941 } else {
4942 // resampling
4943 // FIXME framesInNeeded should really be part of resampler API, and should
4944 // depend on the SRC ratio
4945 // to keep mRsmpInBuffer full so resampler always has sufficient input
4946 size_t framesInNeeded;
4947 // FIXME only re-calculate when it changes, and optimize for common ratios
4948 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4949 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004950 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004951 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4952 framesInNeeded, framesOut, inOverOut);
4953 // Although we theoretically have framesIn in circular buffer, some of those are
4954 // unreleased frames, and thus must be discounted for purpose of budgeting.
4955 size_t unreleased = activeTrack->mRsmpInUnrel;
4956 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004957 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004958 ALOGV("not enough to resample: have %u frames in but need %u in to "
4959 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004960 framesIn, framesInNeeded, framesOut, inOverOut);
4961 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004962 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4963 if (newFramesOut == 0) {
4964 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004965 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004966 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4967 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4968 framesInNeeded, newFramesOut, outOverIn);
4969 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4970 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4971 "given in/out ratio of %.4g",
4972 framesIn, framesInNeeded, newFramesOut, inOverOut);
4973 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004974 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004975 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004976 "given in/out ratio of %.4g",
4977 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004978 }
4979
4980 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4981 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004982 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004983 delete[] activeTrack->mRsmpOutBuffer;
4984 // resampler always outputs stereo
4985 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4986 activeTrack->mRsmpOutFrameCount = framesOut;
4987 }
4988
4989 // resampler accumulates, but we only have one source track
4990 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4991 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004992 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004993 activeTrack->mResamplerBufferProvider
4994 /*this*/ /* AudioBufferProvider* */);
4995 // ditherAndClamp() works as long as all buffers returned by
4996 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004997 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07004998 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004999 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5000 framesOut);
5001 // the resampler always outputs stereo samples:
5002 // do post stereo to mono conversion
5003 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
5004 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
5005 } else {
5006 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5007 activeTrack->mRsmpOutBuffer, framesOut);
5008 }
5009 // now done with mRsmpOutBuffer
5010
5011 }
5012
5013 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5014 overrun = OVERRUN_FALSE;
5015 }
5016
5017 if (activeTrack->mFramesToDrop == 0) {
5018 if (framesOut > 0) {
5019 activeTrack->mSink.frameCount = framesOut;
5020 activeTrack->releaseBuffer(&activeTrack->mSink);
5021 }
5022 } else {
5023 // FIXME could do a partial drop of framesOut
5024 if (activeTrack->mFramesToDrop > 0) {
5025 activeTrack->mFramesToDrop -= framesOut;
5026 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005027 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005028 }
5029 } else {
5030 activeTrack->mFramesToDrop += framesOut;
5031 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5032 activeTrack->mSyncStartEvent->isCancelled()) {
5033 ALOGW("Synced record %s, session %d, trigger session %d",
5034 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5035 activeTrack->sessionId(),
5036 (activeTrack->mSyncStartEvent != 0) ?
5037 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005038 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005039 }
5040 }
5041 }
5042
5043 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005044 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005045 }
5046 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005047
5048 switch (overrun) {
5049 case OVERRUN_TRUE:
5050 // client isn't retrieving buffers fast enough
5051 if (!activeTrack->setOverflow()) {
5052 nsecs_t now = systemTime();
5053 // FIXME should lastWarning per track?
5054 if ((now - lastWarning) > kWarningThrottleNs) {
5055 ALOGW("RecordThread: buffer overflow");
5056 lastWarning = now;
5057 }
5058 }
5059 break;
5060 case OVERRUN_FALSE:
5061 activeTrack->clearOverflow();
5062 break;
5063 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005064 break;
5065 }
5066
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005067 }
5068
Eric Laurent81784c32012-11-19 14:55:58 -08005069 // enable changes in effect chain
5070 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005071 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005072 }
5073
Glenn Kasten93e471f2013-08-19 08:40:07 -07005074 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005075
5076 {
5077 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005078 for (size_t i = 0; i < mTracks.size(); i++) {
5079 sp<RecordTrack> track = mTracks[i];
5080 track->invalidate();
5081 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005082 mActiveTracks.clear();
5083 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005084 mStartStopCond.broadcast();
5085 }
5086
5087 releaseWakeLock();
5088
5089 ALOGV("RecordThread %p exiting", this);
5090 return false;
5091}
5092
Glenn Kasten93e471f2013-08-19 08:40:07 -07005093void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005094{
5095 if (!mStandby) {
5096 inputStandBy();
5097 mStandby = true;
5098 }
5099}
5100
5101void AudioFlinger::RecordThread::inputStandBy()
5102{
5103 mInput->stream->common.standby(&mInput->stream->common);
5104}
5105
Glenn Kasten05997e22014-03-13 15:08:33 -07005106// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005107sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005108 const sp<AudioFlinger::Client>& client,
5109 uint32_t sampleRate,
5110 audio_format_t format,
5111 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005112 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005113 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005114 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005115 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005116 pid_t tid,
5117 status_t *status)
5118{
Glenn Kasten74935e42013-12-19 08:56:45 -08005119 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005120 sp<RecordTrack> track;
5121 status_t lStatus;
5122
Glenn Kasten90e58b12013-07-31 16:16:02 -07005123 // client expresses a preference for FAST, but we get the final say
5124 if (*flags & IAudioFlinger::TRACK_FAST) {
5125 if (
5126 // use case: callback handler and frame count is default or at least as large as HAL
5127 (
5128 (tid != -1) &&
5129 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005130 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005131 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005132 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005133 // PCM data
5134 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005135 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005136 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5137 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005138 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005139 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005140 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005141 // record thread has an associated fast capture
5142 hasFastCapture()
5143 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005144 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005145 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005146 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005147 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005148 frameCount = mFrameCount * kFastTrackMultiplier;
5149 }
5150 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5151 frameCount, mFrameCount);
5152 } else {
5153 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5154 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005155 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005156 frameCount, mFrameCount, format,
5157 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005158 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005159 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005160 // 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 -07005161 // For compatibility with AudioRecord calculation, buffer depth is forced
5162 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5163 // This is probably too conservative, but legacy application code may depend on it.
5164 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005165 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005166 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5167 size_t mNormalFrameCount = 2048; // FIXME
5168 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5169 if (minBufCount < 2) {
5170 minBufCount = 2;
5171 }
5172 size_t minFrameCount = mNormalFrameCount * minBufCount;
5173 if (frameCount < minFrameCount) {
5174 frameCount = minFrameCount;
5175 }
5176 }
5177 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005178 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005179
Glenn Kasten15e57982013-09-24 11:52:37 -07005180 lStatus = initCheck();
5181 if (lStatus != NO_ERROR) {
5182 ALOGE("createRecordTrack_l() audio driver not initialized");
5183 goto Exit;
5184 }
Eric Laurent81784c32012-11-19 14:55:58 -08005185
5186 { // scope for mLock
5187 Mutex::Autolock _l(mLock);
5188
5189 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005190 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005191 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005192
Glenn Kasten03003332013-08-06 15:40:54 -07005193 lStatus = track->initCheck();
5194 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005195 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005196 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005197 goto Exit;
5198 }
5199 mTracks.add(track);
5200
5201 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5202 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5203 mAudioFlinger->btNrecIsOff();
5204 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5205 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005206
5207 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5208 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5209 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5210 // so ask activity manager to do this on our behalf
5211 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5212 }
Eric Laurent81784c32012-11-19 14:55:58 -08005213 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005214
Eric Laurent81784c32012-11-19 14:55:58 -08005215 lStatus = NO_ERROR;
5216
5217Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005218 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005219 return track;
5220}
5221
5222status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5223 AudioSystem::sync_event_t event,
5224 int triggerSession)
5225{
5226 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5227 sp<ThreadBase> strongMe = this;
5228 status_t status = NO_ERROR;
5229
5230 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005231 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005232 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005233 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005234 triggerSession,
5235 recordTrack->sessionId(),
5236 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005237 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005238 // Sync event can be cancelled by the trigger session if the track is not in a
5239 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005240 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005241 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005242 } else {
5243 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005245 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005246 }
5247 }
5248
5249 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005250 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005251 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005252 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5253 if (recordTrack->mState == TrackBase::PAUSING) {
5254 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005255 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005256 } else {
5257 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005258 }
5259 return status;
5260 }
5261
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005262 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5263 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5264 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005265 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005266 mActiveTracks.add(recordTrack);
5267 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005268 mLock.unlock();
5269 status_t status = AudioSystem::startInput(mId);
5270 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005271 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005272 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005273 mActiveTracks.remove(recordTrack);
5274 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005275 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005276 return status;
5277 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005278 // Catch up with current buffer indices if thread is already running.
5279 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5280 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5281 // see previously buffered data before it called start(), but with greater risk of overrun.
5282
5283 recordTrack->mRsmpInFront = mRsmpInRear;
5284 recordTrack->mRsmpInUnrel = 0;
5285 // FIXME why reset?
5286 if (recordTrack->mResampler != NULL) {
5287 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005288 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005289 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005290 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005291 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005292 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005293 ALOGV("Record failed to start");
5294 status = BAD_VALUE;
5295 goto startError;
5296 }
Eric Laurent81784c32012-11-19 14:55:58 -08005297 return status;
5298 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005299
Eric Laurent81784c32012-11-19 14:55:58 -08005300startError:
5301 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005302 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005303 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005304 return status;
5305}
5306
Eric Laurent81784c32012-11-19 14:55:58 -08005307void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5308{
5309 sp<SyncEvent> strongEvent = event.promote();
5310
5311 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005312 sp<RefBase> ptr = strongEvent->cookie().promote();
5313 if (ptr != 0) {
5314 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5315 recordTrack->handleSyncStartEvent(strongEvent);
5316 }
Eric Laurent81784c32012-11-19 14:55:58 -08005317 }
5318}
5319
Glenn Kastena8356f62013-07-25 14:37:52 -07005320bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005321 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005322 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005323 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005324 return false;
5325 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005326 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005327 recordTrack->mState = TrackBase::PAUSING;
5328 // do not wait for mStartStopCond if exiting
5329 if (exitPending()) {
5330 return true;
5331 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005332 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005333 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005334 // if we have been restarted, recordTrack is in mActiveTracks here
5335 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005336 ALOGV("Record stopped OK");
5337 return true;
5338 }
5339 return false;
5340}
5341
Glenn Kasten0f11b512014-01-31 16:18:54 -08005342bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005343{
5344 return false;
5345}
5346
Glenn Kasten0f11b512014-01-31 16:18:54 -08005347status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005348{
5349#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5350 if (!isValidSyncEvent(event)) {
5351 return BAD_VALUE;
5352 }
5353
5354 int eventSession = event->triggerSession();
5355 status_t ret = NAME_NOT_FOUND;
5356
5357 Mutex::Autolock _l(mLock);
5358
5359 for (size_t i = 0; i < mTracks.size(); i++) {
5360 sp<RecordTrack> track = mTracks[i];
5361 if (eventSession == track->sessionId()) {
5362 (void) track->setSyncEvent(event);
5363 ret = NO_ERROR;
5364 }
5365 }
5366 return ret;
5367#else
5368 return BAD_VALUE;
5369#endif
5370}
5371
5372// destroyTrack_l() must be called with ThreadBase::mLock held
5373void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5374{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375 track->terminate();
5376 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005377 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005378 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005379 removeTrack_l(track);
5380 }
5381}
5382
5383void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5384{
5385 mTracks.remove(track);
5386 // need anything related to effects here?
5387}
5388
5389void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5390{
5391 dumpInternals(fd, args);
5392 dumpTracks(fd, args);
5393 dumpEffectChains(fd, args);
5394}
5395
5396void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5397{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005398 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005399
Glenn Kasten2b806402013-11-20 16:37:38 -08005400 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005401 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005402 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005403 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005404 }
5405
Eric Laurent81784c32012-11-19 14:55:58 -08005406 dumpBase(fd, args);
5407}
5408
Glenn Kasten0f11b512014-01-31 16:18:54 -08005409void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005410{
5411 const size_t SIZE = 256;
5412 char buffer[SIZE];
5413 String8 result;
5414
Marco Nelissenb2208842014-02-07 14:00:50 -08005415 size_t numtracks = mTracks.size();
5416 size_t numactive = mActiveTracks.size();
5417 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005418 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005419 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005420 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005421 RecordTrack::appendDumpHeader(result);
5422 for (size_t i = 0; i < numtracks ; ++i) {
5423 sp<RecordTrack> track = mTracks[i];
5424 if (track != 0) {
5425 bool active = mActiveTracks.indexOf(track) >= 0;
5426 if (active) {
5427 numactiveseen++;
5428 }
5429 track->dump(buffer, SIZE, active);
5430 result.append(buffer);
5431 }
Eric Laurent81784c32012-11-19 14:55:58 -08005432 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005433 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005434 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005435 }
5436
Marco Nelissenb2208842014-02-07 14:00:50 -08005437 if (numactiveseen != numactive) {
5438 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5439 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005440 result.append(buffer);
5441 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005442 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005443 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005444 if (mTracks.indexOf(track) < 0) {
5445 track->dump(buffer, SIZE, true);
5446 result.append(buffer);
5447 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005448 }
Eric Laurent81784c32012-11-19 14:55:58 -08005449
5450 }
5451 write(fd, result.string(), result.size());
5452}
5453
5454// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005455status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5456 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005457{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 RecordTrack *activeTrack = mRecordTrack;
5459 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5460 if (threadBase == 0) {
5461 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005462 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005463 return NOT_ENOUGH_DATA;
5464 }
5465 RecordThread *recordThread = (RecordThread *) threadBase.get();
5466 int32_t rear = recordThread->mRsmpInRear;
5467 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005468 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 // FIXME should not be P2 (don't want to increase latency)
5470 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005471 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005472 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005473 front &= recordThread->mRsmpInFramesP2 - 1;
5474 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005475 if (part1 > (size_t) filled) {
5476 part1 = filled;
5477 }
5478 size_t ask = buffer->frameCount;
5479 ALOG_ASSERT(ask > 0);
5480 if (part1 > ask) {
5481 part1 = ask;
5482 }
5483 if (part1 == 0) {
5484 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005485 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005486 buffer->raw = NULL;
5487 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005488 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005489 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005490 }
5491
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005492 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005493 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005494 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005495 return NO_ERROR;
5496}
5497
5498// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005499void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5500 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005501{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005502 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005503 size_t stepCount = buffer->frameCount;
5504 if (stepCount == 0) {
5505 return;
5506 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005507 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5508 activeTrack->mRsmpInUnrel -= stepCount;
5509 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005510 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005511 buffer->frameCount = 0;
5512}
5513
Eric Laurent10351942014-05-08 18:49:52 -07005514bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5515 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005516{
5517 bool reconfig = false;
5518
Eric Laurent10351942014-05-08 18:49:52 -07005519 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005520
Eric Laurent10351942014-05-08 18:49:52 -07005521 audio_format_t reqFormat = mFormat;
5522 uint32_t samplingRate = mSampleRate;
5523 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5524
5525 AudioParameter param = AudioParameter(keyValuePair);
5526 int value;
5527 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5528 // channel count change can be requested. Do we mandate the first client defines the
5529 // HAL sampling rate and channel count or do we allow changes on the fly?
5530 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5531 samplingRate = value;
5532 reconfig = true;
5533 }
5534 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5535 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5536 status = BAD_VALUE;
5537 } else {
5538 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005539 reconfig = true;
5540 }
Eric Laurent10351942014-05-08 18:49:52 -07005541 }
5542 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5543 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5544 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5545 status = BAD_VALUE;
5546 } else {
5547 channelMask = mask;
5548 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005549 }
Eric Laurent10351942014-05-08 18:49:52 -07005550 }
5551 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5552 // do not accept frame count changes if tracks are open as the track buffer
5553 // size depends on frame count and correct behavior would not be guaranteed
5554 // if frame count is changed after track creation
5555 if (mActiveTracks.size() > 0) {
5556 status = INVALID_OPERATION;
5557 } else {
5558 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005559 }
Eric Laurent10351942014-05-08 18:49:52 -07005560 }
5561 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5562 // forward device change to effects that have requested to be
5563 // aware of attached audio device.
5564 for (size_t i = 0; i < mEffectChains.size(); i++) {
5565 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005566 }
Eric Laurent81784c32012-11-19 14:55:58 -08005567
Eric Laurent10351942014-05-08 18:49:52 -07005568 // store input device and output device but do not forward output device to audio HAL.
5569 // Note that status is ignored by the caller for output device
5570 // (see AudioFlinger::setParameters()
5571 if (audio_is_output_devices(value)) {
5572 mOutDevice = value;
5573 status = BAD_VALUE;
5574 } else {
5575 mInDevice = value;
5576 // disable AEC and NS if the device is a BT SCO headset supporting those
5577 // pre processings
5578 if (mTracks.size() > 0) {
5579 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5580 mAudioFlinger->btNrecIsOff();
5581 for (size_t i = 0; i < mTracks.size(); i++) {
5582 sp<RecordTrack> track = mTracks[i];
5583 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5584 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
5586 }
5587 }
Eric Laurent10351942014-05-08 18:49:52 -07005588 }
5589 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5590 mAudioSource != (audio_source_t)value) {
5591 // forward device change to effects that have requested to be
5592 // aware of attached audio device.
5593 for (size_t i = 0; i < mEffectChains.size(); i++) {
5594 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005595 }
Eric Laurent10351942014-05-08 18:49:52 -07005596 mAudioSource = (audio_source_t)value;
5597 }
Glenn Kastene198c362013-08-13 09:13:36 -07005598
Eric Laurent10351942014-05-08 18:49:52 -07005599 if (status == NO_ERROR) {
5600 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5601 keyValuePair.string());
5602 if (status == INVALID_OPERATION) {
5603 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005604 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5605 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005606 }
5607 if (reconfig) {
5608 if (status == BAD_VALUE &&
5609 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5610 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5611 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5612 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005613 audio_channel_count_from_in_mask(
5614 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005615 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5616 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5617 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005618 }
Eric Laurent10351942014-05-08 18:49:52 -07005619 if (status == NO_ERROR) {
5620 readInputParameters_l();
5621 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005622 }
5623 }
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
Eric Laurent10351942014-05-08 18:49:52 -07005625
Eric Laurent81784c32012-11-19 14:55:58 -08005626 return reconfig;
5627}
5628
5629String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5630{
Eric Laurent81784c32012-11-19 14:55:58 -08005631 Mutex::Autolock _l(mLock);
5632 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005633 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005634 }
5635
Glenn Kastend8ea6992013-07-16 14:17:15 -07005636 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5637 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005638 free(s);
5639 return out_s8;
5640}
5641
Eric Laurent021cf962014-05-13 10:18:14 -07005642void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005643 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005644 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005645
5646 switch (event) {
5647 case AudioSystem::INPUT_OPENED:
5648 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005649 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005650 desc.samplingRate = mSampleRate;
5651 desc.format = mFormat;
5652 desc.frameCount = mFrameCount;
5653 desc.latency = 0;
5654 param2 = &desc;
5655 break;
5656
5657 case AudioSystem::INPUT_CLOSED:
5658 default:
5659 break;
5660 }
Eric Laurent021cf962014-05-13 10:18:14 -07005661 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005662}
5663
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005664void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005665{
Eric Laurent81784c32012-11-19 14:55:58 -08005666 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5667 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07005668 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005669 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005670 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005671 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005672 }
Eric Laurent81784c32012-11-19 14:55:58 -08005673 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005674 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5675 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005676 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005677 // 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 -07005678 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005679 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005680 // A larger value should allow more old data to be read after a track calls start(),
5681 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005682 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005683 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005684 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005685 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5686 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005687
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005688 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5689 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005690}
5691
Glenn Kasten5f972c02014-01-13 09:59:31 -08005692uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005693{
5694 Mutex::Autolock _l(mLock);
5695 if (initCheck() != NO_ERROR) {
5696 return 0;
5697 }
5698
5699 return mInput->stream->get_input_frames_lost(mInput->stream);
5700}
5701
5702uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5703{
5704 Mutex::Autolock _l(mLock);
5705 uint32_t result = 0;
5706 if (getEffectChain_l(sessionId) != 0) {
5707 result = EFFECT_SESSION;
5708 }
5709
5710 for (size_t i = 0; i < mTracks.size(); ++i) {
5711 if (sessionId == mTracks[i]->sessionId()) {
5712 result |= TRACK_SESSION;
5713 break;
5714 }
5715 }
5716
5717 return result;
5718}
5719
5720KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5721{
5722 KeyedVector<int, bool> ids;
5723 Mutex::Autolock _l(mLock);
5724 for (size_t j = 0; j < mTracks.size(); ++j) {
5725 sp<RecordThread::RecordTrack> track = mTracks[j];
5726 int sessionId = track->sessionId();
5727 if (ids.indexOfKey(sessionId) < 0) {
5728 ids.add(sessionId, true);
5729 }
5730 }
5731 return ids;
5732}
5733
5734AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5735{
5736 Mutex::Autolock _l(mLock);
5737 AudioStreamIn *input = mInput;
5738 mInput = NULL;
5739 return input;
5740}
5741
5742// this method must always be called either with ThreadBase mLock held or inside the thread loop
5743audio_stream_t* AudioFlinger::RecordThread::stream() const
5744{
5745 if (mInput == NULL) {
5746 return NULL;
5747 }
5748 return &mInput->stream->common;
5749}
5750
5751status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5752{
5753 // only one chain per input thread
5754 if (mEffectChains.size() != 0) {
5755 return INVALID_OPERATION;
5756 }
5757 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5758
5759 chain->setInBuffer(NULL);
5760 chain->setOutBuffer(NULL);
5761
5762 checkSuspendOnAddEffectChain_l(chain);
5763
5764 mEffectChains.add(chain);
5765
5766 return NO_ERROR;
5767}
5768
5769size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5770{
5771 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5772 ALOGW_IF(mEffectChains.size() != 1,
5773 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5774 chain.get(), mEffectChains.size(), this);
5775 if (mEffectChains.size() == 1) {
5776 mEffectChains.removeAt(0);
5777 }
5778 return 0;
5779}
5780
5781}; // namespace android