blob: b6782a930d3916d08bbb2d2baec3bb275fa65435 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070028#include <media/AudioParameter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080030#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031
32#include <private/media/AudioTrackShared.h>
33#include <hardware/audio.h>
34#include <audio_effects/effect_ns.h>
35#include <audio_effects/effect_aec.h>
36#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080037#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039
40// NBAIO implementations
41#include <media/nbaio/AudioStreamOutSink.h>
42#include <media/nbaio/MonoPipe.h>
43#include <media/nbaio/MonoPipeReader.h>
44#include <media/nbaio/Pipe.h>
45#include <media/nbaio/PipeReader.h>
46#include <media/nbaio/SourceAudioBufferProvider.h>
47
48#include <powermanager/PowerManager.h>
49
50#include <common_time/cc_helper.h>
51#include <common_time/local_clock.h>
52
53#include "AudioFlinger.h"
54#include "AudioMixer.h"
55#include "FastMixer.h"
56#include "ServiceUtilities.h"
57#include "SchedulingPolicyService.h"
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef DEBUG_CPU_USAGE
65#include <cpustats/CentralTendencyStatistics.h>
66#include <cpustats/ThreadCpuUsage.h>
67#endif
68
69// ----------------------------------------------------------------------------
70
71// Note: the following macro is used for extremely verbose logging message. In
72// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
73// 0; but one side effect of this is to turn all LOGV's as well. Some messages
74// are so verbose that we want to suppress them even when we have ALOG_ASSERT
75// turned on. Do not uncomment the #def below unless you really know what you
76// are doing and want to see all of the extremely verbose messages.
77//#define VERY_VERY_VERBOSE_LOGGING
78#ifdef VERY_VERY_VERBOSE_LOGGING
79#define ALOGVV ALOGV
80#else
81#define ALOGVV(a...) do { } while(0)
82#endif
83
84namespace android {
85
86// retry counts for buffer fill timeout
87// 50 * ~20msecs = 1 second
88static const int8_t kMaxTrackRetries = 50;
89static const int8_t kMaxTrackStartupRetries = 50;
90// allow less retry attempts on direct output thread.
91// direct outputs can be a scarce resource in audio hardware and should
92// be released as quickly as possible.
93static const int8_t kMaxTrackRetriesDirect = 2;
94
95// don't warn about blocked writes or record buffer overflows more often than this
96static const nsecs_t kWarningThrottleNs = seconds(5);
97
98// RecordThread loop sleep time upon application overrun or audio HAL read error
99static const int kRecordThreadSleepUs = 5000;
100
Eric Laurent10351942014-05-08 18:49:52 -0700101// maximum time to wait in sendConfigEvent_l() for a status to be received
102static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800103
104// minimum sleep time for the mixer thread loop when tracks are active but in underrun
105static const uint32_t kMinThreadSleepTimeUs = 5000;
106// maximum divider applied to the active sleep time in the mixer thread loop
107static const uint32_t kMaxThreadSleepTimeShift = 2;
108
Andy Hung09a50072014-02-27 14:30:47 -0800109// minimum normal sink buffer size, expressed in milliseconds rather than frames
110static const uint32_t kMinNormalSinkBufferSizeMs = 20;
111// maximum normal sink buffer size
112static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800113
Eric Laurent972a1732013-09-04 09:42:59 -0700114// Offloaded output thread standby delay: allows track transition without going to standby
115static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
116
Eric Laurent81784c32012-11-19 14:55:58 -0800117// Whether to use fast mixer
118static const enum {
119 FastMixer_Never, // never initialize or use: for debugging only
120 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
121 // normal mixer multiplier is 1
122 FastMixer_Static, // initialize if needed, then use all the time if initialized,
123 // multiplier is calculated based on min & max normal mixer buffer size
124 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
125 // multiplier is calculated based on min & max normal mixer buffer size
126 // FIXME for FastMixer_Dynamic:
127 // Supporting this option will require fixing HALs that can't handle large writes.
128 // For example, one HAL implementation returns an error from a large write,
129 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
130 // We could either fix the HAL implementations, or provide a wrapper that breaks
131 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
132} kUseFastMixer = FastMixer_Static;
133
134// Priorities for requestPriority
135static const int kPriorityAudioApp = 2;
136static const int kPriorityFastMixer = 3;
137
138// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
139// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800140// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
141// So for now we just assume that client is double-buffered for fast tracks.
142// FIXME It would be better for client to tell AudioFlinger the value of N,
143// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800144// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800145static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800146
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700147// See Thread::readOnlyHeap().
148// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
149// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
150// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
151static const size_t kRecordThreadReadOnlyHeapSize = 0x1000;
152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// ----------------------------------------------------------------------------
154
155#ifdef ADD_BATTERY_DATA
156// To collect the amplifier usage
157static void addBatteryData(uint32_t params) {
158 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
159 if (service == NULL) {
160 // it already logged
161 return;
162 }
163
164 service->addBatteryData(params);
165}
166#endif
167
168
169// ----------------------------------------------------------------------------
170// CPU Stats
171// ----------------------------------------------------------------------------
172
173class CpuStats {
174public:
175 CpuStats();
176 void sample(const String8 &title);
177#ifdef DEBUG_CPU_USAGE
178private:
179 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
180 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
181
182 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
183
184 int mCpuNum; // thread's current CPU number
185 int mCpukHz; // frequency of thread's current CPU in kHz
186#endif
187};
188
189CpuStats::CpuStats()
190#ifdef DEBUG_CPU_USAGE
191 : mCpuNum(-1), mCpukHz(-1)
192#endif
193{
194}
195
Glenn Kasten0f11b512014-01-31 16:18:54 -0800196void CpuStats::sample(const String8 &title
197#ifndef DEBUG_CPU_USAGE
198 __unused
199#endif
200 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800201#ifdef DEBUG_CPU_USAGE
202 // get current thread's delta CPU time in wall clock ns
203 double wcNs;
204 bool valid = mCpuUsage.sampleAndEnable(wcNs);
205
206 // record sample for wall clock statistics
207 if (valid) {
208 mWcStats.sample(wcNs);
209 }
210
211 // get the current CPU number
212 int cpuNum = sched_getcpu();
213
214 // get the current CPU frequency in kHz
215 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
216
217 // check if either CPU number or frequency changed
218 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
219 mCpuNum = cpuNum;
220 mCpukHz = cpukHz;
221 // ignore sample for purposes of cycles
222 valid = false;
223 }
224
225 // if no change in CPU number or frequency, then record sample for cycle statistics
226 if (valid && mCpukHz > 0) {
227 double cycles = wcNs * cpukHz * 0.000001;
228 mHzStats.sample(cycles);
229 }
230
231 unsigned n = mWcStats.n();
232 // mCpuUsage.elapsed() is expensive, so don't call it every loop
233 if ((n & 127) == 1) {
234 long long elapsed = mCpuUsage.elapsed();
235 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
236 double perLoop = elapsed / (double) n;
237 double perLoop100 = perLoop * 0.01;
238 double perLoop1k = perLoop * 0.001;
239 double mean = mWcStats.mean();
240 double stddev = mWcStats.stddev();
241 double minimum = mWcStats.minimum();
242 double maximum = mWcStats.maximum();
243 double meanCycles = mHzStats.mean();
244 double stddevCycles = mHzStats.stddev();
245 double minCycles = mHzStats.minimum();
246 double maxCycles = mHzStats.maximum();
247 mCpuUsage.resetElapsed();
248 mWcStats.reset();
249 mHzStats.reset();
250 ALOGD("CPU usage for %s over past %.1f secs\n"
251 " (%u mixer loops at %.1f mean ms per loop):\n"
252 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
253 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
254 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
255 title.string(),
256 elapsed * .000000001, n, perLoop * .000001,
257 mean * .001,
258 stddev * .001,
259 minimum * .001,
260 maximum * .001,
261 mean / perLoop100,
262 stddev / perLoop100,
263 minimum / perLoop100,
264 maximum / perLoop100,
265 meanCycles / perLoop1k,
266 stddevCycles / perLoop1k,
267 minCycles / perLoop1k,
268 maxCycles / perLoop1k);
269
270 }
271 }
272#endif
273};
274
275// ----------------------------------------------------------------------------
276// ThreadBase
277// ----------------------------------------------------------------------------
278
279AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
280 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
281 : Thread(false /*canCallJava*/),
282 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700283 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700284 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800285 // are set by PlaybackThread::readOutputParameters_l() or
286 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700287 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800288 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
289 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
290 // mName will be set by concrete (non-virtual) subclass
291 mDeathRecipient(new PMDeathRecipient(this))
292{
293}
294
295AudioFlinger::ThreadBase::~ThreadBase()
296{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700297 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700298 mConfigEvents.clear();
299
Eric Laurent81784c32012-11-19 14:55:58 -0800300 // do not lock the mutex in destructor
301 releaseWakeLock_l();
302 if (mPowerManager != 0) {
303 sp<IBinder> binder = mPowerManager->asBinder();
304 binder->unlinkToDeath(mDeathRecipient);
305 }
306}
307
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700308status_t AudioFlinger::ThreadBase::readyToRun()
309{
310 status_t status = initCheck();
311 if (status == NO_ERROR) {
312 ALOGI("AudioFlinger's thread %p ready to run", this);
313 } else {
314 ALOGE("No working audio driver found.");
315 }
316 return status;
317}
318
Eric Laurent81784c32012-11-19 14:55:58 -0800319void AudioFlinger::ThreadBase::exit()
320{
321 ALOGV("ThreadBase::exit");
322 // do any cleanup required for exit to succeed
323 preExit();
324 {
325 // This lock prevents the following race in thread (uniprocessor for illustration):
326 // if (!exitPending()) {
327 // // context switch from here to exit()
328 // // exit() calls requestExit(), what exitPending() observes
329 // // exit() calls signal(), which is dropped since no waiters
330 // // context switch back from exit() to here
331 // mWaitWorkCV.wait(...);
332 // // now thread is hung
333 // }
334 AutoMutex lock(mLock);
335 requestExit();
336 mWaitWorkCV.broadcast();
337 }
338 // When Thread::requestExitAndWait is made virtual and this method is renamed to
339 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
340 requestExitAndWait();
341}
342
343status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
344{
345 status_t status;
346
347 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
348 Mutex::Autolock _l(mLock);
349
Eric Laurent10351942014-05-08 18:49:52 -0700350 return sendSetParameterConfigEvent_l(keyValuePairs);
351}
352
353// sendConfigEvent_l() must be called with ThreadBase::mLock held
354// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
355status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
356{
357 status_t status = NO_ERROR;
358
359 mConfigEvents.add(event);
360 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800361 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700362 mLock.unlock();
363 {
364 Mutex::Autolock _l(event->mLock);
365 while (event->mWaitStatus) {
366 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
367 event->mStatus = TIMED_OUT;
368 event->mWaitStatus = false;
369 }
370 }
371 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800372 }
Eric Laurent10351942014-05-08 18:49:52 -0700373 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800374 return status;
375}
376
377void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
378{
379 Mutex::Autolock _l(mLock);
380 sendIoConfigEvent_l(event, param);
381}
382
383// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
384void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
385{
Eric Laurent10351942014-05-08 18:49:52 -0700386 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
387 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800388}
389
390// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
391void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
392{
Eric Laurent10351942014-05-08 18:49:52 -0700393 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
394 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800395}
396
Eric Laurent10351942014-05-08 18:49:52 -0700397// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
398status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800399{
Eric Laurent10351942014-05-08 18:49:52 -0700400 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
401 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700402}
403
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700404// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700405void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700406{
Eric Laurent10351942014-05-08 18:49:52 -0700407 bool configChanged = false;
408
Eric Laurent81784c32012-11-19 14:55:58 -0800409 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700410 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
411 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800412 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700413 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700414 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700415 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
416 // FIXME Need to understand why this has to be done asynchronously
417 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700418 true /*asynchronous*/);
419 if (err != 0) {
420 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700421 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700422 }
423 } break;
424 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700425 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700426 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700427 } break;
428 case CFG_EVENT_SET_PARAMETER: {
429 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
430 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
431 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700432 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700433 } break;
434 default:
Eric Laurent10351942014-05-08 18:49:52 -0700435 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700436 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800437 }
Eric Laurent10351942014-05-08 18:49:52 -0700438 {
439 Mutex::Autolock _l(event->mLock);
440 if (event->mWaitStatus) {
441 event->mWaitStatus = false;
442 event->mCond.signal();
443 }
444 }
445 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
446 }
447
448 if (configChanged) {
449 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
Eric Laurent81784c32012-11-19 14:55:58 -0800451}
452
Marco Nelissenb2208842014-02-07 14:00:50 -0800453String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
454 String8 s;
455 if (output) {
456 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
457 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
458 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
459 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
460 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
461 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
462 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
463 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
464 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
465 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
466 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
467 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
468 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
469 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
470 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
471 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
472 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
473 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
474 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
475 } else {
476 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
477 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
478 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
479 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
480 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
481 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
482 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
483 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
484 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
485 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
486 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
487 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
488 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
489 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
490 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
491 }
492 int len = s.length();
493 if (s.length() > 2) {
494 char *str = s.lockBuffer(len);
495 s.unlockBuffer(len - 2);
496 }
497 return s;
498}
499
Glenn Kasten0f11b512014-01-31 16:18:54 -0800500void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800501{
502 const size_t SIZE = 256;
503 char buffer[SIZE];
504 String8 result;
505
506 bool locked = AudioFlinger::dumpTryLock(mLock);
507 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800508 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
510
Marco Nelissenb2208842014-02-07 14:00:50 -0800511 fdprintf(fd, " I/O handle: %d\n", mId);
512 fdprintf(fd, " TID: %d\n", getTid());
513 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
514 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000515 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800516 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
517 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
518 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
519 channelMaskToString(mChannelMask, mType != RECORD).string());
520 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000521 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800522 fdprintf(fd, " Pending config events:");
523 size_t numConfig = mConfigEvents.size();
524 if (numConfig) {
525 for (size_t i = 0; i < numConfig; i++) {
526 mConfigEvents[i]->dump(buffer, SIZE);
527 fdprintf(fd, "\n %s", buffer);
528 }
529 fdprintf(fd, "\n");
530 } else {
531 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800532 }
Eric Laurent81784c32012-11-19 14:55:58 -0800533
534 if (locked) {
535 mLock.unlock();
536 }
537}
538
539void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
540{
541 const size_t SIZE = 256;
542 char buffer[SIZE];
543 String8 result;
544
Marco Nelissenb2208842014-02-07 14:00:50 -0800545 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000546 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 write(fd, buffer, strlen(buffer));
548
Marco Nelissenb2208842014-02-07 14:00:50 -0800549 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800550 sp<EffectChain> chain = mEffectChains[i];
551 if (chain != 0) {
552 chain->dump(fd, args);
553 }
554 }
555}
556
Marco Nelissene14a5d62013-10-03 08:51:24 -0700557void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800558{
559 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700560 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800561}
562
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100563String16 AudioFlinger::ThreadBase::getWakeLockTag()
564{
565 switch (mType) {
566 case MIXER:
567 return String16("AudioMix");
568 case DIRECT:
569 return String16("AudioDirectOut");
570 case DUPLICATING:
571 return String16("AudioDup");
572 case RECORD:
573 return String16("AudioIn");
574 case OFFLOAD:
575 return String16("AudioOffload");
576 default:
577 ALOG_ASSERT(false);
578 return String16("AudioUnknown");
579 }
580}
581
Marco Nelissene14a5d62013-10-03 08:51:24 -0700582void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800583{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800584 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800585 if (mPowerManager != 0) {
586 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700587 status_t status;
588 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700589 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700590 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100591 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700592 String16("media"),
593 uid);
594 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700595 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700596 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100597 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700598 String16("media"));
599 }
Eric Laurent81784c32012-11-19 14:55:58 -0800600 if (status == NO_ERROR) {
601 mWakeLockToken = binder;
602 }
603 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
604 }
605}
606
607void AudioFlinger::ThreadBase::releaseWakeLock()
608{
609 Mutex::Autolock _l(mLock);
610 releaseWakeLock_l();
611}
612
613void AudioFlinger::ThreadBase::releaseWakeLock_l()
614{
615 if (mWakeLockToken != 0) {
616 ALOGV("releaseWakeLock_l() %s", mName);
617 if (mPowerManager != 0) {
618 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
619 }
620 mWakeLockToken.clear();
621 }
622}
623
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800624void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
625 Mutex::Autolock _l(mLock);
626 updateWakeLockUids_l(uids);
627}
628
629void AudioFlinger::ThreadBase::getPowerManager_l() {
630
631 if (mPowerManager == 0) {
632 // use checkService() to avoid blocking if power service is not up yet
633 sp<IBinder> binder =
634 defaultServiceManager()->checkService(String16("power"));
635 if (binder == 0) {
636 ALOGW("Thread %s cannot connect to the power manager service", mName);
637 } else {
638 mPowerManager = interface_cast<IPowerManager>(binder);
639 binder->linkToDeath(mDeathRecipient);
640 }
641 }
642}
643
644void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
645
646 getPowerManager_l();
647 if (mWakeLockToken == NULL) {
648 ALOGE("no wake lock to update!");
649 return;
650 }
651 if (mPowerManager != 0) {
652 sp<IBinder> binder = new BBinder();
653 status_t status;
654 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
655 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
656 }
657}
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659void AudioFlinger::ThreadBase::clearPowerManager()
660{
661 Mutex::Autolock _l(mLock);
662 releaseWakeLock_l();
663 mPowerManager.clear();
664}
665
Glenn Kasten0f11b512014-01-31 16:18:54 -0800666void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800667{
668 sp<ThreadBase> thread = mThread.promote();
669 if (thread != 0) {
670 thread->clearPowerManager();
671 }
672 ALOGW("power manager service died !!!");
673}
674
675void AudioFlinger::ThreadBase::setEffectSuspended(
676 const effect_uuid_t *type, bool suspend, int sessionId)
677{
678 Mutex::Autolock _l(mLock);
679 setEffectSuspended_l(type, suspend, sessionId);
680}
681
682void AudioFlinger::ThreadBase::setEffectSuspended_l(
683 const effect_uuid_t *type, bool suspend, int sessionId)
684{
685 sp<EffectChain> chain = getEffectChain_l(sessionId);
686 if (chain != 0) {
687 if (type != NULL) {
688 chain->setEffectSuspended_l(type, suspend);
689 } else {
690 chain->setEffectSuspendedAll_l(suspend);
691 }
692 }
693
694 updateSuspendedSessions_l(type, suspend, sessionId);
695}
696
697void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
698{
699 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
700 if (index < 0) {
701 return;
702 }
703
704 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
705 mSuspendedSessions.valueAt(index);
706
707 for (size_t i = 0; i < sessionEffects.size(); i++) {
708 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
709 for (int j = 0; j < desc->mRefCount; j++) {
710 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
711 chain->setEffectSuspendedAll_l(true);
712 } else {
713 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
714 desc->mType.timeLow);
715 chain->setEffectSuspended_l(&desc->mType, true);
716 }
717 }
718 }
719}
720
721void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
722 bool suspend,
723 int sessionId)
724{
725 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
726
727 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
728
729 if (suspend) {
730 if (index >= 0) {
731 sessionEffects = mSuspendedSessions.valueAt(index);
732 } else {
733 mSuspendedSessions.add(sessionId, sessionEffects);
734 }
735 } else {
736 if (index < 0) {
737 return;
738 }
739 sessionEffects = mSuspendedSessions.valueAt(index);
740 }
741
742
743 int key = EffectChain::kKeyForSuspendAll;
744 if (type != NULL) {
745 key = type->timeLow;
746 }
747 index = sessionEffects.indexOfKey(key);
748
749 sp<SuspendedSessionDesc> desc;
750 if (suspend) {
751 if (index >= 0) {
752 desc = sessionEffects.valueAt(index);
753 } else {
754 desc = new SuspendedSessionDesc();
755 if (type != NULL) {
756 desc->mType = *type;
757 }
758 sessionEffects.add(key, desc);
759 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
760 }
761 desc->mRefCount++;
762 } else {
763 if (index < 0) {
764 return;
765 }
766 desc = sessionEffects.valueAt(index);
767 if (--desc->mRefCount == 0) {
768 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
769 sessionEffects.removeItemsAt(index);
770 if (sessionEffects.isEmpty()) {
771 ALOGV("updateSuspendedSessions_l() restore removing session %d",
772 sessionId);
773 mSuspendedSessions.removeItem(sessionId);
774 }
775 }
776 }
777 if (!sessionEffects.isEmpty()) {
778 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
779 }
780}
781
782void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
783 bool enabled,
784 int sessionId)
785{
786 Mutex::Autolock _l(mLock);
787 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
788}
789
790void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
791 bool enabled,
792 int sessionId)
793{
794 if (mType != RECORD) {
795 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
796 // another session. This gives the priority to well behaved effect control panels
797 // and applications not using global effects.
798 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
799 // global effects
800 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
801 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
802 }
803 }
804
805 sp<EffectChain> chain = getEffectChain_l(sessionId);
806 if (chain != 0) {
807 chain->checkSuspendOnEffectEnabled(effect, enabled);
808 }
809}
810
811// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
812sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
813 const sp<AudioFlinger::Client>& client,
814 const sp<IEffectClient>& effectClient,
815 int32_t priority,
816 int sessionId,
817 effect_descriptor_t *desc,
818 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700819 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800820{
821 sp<EffectModule> effect;
822 sp<EffectHandle> handle;
823 status_t lStatus;
824 sp<EffectChain> chain;
825 bool chainCreated = false;
826 bool effectCreated = false;
827 bool effectRegistered = false;
828
829 lStatus = initCheck();
830 if (lStatus != NO_ERROR) {
831 ALOGW("createEffect_l() Audio driver not initialized.");
832 goto Exit;
833 }
834
Andy Hung98ef9782014-03-04 14:46:50 -0800835 // Reject any effect on Direct output threads for now, since the format of
836 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
837 if (mType == DIRECT) {
838 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
839 desc->name, mName);
840 lStatus = BAD_VALUE;
841 goto Exit;
842 }
843
Eric Laurent5baf2af2013-09-12 17:37:00 -0700844 // Allow global effects only on offloaded and mixer threads
845 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
846 switch (mType) {
847 case MIXER:
848 case OFFLOAD:
849 break;
850 case DIRECT:
851 case DUPLICATING:
852 case RECORD:
853 default:
854 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
855 lStatus = BAD_VALUE;
856 goto Exit;
857 }
Eric Laurent81784c32012-11-19 14:55:58 -0800858 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700859
Eric Laurent81784c32012-11-19 14:55:58 -0800860 // Only Pre processor effects are allowed on input threads and only on input threads
861 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
862 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
863 desc->name, desc->flags, mType);
864 lStatus = BAD_VALUE;
865 goto Exit;
866 }
867
868 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
869
870 { // scope for mLock
871 Mutex::Autolock _l(mLock);
872
873 // check for existing effect chain with the requested audio session
874 chain = getEffectChain_l(sessionId);
875 if (chain == 0) {
876 // create a new chain for this session
877 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
878 chain = new EffectChain(this, sessionId);
879 addEffectChain_l(chain);
880 chain->setStrategy(getStrategyForSession_l(sessionId));
881 chainCreated = true;
882 } else {
883 effect = chain->getEffectFromDesc_l(desc);
884 }
885
886 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
887
888 if (effect == 0) {
889 int id = mAudioFlinger->nextUniqueId();
890 // Check CPU and memory usage
891 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
892 if (lStatus != NO_ERROR) {
893 goto Exit;
894 }
895 effectRegistered = true;
896 // create a new effect module if none present in the chain
897 effect = new EffectModule(this, chain, desc, id, sessionId);
898 lStatus = effect->status();
899 if (lStatus != NO_ERROR) {
900 goto Exit;
901 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700902 effect->setOffloaded(mType == OFFLOAD, mId);
903
Eric Laurent81784c32012-11-19 14:55:58 -0800904 lStatus = chain->addEffect_l(effect);
905 if (lStatus != NO_ERROR) {
906 goto Exit;
907 }
908 effectCreated = true;
909
910 effect->setDevice(mOutDevice);
911 effect->setDevice(mInDevice);
912 effect->setMode(mAudioFlinger->getMode());
913 effect->setAudioSource(mAudioSource);
914 }
915 // create effect handle and connect it to effect module
916 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800917 lStatus = handle->initCheck();
918 if (lStatus == OK) {
919 lStatus = effect->addHandle(handle.get());
920 }
Eric Laurent81784c32012-11-19 14:55:58 -0800921 if (enabled != NULL) {
922 *enabled = (int)effect->isEnabled();
923 }
924 }
925
926Exit:
927 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
928 Mutex::Autolock _l(mLock);
929 if (effectCreated) {
930 chain->removeEffect_l(effect);
931 }
932 if (effectRegistered) {
933 AudioSystem::unregisterEffect(effect->id());
934 }
935 if (chainCreated) {
936 removeEffectChain_l(chain);
937 }
938 handle.clear();
939 }
940
Glenn Kasten9156ef32013-08-06 15:39:08 -0700941 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800942 return handle;
943}
944
945sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
946{
947 Mutex::Autolock _l(mLock);
948 return getEffect_l(sessionId, effectId);
949}
950
951sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
952{
953 sp<EffectChain> chain = getEffectChain_l(sessionId);
954 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
955}
956
957// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
958// PlaybackThread::mLock held
959status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
960{
961 // check for existing effect chain with the requested audio session
962 int sessionId = effect->sessionId();
963 sp<EffectChain> chain = getEffectChain_l(sessionId);
964 bool chainCreated = false;
965
Eric Laurent5baf2af2013-09-12 17:37:00 -0700966 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
967 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
968 this, effect->desc().name, effect->desc().flags);
969
Eric Laurent81784c32012-11-19 14:55:58 -0800970 if (chain == 0) {
971 // create a new chain for this session
972 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
973 chain = new EffectChain(this, sessionId);
974 addEffectChain_l(chain);
975 chain->setStrategy(getStrategyForSession_l(sessionId));
976 chainCreated = true;
977 }
978 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
979
980 if (chain->getEffectFromId_l(effect->id()) != 0) {
981 ALOGW("addEffect_l() %p effect %s already present in chain %p",
982 this, effect->desc().name, chain.get());
983 return BAD_VALUE;
984 }
985
Eric Laurent5baf2af2013-09-12 17:37:00 -0700986 effect->setOffloaded(mType == OFFLOAD, mId);
987
Eric Laurent81784c32012-11-19 14:55:58 -0800988 status_t status = chain->addEffect_l(effect);
989 if (status != NO_ERROR) {
990 if (chainCreated) {
991 removeEffectChain_l(chain);
992 }
993 return status;
994 }
995
996 effect->setDevice(mOutDevice);
997 effect->setDevice(mInDevice);
998 effect->setMode(mAudioFlinger->getMode());
999 effect->setAudioSource(mAudioSource);
1000 return NO_ERROR;
1001}
1002
1003void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1004
1005 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1006 effect_descriptor_t desc = effect->desc();
1007 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1008 detachAuxEffect_l(effect->id());
1009 }
1010
1011 sp<EffectChain> chain = effect->chain().promote();
1012 if (chain != 0) {
1013 // remove effect chain if removing last effect
1014 if (chain->removeEffect_l(effect) == 0) {
1015 removeEffectChain_l(chain);
1016 }
1017 } else {
1018 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1019 }
1020}
1021
1022void AudioFlinger::ThreadBase::lockEffectChains_l(
1023 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1024{
1025 effectChains = mEffectChains;
1026 for (size_t i = 0; i < mEffectChains.size(); i++) {
1027 mEffectChains[i]->lock();
1028 }
1029}
1030
1031void AudioFlinger::ThreadBase::unlockEffectChains(
1032 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1033{
1034 for (size_t i = 0; i < effectChains.size(); i++) {
1035 effectChains[i]->unlock();
1036 }
1037}
1038
1039sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1040{
1041 Mutex::Autolock _l(mLock);
1042 return getEffectChain_l(sessionId);
1043}
1044
1045sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1046{
1047 size_t size = mEffectChains.size();
1048 for (size_t i = 0; i < size; i++) {
1049 if (mEffectChains[i]->sessionId() == sessionId) {
1050 return mEffectChains[i];
1051 }
1052 }
1053 return 0;
1054}
1055
1056void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1057{
1058 Mutex::Autolock _l(mLock);
1059 size_t size = mEffectChains.size();
1060 for (size_t i = 0; i < size; i++) {
1061 mEffectChains[i]->setMode_l(mode);
1062 }
1063}
1064
1065void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1066 EffectHandle *handle,
1067 bool unpinIfLast) {
1068
1069 Mutex::Autolock _l(mLock);
1070 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1071 // delete the effect module if removing last handle on it
1072 if (effect->removeHandle(handle) == 0) {
1073 if (!effect->isPinned() || unpinIfLast) {
1074 removeEffect_l(effect);
1075 AudioSystem::unregisterEffect(effect->id());
1076 }
1077 }
1078}
1079
1080// ----------------------------------------------------------------------------
1081// Playback
1082// ----------------------------------------------------------------------------
1083
1084AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1085 AudioStreamOut* output,
1086 audio_io_handle_t id,
1087 audio_devices_t device,
1088 type_t type)
1089 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001090 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001091 mMixerBufferEnabled(false),
1092 mMixerBuffer(NULL),
1093 mMixerBufferSize(0),
1094 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1095 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001096 mEffectBufferEnabled(false),
1097 mEffectBuffer(NULL),
1098 mEffectBufferSize(0),
1099 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1100 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001101 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001103 // mStreamTypes[] initialized in constructor body
1104 mOutput(output),
1105 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1106 mMixerStatus(MIXER_IDLE),
1107 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1108 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001109 mBytesRemaining(0),
1110 mCurrentWriteLength(0),
1111 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001112 mWriteAckSequence(0),
1113 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001114 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001115 mScreenState(AudioFlinger::mScreenState),
1116 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001117 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1118 // mLatchD, mLatchQ,
1119 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001120{
1121 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001122 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001123
1124 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1125 // it would be safer to explicitly pass initial masterVolume/masterMute as
1126 // parameter.
1127 //
1128 // If the HAL we are using has support for master volume or master mute,
1129 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1130 // and the mute set to false).
1131 mMasterVolume = audioFlinger->masterVolume_l();
1132 mMasterMute = audioFlinger->masterMute_l();
1133 if (mOutput && mOutput->audioHwDev) {
1134 if (mOutput->audioHwDev->canSetMasterVolume()) {
1135 mMasterVolume = 1.0;
1136 }
1137
1138 if (mOutput->audioHwDev->canSetMasterMute()) {
1139 mMasterMute = false;
1140 }
1141 }
1142
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001143 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001144
1145 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1146 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001147 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001148 stream = (audio_stream_type_t) (stream + 1)) {
1149 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1150 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1151 }
1152 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1153 // because mAudioFlinger doesn't have one to copy from
1154}
1155
1156AudioFlinger::PlaybackThread::~PlaybackThread()
1157{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001158 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001159 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001160 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001161 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001162}
1163
1164void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1165{
1166 dumpInternals(fd, args);
1167 dumpTracks(fd, args);
1168 dumpEffectChains(fd, args);
1169}
1170
Glenn Kasten0f11b512014-01-31 16:18:54 -08001171void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001172{
1173 const size_t SIZE = 256;
1174 char buffer[SIZE];
1175 String8 result;
1176
Marco Nelissenb2208842014-02-07 14:00:50 -08001177 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001178 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1179 const stream_type_t *st = &mStreamTypes[i];
1180 if (i > 0) {
1181 result.appendFormat(", ");
1182 }
1183 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1184 if (st->mute) {
1185 result.append("M");
1186 }
1187 }
1188 result.append("\n");
1189 write(fd, result.string(), result.length());
1190 result.clear();
1191
Eric Laurent81784c32012-11-19 14:55:58 -08001192 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1193 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001194 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001195 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001196
1197 size_t numtracks = mTracks.size();
1198 size_t numactive = mActiveTracks.size();
1199 fdprintf(fd, " %d Tracks", numtracks);
1200 size_t numactiveseen = 0;
1201 if (numtracks) {
1202 fdprintf(fd, " of which %d are active\n", numactive);
1203 Track::appendDumpHeader(result);
1204 for (size_t i = 0; i < numtracks; ++i) {
1205 sp<Track> track = mTracks[i];
1206 if (track != 0) {
1207 bool active = mActiveTracks.indexOf(track) >= 0;
1208 if (active) {
1209 numactiveseen++;
1210 }
1211 track->dump(buffer, SIZE, active);
1212 result.append(buffer);
1213 }
1214 }
1215 } else {
1216 result.append("\n");
1217 }
1218 if (numactiveseen != numactive) {
1219 // some tracks in the active list were not in the tracks list
1220 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1221 " not in the track list\n");
1222 result.append(buffer);
1223 Track::appendDumpHeader(result);
1224 for (size_t i = 0; i < numactive; ++i) {
1225 sp<Track> track = mActiveTracks[i].promote();
1226 if (track != 0 && mTracks.indexOf(track) < 0) {
1227 track->dump(buffer, SIZE, true);
1228 result.append(buffer);
1229 }
1230 }
1231 }
1232
1233 write(fd, result.string(), result.size());
1234
Eric Laurent81784c32012-11-19 14:55:58 -08001235}
1236
1237void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1238{
Marco Nelissenb2208842014-02-07 14:00:50 -08001239 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001240 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001241 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1242 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1243 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1244 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1245 fdprintf(fd, " Suspend count: %d\n", mSuspended);
Andy Hung2098f272014-02-27 14:00:06 -08001246 fdprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001247 fdprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001248 fdprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001249 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001250
1251 dumpBase(fd, args);
1252}
1253
1254// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001255
1256void AudioFlinger::PlaybackThread::onFirstRef()
1257{
1258 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1259}
1260
1261// ThreadBase virtuals
1262void AudioFlinger::PlaybackThread::preExit()
1263{
1264 ALOGV(" preExit()");
1265 // FIXME this is using hard-coded strings but in the future, this functionality will be
1266 // converted to use audio HAL extensions required to support tunneling
1267 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1268}
1269
1270// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1271sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1272 const sp<AudioFlinger::Client>& client,
1273 audio_stream_type_t streamType,
1274 uint32_t sampleRate,
1275 audio_format_t format,
1276 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001277 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 const sp<IMemory>& sharedBuffer,
1279 int sessionId,
1280 IAudioFlinger::track_flags_t *flags,
1281 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001282 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001283 status_t *status)
1284{
Glenn Kasten74935e42013-12-19 08:56:45 -08001285 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001286 sp<Track> track;
1287 status_t lStatus;
1288
1289 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1290
1291 // client expresses a preference for FAST, but we get the final say
1292 if (*flags & IAudioFlinger::TRACK_FAST) {
1293 if (
1294 // not timed
1295 (!isTimed) &&
1296 // either of these use cases:
1297 (
1298 // use case 1: shared buffer with any frame count
1299 (
1300 (sharedBuffer != 0)
1301 ) ||
1302 // use case 2: callback handler and frame count is default or at least as large as HAL
1303 (
1304 (tid != -1) &&
1305 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001306 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001307 )
1308 ) &&
1309 // PCM data
1310 audio_is_linear_pcm(format) &&
1311 // mono or stereo
1312 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1313 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001314 // hardware sample rate
1315 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001316 // normal mixer has an associated fast mixer
1317 hasFastMixer() &&
1318 // there are sufficient fast track slots available
1319 (mFastTrackAvailMask != 0)
1320 // FIXME test that MixerThread for this fast track has a capable output HAL
1321 // FIXME add a permission test also?
1322 ) {
1323 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1324 if (frameCount == 0) {
1325 frameCount = mFrameCount * kFastTrackMultiplier;
1326 }
1327 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1328 frameCount, mFrameCount);
1329 } else {
1330 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1331 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1332 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1333 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1334 audio_is_linear_pcm(format),
1335 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1336 *flags &= ~IAudioFlinger::TRACK_FAST;
1337 // For compatibility with AudioTrack calculation, buffer depth is forced
1338 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1339 // This is probably too conservative, but legacy application code may depend on it.
1340 // If you change this calculation, also review the start threshold which is related.
1341 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1342 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1343 if (minBufCount < 2) {
1344 minBufCount = 2;
1345 }
1346 size_t minFrameCount = mNormalFrameCount * minBufCount;
1347 if (frameCount < minFrameCount) {
1348 frameCount = minFrameCount;
1349 }
1350 }
1351 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001352 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001353
Glenn Kastenc3df8382014-03-13 15:05:25 -07001354 switch (mType) {
1355
1356 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001357 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001359 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1360 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001361 sampleRate, format, channelMask, mOutput, mFormat);
1362 lStatus = BAD_VALUE;
1363 goto Exit;
1364 }
1365 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001366 break;
1367
1368 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001369 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001370 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1371 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001372 sampleRate, format, channelMask, mOutput, mFormat);
1373 lStatus = BAD_VALUE;
1374 goto Exit;
1375 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001376 break;
1377
1378 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001379 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001380 ALOGE("createTrack_l() Bad parameter: format %#x \""
1381 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001382 format, mOutput, mFormat);
1383 lStatus = BAD_VALUE;
1384 goto Exit;
1385 }
Eric Laurent81784c32012-11-19 14:55:58 -08001386 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1387 if (sampleRate > mSampleRate*2) {
1388 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1389 lStatus = BAD_VALUE;
1390 goto Exit;
1391 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001392 break;
1393
Eric Laurent81784c32012-11-19 14:55:58 -08001394 }
1395
1396 lStatus = initCheck();
1397 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001398 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001399 goto Exit;
1400 }
1401
1402 { // scope for mLock
1403 Mutex::Autolock _l(mLock);
1404
1405 // all tracks in same audio session must share the same routing strategy otherwise
1406 // conflicts will happen when tracks are moved from one output to another by audio policy
1407 // manager
1408 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1409 for (size_t i = 0; i < mTracks.size(); ++i) {
1410 sp<Track> t = mTracks[i];
1411 if (t != 0 && !t->isOutputTrack()) {
1412 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1413 if (sessionId == t->sessionId() && strategy != actual) {
1414 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1415 strategy, actual);
1416 lStatus = BAD_VALUE;
1417 goto Exit;
1418 }
1419 }
1420 }
1421
1422 if (!isTimed) {
1423 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001424 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001425 } else {
1426 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001427 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001428 }
Glenn Kasten03003332013-08-06 15:40:54 -07001429
1430 // new Track always returns non-NULL,
1431 // but TimedTrack::create() is a factory that could fail by returning NULL
1432 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1433 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001434 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001435 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001436 goto Exit;
1437 }
1438 mTracks.add(track);
1439
1440 sp<EffectChain> chain = getEffectChain_l(sessionId);
1441 if (chain != 0) {
1442 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1443 track->setMainBuffer(chain->inBuffer());
1444 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1445 chain->incTrackCnt();
1446 }
1447
1448 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1449 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1450 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1451 // so ask activity manager to do this on our behalf
1452 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1453 }
1454 }
1455
1456 lStatus = NO_ERROR;
1457
1458Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001459 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001460 return track;
1461}
1462
1463uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1464{
1465 return latency;
1466}
1467
1468uint32_t AudioFlinger::PlaybackThread::latency() const
1469{
1470 Mutex::Autolock _l(mLock);
1471 return latency_l();
1472}
1473uint32_t AudioFlinger::PlaybackThread::latency_l() const
1474{
1475 if (initCheck() == NO_ERROR) {
1476 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1477 } else {
1478 return 0;
1479 }
1480}
1481
1482void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1483{
1484 Mutex::Autolock _l(mLock);
1485 // Don't apply master volume in SW if our HAL can do it for us.
1486 if (mOutput && mOutput->audioHwDev &&
1487 mOutput->audioHwDev->canSetMasterVolume()) {
1488 mMasterVolume = 1.0;
1489 } else {
1490 mMasterVolume = value;
1491 }
1492}
1493
1494void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1495{
1496 Mutex::Autolock _l(mLock);
1497 // Don't apply master mute in SW if our HAL can do it for us.
1498 if (mOutput && mOutput->audioHwDev &&
1499 mOutput->audioHwDev->canSetMasterMute()) {
1500 mMasterMute = false;
1501 } else {
1502 mMasterMute = muted;
1503 }
1504}
1505
1506void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1507{
1508 Mutex::Autolock _l(mLock);
1509 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001510 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001511}
1512
1513void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1514{
1515 Mutex::Autolock _l(mLock);
1516 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001517 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001518}
1519
1520float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1521{
1522 Mutex::Autolock _l(mLock);
1523 return mStreamTypes[stream].volume;
1524}
1525
1526// addTrack_l() must be called with ThreadBase::mLock held
1527status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1528{
1529 status_t status = ALREADY_EXISTS;
1530
1531 // set retry count for buffer fill
1532 track->mRetryCount = kMaxTrackStartupRetries;
1533 if (mActiveTracks.indexOf(track) < 0) {
1534 // the track is newly added, make sure it fills up all its
1535 // buffers before playing. This is to ensure the client will
1536 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001537 if (!track->isOutputTrack()) {
1538 TrackBase::track_state state = track->mState;
1539 mLock.unlock();
1540 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1541 mLock.lock();
1542 // abort track was stopped/paused while we released the lock
1543 if (state != track->mState) {
1544 if (status == NO_ERROR) {
1545 mLock.unlock();
1546 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1547 mLock.lock();
1548 }
1549 return INVALID_OPERATION;
1550 }
1551 // abort if start is rejected by audio policy manager
1552 if (status != NO_ERROR) {
1553 return PERMISSION_DENIED;
1554 }
1555#ifdef ADD_BATTERY_DATA
1556 // to track the speaker usage
1557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1558#endif
1559 }
1560
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001561 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001562 track->mResetDone = false;
1563 track->mPresentationCompleteFrames = 0;
1564 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001565 mWakeLockUids.add(track->uid());
1566 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001567 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001568 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1569 if (chain != 0) {
1570 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1571 track->sessionId());
1572 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001573 }
1574
1575 status = NO_ERROR;
1576 }
1577
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001578 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001579 return status;
1580}
1581
Eric Laurentbfb1b832013-01-07 09:53:42 -08001582bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001583{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001584 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001585 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001586 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1587 track->mState = TrackBase::STOPPED;
1588 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001590 } else if (track->isFastTrack() || track->isOffloaded()) {
1591 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001592 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001593
1594 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001595}
1596
1597void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1598{
1599 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1600 mTracks.remove(track);
1601 deleteTrackName_l(track->name());
1602 // redundant as track is about to be destroyed, for dumpsys only
1603 track->mName = -1;
1604 if (track->isFastTrack()) {
1605 int index = track->mFastIndex;
1606 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1607 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1608 mFastTrackAvailMask |= 1 << index;
1609 // redundant as track is about to be destroyed, for dumpsys only
1610 track->mFastIndex = -1;
1611 }
1612 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1613 if (chain != 0) {
1614 chain->decTrackCnt();
1615 }
1616}
1617
Eric Laurentede6c3b2013-09-19 14:37:46 -07001618void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619{
1620 // Thread could be blocked waiting for async
1621 // so signal it to handle state changes immediately
1622 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1623 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1624 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001625 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001626}
1627
Eric Laurent81784c32012-11-19 14:55:58 -08001628String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1629{
Eric Laurent81784c32012-11-19 14:55:58 -08001630 Mutex::Autolock _l(mLock);
1631 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001632 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001633 }
1634
Glenn Kastend8ea6992013-07-16 14:17:15 -07001635 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1636 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001637 free(s);
1638 return out_s8;
1639}
1640
Eric Laurent021cf962014-05-13 10:18:14 -07001641void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001642 AudioSystem::OutputDescriptor desc;
1643 void *param2 = NULL;
1644
Eric Laurent021cf962014-05-13 10:18:14 -07001645 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001646 param);
1647
1648 switch (event) {
1649 case AudioSystem::OUTPUT_OPENED:
1650 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001651 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001652 desc.samplingRate = mSampleRate;
1653 desc.format = mFormat;
1654 desc.frameCount = mNormalFrameCount; // FIXME see
1655 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001656 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001657 param2 = &desc;
1658 break;
1659
1660 case AudioSystem::STREAM_CONFIG_CHANGED:
1661 param2 = &param;
1662 case AudioSystem::OUTPUT_CLOSED:
1663 default:
1664 break;
1665 }
Eric Laurent021cf962014-05-13 10:18:14 -07001666 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001667}
1668
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669void AudioFlinger::PlaybackThread::writeCallback()
1670{
1671 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001672 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001673}
1674
1675void AudioFlinger::PlaybackThread::drainCallback()
1676{
1677 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001678 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679}
1680
Eric Laurent3b4529e2013-09-05 18:09:19 -07001681void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001682{
1683 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001684 // reject out of sequence requests
1685 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1686 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001687 mWaitWorkCV.signal();
1688 }
1689}
1690
Eric Laurent3b4529e2013-09-05 18:09:19 -07001691void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692{
1693 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001694 // reject out of sequence requests
1695 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1696 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001697 mWaitWorkCV.signal();
1698 }
1699}
1700
1701// static
1702int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001703 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001704 void *cookie)
1705{
1706 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1707 ALOGV("asyncCallback() event %d", event);
1708 switch (event) {
1709 case STREAM_CBK_EVENT_WRITE_READY:
1710 me->writeCallback();
1711 break;
1712 case STREAM_CBK_EVENT_DRAIN_READY:
1713 me->drainCallback();
1714 break;
1715 default:
1716 ALOGW("asyncCallback() unknown event %d", event);
1717 break;
1718 }
1719 return 0;
1720}
1721
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001722void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001723{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001724 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001725 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1726 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001727 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001728 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001729 }
1730 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001731 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001732 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1733 }
Andy Hunge5412692014-05-16 11:25:07 -07001734 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001735 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001736 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001737 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001738 }
1739 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001740 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1741 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001742 }
Eric Laurent81784c32012-11-19 14:55:58 -08001743 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001744 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1745 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001746 if (mFrameCount & 15) {
1747 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1748 mFrameCount);
1749 }
1750
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1752 (mOutput->stream->set_callback != NULL)) {
1753 if (mOutput->stream->set_callback(mOutput->stream,
1754 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1755 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001756 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001757 }
1758 }
1759
Andy Hung09a50072014-02-27 14:30:47 -08001760 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001761 double multiplier = 1.0;
1762 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1763 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001764 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1765 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001766 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1767 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1768 maxNormalFrameCount = maxNormalFrameCount & ~15;
1769 if (maxNormalFrameCount < minNormalFrameCount) {
1770 maxNormalFrameCount = minNormalFrameCount;
1771 }
1772 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1773 if (multiplier <= 1.0) {
1774 multiplier = 1.0;
1775 } else if (multiplier <= 2.0) {
1776 if (2 * mFrameCount <= maxNormalFrameCount) {
1777 multiplier = 2.0;
1778 } else {
1779 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1780 }
1781 } else {
1782 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001783 // 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 -08001784 // track, but we sometimes have to do this to satisfy the maximum frame count
1785 // constraint)
1786 // FIXME this rounding up should not be done if no HAL SRC
1787 uint32_t truncMult = (uint32_t) multiplier;
1788 if ((truncMult & 1)) {
1789 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1790 ++truncMult;
1791 }
1792 }
1793 multiplier = (double) truncMult;
1794 }
1795 }
1796 mNormalFrameCount = multiplier * mFrameCount;
1797 // round up to nearest 16 frames to satisfy AudioMixer
1798 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001799 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001800 mNormalFrameCount);
1801
Andy Hung010a1a12014-03-13 13:57:33 -07001802 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1803 // Originally this was int16_t[] array, need to remove legacy implications.
1804 free(mSinkBuffer);
1805 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001806 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1807 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1808 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001809 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001810
Andy Hung69aed5f2014-02-25 17:24:40 -08001811 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1812 // drives the output.
1813 free(mMixerBuffer);
1814 mMixerBuffer = NULL;
1815 if (mMixerBufferEnabled) {
1816 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1817 mMixerBufferSize = mNormalFrameCount * mChannelCount
1818 * audio_bytes_per_sample(mMixerBufferFormat);
1819 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1820 }
Andy Hung98ef9782014-03-04 14:46:50 -08001821 free(mEffectBuffer);
1822 mEffectBuffer = NULL;
1823 if (mEffectBufferEnabled) {
1824 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1825 mEffectBufferSize = mNormalFrameCount * mChannelCount
1826 * audio_bytes_per_sample(mEffectBufferFormat);
1827 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1828 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001829
Eric Laurent81784c32012-11-19 14:55:58 -08001830 // force reconfiguration of effect chains and engines to take new buffer size and audio
1831 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001832 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001833 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1834 // matter.
1835 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1836 Vector< sp<EffectChain> > effectChains = mEffectChains;
1837 for (size_t i = 0; i < effectChains.size(); i ++) {
1838 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1839 }
1840}
1841
1842
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001843status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001844{
1845 if (halFrames == NULL || dspFrames == NULL) {
1846 return BAD_VALUE;
1847 }
1848 Mutex::Autolock _l(mLock);
1849 if (initCheck() != NO_ERROR) {
1850 return INVALID_OPERATION;
1851 }
1852 size_t framesWritten = mBytesWritten / mFrameSize;
1853 *halFrames = framesWritten;
1854
1855 if (isSuspended()) {
1856 // return an estimation of rendered frames when the output is suspended
1857 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1858 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1859 return NO_ERROR;
1860 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001861 status_t status;
1862 uint32_t frames;
1863 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1864 *dspFrames = (size_t)frames;
1865 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001866 }
1867}
1868
1869uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1870{
1871 Mutex::Autolock _l(mLock);
1872 uint32_t result = 0;
1873 if (getEffectChain_l(sessionId) != 0) {
1874 result = EFFECT_SESSION;
1875 }
1876
1877 for (size_t i = 0; i < mTracks.size(); ++i) {
1878 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001879 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001880 result |= TRACK_SESSION;
1881 break;
1882 }
1883 }
1884
1885 return result;
1886}
1887
1888uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1889{
1890 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1891 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1892 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1893 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1894 }
1895 for (size_t i = 0; i < mTracks.size(); i++) {
1896 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001897 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001898 return AudioSystem::getStrategyForStream(track->streamType());
1899 }
1900 }
1901 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1902}
1903
1904
1905AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1906{
1907 Mutex::Autolock _l(mLock);
1908 return mOutput;
1909}
1910
1911AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1912{
1913 Mutex::Autolock _l(mLock);
1914 AudioStreamOut *output = mOutput;
1915 mOutput = NULL;
1916 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1917 // must push a NULL and wait for ack
1918 mOutputSink.clear();
1919 mPipeSink.clear();
1920 mNormalSink.clear();
1921 return output;
1922}
1923
1924// this method must always be called either with ThreadBase mLock held or inside the thread loop
1925audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1926{
1927 if (mOutput == NULL) {
1928 return NULL;
1929 }
1930 return &mOutput->stream->common;
1931}
1932
1933uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1934{
1935 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1936}
1937
1938status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1939{
1940 if (!isValidSyncEvent(event)) {
1941 return BAD_VALUE;
1942 }
1943
1944 Mutex::Autolock _l(mLock);
1945
1946 for (size_t i = 0; i < mTracks.size(); ++i) {
1947 sp<Track> track = mTracks[i];
1948 if (event->triggerSession() == track->sessionId()) {
1949 (void) track->setSyncEvent(event);
1950 return NO_ERROR;
1951 }
1952 }
1953
1954 return NAME_NOT_FOUND;
1955}
1956
1957bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1958{
1959 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1960}
1961
1962void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1963 const Vector< sp<Track> >& tracksToRemove)
1964{
1965 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001966 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001967 for (size_t i = 0 ; i < count ; i++) {
1968 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001969 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001970 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971#ifdef ADD_BATTERY_DATA
1972 // to track the speaker usage
1973 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1974#endif
1975 if (track->isTerminated()) {
1976 AudioSystem::releaseOutput(mId);
1977 }
Eric Laurent81784c32012-11-19 14:55:58 -08001978 }
1979 }
1980 }
Eric Laurent81784c32012-11-19 14:55:58 -08001981}
1982
1983void AudioFlinger::PlaybackThread::checkSilentMode_l()
1984{
1985 if (!mMasterMute) {
1986 char value[PROPERTY_VALUE_MAX];
1987 if (property_get("ro.audio.silent", value, "0") > 0) {
1988 char *endptr;
1989 unsigned long ul = strtoul(value, &endptr, 0);
1990 if (*endptr == '\0' && ul != 0) {
1991 ALOGD("Silence is golden");
1992 // The setprop command will not allow a property to be changed after
1993 // the first time it is set, so we don't have to worry about un-muting.
1994 setMasterMute_l(true);
1995 }
1996 }
1997 }
1998}
1999
2000// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002001ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002002{
2003 // FIXME rewrite to reduce number of system calls
2004 mLastWriteTime = systemTime();
2005 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002006 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002007 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002008
2009 // If an NBAIO sink is present, use it to write the normal mixer's submix
2010 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002011 const size_t count = mBytesRemaining / mFrameSize;
2012
Simon Wilson2d590962012-11-29 15:18:50 -08002013 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002014 // update the setpoint when AudioFlinger::mScreenState changes
2015 uint32_t screenState = AudioFlinger::mScreenState;
2016 if (screenState != mScreenState) {
2017 mScreenState = screenState;
2018 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2019 if (pipe != NULL) {
2020 pipe->setAvgFrames((mScreenState & 1) ?
2021 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2022 }
2023 }
Andy Hung010a1a12014-03-13 13:57:33 -07002024 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002025 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002026 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002027 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002028 } else {
2029 bytesWritten = framesWritten;
2030 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002031 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002032 if (status == NO_ERROR) {
2033 size_t totalFramesWritten = mNormalSink->framesWritten();
2034 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2035 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2036 mLatchDValid = true;
2037 }
2038 }
Eric Laurent81784c32012-11-19 14:55:58 -08002039 // otherwise use the HAL / AudioStreamOut directly
2040 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002041 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002042
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002044 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2045 mWriteAckSequence += 2;
2046 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002047 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002048 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002049 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002050 // FIXME We should have an implementation of timestamps for direct output threads.
2051 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002052 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002053 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002054 if (mUseAsyncWrite &&
2055 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2056 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002057 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002058 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002059 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060 }
Eric Laurent81784c32012-11-19 14:55:58 -08002061 }
2062
Eric Laurent81784c32012-11-19 14:55:58 -08002063 mNumWrites++;
2064 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002065 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 return bytesWritten;
2067}
2068
2069void AudioFlinger::PlaybackThread::threadLoop_drain()
2070{
2071 if (mOutput->stream->drain) {
2072 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2073 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002074 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2075 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002076 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002077 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078 }
2079 mOutput->stream->drain(mOutput->stream,
2080 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2081 : AUDIO_DRAIN_ALL);
2082 }
2083}
2084
2085void AudioFlinger::PlaybackThread::threadLoop_exit()
2086{
2087 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002088}
2089
2090/*
2091The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002092 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002093 - activeSleepTime from activeSleepTimeUs()
2094 - idleSleepTime from idleSleepTimeUs()
2095 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2096 - maxPeriod from frame count and sample rate (MIXER only)
2097
2098The parameters that affect these derived values are:
2099 - frame count
2100 - frame size
2101 - sample rate
2102 - device type: A2DP or not
2103 - device latency
2104 - format: PCM or not
2105 - active sleep time
2106 - idle sleep time
2107*/
2108
2109void AudioFlinger::PlaybackThread::cacheParameters_l()
2110{
Andy Hung25c2dac2014-02-27 14:56:00 -08002111 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002112 activeSleepTime = activeSleepTimeUs();
2113 idleSleepTime = idleSleepTimeUs();
2114}
2115
2116void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2117{
Glenn Kasten7c027242012-12-26 14:43:16 -08002118 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002119 this, streamType, mTracks.size());
2120 Mutex::Autolock _l(mLock);
2121
2122 size_t size = mTracks.size();
2123 for (size_t i = 0; i < size; i++) {
2124 sp<Track> t = mTracks[i];
2125 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002126 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002127 }
2128 }
2129}
2130
2131status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2132{
2133 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002134 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2135 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002136 bool ownsBuffer = false;
2137
2138 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2139 if (session > 0) {
2140 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002141 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002142 if (mType != DIRECT) {
2143 size_t numSamples = mNormalFrameCount * mChannelCount;
2144 buffer = new int16_t[numSamples];
2145 memset(buffer, 0, numSamples * sizeof(int16_t));
2146 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2147 ownsBuffer = true;
2148 }
2149
2150 // Attach all tracks with same session ID to this chain.
2151 for (size_t i = 0; i < mTracks.size(); ++i) {
2152 sp<Track> track = mTracks[i];
2153 if (session == track->sessionId()) {
2154 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2155 buffer);
2156 track->setMainBuffer(buffer);
2157 chain->incTrackCnt();
2158 }
2159 }
2160
2161 // indicate all active tracks in the chain
2162 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2163 sp<Track> track = mActiveTracks[i].promote();
2164 if (track == 0) {
2165 continue;
2166 }
2167 if (session == track->sessionId()) {
2168 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2169 chain->incActiveTrackCnt();
2170 }
2171 }
2172 }
2173
2174 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002175 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2176 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002177 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2178 // chains list in order to be processed last as it contains output stage effects
2179 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2180 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2181 // after track specific effects and before output stage
2182 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2183 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2184 // Effect chain for other sessions are inserted at beginning of effect
2185 // chains list to be processed before output mix effects. Relative order between other
2186 // sessions is not important
2187 size_t size = mEffectChains.size();
2188 size_t i = 0;
2189 for (i = 0; i < size; i++) {
2190 if (mEffectChains[i]->sessionId() < session) {
2191 break;
2192 }
2193 }
2194 mEffectChains.insertAt(chain, i);
2195 checkSuspendOnAddEffectChain_l(chain);
2196
2197 return NO_ERROR;
2198}
2199
2200size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2201{
2202 int session = chain->sessionId();
2203
2204 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2205
2206 for (size_t i = 0; i < mEffectChains.size(); i++) {
2207 if (chain == mEffectChains[i]) {
2208 mEffectChains.removeAt(i);
2209 // detach all active tracks from the chain
2210 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2211 sp<Track> track = mActiveTracks[i].promote();
2212 if (track == 0) {
2213 continue;
2214 }
2215 if (session == track->sessionId()) {
2216 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2217 chain.get(), session);
2218 chain->decActiveTrackCnt();
2219 }
2220 }
2221
2222 // detach all tracks with same session ID from this chain
2223 for (size_t i = 0; i < mTracks.size(); ++i) {
2224 sp<Track> track = mTracks[i];
2225 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002226 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002227 chain->decTrackCnt();
2228 }
2229 }
2230 break;
2231 }
2232 }
2233 return mEffectChains.size();
2234}
2235
2236status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2237 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2238{
2239 Mutex::Autolock _l(mLock);
2240 return attachAuxEffect_l(track, EffectId);
2241}
2242
2243status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2244 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2245{
2246 status_t status = NO_ERROR;
2247
2248 if (EffectId == 0) {
2249 track->setAuxBuffer(0, NULL);
2250 } else {
2251 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2252 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2253 if (effect != 0) {
2254 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2255 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2256 } else {
2257 status = INVALID_OPERATION;
2258 }
2259 } else {
2260 status = BAD_VALUE;
2261 }
2262 }
2263 return status;
2264}
2265
2266void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2267{
2268 for (size_t i = 0; i < mTracks.size(); ++i) {
2269 sp<Track> track = mTracks[i];
2270 if (track->auxEffectId() == effectId) {
2271 attachAuxEffect_l(track, 0);
2272 }
2273 }
2274}
2275
2276bool AudioFlinger::PlaybackThread::threadLoop()
2277{
2278 Vector< sp<Track> > tracksToRemove;
2279
2280 standbyTime = systemTime();
2281
2282 // MIXER
2283 nsecs_t lastWarning = 0;
2284
2285 // DUPLICATING
2286 // FIXME could this be made local to while loop?
2287 writeFrames = 0;
2288
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002289 int lastGeneration = 0;
2290
Eric Laurent81784c32012-11-19 14:55:58 -08002291 cacheParameters_l();
2292 sleepTime = idleSleepTime;
2293
2294 if (mType == MIXER) {
2295 sleepTimeShift = 0;
2296 }
2297
2298 CpuStats cpuStats;
2299 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2300
2301 acquireWakeLock();
2302
Glenn Kasten9e58b552013-01-18 15:09:48 -08002303 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2304 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2305 // and then that string will be logged at the next convenient opportunity.
2306 const char *logString = NULL;
2307
Eric Laurent664539d2013-09-23 18:24:31 -07002308 checkSilentMode_l();
2309
Eric Laurent81784c32012-11-19 14:55:58 -08002310 while (!exitPending())
2311 {
2312 cpuStats.sample(myName);
2313
2314 Vector< sp<EffectChain> > effectChains;
2315
Eric Laurent81784c32012-11-19 14:55:58 -08002316 { // scope for mLock
2317
2318 Mutex::Autolock _l(mLock);
2319
Eric Laurent021cf962014-05-13 10:18:14 -07002320 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002321
Glenn Kasten9e58b552013-01-18 15:09:48 -08002322 if (logString != NULL) {
2323 mNBLogWriter->logTimestamp();
2324 mNBLogWriter->log(logString);
2325 logString = NULL;
2326 }
2327
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002328 if (mLatchDValid) {
2329 mLatchQ = mLatchD;
2330 mLatchDValid = false;
2331 mLatchQValid = true;
2332 }
2333
Eric Laurent81784c32012-11-19 14:55:58 -08002334 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 if (mSignalPending) {
2336 // A signal was raised while we were unlocked
2337 mSignalPending = false;
2338 } else if (waitingAsyncCallback_l()) {
2339 if (exitPending()) {
2340 break;
2341 }
2342 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002343 mWakeLockUids.clear();
2344 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345 ALOGV("wait async completion");
2346 mWaitWorkCV.wait(mLock);
2347 ALOGV("async completion/wake");
2348 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002349 standbyTime = systemTime() + standbyDelay;
2350 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002351
2352 continue;
2353 }
2354 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355 isSuspended()) {
2356 // put audio hardware into standby after short delay
2357 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002358
2359 threadLoop_standby();
2360
2361 mStandby = true;
2362 }
2363
2364 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2365 // we're about to wait, flush the binder command buffer
2366 IPCThreadState::self()->flushCommands();
2367
2368 clearOutputTracks();
2369
2370 if (exitPending()) {
2371 break;
2372 }
2373
2374 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002375 mWakeLockUids.clear();
2376 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002377 // wait until we have something to do...
2378 ALOGV("%s going to sleep", myName.string());
2379 mWaitWorkCV.wait(mLock);
2380 ALOGV("%s waking up", myName.string());
2381 acquireWakeLock_l();
2382
2383 mMixerStatus = MIXER_IDLE;
2384 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2385 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002387 checkSilentMode_l();
2388
2389 standbyTime = systemTime() + standbyDelay;
2390 sleepTime = idleSleepTime;
2391 if (mType == MIXER) {
2392 sleepTimeShift = 0;
2393 }
2394
2395 continue;
2396 }
2397 }
Eric Laurent81784c32012-11-19 14:55:58 -08002398 // mMixerStatusIgnoringFastTracks is also updated internally
2399 mMixerStatus = prepareTracks_l(&tracksToRemove);
2400
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002401 // compare with previously applied list
2402 if (lastGeneration != mActiveTracksGeneration) {
2403 // update wakelock
2404 updateWakeLockUids_l(mWakeLockUids);
2405 lastGeneration = mActiveTracksGeneration;
2406 }
2407
Eric Laurent81784c32012-11-19 14:55:58 -08002408 // prevent any changes in effect chain list and in each effect chain
2409 // during mixing and effect process as the audio buffers could be deleted
2410 // or modified if an effect is created or deleted
2411 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002412 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002413
Eric Laurentbfb1b832013-01-07 09:53:42 -08002414 if (mBytesRemaining == 0) {
2415 mCurrentWriteLength = 0;
2416 if (mMixerStatus == MIXER_TRACKS_READY) {
2417 // threadLoop_mix() sets mCurrentWriteLength
2418 threadLoop_mix();
2419 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2420 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2421 // threadLoop_sleepTime sets sleepTime to 0 if data
2422 // must be written to HAL
2423 threadLoop_sleepTime();
2424 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002425 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002426 }
2427 }
Andy Hung98ef9782014-03-04 14:46:50 -08002428 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2429 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2430 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2431 // or mSinkBuffer (if there are no effects).
2432 //
2433 // This is done pre-effects computation; if effects change to
2434 // support higher precision, this needs to move.
2435 //
2436 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2437 // TODO use sleepTime == 0 as an additional condition.
2438 if (mMixerBufferValid) {
2439 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2440 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2441
2442 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2443 mNormalFrameCount * mChannelCount);
2444 }
2445
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446 mBytesRemaining = mCurrentWriteLength;
2447 if (isSuspended()) {
2448 sleepTime = suspendSleepTimeUs();
2449 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002450 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 mBytesRemaining = 0;
2452 }
Eric Laurent81784c32012-11-19 14:55:58 -08002453
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002455 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456 for (size_t i = 0; i < effectChains.size(); i ++) {
2457 effectChains[i]->process_l();
2458 }
Eric Laurent81784c32012-11-19 14:55:58 -08002459 }
2460 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002461 // Process effect chains for offloaded thread even if no audio
2462 // was read from audio track: process only updates effect state
2463 // and thus does have to be synchronized with audio writes but may have
2464 // to be called while waiting for async write callback
2465 if (mType == OFFLOAD) {
2466 for (size_t i = 0; i < effectChains.size(); i ++) {
2467 effectChains[i]->process_l();
2468 }
2469 }
Eric Laurent81784c32012-11-19 14:55:58 -08002470
Andy Hung98ef9782014-03-04 14:46:50 -08002471 // Only if the Effects buffer is enabled and there is data in the
2472 // Effects buffer (buffer valid), we need to
2473 // copy into the sink buffer.
2474 // TODO use sleepTime == 0 as an additional condition.
2475 if (mEffectBufferValid) {
2476 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2477 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2478 mNormalFrameCount * mChannelCount);
2479 }
2480
Eric Laurent81784c32012-11-19 14:55:58 -08002481 // enable changes in effect chain
2482 unlockEffectChains(effectChains);
2483
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484 if (!waitingAsyncCallback()) {
2485 // sleepTime == 0 means we must write to audio hardware
2486 if (sleepTime == 0) {
2487 if (mBytesRemaining) {
2488 ssize_t ret = threadLoop_write();
2489 if (ret < 0) {
2490 mBytesRemaining = 0;
2491 } else {
2492 mBytesWritten += ret;
2493 mBytesRemaining -= ret;
2494 }
2495 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2496 (mMixerStatus == MIXER_DRAIN_ALL)) {
2497 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002499 if (mType == MIXER) {
2500 // write blocked detection
2501 nsecs_t now = systemTime();
2502 nsecs_t delta = now - mLastWriteTime;
2503 if (!mStandby && delta > maxPeriod) {
2504 mNumDelayedWrites++;
2505 if ((now - lastWarning) > kWarningThrottleNs) {
2506 ATRACE_NAME("underrun");
2507 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2508 ns2ms(delta), mNumDelayedWrites, this);
2509 lastWarning = now;
2510 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002511 }
2512 }
Eric Laurent81784c32012-11-19 14:55:58 -08002513
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 } else {
2515 usleep(sleepTime);
2516 }
Eric Laurent81784c32012-11-19 14:55:58 -08002517 }
2518
2519 // Finally let go of removed track(s), without the lock held
2520 // since we can't guarantee the destructors won't acquire that
2521 // same lock. This will also mutate and push a new fast mixer state.
2522 threadLoop_removeTracks(tracksToRemove);
2523 tracksToRemove.clear();
2524
2525 // FIXME I don't understand the need for this here;
2526 // it was in the original code but maybe the
2527 // assignment in saveOutputTracks() makes this unnecessary?
2528 clearOutputTracks();
2529
2530 // Effect chains will be actually deleted here if they were removed from
2531 // mEffectChains list during mixing or effects processing
2532 effectChains.clear();
2533
2534 // FIXME Note that the above .clear() is no longer necessary since effectChains
2535 // is now local to this block, but will keep it for now (at least until merge done).
2536 }
2537
Eric Laurentbfb1b832013-01-07 09:53:42 -08002538 threadLoop_exit();
2539
Eric Laurent81784c32012-11-19 14:55:58 -08002540 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002541 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002542 // put output stream into standby mode
2543 if (!mStandby) {
2544 mOutput->stream->common.standby(&mOutput->stream->common);
2545 }
2546 }
2547
2548 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002549 mWakeLockUids.clear();
2550 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002551
2552 ALOGV("Thread %p type %d exiting", this, mType);
2553 return false;
2554}
2555
Eric Laurentbfb1b832013-01-07 09:53:42 -08002556// removeTracks_l() must be called with ThreadBase::mLock held
2557void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2558{
2559 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002560 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002561 for (size_t i=0 ; i<count ; i++) {
2562 const sp<Track>& track = tracksToRemove.itemAt(i);
2563 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002564 mWakeLockUids.remove(track->uid());
2565 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002566 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2567 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2568 if (chain != 0) {
2569 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2570 track->sessionId());
2571 chain->decActiveTrackCnt();
2572 }
2573 if (track->isTerminated()) {
2574 removeTrack_l(track);
2575 }
2576 }
2577 }
2578
2579}
Eric Laurent81784c32012-11-19 14:55:58 -08002580
Eric Laurentaccc1472013-09-20 09:36:34 -07002581status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2582{
2583 if (mNormalSink != 0) {
2584 return mNormalSink->getTimestamp(timestamp);
2585 }
2586 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2587 uint64_t position64;
2588 int ret = mOutput->stream->get_presentation_position(
2589 mOutput->stream, &position64, &timestamp.mTime);
2590 if (ret == 0) {
2591 timestamp.mPosition = (uint32_t)position64;
2592 return NO_ERROR;
2593 }
2594 }
2595 return INVALID_OPERATION;
2596}
Eric Laurent81784c32012-11-19 14:55:58 -08002597// ----------------------------------------------------------------------------
2598
2599AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2600 audio_io_handle_t id, audio_devices_t device, type_t type)
2601 : PlaybackThread(audioFlinger, output, id, device, type),
2602 // mAudioMixer below
2603 // mFastMixer below
2604 mFastMixerFutex(0)
2605 // mOutputSink below
2606 // mPipeSink below
2607 // mNormalSink below
2608{
2609 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002610 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002611 "mFrameCount=%d, mNormalFrameCount=%d",
2612 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2613 mNormalFrameCount);
2614 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2615
2616 // FIXME - Current mixer implementation only supports stereo output
2617 if (mChannelCount != FCC_2) {
2618 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2619 }
2620
2621 // create an NBAIO sink for the HAL output stream, and negotiate
2622 mOutputSink = new AudioStreamOutSink(output->stream);
2623 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002624 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002625 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2626 ALOG_ASSERT(index == 0);
2627
2628 // initialize fast mixer depending on configuration
2629 bool initFastMixer;
2630 switch (kUseFastMixer) {
2631 case FastMixer_Never:
2632 initFastMixer = false;
2633 break;
2634 case FastMixer_Always:
2635 initFastMixer = true;
2636 break;
2637 case FastMixer_Static:
2638 case FastMixer_Dynamic:
2639 initFastMixer = mFrameCount < mNormalFrameCount;
2640 break;
2641 }
2642 if (initFastMixer) {
2643
2644 // create a MonoPipe to connect our submix to FastMixer
2645 NBAIO_Format format = mOutputSink->format();
2646 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2647 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2648 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2649 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2650 const NBAIO_Format offers[1] = {format};
2651 size_t numCounterOffers = 0;
2652 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2653 ALOG_ASSERT(index == 0);
2654 monoPipe->setAvgFrames((mScreenState & 1) ?
2655 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2656 mPipeSink = monoPipe;
2657
Glenn Kasten46909e72013-02-26 09:20:22 -08002658#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002659 if (mTeeSinkOutputEnabled) {
2660 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2661 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2662 numCounterOffers = 0;
2663 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2664 ALOG_ASSERT(index == 0);
2665 mTeeSink = teeSink;
2666 PipeReader *teeSource = new PipeReader(*teeSink);
2667 numCounterOffers = 0;
2668 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2669 ALOG_ASSERT(index == 0);
2670 mTeeSource = teeSource;
2671 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002672#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002673
2674 // create fast mixer and configure it initially with just one fast track for our submix
2675 mFastMixer = new FastMixer();
2676 FastMixerStateQueue *sq = mFastMixer->sq();
2677#ifdef STATE_QUEUE_DUMP
2678 sq->setObserverDump(&mStateQueueObserverDump);
2679 sq->setMutatorDump(&mStateQueueMutatorDump);
2680#endif
2681 FastMixerState *state = sq->begin();
2682 FastTrack *fastTrack = &state->mFastTracks[0];
2683 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2684 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2685 fastTrack->mVolumeProvider = NULL;
2686 fastTrack->mGeneration++;
2687 state->mFastTracksGen++;
2688 state->mTrackMask = 1;
2689 // fast mixer will use the HAL output sink
2690 state->mOutputSink = mOutputSink.get();
2691 state->mOutputSinkGen++;
2692 state->mFrameCount = mFrameCount;
2693 state->mCommand = FastMixerState::COLD_IDLE;
2694 // already done in constructor initialization list
2695 //mFastMixerFutex = 0;
2696 state->mColdFutexAddr = &mFastMixerFutex;
2697 state->mColdGen++;
2698 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002699#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002700 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002701#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002702 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2703 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002704 sq->end();
2705 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2706
2707 // start the fast mixer
2708 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2709 pid_t tid = mFastMixer->getTid();
2710 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2711 if (err != 0) {
2712 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2713 kPriorityFastMixer, getpid_cached, tid, err);
2714 }
2715
2716#ifdef AUDIO_WATCHDOG
2717 // create and start the watchdog
2718 mAudioWatchdog = new AudioWatchdog();
2719 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2720 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2721 tid = mAudioWatchdog->getTid();
2722 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2723 if (err != 0) {
2724 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2725 kPriorityFastMixer, getpid_cached, tid, err);
2726 }
2727#endif
2728
2729 } else {
2730 mFastMixer = NULL;
2731 }
2732
2733 switch (kUseFastMixer) {
2734 case FastMixer_Never:
2735 case FastMixer_Dynamic:
2736 mNormalSink = mOutputSink;
2737 break;
2738 case FastMixer_Always:
2739 mNormalSink = mPipeSink;
2740 break;
2741 case FastMixer_Static:
2742 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2743 break;
2744 }
2745}
2746
2747AudioFlinger::MixerThread::~MixerThread()
2748{
2749 if (mFastMixer != NULL) {
2750 FastMixerStateQueue *sq = mFastMixer->sq();
2751 FastMixerState *state = sq->begin();
2752 if (state->mCommand == FastMixerState::COLD_IDLE) {
2753 int32_t old = android_atomic_inc(&mFastMixerFutex);
2754 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002755 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002756 }
2757 }
2758 state->mCommand = FastMixerState::EXIT;
2759 sq->end();
2760 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2761 mFastMixer->join();
2762 // Though the fast mixer thread has exited, it's state queue is still valid.
2763 // We'll use that extract the final state which contains one remaining fast track
2764 // corresponding to our sub-mix.
2765 state = sq->begin();
2766 ALOG_ASSERT(state->mTrackMask == 1);
2767 FastTrack *fastTrack = &state->mFastTracks[0];
2768 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2769 delete fastTrack->mBufferProvider;
2770 sq->end(false /*didModify*/);
2771 delete mFastMixer;
2772#ifdef AUDIO_WATCHDOG
2773 if (mAudioWatchdog != 0) {
2774 mAudioWatchdog->requestExit();
2775 mAudioWatchdog->requestExitAndWait();
2776 mAudioWatchdog.clear();
2777 }
2778#endif
2779 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002780 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002781 delete mAudioMixer;
2782}
2783
2784
2785uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2786{
2787 if (mFastMixer != NULL) {
2788 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2789 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2790 }
2791 return latency;
2792}
2793
2794
2795void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2796{
2797 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2798}
2799
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002801{
2802 // FIXME we should only do one push per cycle; confirm this is true
2803 // Start the fast mixer if it's not already running
2804 if (mFastMixer != NULL) {
2805 FastMixerStateQueue *sq = mFastMixer->sq();
2806 FastMixerState *state = sq->begin();
2807 if (state->mCommand != FastMixerState::MIX_WRITE &&
2808 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2809 if (state->mCommand == FastMixerState::COLD_IDLE) {
2810 int32_t old = android_atomic_inc(&mFastMixerFutex);
2811 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002812 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002813 }
2814#ifdef AUDIO_WATCHDOG
2815 if (mAudioWatchdog != 0) {
2816 mAudioWatchdog->resume();
2817 }
2818#endif
2819 }
2820 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002821 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2822 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002823 sq->end();
2824 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2825 if (kUseFastMixer == FastMixer_Dynamic) {
2826 mNormalSink = mPipeSink;
2827 }
2828 } else {
2829 sq->end(false /*didModify*/);
2830 }
2831 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002833}
2834
2835void AudioFlinger::MixerThread::threadLoop_standby()
2836{
2837 // Idle the fast mixer if it's currently running
2838 if (mFastMixer != NULL) {
2839 FastMixerStateQueue *sq = mFastMixer->sq();
2840 FastMixerState *state = sq->begin();
2841 if (!(state->mCommand & FastMixerState::IDLE)) {
2842 state->mCommand = FastMixerState::COLD_IDLE;
2843 state->mColdFutexAddr = &mFastMixerFutex;
2844 state->mColdGen++;
2845 mFastMixerFutex = 0;
2846 sq->end();
2847 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2848 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2849 if (kUseFastMixer == FastMixer_Dynamic) {
2850 mNormalSink = mOutputSink;
2851 }
2852#ifdef AUDIO_WATCHDOG
2853 if (mAudioWatchdog != 0) {
2854 mAudioWatchdog->pause();
2855 }
2856#endif
2857 } else {
2858 sq->end(false /*didModify*/);
2859 }
2860 }
2861 PlaybackThread::threadLoop_standby();
2862}
2863
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2865{
2866 return false;
2867}
2868
2869bool AudioFlinger::PlaybackThread::shouldStandby_l()
2870{
2871 return !mStandby;
2872}
2873
2874bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2875{
2876 Mutex::Autolock _l(mLock);
2877 return waitingAsyncCallback_l();
2878}
2879
Eric Laurent81784c32012-11-19 14:55:58 -08002880// shared by MIXER and DIRECT, overridden by DUPLICATING
2881void AudioFlinger::PlaybackThread::threadLoop_standby()
2882{
2883 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2884 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002886 // discard any pending drain or write ack by incrementing sequence
2887 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2888 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002890 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2891 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 }
Eric Laurent81784c32012-11-19 14:55:58 -08002893}
2894
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002895void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2896{
2897 ALOGV("signal playback thread");
2898 broadcast_l();
2899}
2900
Eric Laurent81784c32012-11-19 14:55:58 -08002901void AudioFlinger::MixerThread::threadLoop_mix()
2902{
2903 // obtain the presentation timestamp of the next output buffer
2904 int64_t pts;
2905 status_t status = INVALID_OPERATION;
2906
2907 if (mNormalSink != 0) {
2908 status = mNormalSink->getNextWriteTimestamp(&pts);
2909 } else {
2910 status = mOutputSink->getNextWriteTimestamp(&pts);
2911 }
2912
2913 if (status != NO_ERROR) {
2914 pts = AudioBufferProvider::kInvalidPTS;
2915 }
2916
2917 // mix buffers...
2918 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002919 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002920 // increase sleep time progressively when application underrun condition clears.
2921 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2922 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2923 // such that we would underrun the audio HAL.
2924 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2925 sleepTimeShift--;
2926 }
2927 sleepTime = 0;
2928 standbyTime = systemTime() + standbyDelay;
2929 //TODO: delay standby when effects have a tail
2930}
2931
2932void AudioFlinger::MixerThread::threadLoop_sleepTime()
2933{
2934 // If no tracks are ready, sleep once for the duration of an output
2935 // buffer size, then write 0s to the output
2936 if (sleepTime == 0) {
2937 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2938 sleepTime = activeSleepTime >> sleepTimeShift;
2939 if (sleepTime < kMinThreadSleepTimeUs) {
2940 sleepTime = kMinThreadSleepTimeUs;
2941 }
2942 // reduce sleep time in case of consecutive application underruns to avoid
2943 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2944 // duration we would end up writing less data than needed by the audio HAL if
2945 // the condition persists.
2946 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2947 sleepTimeShift++;
2948 }
2949 } else {
2950 sleepTime = idleSleepTime;
2951 }
2952 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002953 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2954 // before effects processing or output.
2955 if (mMixerBufferValid) {
2956 memset(mMixerBuffer, 0, mMixerBufferSize);
2957 } else {
2958 memset(mSinkBuffer, 0, mSinkBufferSize);
2959 }
Eric Laurent81784c32012-11-19 14:55:58 -08002960 sleepTime = 0;
2961 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2962 "anticipated start");
2963 }
2964 // TODO add standby time extension fct of effect tail
2965}
2966
2967// prepareTracks_l() must be called with ThreadBase::mLock held
2968AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2969 Vector< sp<Track> > *tracksToRemove)
2970{
2971
2972 mixer_state mixerStatus = MIXER_IDLE;
2973 // find out which tracks need to be processed
2974 size_t count = mActiveTracks.size();
2975 size_t mixedTracks = 0;
2976 size_t tracksWithEffect = 0;
2977 // counts only _active_ fast tracks
2978 size_t fastTracks = 0;
2979 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2980
2981 float masterVolume = mMasterVolume;
2982 bool masterMute = mMasterMute;
2983
2984 if (masterMute) {
2985 masterVolume = 0;
2986 }
2987 // Delegate master volume control to effect in output mix effect chain if needed
2988 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2989 if (chain != 0) {
2990 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2991 chain->setVolume_l(&v, &v);
2992 masterVolume = (float)((v + (1 << 23)) >> 24);
2993 chain.clear();
2994 }
2995
2996 // prepare a new state to push
2997 FastMixerStateQueue *sq = NULL;
2998 FastMixerState *state = NULL;
2999 bool didModify = false;
3000 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3001 if (mFastMixer != NULL) {
3002 sq = mFastMixer->sq();
3003 state = sq->begin();
3004 }
3005
Andy Hung69aed5f2014-02-25 17:24:40 -08003006 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003007 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003008
Eric Laurent81784c32012-11-19 14:55:58 -08003009 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003010 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003011 if (t == 0) {
3012 continue;
3013 }
3014
3015 // this const just means the local variable doesn't change
3016 Track* const track = t.get();
3017
3018 // process fast tracks
3019 if (track->isFastTrack()) {
3020
3021 // It's theoretically possible (though unlikely) for a fast track to be created
3022 // and then removed within the same normal mix cycle. This is not a problem, as
3023 // the track never becomes active so it's fast mixer slot is never touched.
3024 // The converse, of removing an (active) track and then creating a new track
3025 // at the identical fast mixer slot within the same normal mix cycle,
3026 // is impossible because the slot isn't marked available until the end of each cycle.
3027 int j = track->mFastIndex;
3028 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3029 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3030 FastTrack *fastTrack = &state->mFastTracks[j];
3031
3032 // Determine whether the track is currently in underrun condition,
3033 // and whether it had a recent underrun.
3034 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3035 FastTrackUnderruns underruns = ftDump->mUnderruns;
3036 uint32_t recentFull = (underruns.mBitFields.mFull -
3037 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3038 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3039 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3040 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3041 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3042 uint32_t recentUnderruns = recentPartial + recentEmpty;
3043 track->mObservedUnderruns = underruns;
3044 // don't count underruns that occur while stopping or pausing
3045 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003046 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3047 recentUnderruns > 0) {
3048 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3049 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003050 }
3051
3052 // This is similar to the state machine for normal tracks,
3053 // with a few modifications for fast tracks.
3054 bool isActive = true;
3055 switch (track->mState) {
3056 case TrackBase::STOPPING_1:
3057 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003058 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003059 track->mState = TrackBase::STOPPING_2;
3060 }
3061 break;
3062 case TrackBase::PAUSING:
3063 // ramp down is not yet implemented
3064 track->setPaused();
3065 break;
3066 case TrackBase::RESUMING:
3067 // ramp up is not yet implemented
3068 track->mState = TrackBase::ACTIVE;
3069 break;
3070 case TrackBase::ACTIVE:
3071 if (recentFull > 0 || recentPartial > 0) {
3072 // track has provided at least some frames recently: reset retry count
3073 track->mRetryCount = kMaxTrackRetries;
3074 }
3075 if (recentUnderruns == 0) {
3076 // no recent underruns: stay active
3077 break;
3078 }
3079 // there has recently been an underrun of some kind
3080 if (track->sharedBuffer() == 0) {
3081 // were any of the recent underruns "empty" (no frames available)?
3082 if (recentEmpty == 0) {
3083 // no, then ignore the partial underruns as they are allowed indefinitely
3084 break;
3085 }
3086 // there has recently been an "empty" underrun: decrement the retry counter
3087 if (--(track->mRetryCount) > 0) {
3088 break;
3089 }
3090 // indicate to client process that the track was disabled because of underrun;
3091 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003092 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // remove from active list, but state remains ACTIVE [confusing but true]
3094 isActive = false;
3095 break;
3096 }
3097 // fall through
3098 case TrackBase::STOPPING_2:
3099 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003100 case TrackBase::STOPPED:
3101 case TrackBase::FLUSHED: // flush() while active
3102 // Check for presentation complete if track is inactive
3103 // We have consumed all the buffers of this track.
3104 // This would be incomplete if we auto-paused on underrun
3105 {
3106 size_t audioHALFrames =
3107 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3108 size_t framesWritten = mBytesWritten / mFrameSize;
3109 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3110 // track stays in active list until presentation is complete
3111 break;
3112 }
3113 }
3114 if (track->isStopping_2()) {
3115 track->mState = TrackBase::STOPPED;
3116 }
3117 if (track->isStopped()) {
3118 // Can't reset directly, as fast mixer is still polling this track
3119 // track->reset();
3120 // So instead mark this track as needing to be reset after push with ack
3121 resetMask |= 1 << i;
3122 }
3123 isActive = false;
3124 break;
3125 case TrackBase::IDLE:
3126 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003127 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003128 }
3129
3130 if (isActive) {
3131 // was it previously inactive?
3132 if (!(state->mTrackMask & (1 << j))) {
3133 ExtendedAudioBufferProvider *eabp = track;
3134 VolumeProvider *vp = track;
3135 fastTrack->mBufferProvider = eabp;
3136 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003137 fastTrack->mChannelMask = track->mChannelMask;
3138 fastTrack->mGeneration++;
3139 state->mTrackMask |= 1 << j;
3140 didModify = true;
3141 // no acknowledgement required for newly active tracks
3142 }
3143 // cache the combined master volume and stream type volume for fast mixer; this
3144 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003145 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003146 ++fastTracks;
3147 } else {
3148 // was it previously active?
3149 if (state->mTrackMask & (1 << j)) {
3150 fastTrack->mBufferProvider = NULL;
3151 fastTrack->mGeneration++;
3152 state->mTrackMask &= ~(1 << j);
3153 didModify = true;
3154 // If any fast tracks were removed, we must wait for acknowledgement
3155 // because we're about to decrement the last sp<> on those tracks.
3156 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3157 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003158 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003159 }
3160 tracksToRemove->add(track);
3161 // Avoids a misleading display in dumpsys
3162 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3163 }
3164 continue;
3165 }
3166
3167 { // local variable scope to avoid goto warning
3168
3169 audio_track_cblk_t* cblk = track->cblk();
3170
3171 // The first time a track is added we wait
3172 // for all its buffers to be filled before processing it
3173 int name = track->name();
3174 // make sure that we have enough frames to mix one full buffer.
3175 // enforce this condition only once to enable draining the buffer in case the client
3176 // app does not call stop() and relies on underrun to stop:
3177 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3178 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003179 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003180 uint32_t sr = track->sampleRate();
3181 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003182 desiredFrames = mNormalFrameCount;
3183 } else {
3184 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003185 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003186 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003187 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003188 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003189#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003190 // the minimum track buffer size is normally twice the number of frames necessary
3191 // to fill one buffer and the resampler should not leave more than one buffer worth
3192 // of unreleased frames after each pass, but just in case...
3193 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003194#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003195 }
Eric Laurent81784c32012-11-19 14:55:58 -08003196 uint32_t minFrames = 1;
3197 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3198 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003199 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003200 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003201
3202 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003203 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003204 !track->isPaused() && !track->isTerminated())
3205 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003206 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003207
3208 mixedTracks++;
3209
Andy Hung69aed5f2014-02-25 17:24:40 -08003210 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3211 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003212 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003213 if (track->mainBuffer() != mSinkBuffer &&
3214 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003215 if (mEffectBufferEnabled) {
3216 mEffectBufferValid = true; // Later can set directly.
3217 }
Eric Laurent81784c32012-11-19 14:55:58 -08003218 chain = getEffectChain_l(track->sessionId());
3219 // Delegate volume control to effect in track effect chain if needed
3220 if (chain != 0) {
3221 tracksWithEffect++;
3222 } else {
3223 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3224 "session %d",
3225 name, track->sessionId());
3226 }
3227 }
3228
3229
3230 int param = AudioMixer::VOLUME;
3231 if (track->mFillingUpStatus == Track::FS_FILLED) {
3232 // no ramp for the first volume setting
3233 track->mFillingUpStatus = Track::FS_ACTIVE;
3234 if (track->mState == TrackBase::RESUMING) {
3235 track->mState = TrackBase::ACTIVE;
3236 param = AudioMixer::RAMP_VOLUME;
3237 }
3238 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003239 // FIXME should not make a decision based on mServer
3240 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003241 // If the track is stopped before the first frame was mixed,
3242 // do not apply ramp
3243 param = AudioMixer::RAMP_VOLUME;
3244 }
3245
3246 // compute volume for this track
3247 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003248 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003249 vl = vr = va = 0;
3250 if (track->isPausing()) {
3251 track->setPaused();
3252 }
3253 } else {
3254
3255 // read original volumes with volume control
3256 float typeVolume = mStreamTypes[track->streamType()].volume;
3257 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003258 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003259 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3260 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3261 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003262 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003263 if (vlf > GAIN_FLOAT_UNITY) {
3264 ALOGV("Track left volume out of range: %.3g", vlf);
3265 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003266 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003267 if (vrf > GAIN_FLOAT_UNITY) {
3268 ALOGV("Track right volume out of range: %.3g", vrf);
3269 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003270 }
3271 // now apply the master volume and stream type volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07003272 // FIXME we're losing the wonderful dynamic range in the minifloat representation
3273 float v8_24 = v * (MAX_GAIN_INT * MAX_GAIN_INT);
3274 vl = (uint32_t) (v8_24 * vlf);
3275 vr = (uint32_t) (v8_24 * vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08003276 // assuming master volume and stream type volume each go up to 1.0,
3277 // vl and vr are now in 8.24 format
3278
Glenn Kastene3aa6592012-12-04 12:22:46 -08003279 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003280 // send level comes from shared memory and so may be corrupt
3281 if (sendLevel > MAX_GAIN_INT) {
3282 ALOGV("Track send level out of range: %04X", sendLevel);
3283 sendLevel = MAX_GAIN_INT;
3284 }
3285 va = (uint32_t)(v * sendLevel);
3286 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003287
Eric Laurent81784c32012-11-19 14:55:58 -08003288 // Delegate volume control to effect in track effect chain if needed
3289 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3290 // Do not ramp volume if volume is controlled by effect
3291 param = AudioMixer::VOLUME;
3292 track->mHasVolumeController = true;
3293 } else {
3294 // force no volume ramp when volume controller was just disabled or removed
3295 // from effect chain to avoid volume spike
3296 if (track->mHasVolumeController) {
3297 param = AudioMixer::VOLUME;
3298 }
3299 track->mHasVolumeController = false;
3300 }
3301
Glenn Kastenc56f3422014-03-21 17:53:17 -07003302 // FIXME Use float
Eric Laurent81784c32012-11-19 14:55:58 -08003303 // Convert volumes from 8.24 to 4.12 format
3304 // This additional clamping is needed in case chain->setVolume_l() overshot
3305 vl = (vl + (1 << 11)) >> 12;
3306 if (vl > MAX_GAIN_INT) {
3307 vl = MAX_GAIN_INT;
3308 }
3309 vr = (vr + (1 << 11)) >> 12;
3310 if (vr > MAX_GAIN_INT) {
3311 vr = MAX_GAIN_INT;
3312 }
3313
3314 if (va > MAX_GAIN_INT) {
3315 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3316 }
3317
3318 // XXX: these things DON'T need to be done each time
3319 mAudioMixer->setBufferProvider(name, track);
3320 mAudioMixer->enable(name);
3321
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003322 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3323 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3324 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003325 mAudioMixer->setParameter(
3326 name,
3327 AudioMixer::TRACK,
3328 AudioMixer::FORMAT, (void *)track->format());
3329 mAudioMixer->setParameter(
3330 name,
3331 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003332 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003333 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3334 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003335 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003336 if (reqSampleRate == 0) {
3337 reqSampleRate = mSampleRate;
3338 } else if (reqSampleRate > maxSampleRate) {
3339 reqSampleRate = maxSampleRate;
3340 }
Eric Laurent81784c32012-11-19 14:55:58 -08003341 mAudioMixer->setParameter(
3342 name,
3343 AudioMixer::RESAMPLE,
3344 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003345 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003346 /*
3347 * Select the appropriate output buffer for the track.
3348 *
Andy Hung98ef9782014-03-04 14:46:50 -08003349 * Tracks with effects go into their own effects chain buffer
3350 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003351 *
3352 * Other tracks can use mMixerBuffer for higher precision
3353 * channel accumulation. If this buffer is enabled
3354 * (mMixerBufferEnabled true), then selected tracks will accumulate
3355 * into it.
3356 *
3357 */
3358 if (mMixerBufferEnabled
3359 && (track->mainBuffer() == mSinkBuffer
3360 || track->mainBuffer() == mMixerBuffer)) {
3361 mAudioMixer->setParameter(
3362 name,
3363 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003364 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003365 mAudioMixer->setParameter(
3366 name,
3367 AudioMixer::TRACK,
3368 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3369 // TODO: override track->mainBuffer()?
3370 mMixerBufferValid = true;
3371 } else {
3372 mAudioMixer->setParameter(
3373 name,
3374 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003375 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003376 mAudioMixer->setParameter(
3377 name,
3378 AudioMixer::TRACK,
3379 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3380 }
Eric Laurent81784c32012-11-19 14:55:58 -08003381 mAudioMixer->setParameter(
3382 name,
3383 AudioMixer::TRACK,
3384 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3385
3386 // reset retry count
3387 track->mRetryCount = kMaxTrackRetries;
3388
3389 // If one track is ready, set the mixer ready if:
3390 // - the mixer was not ready during previous round OR
3391 // - no other track is not ready
3392 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3393 mixerStatus != MIXER_TRACKS_ENABLED) {
3394 mixerStatus = MIXER_TRACKS_READY;
3395 }
3396 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003397 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003398 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003399 }
Eric Laurent81784c32012-11-19 14:55:58 -08003400 // clear effect chain input buffer if an active track underruns to avoid sending
3401 // previous audio buffer again to effects
3402 chain = getEffectChain_l(track->sessionId());
3403 if (chain != 0) {
3404 chain->clearInputBuffer();
3405 }
3406
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003407 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003408 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3409 track->isStopped() || track->isPaused()) {
3410 // We have consumed all the buffers of this track.
3411 // Remove it from the list of active tracks.
3412 // TODO: use actual buffer filling status instead of latency when available from
3413 // audio HAL
3414 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3415 size_t framesWritten = mBytesWritten / mFrameSize;
3416 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3417 if (track->isStopped()) {
3418 track->reset();
3419 }
3420 tracksToRemove->add(track);
3421 }
3422 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003423 // No buffers for this track. Give it a few chances to
3424 // fill a buffer, then remove it from active list.
3425 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003426 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003427 tracksToRemove->add(track);
3428 // indicate to client process that the track was disabled because of underrun;
3429 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003430 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003431 // If one track is not ready, mark the mixer also not ready if:
3432 // - the mixer was ready during previous round OR
3433 // - no other track is ready
3434 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3435 mixerStatus != MIXER_TRACKS_READY) {
3436 mixerStatus = MIXER_TRACKS_ENABLED;
3437 }
3438 }
3439 mAudioMixer->disable(name);
3440 }
3441
3442 } // local variable scope to avoid goto warning
3443track_is_ready: ;
3444
3445 }
3446
3447 // Push the new FastMixer state if necessary
3448 bool pauseAudioWatchdog = false;
3449 if (didModify) {
3450 state->mFastTracksGen++;
3451 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3452 if (kUseFastMixer == FastMixer_Dynamic &&
3453 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3454 state->mCommand = FastMixerState::COLD_IDLE;
3455 state->mColdFutexAddr = &mFastMixerFutex;
3456 state->mColdGen++;
3457 mFastMixerFutex = 0;
3458 if (kUseFastMixer == FastMixer_Dynamic) {
3459 mNormalSink = mOutputSink;
3460 }
3461 // If we go into cold idle, need to wait for acknowledgement
3462 // so that fast mixer stops doing I/O.
3463 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3464 pauseAudioWatchdog = true;
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466 }
3467 if (sq != NULL) {
3468 sq->end(didModify);
3469 sq->push(block);
3470 }
3471#ifdef AUDIO_WATCHDOG
3472 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3473 mAudioWatchdog->pause();
3474 }
3475#endif
3476
3477 // Now perform the deferred reset on fast tracks that have stopped
3478 while (resetMask != 0) {
3479 size_t i = __builtin_ctz(resetMask);
3480 ALOG_ASSERT(i < count);
3481 resetMask &= ~(1 << i);
3482 sp<Track> t = mActiveTracks[i].promote();
3483 if (t == 0) {
3484 continue;
3485 }
3486 Track* track = t.get();
3487 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3488 track->reset();
3489 }
3490
3491 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003492 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003493
Andy Hung69aed5f2014-02-25 17:24:40 -08003494 // sink or mix buffer must be cleared if all tracks are connected to an
3495 // effect chain as in this case the mixer will not write to the sink or mix buffer
3496 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3498 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003499 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003500 if (mMixerBufferValid) {
3501 memset(mMixerBuffer, 0, mMixerBufferSize);
3502 // TODO: In testing, mSinkBuffer below need not be cleared because
3503 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3504 // after mixing.
3505 //
3506 // To enforce this guarantee:
3507 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3508 // (mixedTracks == 0 && fastTracks > 0))
3509 // must imply MIXER_TRACKS_READY.
3510 // Later, we may clear buffers regardless, and skip much of this logic.
3511 }
Andy Hung98ef9782014-03-04 14:46:50 -08003512 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3513 if (mEffectBufferValid) {
3514 memset(mEffectBuffer, 0, mEffectBufferSize);
3515 }
3516 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003517 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003518 }
3519
3520 // if any fast tracks, then status is ready
3521 mMixerStatusIgnoringFastTracks = mixerStatus;
3522 if (fastTracks > 0) {
3523 mixerStatus = MIXER_TRACKS_READY;
3524 }
3525 return mixerStatus;
3526}
3527
3528// getTrackName_l() must be called with ThreadBase::mLock held
3529int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3530{
3531 return mAudioMixer->getTrackName(channelMask, sessionId);
3532}
3533
3534// deleteTrackName_l() must be called with ThreadBase::mLock held
3535void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3536{
3537 ALOGV("remove track (%d) and delete from mixer", name);
3538 mAudioMixer->deleteTrackName(name);
3539}
3540
Eric Laurent10351942014-05-08 18:49:52 -07003541// checkForNewParameter_l() must be called with ThreadBase::mLock held
3542bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3543 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003544{
Eric Laurent81784c32012-11-19 14:55:58 -08003545 bool reconfig = false;
3546
Eric Laurent10351942014-05-08 18:49:52 -07003547 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003548
Eric Laurent10351942014-05-08 18:49:52 -07003549 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3550 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3551 if (mFastMixer != NULL) {
3552 FastMixerStateQueue *sq = mFastMixer->sq();
3553 FastMixerState *state = sq->begin();
3554 if (!(state->mCommand & FastMixerState::IDLE)) {
3555 previousCommand = state->mCommand;
3556 state->mCommand = FastMixerState::HOT_IDLE;
3557 sq->end();
3558 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3559 } else {
3560 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003561 }
Eric Laurent10351942014-05-08 18:49:52 -07003562 }
Eric Laurent81784c32012-11-19 14:55:58 -08003563
Eric Laurent10351942014-05-08 18:49:52 -07003564 AudioParameter param = AudioParameter(keyValuePair);
3565 int value;
3566 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3567 reconfig = true;
3568 }
3569 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3570 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3571 status = BAD_VALUE;
3572 } else {
3573 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003574 reconfig = true;
3575 }
Eric Laurent10351942014-05-08 18:49:52 -07003576 }
3577 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3578 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3579 status = BAD_VALUE;
3580 } else {
3581 // no need to save value, since it's constant
3582 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003583 }
Eric Laurent10351942014-05-08 18:49:52 -07003584 }
3585 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3586 // do not accept frame count changes if tracks are open as the track buffer
3587 // size depends on frame count and correct behavior would not be guaranteed
3588 // if frame count is changed after track creation
3589 if (!mTracks.isEmpty()) {
3590 status = INVALID_OPERATION;
3591 } else {
3592 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003593 }
Eric Laurent10351942014-05-08 18:49:52 -07003594 }
3595 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003596#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003597 // when changing the audio output device, call addBatteryData to notify
3598 // the change
3599 if (mOutDevice != value) {
3600 uint32_t params = 0;
3601 // check whether speaker is on
3602 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3603 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003604 }
Eric Laurent10351942014-05-08 18:49:52 -07003605
3606 audio_devices_t deviceWithoutSpeaker
3607 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3608 // check if any other device (except speaker) is on
3609 if (value & deviceWithoutSpeaker ) {
3610 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3611 }
3612
3613 if (params != 0) {
3614 addBatteryData(params);
3615 }
3616 }
Eric Laurent81784c32012-11-19 14:55:58 -08003617#endif
3618
Eric Laurent10351942014-05-08 18:49:52 -07003619 // forward device change to effects that have requested to be
3620 // aware of attached audio device.
3621 if (value != AUDIO_DEVICE_NONE) {
3622 mOutDevice = value;
3623 for (size_t i = 0; i < mEffectChains.size(); i++) {
3624 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003625 }
3626 }
Eric Laurent10351942014-05-08 18:49:52 -07003627 }
Eric Laurent81784c32012-11-19 14:55:58 -08003628
Eric Laurent10351942014-05-08 18:49:52 -07003629 if (status == NO_ERROR) {
3630 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3631 keyValuePair.string());
3632 if (!mStandby && status == INVALID_OPERATION) {
3633 mOutput->stream->common.standby(&mOutput->stream->common);
3634 mStandby = true;
3635 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003636 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003637 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003638 }
Eric Laurent10351942014-05-08 18:49:52 -07003639 if (status == NO_ERROR && reconfig) {
3640 readOutputParameters_l();
3641 delete mAudioMixer;
3642 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3643 for (size_t i = 0; i < mTracks.size() ; i++) {
3644 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3645 if (name < 0) {
3646 break;
3647 }
3648 mTracks[i]->mName = name;
3649 }
3650 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3651 }
Eric Laurent81784c32012-11-19 14:55:58 -08003652 }
3653
3654 if (!(previousCommand & FastMixerState::IDLE)) {
3655 ALOG_ASSERT(mFastMixer != NULL);
3656 FastMixerStateQueue *sq = mFastMixer->sq();
3657 FastMixerState *state = sq->begin();
3658 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3659 state->mCommand = previousCommand;
3660 sq->end();
3661 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3662 }
3663
3664 return reconfig;
3665}
3666
3667
3668void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3669{
3670 const size_t SIZE = 256;
3671 char buffer[SIZE];
3672 String8 result;
3673
3674 PlaybackThread::dumpInternals(fd, args);
3675
Marco Nelissenb2208842014-02-07 14:00:50 -08003676 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003677
3678 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003679 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003680 copy.dump(fd);
3681
3682#ifdef STATE_QUEUE_DUMP
3683 // Similar for state queue
3684 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3685 observerCopy.dump(fd);
3686 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3687 mutatorCopy.dump(fd);
3688#endif
3689
Glenn Kasten46909e72013-02-26 09:20:22 -08003690#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003691 // Write the tee output to a .wav file
3692 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003693#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003694
3695#ifdef AUDIO_WATCHDOG
3696 if (mAudioWatchdog != 0) {
3697 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3698 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3699 wdCopy.dump(fd);
3700 }
3701#endif
3702}
3703
3704uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3705{
3706 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3707}
3708
3709uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3710{
3711 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3712}
3713
3714void AudioFlinger::MixerThread::cacheParameters_l()
3715{
3716 PlaybackThread::cacheParameters_l();
3717
3718 // FIXME: Relaxed timing because of a certain device that can't meet latency
3719 // Should be reduced to 2x after the vendor fixes the driver issue
3720 // increase threshold again due to low power audio mode. The way this warning
3721 // threshold is calculated and its usefulness should be reconsidered anyway.
3722 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3723}
3724
3725// ----------------------------------------------------------------------------
3726
3727AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3728 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3729 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3730 // mLeftVolFloat, mRightVolFloat
3731{
3732}
3733
Eric Laurentbfb1b832013-01-07 09:53:42 -08003734AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3735 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3736 ThreadBase::type_t type)
3737 : PlaybackThread(audioFlinger, output, id, device, type)
3738 // mLeftVolFloat, mRightVolFloat
3739{
3740}
3741
Eric Laurent81784c32012-11-19 14:55:58 -08003742AudioFlinger::DirectOutputThread::~DirectOutputThread()
3743{
3744}
3745
Eric Laurentbfb1b832013-01-07 09:53:42 -08003746void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3747{
3748 audio_track_cblk_t* cblk = track->cblk();
3749 float left, right;
3750
3751 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3752 left = right = 0;
3753 } else {
3754 float typeVolume = mStreamTypes[track->streamType()].volume;
3755 float v = mMasterVolume * typeVolume;
3756 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003757 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3758 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3759 if (left > GAIN_FLOAT_UNITY) {
3760 left = GAIN_FLOAT_UNITY;
3761 }
3762 left *= v;
3763 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3764 if (right > GAIN_FLOAT_UNITY) {
3765 right = GAIN_FLOAT_UNITY;
3766 }
3767 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003768 }
3769
3770 if (lastTrack) {
3771 if (left != mLeftVolFloat || right != mRightVolFloat) {
3772 mLeftVolFloat = left;
3773 mRightVolFloat = right;
3774
3775 // Convert volumes from float to 8.24
3776 uint32_t vl = (uint32_t)(left * (1 << 24));
3777 uint32_t vr = (uint32_t)(right * (1 << 24));
3778
3779 // Delegate volume control to effect in track effect chain if needed
3780 // only one effect chain can be present on DirectOutputThread, so if
3781 // there is one, the track is connected to it
3782 if (!mEffectChains.isEmpty()) {
3783 mEffectChains[0]->setVolume_l(&vl, &vr);
3784 left = (float)vl / (1 << 24);
3785 right = (float)vr / (1 << 24);
3786 }
3787 if (mOutput->stream->set_volume) {
3788 mOutput->stream->set_volume(mOutput->stream, left, right);
3789 }
3790 }
3791 }
3792}
3793
3794
Eric Laurent81784c32012-11-19 14:55:58 -08003795AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3796 Vector< sp<Track> > *tracksToRemove
3797)
3798{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003799 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003800 mixer_state mixerStatus = MIXER_IDLE;
3801
3802 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003803 for (size_t i = 0; i < count; i++) {
3804 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003805 // The track died recently
3806 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003807 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003808 }
3809
3810 Track* const track = t.get();
3811 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003812 // Only consider last track started for volume and mixer state control.
3813 // In theory an older track could underrun and restart after the new one starts
3814 // but as we only care about the transition phase between two tracks on a
3815 // direct output, it is not a problem to ignore the underrun case.
3816 sp<Track> l = mLatestActiveTrack.promote();
3817 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003818
3819 // The first time a track is added we wait
3820 // for all its buffers to be filled before processing it
3821 uint32_t minFrames;
3822 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3823 minFrames = mNormalFrameCount;
3824 } else {
3825 minFrames = 1;
3826 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003827
Eric Laurent81784c32012-11-19 14:55:58 -08003828 if ((track->framesReady() >= minFrames) && track->isReady() &&
3829 !track->isPaused() && !track->isTerminated())
3830 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003831 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003832
3833 if (track->mFillingUpStatus == Track::FS_FILLED) {
3834 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003835 // make sure processVolume_l() will apply new volume even if 0
3836 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003837 if (track->mState == TrackBase::RESUMING) {
3838 track->mState = TrackBase::ACTIVE;
3839 }
3840 }
3841
3842 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003843 processVolume_l(track, last);
3844 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003845 // reset retry count
3846 track->mRetryCount = kMaxTrackRetriesDirect;
3847 mActiveTrack = t;
3848 mixerStatus = MIXER_TRACKS_READY;
3849 }
Eric Laurent81784c32012-11-19 14:55:58 -08003850 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003851 // clear effect chain input buffer if the last active track started underruns
3852 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003853 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003854 mEffectChains[0]->clearInputBuffer();
3855 }
3856
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003857 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003858 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3859 track->isStopped() || track->isPaused()) {
3860 // We have consumed all the buffers of this track.
3861 // Remove it from the list of active tracks.
3862 // TODO: implement behavior for compressed audio
3863 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3864 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003865 if (mStandby || !last ||
3866 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003867 if (track->isStopped()) {
3868 track->reset();
3869 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003870 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003871 }
3872 } else {
3873 // No buffers for this track. Give it a few chances to
3874 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003875 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003876 if (--(track->mRetryCount) <= 0) {
3877 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003878 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003879 // indicate to client process that the track was disabled because of underrun;
3880 // it will then automatically call start() when data is available
3881 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003882 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003883 mixerStatus = MIXER_TRACKS_ENABLED;
3884 }
3885 }
3886 }
3887 }
3888
Eric Laurent81784c32012-11-19 14:55:58 -08003889 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003890 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003891
3892 return mixerStatus;
3893}
3894
3895void AudioFlinger::DirectOutputThread::threadLoop_mix()
3896{
Eric Laurent81784c32012-11-19 14:55:58 -08003897 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003898 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003899 // output audio to hardware
3900 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003901 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003902 buffer.frameCount = frameCount;
3903 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003904 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003905 memset(curBuf, 0, frameCount * mFrameSize);
3906 break;
3907 }
3908 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3909 frameCount -= buffer.frameCount;
3910 curBuf += buffer.frameCount * mFrameSize;
3911 mActiveTrack->releaseBuffer(&buffer);
3912 }
Andy Hung2098f272014-02-27 14:00:06 -08003913 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003914 sleepTime = 0;
3915 standbyTime = systemTime() + standbyDelay;
3916 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003917}
3918
3919void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3920{
3921 if (sleepTime == 0) {
3922 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3923 sleepTime = activeSleepTime;
3924 } else {
3925 sleepTime = idleSleepTime;
3926 }
3927 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003928 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003929 sleepTime = 0;
3930 }
3931}
3932
3933// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003934int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3935 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003936{
3937 return 0;
3938}
3939
3940// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003941void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003942{
3943}
3944
Eric Laurent10351942014-05-08 18:49:52 -07003945// checkForNewParameter_l() must be called with ThreadBase::mLock held
3946bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
3947 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003948{
3949 bool reconfig = false;
3950
Eric Laurent10351942014-05-08 18:49:52 -07003951 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003952
Eric Laurent10351942014-05-08 18:49:52 -07003953 AudioParameter param = AudioParameter(keyValuePair);
3954 int value;
3955 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3956 // forward device change to effects that have requested to be
3957 // aware of attached audio device.
3958 if (value != AUDIO_DEVICE_NONE) {
3959 mOutDevice = value;
3960 for (size_t i = 0; i < mEffectChains.size(); i++) {
3961 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07003962 }
3963 }
Eric Laurent81784c32012-11-19 14:55:58 -08003964 }
Eric Laurent10351942014-05-08 18:49:52 -07003965 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3966 // do not accept frame count changes if tracks are open as the track buffer
3967 // size depends on frame count and correct behavior would not be garantied
3968 // if frame count is changed after track creation
3969 if (!mTracks.isEmpty()) {
3970 status = INVALID_OPERATION;
3971 } else {
3972 reconfig = true;
3973 }
3974 }
3975 if (status == NO_ERROR) {
3976 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3977 keyValuePair.string());
3978 if (!mStandby && status == INVALID_OPERATION) {
3979 mOutput->stream->common.standby(&mOutput->stream->common);
3980 mStandby = true;
3981 mBytesWritten = 0;
3982 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3983 keyValuePair.string());
3984 }
3985 if (status == NO_ERROR && reconfig) {
3986 readOutputParameters_l();
3987 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3988 }
3989 }
3990
Eric Laurent81784c32012-11-19 14:55:58 -08003991 return reconfig;
3992}
3993
3994uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3995{
3996 uint32_t time;
3997 if (audio_is_linear_pcm(mFormat)) {
3998 time = PlaybackThread::activeSleepTimeUs();
3999 } else {
4000 time = 10000;
4001 }
4002 return time;
4003}
4004
4005uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4006{
4007 uint32_t time;
4008 if (audio_is_linear_pcm(mFormat)) {
4009 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4010 } else {
4011 time = 10000;
4012 }
4013 return time;
4014}
4015
4016uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4017{
4018 uint32_t time;
4019 if (audio_is_linear_pcm(mFormat)) {
4020 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4021 } else {
4022 time = 10000;
4023 }
4024 return time;
4025}
4026
4027void AudioFlinger::DirectOutputThread::cacheParameters_l()
4028{
4029 PlaybackThread::cacheParameters_l();
4030
4031 // use shorter standby delay as on normal output to release
4032 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004033 if (audio_is_linear_pcm(mFormat)) {
4034 standbyDelay = microseconds(activeSleepTime*2);
4035 } else {
4036 standbyDelay = kOffloadStandbyDelayNs;
4037 }
Eric Laurent81784c32012-11-19 14:55:58 -08004038}
4039
4040// ----------------------------------------------------------------------------
4041
Eric Laurentbfb1b832013-01-07 09:53:42 -08004042AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004043 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004045 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004046 mWriteAckSequence(0),
4047 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004048{
4049}
4050
4051AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4052{
4053}
4054
4055void AudioFlinger::AsyncCallbackThread::onFirstRef()
4056{
4057 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4058}
4059
4060bool AudioFlinger::AsyncCallbackThread::threadLoop()
4061{
4062 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004063 uint32_t writeAckSequence;
4064 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065
4066 {
4067 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004068 while (!((mWriteAckSequence & 1) ||
4069 (mDrainSequence & 1) ||
4070 exitPending())) {
4071 mWaitWorkCV.wait(mLock);
4072 }
4073
Eric Laurentbfb1b832013-01-07 09:53:42 -08004074 if (exitPending()) {
4075 break;
4076 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004077 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4078 mWriteAckSequence, mDrainSequence);
4079 writeAckSequence = mWriteAckSequence;
4080 mWriteAckSequence &= ~1;
4081 drainSequence = mDrainSequence;
4082 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004083 }
4084 {
Eric Laurent4de95592013-09-26 15:28:21 -07004085 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4086 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004087 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004088 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004089 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004090 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004091 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004092 }
4093 }
4094 }
4095 }
4096 return false;
4097}
4098
4099void AudioFlinger::AsyncCallbackThread::exit()
4100{
4101 ALOGV("AsyncCallbackThread::exit");
4102 Mutex::Autolock _l(mLock);
4103 requestExit();
4104 mWaitWorkCV.broadcast();
4105}
4106
Eric Laurent3b4529e2013-09-05 18:09:19 -07004107void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108{
4109 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004110 // bit 0 is cleared
4111 mWriteAckSequence = sequence << 1;
4112}
4113
4114void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4115{
4116 Mutex::Autolock _l(mLock);
4117 // ignore unexpected callbacks
4118 if (mWriteAckSequence & 2) {
4119 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004120 mWaitWorkCV.signal();
4121 }
4122}
4123
Eric Laurent3b4529e2013-09-05 18:09:19 -07004124void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125{
4126 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004127 // bit 0 is cleared
4128 mDrainSequence = sequence << 1;
4129}
4130
4131void AudioFlinger::AsyncCallbackThread::resetDraining()
4132{
4133 Mutex::Autolock _l(mLock);
4134 // ignore unexpected callbacks
4135 if (mDrainSequence & 2) {
4136 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004137 mWaitWorkCV.signal();
4138 }
4139}
4140
4141
4142// ----------------------------------------------------------------------------
4143AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4144 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4145 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4146 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004147 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004148 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004149{
Eric Laurentfd477972013-10-25 18:10:40 -07004150 //FIXME: mStandby should be set to true by ThreadBase constructor
4151 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004152}
4153
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154void AudioFlinger::OffloadThread::threadLoop_exit()
4155{
4156 if (mFlushPending || mHwPaused) {
4157 // If a flush is pending or track was paused, just discard buffered data
4158 flushHw_l();
4159 } else {
4160 mMixerStatus = MIXER_DRAIN_ALL;
4161 threadLoop_drain();
4162 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004163 if (mUseAsyncWrite) {
4164 ALOG_ASSERT(mCallbackThread != 0);
4165 mCallbackThread->exit();
4166 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 PlaybackThread::threadLoop_exit();
4168}
4169
4170AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4171 Vector< sp<Track> > *tracksToRemove
4172)
4173{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174 size_t count = mActiveTracks.size();
4175
4176 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004177 bool doHwPause = false;
4178 bool doHwResume = false;
4179
Eric Laurentede6c3b2013-09-19 14:37:46 -07004180 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4181
Eric Laurentbfb1b832013-01-07 09:53:42 -08004182 // find out which tracks need to be processed
4183 for (size_t i = 0; i < count; i++) {
4184 sp<Track> t = mActiveTracks[i].promote();
4185 // The track died recently
4186 if (t == 0) {
4187 continue;
4188 }
4189 Track* const track = t.get();
4190 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004191 // Only consider last track started for volume and mixer state control.
4192 // In theory an older track could underrun and restart after the new one starts
4193 // but as we only care about the transition phase between two tracks on a
4194 // direct output, it is not a problem to ignore the underrun case.
4195 sp<Track> l = mLatestActiveTrack.promote();
4196 bool last = l.get() == track;
4197
Haynes Mathew George7844f672014-01-15 12:32:55 -08004198 if (track->isInvalid()) {
4199 ALOGW("An invalidated track shouldn't be in active list");
4200 tracksToRemove->add(track);
4201 continue;
4202 }
4203
4204 if (track->mState == TrackBase::IDLE) {
4205 ALOGW("An idle track shouldn't be in active list");
4206 continue;
4207 }
4208
Eric Laurentbfb1b832013-01-07 09:53:42 -08004209 if (track->isPausing()) {
4210 track->setPaused();
4211 if (last) {
4212 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004213 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 mHwPaused = true;
4215 }
4216 // If we were part way through writing the mixbuffer to
4217 // the HAL we must save this until we resume
4218 // BUG - this will be wrong if a different track is made active,
4219 // in that case we want to discard the pending data in the
4220 // mixbuffer and tell the client to present it again when the
4221 // track is resumed
4222 mPausedWriteLength = mCurrentWriteLength;
4223 mPausedBytesRemaining = mBytesRemaining;
4224 mBytesRemaining = 0; // stop writing
4225 }
4226 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004227 } else if (track->isFlushPending()) {
4228 track->flushAck();
4229 if (last) {
4230 mFlushPending = true;
4231 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004232 } else if (track->isResumePending()){
4233 track->resumeAck();
4234 if (last) {
4235 if (mPausedBytesRemaining) {
4236 // Need to continue write that was interrupted
4237 mCurrentWriteLength = mPausedWriteLength;
4238 mBytesRemaining = mPausedBytesRemaining;
4239 mPausedBytesRemaining = 0;
4240 }
4241 if (mHwPaused) {
4242 doHwResume = true;
4243 mHwPaused = false;
4244 // threadLoop_mix() will handle the case that we need to
4245 // resume an interrupted write
4246 }
4247 // enable write to audio HAL
4248 sleepTime = 0;
4249
4250 // Do not handle new data in this iteration even if track->framesReady()
4251 mixerStatus = MIXER_TRACKS_ENABLED;
4252 }
4253 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004254 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004255 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004256 if (track->mFillingUpStatus == Track::FS_FILLED) {
4257 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004258 // make sure processVolume_l() will apply new volume even if 0
4259 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004260 }
4261
4262 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004263 sp<Track> previousTrack = mPreviousTrack.promote();
4264 if (previousTrack != 0) {
4265 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004266 // Flush any data still being written from last track
4267 mBytesRemaining = 0;
4268 if (mPausedBytesRemaining) {
4269 // Last track was paused so we also need to flush saved
4270 // mixbuffer state and invalidate track so that it will
4271 // re-submit that unwritten data when it is next resumed
4272 mPausedBytesRemaining = 0;
4273 // Invalidate is a bit drastic - would be more efficient
4274 // to have a flag to tell client that some of the
4275 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004276 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004277 }
4278 // flush data already sent to the DSP if changing audio session as audio
4279 // comes from a different source. Also invalidate previous track to force a
4280 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004281 if (previousTrack->sessionId() != track->sessionId()) {
4282 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004283 }
4284 }
4285 }
4286 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004287 // reset retry count
4288 track->mRetryCount = kMaxTrackRetriesOffload;
4289 mActiveTrack = t;
4290 mixerStatus = MIXER_TRACKS_READY;
4291 }
4292 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004293 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 if (track->isStopping_1()) {
4295 // Hardware buffer can hold a large amount of audio so we must
4296 // wait for all current track's data to drain before we say
4297 // that the track is stopped.
4298 if (mBytesRemaining == 0) {
4299 // Only start draining when all data in mixbuffer
4300 // has been written
4301 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4302 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004303 // do not drain if no data was ever sent to HAL (mStandby == true)
4304 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004305 // do not modify drain sequence if we are already draining. This happens
4306 // when resuming from pause after drain.
4307 if ((mDrainSequence & 1) == 0) {
4308 sleepTime = 0;
4309 standbyTime = systemTime() + standbyDelay;
4310 mixerStatus = MIXER_DRAIN_TRACK;
4311 mDrainSequence += 2;
4312 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004313 if (mHwPaused) {
4314 // It is possible to move from PAUSED to STOPPING_1 without
4315 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004316 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004317 mHwPaused = false;
4318 }
4319 }
4320 }
4321 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004322 // Drain has completed or we are in standby, signal presentation complete
4323 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324 track->mState = TrackBase::STOPPED;
4325 size_t audioHALFrames =
4326 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4327 size_t framesWritten =
4328 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4329 track->presentationComplete(framesWritten, audioHALFrames);
4330 track->reset();
4331 tracksToRemove->add(track);
4332 }
4333 } else {
4334 // No buffers for this track. Give it a few chances to
4335 // fill a buffer, then remove it from active list.
4336 if (--(track->mRetryCount) <= 0) {
4337 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4338 track->name());
4339 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004340 // indicate to client process that the track was disabled because of underrun;
4341 // it will then automatically call start() when data is available
4342 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004343 } else if (last){
4344 mixerStatus = MIXER_TRACKS_ENABLED;
4345 }
4346 }
4347 }
4348 // compute volume for this track
4349 processVolume_l(track, last);
4350 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004351
Eric Laurentea0fade2013-10-04 16:23:48 -07004352 // make sure the pause/flush/resume sequence is executed in the right order.
4353 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4354 // before flush and then resume HW. This can happen in case of pause/flush/resume
4355 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004356 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004357 mOutput->stream->pause(mOutput->stream);
4358 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004359 if (mFlushPending) {
4360 flushHw_l();
4361 mFlushPending = false;
4362 }
Eric Laurentfd477972013-10-25 18:10:40 -07004363 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004364 mOutput->stream->resume(mOutput->stream);
4365 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004366
Eric Laurentbfb1b832013-01-07 09:53:42 -08004367 // remove all the tracks that need to be...
4368 removeTracks_l(*tracksToRemove);
4369
4370 return mixerStatus;
4371}
4372
Eric Laurentbfb1b832013-01-07 09:53:42 -08004373// must be called with thread mutex locked
4374bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4375{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004376 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4377 mWriteAckSequence, mDrainSequence);
4378 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004379 return true;
4380 }
4381 return false;
4382}
4383
4384// must be called with thread mutex locked
4385bool AudioFlinger::OffloadThread::shouldStandby_l()
4386{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004387 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388
4389 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4390 // after a timeout and we will enter standby then.
4391 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004392 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004393 }
4394
Glenn Kastene6f35b12013-08-19 09:58:50 -07004395 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004396}
4397
4398
4399bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4400{
4401 Mutex::Autolock _l(mLock);
4402 return waitingAsyncCallback_l();
4403}
4404
4405void AudioFlinger::OffloadThread::flushHw_l()
4406{
4407 mOutput->stream->flush(mOutput->stream);
4408 // Flush anything still waiting in the mixbuffer
4409 mCurrentWriteLength = 0;
4410 mBytesRemaining = 0;
4411 mPausedWriteLength = 0;
4412 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004413 mHwPaused = false;
4414
Eric Laurentbfb1b832013-01-07 09:53:42 -08004415 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004416 // discard any pending drain or write ack by incrementing sequence
4417 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4418 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004419 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004420 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4421 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004422 }
4423}
4424
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004425void AudioFlinger::OffloadThread::onAddNewTrack_l()
4426{
4427 sp<Track> previousTrack = mPreviousTrack.promote();
4428 sp<Track> latestTrack = mLatestActiveTrack.promote();
4429
4430 if (previousTrack != 0 && latestTrack != 0 &&
4431 (previousTrack->sessionId() != latestTrack->sessionId())) {
4432 mFlushPending = true;
4433 }
4434 PlaybackThread::onAddNewTrack_l();
4435}
4436
Eric Laurentbfb1b832013-01-07 09:53:42 -08004437// ----------------------------------------------------------------------------
4438
Eric Laurent81784c32012-11-19 14:55:58 -08004439AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4440 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4441 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4442 DUPLICATING),
4443 mWaitTimeMs(UINT_MAX)
4444{
4445 addOutputTrack(mainThread);
4446}
4447
4448AudioFlinger::DuplicatingThread::~DuplicatingThread()
4449{
4450 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4451 mOutputTracks[i]->destroy();
4452 }
4453}
4454
4455void AudioFlinger::DuplicatingThread::threadLoop_mix()
4456{
4457 // mix buffers...
4458 if (outputsReady(outputTracks)) {
4459 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4460 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004461 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004462 }
4463 sleepTime = 0;
4464 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004465 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004466 standbyTime = systemTime() + standbyDelay;
4467}
4468
4469void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4470{
4471 if (sleepTime == 0) {
4472 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4473 sleepTime = activeSleepTime;
4474 } else {
4475 sleepTime = idleSleepTime;
4476 }
4477 } else if (mBytesWritten != 0) {
4478 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4479 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004480 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004481 } else {
4482 // flush remaining overflow buffers in output tracks
4483 writeFrames = 0;
4484 }
4485 sleepTime = 0;
4486 }
4487}
4488
Eric Laurentbfb1b832013-01-07 09:53:42 -08004489ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004490{
4491 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004492 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4493 // for delivery downstream as needed. This in-place conversion is safe as
4494 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4495 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4496 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4497 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4498 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4499 }
4500 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004501 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004502 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004503 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004504}
4505
4506void AudioFlinger::DuplicatingThread::threadLoop_standby()
4507{
4508 // DuplicatingThread implements standby by stopping all tracks
4509 for (size_t i = 0; i < outputTracks.size(); i++) {
4510 outputTracks[i]->stop();
4511 }
4512}
4513
4514void AudioFlinger::DuplicatingThread::saveOutputTracks()
4515{
4516 outputTracks = mOutputTracks;
4517}
4518
4519void AudioFlinger::DuplicatingThread::clearOutputTracks()
4520{
4521 outputTracks.clear();
4522}
4523
4524void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4525{
4526 Mutex::Autolock _l(mLock);
4527 // FIXME explain this formula
4528 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004529 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4530 // due to current usage case and restrictions on the AudioBufferProvider.
4531 // Actual buffer conversion is done in threadLoop_write().
4532 //
4533 // TODO: This may change in the future, depending on multichannel
4534 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004535 OutputTrack *outputTrack = new OutputTrack(thread,
4536 this,
4537 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004538 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004539 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004540 frameCount,
4541 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004542 if (outputTrack->cblk() != NULL) {
4543 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4544 mOutputTracks.add(outputTrack);
4545 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4546 updateWaitTime_l();
4547 }
4548}
4549
4550void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4551{
4552 Mutex::Autolock _l(mLock);
4553 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4554 if (mOutputTracks[i]->thread() == thread) {
4555 mOutputTracks[i]->destroy();
4556 mOutputTracks.removeAt(i);
4557 updateWaitTime_l();
4558 return;
4559 }
4560 }
4561 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4562}
4563
4564// caller must hold mLock
4565void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4566{
4567 mWaitTimeMs = UINT_MAX;
4568 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4569 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4570 if (strong != 0) {
4571 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4572 if (waitTimeMs < mWaitTimeMs) {
4573 mWaitTimeMs = waitTimeMs;
4574 }
4575 }
4576 }
4577}
4578
4579
4580bool AudioFlinger::DuplicatingThread::outputsReady(
4581 const SortedVector< sp<OutputTrack> > &outputTracks)
4582{
4583 for (size_t i = 0; i < outputTracks.size(); i++) {
4584 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4585 if (thread == 0) {
4586 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4587 outputTracks[i].get());
4588 return false;
4589 }
4590 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4591 // see note at standby() declaration
4592 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4593 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4594 thread.get());
4595 return false;
4596 }
4597 }
4598 return true;
4599}
4600
4601uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4602{
4603 return (mWaitTimeMs * 1000) / 2;
4604}
4605
4606void AudioFlinger::DuplicatingThread::cacheParameters_l()
4607{
4608 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4609 updateWaitTime_l();
4610
4611 MixerThread::cacheParameters_l();
4612}
4613
4614// ----------------------------------------------------------------------------
4615// Record
4616// ----------------------------------------------------------------------------
4617
4618AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4619 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004620 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004621 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004622 audio_devices_t inDevice
4623#ifdef TEE_SINK
4624 , const sp<NBAIO_Sink>& teeSink
4625#endif
4626 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004627 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004628 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004629 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004630 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004631#ifdef TEE_SINK
4632 , mTeeSink(teeSink)
4633#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004634 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4635 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004636{
4637 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004638 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004639
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004640 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004641}
4642
4643
4644AudioFlinger::RecordThread::~RecordThread()
4645{
Glenn Kasten481fb672013-09-30 14:39:28 -07004646 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004647 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004648}
4649
4650void AudioFlinger::RecordThread::onFirstRef()
4651{
4652 run(mName, PRIORITY_URGENT_AUDIO);
4653}
4654
Eric Laurent81784c32012-11-19 14:55:58 -08004655bool AudioFlinger::RecordThread::threadLoop()
4656{
Eric Laurent81784c32012-11-19 14:55:58 -08004657 nsecs_t lastWarning = 0;
4658
4659 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004660
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004661reacquire_wakelock:
4662 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004663 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004664 {
4665 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004666 size_t size = mActiveTracks.size();
4667 activeTracksGen = mActiveTracksGen;
4668 if (size > 0) {
4669 // FIXME an arbitrary choice
4670 activeTrack = mActiveTracks[0];
4671 acquireWakeLock_l(activeTrack->uid());
4672 if (size > 1) {
4673 SortedVector<int> tmp;
4674 for (size_t i = 0; i < size; i++) {
4675 tmp.add(mActiveTracks[i]->uid());
4676 }
4677 updateWakeLockUids_l(tmp);
4678 }
4679 } else {
4680 acquireWakeLock_l(-1);
4681 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004682 }
4683
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004684 // used to request a deferred sleep, to be executed later while mutex is unlocked
4685 uint32_t sleepUs = 0;
4686
4687 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004688 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004689 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004690
Glenn Kasten5edadd42013-08-14 16:30:49 -07004691 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004692 if (sleepUs > 0) {
4693 usleep(sleepUs);
4694 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004695 }
4696
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004697 // activeTracks accumulates a copy of a subset of mActiveTracks
4698 Vector< sp<RecordTrack> > activeTracks;
4699
Eric Laurent10351942014-05-08 18:49:52 -07004700
Eric Laurent81784c32012-11-19 14:55:58 -08004701 { // scope for mLock
4702 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004703
Eric Laurent021cf962014-05-13 10:18:14 -07004704 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004705
Eric Laurent000a4192014-01-29 15:17:32 -08004706 // check exitPending here because checkForNewParameters_l() and
4707 // checkForNewParameters_l() can temporarily release mLock
4708 if (exitPending()) {
4709 break;
4710 }
4711
Glenn Kasten2b806402013-11-20 16:37:38 -08004712 // if no active track(s), then standby and release wakelock
4713 size_t size = mActiveTracks.size();
4714 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004715 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004716 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004717 releaseWakeLock_l();
4718 ALOGV("RecordThread: loop stopping");
4719 // go to sleep
4720 mWaitWorkCV.wait(mLock);
4721 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004722 goto reacquire_wakelock;
4723 }
4724
Glenn Kasten2b806402013-11-20 16:37:38 -08004725 if (mActiveTracksGen != activeTracksGen) {
4726 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004727 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004728 for (size_t i = 0; i < size; i++) {
4729 tmp.add(mActiveTracks[i]->uid());
4730 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004731 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004732 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004733
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004734 bool doBroadcast = false;
4735 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004736
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004737 activeTrack = mActiveTracks[i];
4738 if (activeTrack->isTerminated()) {
4739 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004740 mActiveTracks.remove(activeTrack);
4741 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004742 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004743 continue;
4744 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004745
4746 TrackBase::track_state activeTrackState = activeTrack->mState;
4747 switch (activeTrackState) {
4748
4749 case TrackBase::PAUSING:
4750 mActiveTracks.remove(activeTrack);
4751 mActiveTracksGen++;
4752 doBroadcast = true;
4753 size--;
4754 continue;
4755
4756 case TrackBase::STARTING_1:
4757 sleepUs = 10000;
4758 i++;
4759 continue;
4760
4761 case TrackBase::STARTING_2:
4762 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004763 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004764 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004765 break;
4766
4767 case TrackBase::ACTIVE:
4768 break;
4769
4770 case TrackBase::IDLE:
4771 i++;
4772 continue;
4773
4774 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004775 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004776 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004777
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004778 activeTracks.add(activeTrack);
4779 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004780
Glenn Kasten9e982352013-08-14 14:39:50 -07004781 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004782 if (doBroadcast) {
4783 mStartStopCond.broadcast();
4784 }
4785
4786 // sleep if there are no active tracks to process
4787 if (activeTracks.size() == 0) {
4788 if (sleepUs == 0) {
4789 sleepUs = kRecordThreadSleepUs;
4790 }
4791 continue;
4792 }
4793 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004794
Eric Laurent81784c32012-11-19 14:55:58 -08004795 lockEffectChains_l(effectChains);
4796 }
4797
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004798 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004799
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004800 size_t size = effectChains.size();
4801 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004802 // thread mutex is not locked, but effect chain is locked
4803 effectChains[i]->process_l();
4804 }
4805
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004806 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4807 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4808 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4809 // If destination is non-contiguous, first read past the nominal end of buffer, then
4810 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004811
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004812 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4813 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4814 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4815 if (bytesRead <= 0) {
4816 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4817 // Force input into standby so that it tries to recover at next read attempt
4818 inputStandBy();
4819 sleepUs = kRecordThreadSleepUs;
4820 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004821 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004822 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4823 size_t framesRead = bytesRead / mFrameSize;
4824 ALOG_ASSERT(framesRead > 0);
4825 if (mTeeSink != 0) {
4826 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4827 }
4828 // If destination is non-contiguous, we now correct for reading past end of buffer.
4829 size_t part1 = mRsmpInFramesP2 - rear;
4830 if (framesRead > part1) {
4831 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4832 (framesRead - part1) * mFrameSize);
4833 }
4834 rear = mRsmpInRear += framesRead;
4835
4836 size = activeTracks.size();
4837 // loop over each active track
4838 for (size_t i = 0; i < size; i++) {
4839 activeTrack = activeTracks[i];
4840
4841 enum {
4842 OVERRUN_UNKNOWN,
4843 OVERRUN_TRUE,
4844 OVERRUN_FALSE
4845 } overrun = OVERRUN_UNKNOWN;
4846
4847 // loop over getNextBuffer to handle circular sink
4848 for (;;) {
4849
4850 activeTrack->mSink.frameCount = ~0;
4851 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4852 size_t framesOut = activeTrack->mSink.frameCount;
4853 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4854
4855 int32_t front = activeTrack->mRsmpInFront;
4856 ssize_t filled = rear - front;
4857 size_t framesIn;
4858
4859 if (filled < 0) {
4860 // should not happen, but treat like a massive overrun and re-sync
4861 framesIn = 0;
4862 activeTrack->mRsmpInFront = rear;
4863 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004864 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004865 framesIn = (size_t) filled;
4866 } else {
4867 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004868 framesIn = mRsmpInFrames;
4869 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004870 overrun = OVERRUN_TRUE;
4871 }
4872
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004873 if (framesOut == 0 || framesIn == 0) {
4874 break;
4875 }
4876
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004877 if (activeTrack->mResampler == NULL) {
4878 // no resampling
4879 if (framesIn > framesOut) {
4880 framesIn = framesOut;
4881 } else {
4882 framesOut = framesIn;
4883 }
4884 int8_t *dst = activeTrack->mSink.i8;
4885 while (framesIn > 0) {
4886 front &= mRsmpInFramesP2 - 1;
4887 size_t part1 = mRsmpInFramesP2 - front;
4888 if (part1 > framesIn) {
4889 part1 = framesIn;
4890 }
4891 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004892 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004893 memcpy(dst, src, part1 * mFrameSize);
4894 } else if (mChannelCount == 1) {
4895 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4896 part1);
4897 } else {
4898 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4899 part1);
4900 }
4901 dst += part1 * activeTrack->mFrameSize;
4902 front += part1;
4903 framesIn -= part1;
4904 }
4905 activeTrack->mRsmpInFront += framesOut;
4906
4907 } else {
4908 // resampling
4909 // FIXME framesInNeeded should really be part of resampler API, and should
4910 // depend on the SRC ratio
4911 // to keep mRsmpInBuffer full so resampler always has sufficient input
4912 size_t framesInNeeded;
4913 // FIXME only re-calculate when it changes, and optimize for common ratios
4914 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4915 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004916 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004917 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4918 framesInNeeded, framesOut, inOverOut);
4919 // Although we theoretically have framesIn in circular buffer, some of those are
4920 // unreleased frames, and thus must be discounted for purpose of budgeting.
4921 size_t unreleased = activeTrack->mRsmpInUnrel;
4922 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004923 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004924 ALOGV("not enough to resample: have %u frames in but need %u in to "
4925 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004926 framesIn, framesInNeeded, framesOut, inOverOut);
4927 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004928 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4929 if (newFramesOut == 0) {
4930 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004931 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004932 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4933 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4934 framesInNeeded, newFramesOut, outOverIn);
4935 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4936 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4937 "given in/out ratio of %.4g",
4938 framesIn, framesInNeeded, newFramesOut, inOverOut);
4939 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004940 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004941 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004942 "given in/out ratio of %.4g",
4943 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004944 }
4945
4946 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4947 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004948 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004949 delete[] activeTrack->mRsmpOutBuffer;
4950 // resampler always outputs stereo
4951 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4952 activeTrack->mRsmpOutFrameCount = framesOut;
4953 }
4954
4955 // resampler accumulates, but we only have one source track
4956 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4957 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004958 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004959 activeTrack->mResamplerBufferProvider
4960 /*this*/ /* AudioBufferProvider* */);
4961 // ditherAndClamp() works as long as all buffers returned by
4962 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004963 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07004964 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004965 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4966 framesOut);
4967 // the resampler always outputs stereo samples:
4968 // do post stereo to mono conversion
4969 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4970 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4971 } else {
4972 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4973 activeTrack->mRsmpOutBuffer, framesOut);
4974 }
4975 // now done with mRsmpOutBuffer
4976
4977 }
4978
4979 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4980 overrun = OVERRUN_FALSE;
4981 }
4982
4983 if (activeTrack->mFramesToDrop == 0) {
4984 if (framesOut > 0) {
4985 activeTrack->mSink.frameCount = framesOut;
4986 activeTrack->releaseBuffer(&activeTrack->mSink);
4987 }
4988 } else {
4989 // FIXME could do a partial drop of framesOut
4990 if (activeTrack->mFramesToDrop > 0) {
4991 activeTrack->mFramesToDrop -= framesOut;
4992 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004993 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004994 }
4995 } else {
4996 activeTrack->mFramesToDrop += framesOut;
4997 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
4998 activeTrack->mSyncStartEvent->isCancelled()) {
4999 ALOGW("Synced record %s, session %d, trigger session %d",
5000 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5001 activeTrack->sessionId(),
5002 (activeTrack->mSyncStartEvent != 0) ?
5003 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005004 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005005 }
5006 }
5007 }
5008
5009 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005010 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005011 }
5012 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005013
5014 switch (overrun) {
5015 case OVERRUN_TRUE:
5016 // client isn't retrieving buffers fast enough
5017 if (!activeTrack->setOverflow()) {
5018 nsecs_t now = systemTime();
5019 // FIXME should lastWarning per track?
5020 if ((now - lastWarning) > kWarningThrottleNs) {
5021 ALOGW("RecordThread: buffer overflow");
5022 lastWarning = now;
5023 }
5024 }
5025 break;
5026 case OVERRUN_FALSE:
5027 activeTrack->clearOverflow();
5028 break;
5029 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005030 break;
5031 }
5032
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005033 }
5034
Eric Laurent81784c32012-11-19 14:55:58 -08005035 // enable changes in effect chain
5036 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005037 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005038 }
5039
Glenn Kasten93e471f2013-08-19 08:40:07 -07005040 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005041
5042 {
5043 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005044 for (size_t i = 0; i < mTracks.size(); i++) {
5045 sp<RecordTrack> track = mTracks[i];
5046 track->invalidate();
5047 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005048 mActiveTracks.clear();
5049 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005050 mStartStopCond.broadcast();
5051 }
5052
5053 releaseWakeLock();
5054
5055 ALOGV("RecordThread %p exiting", this);
5056 return false;
5057}
5058
Glenn Kasten93e471f2013-08-19 08:40:07 -07005059void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005060{
5061 if (!mStandby) {
5062 inputStandBy();
5063 mStandby = true;
5064 }
5065}
5066
5067void AudioFlinger::RecordThread::inputStandBy()
5068{
5069 mInput->stream->common.standby(&mInput->stream->common);
5070}
5071
Glenn Kasten05997e22014-03-13 15:08:33 -07005072// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005073sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005074 const sp<AudioFlinger::Client>& client,
5075 uint32_t sampleRate,
5076 audio_format_t format,
5077 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005078 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005079 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005080 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005081 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005082 pid_t tid,
5083 status_t *status)
5084{
Glenn Kasten74935e42013-12-19 08:56:45 -08005085 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005086 sp<RecordTrack> track;
5087 status_t lStatus;
5088
Glenn Kasten90e58b12013-07-31 16:16:02 -07005089 // client expresses a preference for FAST, but we get the final say
5090 if (*flags & IAudioFlinger::TRACK_FAST) {
5091 if (
5092 // use case: callback handler and frame count is default or at least as large as HAL
5093 (
5094 (tid != -1) &&
5095 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005096 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005097 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005098 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005099 // PCM data
5100 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005101 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005102 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5103 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005104 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005105 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005106 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005107 // record thread has an associated fast capture
5108 hasFastCapture()
5109 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005110 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005111 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005112 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005113 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005114 frameCount = mFrameCount * kFastTrackMultiplier;
5115 }
5116 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5117 frameCount, mFrameCount);
5118 } else {
5119 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5120 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005121 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005122 frameCount, mFrameCount, format,
5123 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005124 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005125 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005126 // 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 -07005127 // For compatibility with AudioRecord calculation, buffer depth is forced
5128 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5129 // This is probably too conservative, but legacy application code may depend on it.
5130 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005131 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005132 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5133 size_t mNormalFrameCount = 2048; // FIXME
5134 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5135 if (minBufCount < 2) {
5136 minBufCount = 2;
5137 }
5138 size_t minFrameCount = mNormalFrameCount * minBufCount;
5139 if (frameCount < minFrameCount) {
5140 frameCount = minFrameCount;
5141 }
5142 }
5143 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005144 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005145
Glenn Kasten15e57982013-09-24 11:52:37 -07005146 lStatus = initCheck();
5147 if (lStatus != NO_ERROR) {
5148 ALOGE("createRecordTrack_l() audio driver not initialized");
5149 goto Exit;
5150 }
Eric Laurent81784c32012-11-19 14:55:58 -08005151
5152 { // scope for mLock
5153 Mutex::Autolock _l(mLock);
5154
5155 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005156 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005157 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005158
Glenn Kasten03003332013-08-06 15:40:54 -07005159 lStatus = track->initCheck();
5160 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005161 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005162 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005163 goto Exit;
5164 }
5165 mTracks.add(track);
5166
5167 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5168 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5169 mAudioFlinger->btNrecIsOff();
5170 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5171 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005172
5173 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5174 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5175 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5176 // so ask activity manager to do this on our behalf
5177 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005180
Eric Laurent81784c32012-11-19 14:55:58 -08005181 lStatus = NO_ERROR;
5182
5183Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005184 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005185 return track;
5186}
5187
5188status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5189 AudioSystem::sync_event_t event,
5190 int triggerSession)
5191{
5192 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5193 sp<ThreadBase> strongMe = this;
5194 status_t status = NO_ERROR;
5195
5196 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005197 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005198 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005199 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005200 triggerSession,
5201 recordTrack->sessionId(),
5202 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005203 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005204 // Sync event can be cancelled by the trigger session if the track is not in a
5205 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005206 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005207 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005208 } else {
5209 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005210 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005211 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005212 }
5213 }
5214
5215 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005216 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005217 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005218 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5219 if (recordTrack->mState == TrackBase::PAUSING) {
5220 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005221 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005222 } else {
5223 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005224 }
5225 return status;
5226 }
5227
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005228 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5229 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5230 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005231 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005232 mActiveTracks.add(recordTrack);
5233 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005234 mLock.unlock();
5235 status_t status = AudioSystem::startInput(mId);
5236 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005237 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005238 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005239 mActiveTracks.remove(recordTrack);
5240 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005241 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005242 return status;
5243 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 // Catch up with current buffer indices if thread is already running.
5245 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5246 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5247 // see previously buffered data before it called start(), but with greater risk of overrun.
5248
5249 recordTrack->mRsmpInFront = mRsmpInRear;
5250 recordTrack->mRsmpInUnrel = 0;
5251 // FIXME why reset?
5252 if (recordTrack->mResampler != NULL) {
5253 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005254 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005255 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005256 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005257 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005258 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005259 ALOGV("Record failed to start");
5260 status = BAD_VALUE;
5261 goto startError;
5262 }
Eric Laurent81784c32012-11-19 14:55:58 -08005263 return status;
5264 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005265
Eric Laurent81784c32012-11-19 14:55:58 -08005266startError:
5267 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005268 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005269 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005270 return status;
5271}
5272
Eric Laurent81784c32012-11-19 14:55:58 -08005273void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5274{
5275 sp<SyncEvent> strongEvent = event.promote();
5276
5277 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005278 sp<RefBase> ptr = strongEvent->cookie().promote();
5279 if (ptr != 0) {
5280 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5281 recordTrack->handleSyncStartEvent(strongEvent);
5282 }
Eric Laurent81784c32012-11-19 14:55:58 -08005283 }
5284}
5285
Glenn Kastena8356f62013-07-25 14:37:52 -07005286bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005287 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005288 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005289 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005290 return false;
5291 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005292 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005293 recordTrack->mState = TrackBase::PAUSING;
5294 // do not wait for mStartStopCond if exiting
5295 if (exitPending()) {
5296 return true;
5297 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005298 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005299 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005300 // if we have been restarted, recordTrack is in mActiveTracks here
5301 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005302 ALOGV("Record stopped OK");
5303 return true;
5304 }
5305 return false;
5306}
5307
Glenn Kasten0f11b512014-01-31 16:18:54 -08005308bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005309{
5310 return false;
5311}
5312
Glenn Kasten0f11b512014-01-31 16:18:54 -08005313status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005314{
5315#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5316 if (!isValidSyncEvent(event)) {
5317 return BAD_VALUE;
5318 }
5319
5320 int eventSession = event->triggerSession();
5321 status_t ret = NAME_NOT_FOUND;
5322
5323 Mutex::Autolock _l(mLock);
5324
5325 for (size_t i = 0; i < mTracks.size(); i++) {
5326 sp<RecordTrack> track = mTracks[i];
5327 if (eventSession == track->sessionId()) {
5328 (void) track->setSyncEvent(event);
5329 ret = NO_ERROR;
5330 }
5331 }
5332 return ret;
5333#else
5334 return BAD_VALUE;
5335#endif
5336}
5337
5338// destroyTrack_l() must be called with ThreadBase::mLock held
5339void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5340{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 track->terminate();
5342 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005343 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005344 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005345 removeTrack_l(track);
5346 }
5347}
5348
5349void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5350{
5351 mTracks.remove(track);
5352 // need anything related to effects here?
5353}
5354
5355void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5356{
5357 dumpInternals(fd, args);
5358 dumpTracks(fd, args);
5359 dumpEffectChains(fd, args);
5360}
5361
5362void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5363{
Marco Nelissenb2208842014-02-07 14:00:50 -08005364 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005365
Glenn Kasten2b806402013-11-20 16:37:38 -08005366 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005367 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005368 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005369 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005370 }
5371
Eric Laurent81784c32012-11-19 14:55:58 -08005372 dumpBase(fd, args);
5373}
5374
Glenn Kasten0f11b512014-01-31 16:18:54 -08005375void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005376{
5377 const size_t SIZE = 256;
5378 char buffer[SIZE];
5379 String8 result;
5380
Marco Nelissenb2208842014-02-07 14:00:50 -08005381 size_t numtracks = mTracks.size();
5382 size_t numactive = mActiveTracks.size();
5383 size_t numactiveseen = 0;
5384 fdprintf(fd, " %d Tracks", numtracks);
5385 if (numtracks) {
5386 fdprintf(fd, " of which %d are active\n", numactive);
5387 RecordTrack::appendDumpHeader(result);
5388 for (size_t i = 0; i < numtracks ; ++i) {
5389 sp<RecordTrack> track = mTracks[i];
5390 if (track != 0) {
5391 bool active = mActiveTracks.indexOf(track) >= 0;
5392 if (active) {
5393 numactiveseen++;
5394 }
5395 track->dump(buffer, SIZE, active);
5396 result.append(buffer);
5397 }
Eric Laurent81784c32012-11-19 14:55:58 -08005398 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005399 } else {
5400 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005401 }
5402
Marco Nelissenb2208842014-02-07 14:00:50 -08005403 if (numactiveseen != numactive) {
5404 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5405 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005406 result.append(buffer);
5407 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005408 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005409 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005410 if (mTracks.indexOf(track) < 0) {
5411 track->dump(buffer, SIZE, true);
5412 result.append(buffer);
5413 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005414 }
Eric Laurent81784c32012-11-19 14:55:58 -08005415
5416 }
5417 write(fd, result.string(), result.size());
5418}
5419
5420// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005421status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5422 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005423{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005424 RecordTrack *activeTrack = mRecordTrack;
5425 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5426 if (threadBase == 0) {
5427 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005428 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005429 return NOT_ENOUGH_DATA;
5430 }
5431 RecordThread *recordThread = (RecordThread *) threadBase.get();
5432 int32_t rear = recordThread->mRsmpInRear;
5433 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005434 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005435 // FIXME should not be P2 (don't want to increase latency)
5436 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005437 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005438 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005439 front &= recordThread->mRsmpInFramesP2 - 1;
5440 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005441 if (part1 > (size_t) filled) {
5442 part1 = filled;
5443 }
5444 size_t ask = buffer->frameCount;
5445 ALOG_ASSERT(ask > 0);
5446 if (part1 > ask) {
5447 part1 = ask;
5448 }
5449 if (part1 == 0) {
5450 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005451 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005452 buffer->raw = NULL;
5453 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005454 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005455 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 }
5457
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005459 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005460 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005461 return NO_ERROR;
5462}
5463
5464// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005465void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5466 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005467{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005468 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005469 size_t stepCount = buffer->frameCount;
5470 if (stepCount == 0) {
5471 return;
5472 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005473 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5474 activeTrack->mRsmpInUnrel -= stepCount;
5475 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005476 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 buffer->frameCount = 0;
5478}
5479
Eric Laurent10351942014-05-08 18:49:52 -07005480bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5481 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005482{
5483 bool reconfig = false;
5484
Eric Laurent10351942014-05-08 18:49:52 -07005485 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005486
Eric Laurent10351942014-05-08 18:49:52 -07005487 audio_format_t reqFormat = mFormat;
5488 uint32_t samplingRate = mSampleRate;
5489 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5490
5491 AudioParameter param = AudioParameter(keyValuePair);
5492 int value;
5493 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5494 // channel count change can be requested. Do we mandate the first client defines the
5495 // HAL sampling rate and channel count or do we allow changes on the fly?
5496 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5497 samplingRate = value;
5498 reconfig = true;
5499 }
5500 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5501 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5502 status = BAD_VALUE;
5503 } else {
5504 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005505 reconfig = true;
5506 }
Eric Laurent10351942014-05-08 18:49:52 -07005507 }
5508 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5509 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5510 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5511 status = BAD_VALUE;
5512 } else {
5513 channelMask = mask;
5514 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005515 }
Eric Laurent10351942014-05-08 18:49:52 -07005516 }
5517 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5518 // do not accept frame count changes if tracks are open as the track buffer
5519 // size depends on frame count and correct behavior would not be guaranteed
5520 // if frame count is changed after track creation
5521 if (mActiveTracks.size() > 0) {
5522 status = INVALID_OPERATION;
5523 } else {
5524 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005525 }
Eric Laurent10351942014-05-08 18:49:52 -07005526 }
5527 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5528 // forward device change to effects that have requested to be
5529 // aware of attached audio device.
5530 for (size_t i = 0; i < mEffectChains.size(); i++) {
5531 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005532 }
Eric Laurent81784c32012-11-19 14:55:58 -08005533
Eric Laurent10351942014-05-08 18:49:52 -07005534 // store input device and output device but do not forward output device to audio HAL.
5535 // Note that status is ignored by the caller for output device
5536 // (see AudioFlinger::setParameters()
5537 if (audio_is_output_devices(value)) {
5538 mOutDevice = value;
5539 status = BAD_VALUE;
5540 } else {
5541 mInDevice = value;
5542 // disable AEC and NS if the device is a BT SCO headset supporting those
5543 // pre processings
5544 if (mTracks.size() > 0) {
5545 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5546 mAudioFlinger->btNrecIsOff();
5547 for (size_t i = 0; i < mTracks.size(); i++) {
5548 sp<RecordTrack> track = mTracks[i];
5549 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5550 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005551 }
5552 }
5553 }
Eric Laurent10351942014-05-08 18:49:52 -07005554 }
5555 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5556 mAudioSource != (audio_source_t)value) {
5557 // forward device change to effects that have requested to be
5558 // aware of attached audio device.
5559 for (size_t i = 0; i < mEffectChains.size(); i++) {
5560 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005561 }
Eric Laurent10351942014-05-08 18:49:52 -07005562 mAudioSource = (audio_source_t)value;
5563 }
Glenn Kastene198c362013-08-13 09:13:36 -07005564
Eric Laurent10351942014-05-08 18:49:52 -07005565 if (status == NO_ERROR) {
5566 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5567 keyValuePair.string());
5568 if (status == INVALID_OPERATION) {
5569 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005570 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5571 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005572 }
5573 if (reconfig) {
5574 if (status == BAD_VALUE &&
5575 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5576 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5577 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5578 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005579 audio_channel_count_from_in_mask(
5580 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005581 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5582 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5583 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 }
Eric Laurent10351942014-05-08 18:49:52 -07005585 if (status == NO_ERROR) {
5586 readInputParameters_l();
5587 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
5589 }
Eric Laurent81784c32012-11-19 14:55:58 -08005590 }
Eric Laurent10351942014-05-08 18:49:52 -07005591
Eric Laurent81784c32012-11-19 14:55:58 -08005592 return reconfig;
5593}
5594
5595String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5596{
Eric Laurent81784c32012-11-19 14:55:58 -08005597 Mutex::Autolock _l(mLock);
5598 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005599 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005600 }
5601
Glenn Kastend8ea6992013-07-16 14:17:15 -07005602 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5603 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005604 free(s);
5605 return out_s8;
5606}
5607
Eric Laurent021cf962014-05-13 10:18:14 -07005608void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005609 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005610 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005611
5612 switch (event) {
5613 case AudioSystem::INPUT_OPENED:
5614 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005615 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 desc.samplingRate = mSampleRate;
5617 desc.format = mFormat;
5618 desc.frameCount = mFrameCount;
5619 desc.latency = 0;
5620 param2 = &desc;
5621 break;
5622
5623 case AudioSystem::INPUT_CLOSED:
5624 default:
5625 break;
5626 }
Eric Laurent021cf962014-05-13 10:18:14 -07005627 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005628}
5629
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005630void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005631{
Eric Laurent81784c32012-11-19 14:55:58 -08005632 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5633 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07005634 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005635 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005636 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005637 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005638 }
Eric Laurent81784c32012-11-19 14:55:58 -08005639 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005640 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5641 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005642 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005643 // 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 -07005644 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005645 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005646 // A larger value should allow more old data to be read after a track calls start(),
5647 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005648 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005649 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005651 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5652 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005653
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005654 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5655 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005656}
5657
Glenn Kasten5f972c02014-01-13 09:59:31 -08005658uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005659{
5660 Mutex::Autolock _l(mLock);
5661 if (initCheck() != NO_ERROR) {
5662 return 0;
5663 }
5664
5665 return mInput->stream->get_input_frames_lost(mInput->stream);
5666}
5667
5668uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5669{
5670 Mutex::Autolock _l(mLock);
5671 uint32_t result = 0;
5672 if (getEffectChain_l(sessionId) != 0) {
5673 result = EFFECT_SESSION;
5674 }
5675
5676 for (size_t i = 0; i < mTracks.size(); ++i) {
5677 if (sessionId == mTracks[i]->sessionId()) {
5678 result |= TRACK_SESSION;
5679 break;
5680 }
5681 }
5682
5683 return result;
5684}
5685
5686KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5687{
5688 KeyedVector<int, bool> ids;
5689 Mutex::Autolock _l(mLock);
5690 for (size_t j = 0; j < mTracks.size(); ++j) {
5691 sp<RecordThread::RecordTrack> track = mTracks[j];
5692 int sessionId = track->sessionId();
5693 if (ids.indexOfKey(sessionId) < 0) {
5694 ids.add(sessionId, true);
5695 }
5696 }
5697 return ids;
5698}
5699
5700AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5701{
5702 Mutex::Autolock _l(mLock);
5703 AudioStreamIn *input = mInput;
5704 mInput = NULL;
5705 return input;
5706}
5707
5708// this method must always be called either with ThreadBase mLock held or inside the thread loop
5709audio_stream_t* AudioFlinger::RecordThread::stream() const
5710{
5711 if (mInput == NULL) {
5712 return NULL;
5713 }
5714 return &mInput->stream->common;
5715}
5716
5717status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5718{
5719 // only one chain per input thread
5720 if (mEffectChains.size() != 0) {
5721 return INVALID_OPERATION;
5722 }
5723 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5724
5725 chain->setInBuffer(NULL);
5726 chain->setOutBuffer(NULL);
5727
5728 checkSuspendOnAddEffectChain_l(chain);
5729
5730 mEffectChains.add(chain);
5731
5732 return NO_ERROR;
5733}
5734
5735size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5736{
5737 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5738 ALOGW_IF(mEffectChains.size() != 1,
5739 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5740 chain.get(), mEffectChains.size(), this);
5741 if (mEffectChains.size() == 1) {
5742 mEffectChains.removeAt(0);
5743 }
5744 return 0;
5745}
5746
5747}; // namespace android