blob: 784338785a91f5710f74e7512cd12dadc3f5ffda [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) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700508 dprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
510
Elliott Hughes87cebad2014-05-22 10:14:43 -0700511 dprintf(fd, " I/O handle: %d\n", mId);
512 dprintf(fd, " TID: %d\n", getTid());
513 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
514 dprintf(fd, " Sample rate: %u\n", mSampleRate);
515 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
516 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
517 dprintf(fd, " Channel Count: %u\n", mChannelCount);
518 dprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800519 channelMaskToString(mChannelMask, mType != RECORD).string());
Elliott Hughes87cebad2014-05-22 10:14:43 -0700520 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
521 dprintf(fd, " Frame size: %zu\n", mFrameSize);
522 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800523 size_t numConfig = mConfigEvents.size();
524 if (numConfig) {
525 for (size_t i = 0; i < numConfig; i++) {
526 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700527 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800528 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700529 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800530 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700531 dprintf(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);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001194 dprintf(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();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001199 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001200 size_t numactiveseen = 0;
1201 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001202 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001203 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());
Eric Laurent81784c32012-11-19 14:55:58 -08001234}
1235
1236void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1237{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001238 dprintf(fd, "\nOutput thread %p:\n", this);
1239 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1240 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1241 dprintf(fd, " Total writes: %d\n", mNumWrites);
1242 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1243 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1244 dprintf(fd, " Suspend count: %d\n", mSuspended);
1245 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1246 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1247 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1248 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001249
1250 dumpBase(fd, args);
1251}
1252
1253// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001254
1255void AudioFlinger::PlaybackThread::onFirstRef()
1256{
1257 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1258}
1259
1260// ThreadBase virtuals
1261void AudioFlinger::PlaybackThread::preExit()
1262{
1263 ALOGV(" preExit()");
1264 // FIXME this is using hard-coded strings but in the future, this functionality will be
1265 // converted to use audio HAL extensions required to support tunneling
1266 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1267}
1268
1269// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1270sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1271 const sp<AudioFlinger::Client>& client,
1272 audio_stream_type_t streamType,
1273 uint32_t sampleRate,
1274 audio_format_t format,
1275 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001276 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001277 const sp<IMemory>& sharedBuffer,
1278 int sessionId,
1279 IAudioFlinger::track_flags_t *flags,
1280 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001281 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001282 status_t *status)
1283{
Glenn Kasten74935e42013-12-19 08:56:45 -08001284 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001285 sp<Track> track;
1286 status_t lStatus;
1287
1288 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1289
1290 // client expresses a preference for FAST, but we get the final say
1291 if (*flags & IAudioFlinger::TRACK_FAST) {
1292 if (
1293 // not timed
1294 (!isTimed) &&
1295 // either of these use cases:
1296 (
1297 // use case 1: shared buffer with any frame count
1298 (
1299 (sharedBuffer != 0)
1300 ) ||
1301 // use case 2: callback handler and frame count is default or at least as large as HAL
1302 (
1303 (tid != -1) &&
1304 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001305 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001306 )
1307 ) &&
1308 // PCM data
1309 audio_is_linear_pcm(format) &&
1310 // mono or stereo
1311 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1312 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001313 // hardware sample rate
1314 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001315 // normal mixer has an associated fast mixer
1316 hasFastMixer() &&
1317 // there are sufficient fast track slots available
1318 (mFastTrackAvailMask != 0)
1319 // FIXME test that MixerThread for this fast track has a capable output HAL
1320 // FIXME add a permission test also?
1321 ) {
1322 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1323 if (frameCount == 0) {
1324 frameCount = mFrameCount * kFastTrackMultiplier;
1325 }
1326 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1327 frameCount, mFrameCount);
1328 } else {
1329 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1330 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1331 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1332 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1333 audio_is_linear_pcm(format),
1334 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1335 *flags &= ~IAudioFlinger::TRACK_FAST;
1336 // For compatibility with AudioTrack calculation, buffer depth is forced
1337 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1338 // This is probably too conservative, but legacy application code may depend on it.
1339 // If you change this calculation, also review the start threshold which is related.
1340 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1341 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1342 if (minBufCount < 2) {
1343 minBufCount = 2;
1344 }
1345 size_t minFrameCount = mNormalFrameCount * minBufCount;
1346 if (frameCount < minFrameCount) {
1347 frameCount = minFrameCount;
1348 }
1349 }
1350 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001351 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001352
Glenn Kastenc3df8382014-03-13 15:05:25 -07001353 switch (mType) {
1354
1355 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001356 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001357 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001358 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1359 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001360 sampleRate, format, channelMask, mOutput, mFormat);
1361 lStatus = BAD_VALUE;
1362 goto Exit;
1363 }
1364 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001365 break;
1366
1367 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001368 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001369 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1370 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001371 sampleRate, format, channelMask, mOutput, mFormat);
1372 lStatus = BAD_VALUE;
1373 goto Exit;
1374 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001375 break;
1376
1377 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001378 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001379 ALOGE("createTrack_l() Bad parameter: format %#x \""
1380 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001381 format, mOutput, mFormat);
1382 lStatus = BAD_VALUE;
1383 goto Exit;
1384 }
Eric Laurent81784c32012-11-19 14:55:58 -08001385 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1386 if (sampleRate > mSampleRate*2) {
1387 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1388 lStatus = BAD_VALUE;
1389 goto Exit;
1390 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001391 break;
1392
Eric Laurent81784c32012-11-19 14:55:58 -08001393 }
1394
1395 lStatus = initCheck();
1396 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001397 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001398 goto Exit;
1399 }
1400
1401 { // scope for mLock
1402 Mutex::Autolock _l(mLock);
1403
1404 // all tracks in same audio session must share the same routing strategy otherwise
1405 // conflicts will happen when tracks are moved from one output to another by audio policy
1406 // manager
1407 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1408 for (size_t i = 0; i < mTracks.size(); ++i) {
1409 sp<Track> t = mTracks[i];
1410 if (t != 0 && !t->isOutputTrack()) {
1411 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1412 if (sessionId == t->sessionId() && strategy != actual) {
1413 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1414 strategy, actual);
1415 lStatus = BAD_VALUE;
1416 goto Exit;
1417 }
1418 }
1419 }
1420
1421 if (!isTimed) {
1422 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001423 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001424 } else {
1425 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001426 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001427 }
Glenn Kasten03003332013-08-06 15:40:54 -07001428
1429 // new Track always returns non-NULL,
1430 // but TimedTrack::create() is a factory that could fail by returning NULL
1431 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1432 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001433 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001434 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001435 goto Exit;
1436 }
1437 mTracks.add(track);
1438
1439 sp<EffectChain> chain = getEffectChain_l(sessionId);
1440 if (chain != 0) {
1441 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1442 track->setMainBuffer(chain->inBuffer());
1443 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1444 chain->incTrackCnt();
1445 }
1446
1447 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1448 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1449 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1450 // so ask activity manager to do this on our behalf
1451 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1452 }
1453 }
1454
1455 lStatus = NO_ERROR;
1456
1457Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001458 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001459 return track;
1460}
1461
1462uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1463{
1464 return latency;
1465}
1466
1467uint32_t AudioFlinger::PlaybackThread::latency() const
1468{
1469 Mutex::Autolock _l(mLock);
1470 return latency_l();
1471}
1472uint32_t AudioFlinger::PlaybackThread::latency_l() const
1473{
1474 if (initCheck() == NO_ERROR) {
1475 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1476 } else {
1477 return 0;
1478 }
1479}
1480
1481void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1482{
1483 Mutex::Autolock _l(mLock);
1484 // Don't apply master volume in SW if our HAL can do it for us.
1485 if (mOutput && mOutput->audioHwDev &&
1486 mOutput->audioHwDev->canSetMasterVolume()) {
1487 mMasterVolume = 1.0;
1488 } else {
1489 mMasterVolume = value;
1490 }
1491}
1492
1493void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1494{
1495 Mutex::Autolock _l(mLock);
1496 // Don't apply master mute in SW if our HAL can do it for us.
1497 if (mOutput && mOutput->audioHwDev &&
1498 mOutput->audioHwDev->canSetMasterMute()) {
1499 mMasterMute = false;
1500 } else {
1501 mMasterMute = muted;
1502 }
1503}
1504
1505void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1506{
1507 Mutex::Autolock _l(mLock);
1508 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001509 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001510}
1511
1512void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1513{
1514 Mutex::Autolock _l(mLock);
1515 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001516 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001517}
1518
1519float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1520{
1521 Mutex::Autolock _l(mLock);
1522 return mStreamTypes[stream].volume;
1523}
1524
1525// addTrack_l() must be called with ThreadBase::mLock held
1526status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1527{
1528 status_t status = ALREADY_EXISTS;
1529
1530 // set retry count for buffer fill
1531 track->mRetryCount = kMaxTrackStartupRetries;
1532 if (mActiveTracks.indexOf(track) < 0) {
1533 // the track is newly added, make sure it fills up all its
1534 // buffers before playing. This is to ensure the client will
1535 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001536 if (!track->isOutputTrack()) {
1537 TrackBase::track_state state = track->mState;
1538 mLock.unlock();
1539 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1540 mLock.lock();
1541 // abort track was stopped/paused while we released the lock
1542 if (state != track->mState) {
1543 if (status == NO_ERROR) {
1544 mLock.unlock();
1545 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1546 mLock.lock();
1547 }
1548 return INVALID_OPERATION;
1549 }
1550 // abort if start is rejected by audio policy manager
1551 if (status != NO_ERROR) {
1552 return PERMISSION_DENIED;
1553 }
1554#ifdef ADD_BATTERY_DATA
1555 // to track the speaker usage
1556 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1557#endif
1558 }
1559
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001560 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001561 track->mResetDone = false;
1562 track->mPresentationCompleteFrames = 0;
1563 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001564 mWakeLockUids.add(track->uid());
1565 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001566 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001567 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1568 if (chain != 0) {
1569 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1570 track->sessionId());
1571 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001572 }
1573
1574 status = NO_ERROR;
1575 }
1576
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001577 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001578 return status;
1579}
1580
Eric Laurentbfb1b832013-01-07 09:53:42 -08001581bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001582{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001583 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001584 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001585 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1586 track->mState = TrackBase::STOPPED;
1587 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001588 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001589 } else if (track->isFastTrack() || track->isOffloaded()) {
1590 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001591 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001592
1593 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001594}
1595
1596void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1597{
1598 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1599 mTracks.remove(track);
1600 deleteTrackName_l(track->name());
1601 // redundant as track is about to be destroyed, for dumpsys only
1602 track->mName = -1;
1603 if (track->isFastTrack()) {
1604 int index = track->mFastIndex;
1605 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1606 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1607 mFastTrackAvailMask |= 1 << index;
1608 // redundant as track is about to be destroyed, for dumpsys only
1609 track->mFastIndex = -1;
1610 }
1611 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1612 if (chain != 0) {
1613 chain->decTrackCnt();
1614 }
1615}
1616
Eric Laurentede6c3b2013-09-19 14:37:46 -07001617void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001618{
1619 // Thread could be blocked waiting for async
1620 // so signal it to handle state changes immediately
1621 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1622 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1623 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001624 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001625}
1626
Eric Laurent81784c32012-11-19 14:55:58 -08001627String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1628{
Eric Laurent81784c32012-11-19 14:55:58 -08001629 Mutex::Autolock _l(mLock);
1630 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001631 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001632 }
1633
Glenn Kastend8ea6992013-07-16 14:17:15 -07001634 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1635 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001636 free(s);
1637 return out_s8;
1638}
1639
Eric Laurent021cf962014-05-13 10:18:14 -07001640void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001641 AudioSystem::OutputDescriptor desc;
1642 void *param2 = NULL;
1643
Eric Laurent021cf962014-05-13 10:18:14 -07001644 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001645 param);
1646
1647 switch (event) {
1648 case AudioSystem::OUTPUT_OPENED:
1649 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001650 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001651 desc.samplingRate = mSampleRate;
1652 desc.format = mFormat;
1653 desc.frameCount = mNormalFrameCount; // FIXME see
1654 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001655 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001656 param2 = &desc;
1657 break;
1658
1659 case AudioSystem::STREAM_CONFIG_CHANGED:
1660 param2 = &param;
1661 case AudioSystem::OUTPUT_CLOSED:
1662 default:
1663 break;
1664 }
Eric Laurent021cf962014-05-13 10:18:14 -07001665 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001666}
1667
Eric Laurentbfb1b832013-01-07 09:53:42 -08001668void AudioFlinger::PlaybackThread::writeCallback()
1669{
1670 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001671 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001672}
1673
1674void AudioFlinger::PlaybackThread::drainCallback()
1675{
1676 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001677 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678}
1679
Eric Laurent3b4529e2013-09-05 18:09:19 -07001680void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001681{
1682 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001683 // reject out of sequence requests
1684 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1685 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001686 mWaitWorkCV.signal();
1687 }
1688}
1689
Eric Laurent3b4529e2013-09-05 18:09:19 -07001690void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001691{
1692 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001693 // reject out of sequence requests
1694 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1695 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001696 mWaitWorkCV.signal();
1697 }
1698}
1699
1700// static
1701int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001702 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001703 void *cookie)
1704{
1705 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1706 ALOGV("asyncCallback() event %d", event);
1707 switch (event) {
1708 case STREAM_CBK_EVENT_WRITE_READY:
1709 me->writeCallback();
1710 break;
1711 case STREAM_CBK_EVENT_DRAIN_READY:
1712 me->drainCallback();
1713 break;
1714 default:
1715 ALOGW("asyncCallback() unknown event %d", event);
1716 break;
1717 }
1718 return 0;
1719}
1720
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001721void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001722{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001723 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001724 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1725 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001726 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001727 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001728 }
1729 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001730 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001731 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1732 }
Andy Hunge5412692014-05-16 11:25:07 -07001733 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001734 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001735 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001736 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001737 }
1738 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001739 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1740 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001741 }
Eric Laurent81784c32012-11-19 14:55:58 -08001742 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001743 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1744 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (mFrameCount & 15) {
1746 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1747 mFrameCount);
1748 }
1749
Eric Laurentbfb1b832013-01-07 09:53:42 -08001750 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1751 (mOutput->stream->set_callback != NULL)) {
1752 if (mOutput->stream->set_callback(mOutput->stream,
1753 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1754 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001755 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756 }
1757 }
1758
Andy Hung09a50072014-02-27 14:30:47 -08001759 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001760 double multiplier = 1.0;
1761 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1762 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001763 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1764 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001765 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1766 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1767 maxNormalFrameCount = maxNormalFrameCount & ~15;
1768 if (maxNormalFrameCount < minNormalFrameCount) {
1769 maxNormalFrameCount = minNormalFrameCount;
1770 }
1771 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1772 if (multiplier <= 1.0) {
1773 multiplier = 1.0;
1774 } else if (multiplier <= 2.0) {
1775 if (2 * mFrameCount <= maxNormalFrameCount) {
1776 multiplier = 2.0;
1777 } else {
1778 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1779 }
1780 } else {
1781 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001782 // 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 -08001783 // track, but we sometimes have to do this to satisfy the maximum frame count
1784 // constraint)
1785 // FIXME this rounding up should not be done if no HAL SRC
1786 uint32_t truncMult = (uint32_t) multiplier;
1787 if ((truncMult & 1)) {
1788 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1789 ++truncMult;
1790 }
1791 }
1792 multiplier = (double) truncMult;
1793 }
1794 }
1795 mNormalFrameCount = multiplier * mFrameCount;
1796 // round up to nearest 16 frames to satisfy AudioMixer
1797 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001798 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001799 mNormalFrameCount);
1800
Andy Hung010a1a12014-03-13 13:57:33 -07001801 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1802 // Originally this was int16_t[] array, need to remove legacy implications.
1803 free(mSinkBuffer);
1804 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001805 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1806 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1807 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001808 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001809
Andy Hung69aed5f2014-02-25 17:24:40 -08001810 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1811 // drives the output.
1812 free(mMixerBuffer);
1813 mMixerBuffer = NULL;
1814 if (mMixerBufferEnabled) {
1815 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1816 mMixerBufferSize = mNormalFrameCount * mChannelCount
1817 * audio_bytes_per_sample(mMixerBufferFormat);
1818 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1819 }
Andy Hung98ef9782014-03-04 14:46:50 -08001820 free(mEffectBuffer);
1821 mEffectBuffer = NULL;
1822 if (mEffectBufferEnabled) {
1823 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1824 mEffectBufferSize = mNormalFrameCount * mChannelCount
1825 * audio_bytes_per_sample(mEffectBufferFormat);
1826 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1827 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001828
Eric Laurent81784c32012-11-19 14:55:58 -08001829 // force reconfiguration of effect chains and engines to take new buffer size and audio
1830 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001831 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001832 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1833 // matter.
1834 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1835 Vector< sp<EffectChain> > effectChains = mEffectChains;
1836 for (size_t i = 0; i < effectChains.size(); i ++) {
1837 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1838 }
1839}
1840
1841
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001842status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001843{
1844 if (halFrames == NULL || dspFrames == NULL) {
1845 return BAD_VALUE;
1846 }
1847 Mutex::Autolock _l(mLock);
1848 if (initCheck() != NO_ERROR) {
1849 return INVALID_OPERATION;
1850 }
1851 size_t framesWritten = mBytesWritten / mFrameSize;
1852 *halFrames = framesWritten;
1853
1854 if (isSuspended()) {
1855 // return an estimation of rendered frames when the output is suspended
1856 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1857 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1858 return NO_ERROR;
1859 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001860 status_t status;
1861 uint32_t frames;
1862 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1863 *dspFrames = (size_t)frames;
1864 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001865 }
1866}
1867
1868uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1869{
1870 Mutex::Autolock _l(mLock);
1871 uint32_t result = 0;
1872 if (getEffectChain_l(sessionId) != 0) {
1873 result = EFFECT_SESSION;
1874 }
1875
1876 for (size_t i = 0; i < mTracks.size(); ++i) {
1877 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001878 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001879 result |= TRACK_SESSION;
1880 break;
1881 }
1882 }
1883
1884 return result;
1885}
1886
1887uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1888{
1889 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1890 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1891 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1892 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1893 }
1894 for (size_t i = 0; i < mTracks.size(); i++) {
1895 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001896 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001897 return AudioSystem::getStrategyForStream(track->streamType());
1898 }
1899 }
1900 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1901}
1902
1903
1904AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1905{
1906 Mutex::Autolock _l(mLock);
1907 return mOutput;
1908}
1909
1910AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1911{
1912 Mutex::Autolock _l(mLock);
1913 AudioStreamOut *output = mOutput;
1914 mOutput = NULL;
1915 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1916 // must push a NULL and wait for ack
1917 mOutputSink.clear();
1918 mPipeSink.clear();
1919 mNormalSink.clear();
1920 return output;
1921}
1922
1923// this method must always be called either with ThreadBase mLock held or inside the thread loop
1924audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1925{
1926 if (mOutput == NULL) {
1927 return NULL;
1928 }
1929 return &mOutput->stream->common;
1930}
1931
1932uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1933{
1934 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1935}
1936
1937status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1938{
1939 if (!isValidSyncEvent(event)) {
1940 return BAD_VALUE;
1941 }
1942
1943 Mutex::Autolock _l(mLock);
1944
1945 for (size_t i = 0; i < mTracks.size(); ++i) {
1946 sp<Track> track = mTracks[i];
1947 if (event->triggerSession() == track->sessionId()) {
1948 (void) track->setSyncEvent(event);
1949 return NO_ERROR;
1950 }
1951 }
1952
1953 return NAME_NOT_FOUND;
1954}
1955
1956bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1957{
1958 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1959}
1960
1961void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1962 const Vector< sp<Track> >& tracksToRemove)
1963{
1964 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001965 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001966 for (size_t i = 0 ; i < count ; i++) {
1967 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001969 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970#ifdef ADD_BATTERY_DATA
1971 // to track the speaker usage
1972 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1973#endif
1974 if (track->isTerminated()) {
1975 AudioSystem::releaseOutput(mId);
1976 }
Eric Laurent81784c32012-11-19 14:55:58 -08001977 }
1978 }
1979 }
Eric Laurent81784c32012-11-19 14:55:58 -08001980}
1981
1982void AudioFlinger::PlaybackThread::checkSilentMode_l()
1983{
1984 if (!mMasterMute) {
1985 char value[PROPERTY_VALUE_MAX];
1986 if (property_get("ro.audio.silent", value, "0") > 0) {
1987 char *endptr;
1988 unsigned long ul = strtoul(value, &endptr, 0);
1989 if (*endptr == '\0' && ul != 0) {
1990 ALOGD("Silence is golden");
1991 // The setprop command will not allow a property to be changed after
1992 // the first time it is set, so we don't have to worry about un-muting.
1993 setMasterMute_l(true);
1994 }
1995 }
1996 }
1997}
1998
1999// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002000ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002001{
2002 // FIXME rewrite to reduce number of system calls
2003 mLastWriteTime = systemTime();
2004 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002005 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002006 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002007
2008 // If an NBAIO sink is present, use it to write the normal mixer's submix
2009 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002010 const size_t count = mBytesRemaining / mFrameSize;
2011
Simon Wilson2d590962012-11-29 15:18:50 -08002012 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002013 // update the setpoint when AudioFlinger::mScreenState changes
2014 uint32_t screenState = AudioFlinger::mScreenState;
2015 if (screenState != mScreenState) {
2016 mScreenState = screenState;
2017 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2018 if (pipe != NULL) {
2019 pipe->setAvgFrames((mScreenState & 1) ?
2020 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2021 }
2022 }
Andy Hung010a1a12014-03-13 13:57:33 -07002023 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002024 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002025 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002026 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002027 } else {
2028 bytesWritten = framesWritten;
2029 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002030 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002031 if (status == NO_ERROR) {
2032 size_t totalFramesWritten = mNormalSink->framesWritten();
2033 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2034 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2035 mLatchDValid = true;
2036 }
2037 }
Eric Laurent81784c32012-11-19 14:55:58 -08002038 // otherwise use the HAL / AudioStreamOut directly
2039 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002041
Eric Laurentbfb1b832013-01-07 09:53:42 -08002042 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002043 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2044 mWriteAckSequence += 2;
2045 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002046 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002047 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002049 // FIXME We should have an implementation of timestamps for direct output threads.
2050 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002051 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002052 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002053 if (mUseAsyncWrite &&
2054 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2055 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002056 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002057 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002058 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002059 }
Eric Laurent81784c32012-11-19 14:55:58 -08002060 }
2061
Eric Laurent81784c32012-11-19 14:55:58 -08002062 mNumWrites++;
2063 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002064 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002065 return bytesWritten;
2066}
2067
2068void AudioFlinger::PlaybackThread::threadLoop_drain()
2069{
2070 if (mOutput->stream->drain) {
2071 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2072 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002073 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2074 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002075 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002076 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002077 }
2078 mOutput->stream->drain(mOutput->stream,
2079 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2080 : AUDIO_DRAIN_ALL);
2081 }
2082}
2083
2084void AudioFlinger::PlaybackThread::threadLoop_exit()
2085{
2086 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002087}
2088
2089/*
2090The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002091 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002092 - activeSleepTime from activeSleepTimeUs()
2093 - idleSleepTime from idleSleepTimeUs()
2094 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2095 - maxPeriod from frame count and sample rate (MIXER only)
2096
2097The parameters that affect these derived values are:
2098 - frame count
2099 - frame size
2100 - sample rate
2101 - device type: A2DP or not
2102 - device latency
2103 - format: PCM or not
2104 - active sleep time
2105 - idle sleep time
2106*/
2107
2108void AudioFlinger::PlaybackThread::cacheParameters_l()
2109{
Andy Hung25c2dac2014-02-27 14:56:00 -08002110 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002111 activeSleepTime = activeSleepTimeUs();
2112 idleSleepTime = idleSleepTimeUs();
2113}
2114
2115void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2116{
Glenn Kasten7c027242012-12-26 14:43:16 -08002117 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002118 this, streamType, mTracks.size());
2119 Mutex::Autolock _l(mLock);
2120
2121 size_t size = mTracks.size();
2122 for (size_t i = 0; i < size; i++) {
2123 sp<Track> t = mTracks[i];
2124 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002125 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002126 }
2127 }
2128}
2129
2130status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2131{
2132 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002133 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2134 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002135 bool ownsBuffer = false;
2136
2137 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2138 if (session > 0) {
2139 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002140 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002141 if (mType != DIRECT) {
2142 size_t numSamples = mNormalFrameCount * mChannelCount;
2143 buffer = new int16_t[numSamples];
2144 memset(buffer, 0, numSamples * sizeof(int16_t));
2145 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2146 ownsBuffer = true;
2147 }
2148
2149 // Attach all tracks with same session ID to this chain.
2150 for (size_t i = 0; i < mTracks.size(); ++i) {
2151 sp<Track> track = mTracks[i];
2152 if (session == track->sessionId()) {
2153 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2154 buffer);
2155 track->setMainBuffer(buffer);
2156 chain->incTrackCnt();
2157 }
2158 }
2159
2160 // indicate all active tracks in the chain
2161 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2162 sp<Track> track = mActiveTracks[i].promote();
2163 if (track == 0) {
2164 continue;
2165 }
2166 if (session == track->sessionId()) {
2167 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2168 chain->incActiveTrackCnt();
2169 }
2170 }
2171 }
2172
2173 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002174 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2175 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002176 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2177 // chains list in order to be processed last as it contains output stage effects
2178 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2179 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2180 // after track specific effects and before output stage
2181 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2182 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2183 // Effect chain for other sessions are inserted at beginning of effect
2184 // chains list to be processed before output mix effects. Relative order between other
2185 // sessions is not important
2186 size_t size = mEffectChains.size();
2187 size_t i = 0;
2188 for (i = 0; i < size; i++) {
2189 if (mEffectChains[i]->sessionId() < session) {
2190 break;
2191 }
2192 }
2193 mEffectChains.insertAt(chain, i);
2194 checkSuspendOnAddEffectChain_l(chain);
2195
2196 return NO_ERROR;
2197}
2198
2199size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2200{
2201 int session = chain->sessionId();
2202
2203 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2204
2205 for (size_t i = 0; i < mEffectChains.size(); i++) {
2206 if (chain == mEffectChains[i]) {
2207 mEffectChains.removeAt(i);
2208 // detach all active tracks from the chain
2209 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2210 sp<Track> track = mActiveTracks[i].promote();
2211 if (track == 0) {
2212 continue;
2213 }
2214 if (session == track->sessionId()) {
2215 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2216 chain.get(), session);
2217 chain->decActiveTrackCnt();
2218 }
2219 }
2220
2221 // detach all tracks with same session ID from this chain
2222 for (size_t i = 0; i < mTracks.size(); ++i) {
2223 sp<Track> track = mTracks[i];
2224 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002225 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002226 chain->decTrackCnt();
2227 }
2228 }
2229 break;
2230 }
2231 }
2232 return mEffectChains.size();
2233}
2234
2235status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2236 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2237{
2238 Mutex::Autolock _l(mLock);
2239 return attachAuxEffect_l(track, EffectId);
2240}
2241
2242status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2243 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2244{
2245 status_t status = NO_ERROR;
2246
2247 if (EffectId == 0) {
2248 track->setAuxBuffer(0, NULL);
2249 } else {
2250 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2251 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2252 if (effect != 0) {
2253 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2254 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2255 } else {
2256 status = INVALID_OPERATION;
2257 }
2258 } else {
2259 status = BAD_VALUE;
2260 }
2261 }
2262 return status;
2263}
2264
2265void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2266{
2267 for (size_t i = 0; i < mTracks.size(); ++i) {
2268 sp<Track> track = mTracks[i];
2269 if (track->auxEffectId() == effectId) {
2270 attachAuxEffect_l(track, 0);
2271 }
2272 }
2273}
2274
2275bool AudioFlinger::PlaybackThread::threadLoop()
2276{
2277 Vector< sp<Track> > tracksToRemove;
2278
2279 standbyTime = systemTime();
2280
2281 // MIXER
2282 nsecs_t lastWarning = 0;
2283
2284 // DUPLICATING
2285 // FIXME could this be made local to while loop?
2286 writeFrames = 0;
2287
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002288 int lastGeneration = 0;
2289
Eric Laurent81784c32012-11-19 14:55:58 -08002290 cacheParameters_l();
2291 sleepTime = idleSleepTime;
2292
2293 if (mType == MIXER) {
2294 sleepTimeShift = 0;
2295 }
2296
2297 CpuStats cpuStats;
2298 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2299
2300 acquireWakeLock();
2301
Glenn Kasten9e58b552013-01-18 15:09:48 -08002302 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2303 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2304 // and then that string will be logged at the next convenient opportunity.
2305 const char *logString = NULL;
2306
Eric Laurent664539d2013-09-23 18:24:31 -07002307 checkSilentMode_l();
2308
Eric Laurent81784c32012-11-19 14:55:58 -08002309 while (!exitPending())
2310 {
2311 cpuStats.sample(myName);
2312
2313 Vector< sp<EffectChain> > effectChains;
2314
Eric Laurent81784c32012-11-19 14:55:58 -08002315 { // scope for mLock
2316
2317 Mutex::Autolock _l(mLock);
2318
Eric Laurent021cf962014-05-13 10:18:14 -07002319 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002320
Glenn Kasten9e58b552013-01-18 15:09:48 -08002321 if (logString != NULL) {
2322 mNBLogWriter->logTimestamp();
2323 mNBLogWriter->log(logString);
2324 logString = NULL;
2325 }
2326
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002327 if (mLatchDValid) {
2328 mLatchQ = mLatchD;
2329 mLatchDValid = false;
2330 mLatchQValid = true;
2331 }
2332
Eric Laurent81784c32012-11-19 14:55:58 -08002333 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002334 if (mSignalPending) {
2335 // A signal was raised while we were unlocked
2336 mSignalPending = false;
2337 } else if (waitingAsyncCallback_l()) {
2338 if (exitPending()) {
2339 break;
2340 }
2341 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002342 mWakeLockUids.clear();
2343 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002344 ALOGV("wait async completion");
2345 mWaitWorkCV.wait(mLock);
2346 ALOGV("async completion/wake");
2347 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002348 standbyTime = systemTime() + standbyDelay;
2349 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002350
2351 continue;
2352 }
2353 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 isSuspended()) {
2355 // put audio hardware into standby after short delay
2356 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002357
2358 threadLoop_standby();
2359
2360 mStandby = true;
2361 }
2362
2363 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2364 // we're about to wait, flush the binder command buffer
2365 IPCThreadState::self()->flushCommands();
2366
2367 clearOutputTracks();
2368
2369 if (exitPending()) {
2370 break;
2371 }
2372
2373 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002374 mWakeLockUids.clear();
2375 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002376 // wait until we have something to do...
2377 ALOGV("%s going to sleep", myName.string());
2378 mWaitWorkCV.wait(mLock);
2379 ALOGV("%s waking up", myName.string());
2380 acquireWakeLock_l();
2381
2382 mMixerStatus = MIXER_IDLE;
2383 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2384 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002386 checkSilentMode_l();
2387
2388 standbyTime = systemTime() + standbyDelay;
2389 sleepTime = idleSleepTime;
2390 if (mType == MIXER) {
2391 sleepTimeShift = 0;
2392 }
2393
2394 continue;
2395 }
2396 }
Eric Laurent81784c32012-11-19 14:55:58 -08002397 // mMixerStatusIgnoringFastTracks is also updated internally
2398 mMixerStatus = prepareTracks_l(&tracksToRemove);
2399
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002400 // compare with previously applied list
2401 if (lastGeneration != mActiveTracksGeneration) {
2402 // update wakelock
2403 updateWakeLockUids_l(mWakeLockUids);
2404 lastGeneration = mActiveTracksGeneration;
2405 }
2406
Eric Laurent81784c32012-11-19 14:55:58 -08002407 // prevent any changes in effect chain list and in each effect chain
2408 // during mixing and effect process as the audio buffers could be deleted
2409 // or modified if an effect is created or deleted
2410 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002411 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002412
Eric Laurentbfb1b832013-01-07 09:53:42 -08002413 if (mBytesRemaining == 0) {
2414 mCurrentWriteLength = 0;
2415 if (mMixerStatus == MIXER_TRACKS_READY) {
2416 // threadLoop_mix() sets mCurrentWriteLength
2417 threadLoop_mix();
2418 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2419 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2420 // threadLoop_sleepTime sets sleepTime to 0 if data
2421 // must be written to HAL
2422 threadLoop_sleepTime();
2423 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002424 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 }
2426 }
Andy Hung98ef9782014-03-04 14:46:50 -08002427 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2428 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2429 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2430 // or mSinkBuffer (if there are no effects).
2431 //
2432 // This is done pre-effects computation; if effects change to
2433 // support higher precision, this needs to move.
2434 //
2435 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2436 // TODO use sleepTime == 0 as an additional condition.
2437 if (mMixerBufferValid) {
2438 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2439 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2440
2441 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2442 mNormalFrameCount * mChannelCount);
2443 }
2444
Eric Laurentbfb1b832013-01-07 09:53:42 -08002445 mBytesRemaining = mCurrentWriteLength;
2446 if (isSuspended()) {
2447 sleepTime = suspendSleepTimeUs();
2448 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002449 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450 mBytesRemaining = 0;
2451 }
Eric Laurent81784c32012-11-19 14:55:58 -08002452
Eric Laurentbfb1b832013-01-07 09:53:42 -08002453 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002454 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455 for (size_t i = 0; i < effectChains.size(); i ++) {
2456 effectChains[i]->process_l();
2457 }
Eric Laurent81784c32012-11-19 14:55:58 -08002458 }
2459 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002460 // Process effect chains for offloaded thread even if no audio
2461 // was read from audio track: process only updates effect state
2462 // and thus does have to be synchronized with audio writes but may have
2463 // to be called while waiting for async write callback
2464 if (mType == OFFLOAD) {
2465 for (size_t i = 0; i < effectChains.size(); i ++) {
2466 effectChains[i]->process_l();
2467 }
2468 }
Eric Laurent81784c32012-11-19 14:55:58 -08002469
Andy Hung98ef9782014-03-04 14:46:50 -08002470 // Only if the Effects buffer is enabled and there is data in the
2471 // Effects buffer (buffer valid), we need to
2472 // copy into the sink buffer.
2473 // TODO use sleepTime == 0 as an additional condition.
2474 if (mEffectBufferValid) {
2475 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2476 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2477 mNormalFrameCount * mChannelCount);
2478 }
2479
Eric Laurent81784c32012-11-19 14:55:58 -08002480 // enable changes in effect chain
2481 unlockEffectChains(effectChains);
2482
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 if (!waitingAsyncCallback()) {
2484 // sleepTime == 0 means we must write to audio hardware
2485 if (sleepTime == 0) {
2486 if (mBytesRemaining) {
2487 ssize_t ret = threadLoop_write();
2488 if (ret < 0) {
2489 mBytesRemaining = 0;
2490 } else {
2491 mBytesWritten += ret;
2492 mBytesRemaining -= ret;
2493 }
2494 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2495 (mMixerStatus == MIXER_DRAIN_ALL)) {
2496 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002497 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002498 if (mType == MIXER) {
2499 // write blocked detection
2500 nsecs_t now = systemTime();
2501 nsecs_t delta = now - mLastWriteTime;
2502 if (!mStandby && delta > maxPeriod) {
2503 mNumDelayedWrites++;
2504 if ((now - lastWarning) > kWarningThrottleNs) {
2505 ATRACE_NAME("underrun");
2506 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2507 ns2ms(delta), mNumDelayedWrites, this);
2508 lastWarning = now;
2509 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002510 }
2511 }
Eric Laurent81784c32012-11-19 14:55:58 -08002512
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 } else {
2514 usleep(sleepTime);
2515 }
Eric Laurent81784c32012-11-19 14:55:58 -08002516 }
2517
2518 // Finally let go of removed track(s), without the lock held
2519 // since we can't guarantee the destructors won't acquire that
2520 // same lock. This will also mutate and push a new fast mixer state.
2521 threadLoop_removeTracks(tracksToRemove);
2522 tracksToRemove.clear();
2523
2524 // FIXME I don't understand the need for this here;
2525 // it was in the original code but maybe the
2526 // assignment in saveOutputTracks() makes this unnecessary?
2527 clearOutputTracks();
2528
2529 // Effect chains will be actually deleted here if they were removed from
2530 // mEffectChains list during mixing or effects processing
2531 effectChains.clear();
2532
2533 // FIXME Note that the above .clear() is no longer necessary since effectChains
2534 // is now local to this block, but will keep it for now (at least until merge done).
2535 }
2536
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537 threadLoop_exit();
2538
Eric Laurent81784c32012-11-19 14:55:58 -08002539 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002540 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002541 // put output stream into standby mode
2542 if (!mStandby) {
2543 mOutput->stream->common.standby(&mOutput->stream->common);
2544 }
2545 }
2546
2547 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002548 mWakeLockUids.clear();
2549 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002550
2551 ALOGV("Thread %p type %d exiting", this, mType);
2552 return false;
2553}
2554
Eric Laurentbfb1b832013-01-07 09:53:42 -08002555// removeTracks_l() must be called with ThreadBase::mLock held
2556void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2557{
2558 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002559 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560 for (size_t i=0 ; i<count ; i++) {
2561 const sp<Track>& track = tracksToRemove.itemAt(i);
2562 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002563 mWakeLockUids.remove(track->uid());
2564 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2566 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2567 if (chain != 0) {
2568 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2569 track->sessionId());
2570 chain->decActiveTrackCnt();
2571 }
2572 if (track->isTerminated()) {
2573 removeTrack_l(track);
2574 }
2575 }
2576 }
2577
2578}
Eric Laurent81784c32012-11-19 14:55:58 -08002579
Eric Laurentaccc1472013-09-20 09:36:34 -07002580status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2581{
2582 if (mNormalSink != 0) {
2583 return mNormalSink->getTimestamp(timestamp);
2584 }
2585 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2586 uint64_t position64;
2587 int ret = mOutput->stream->get_presentation_position(
2588 mOutput->stream, &position64, &timestamp.mTime);
2589 if (ret == 0) {
2590 timestamp.mPosition = (uint32_t)position64;
2591 return NO_ERROR;
2592 }
2593 }
2594 return INVALID_OPERATION;
2595}
Eric Laurent81784c32012-11-19 14:55:58 -08002596// ----------------------------------------------------------------------------
2597
2598AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2599 audio_io_handle_t id, audio_devices_t device, type_t type)
2600 : PlaybackThread(audioFlinger, output, id, device, type),
2601 // mAudioMixer below
2602 // mFastMixer below
2603 mFastMixerFutex(0)
2604 // mOutputSink below
2605 // mPipeSink below
2606 // mNormalSink below
2607{
2608 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002609 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002610 "mFrameCount=%d, mNormalFrameCount=%d",
2611 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2612 mNormalFrameCount);
2613 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2614
2615 // FIXME - Current mixer implementation only supports stereo output
2616 if (mChannelCount != FCC_2) {
2617 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2618 }
2619
2620 // create an NBAIO sink for the HAL output stream, and negotiate
2621 mOutputSink = new AudioStreamOutSink(output->stream);
2622 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002623 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002624 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2625 ALOG_ASSERT(index == 0);
2626
2627 // initialize fast mixer depending on configuration
2628 bool initFastMixer;
2629 switch (kUseFastMixer) {
2630 case FastMixer_Never:
2631 initFastMixer = false;
2632 break;
2633 case FastMixer_Always:
2634 initFastMixer = true;
2635 break;
2636 case FastMixer_Static:
2637 case FastMixer_Dynamic:
2638 initFastMixer = mFrameCount < mNormalFrameCount;
2639 break;
2640 }
2641 if (initFastMixer) {
2642
2643 // create a MonoPipe to connect our submix to FastMixer
2644 NBAIO_Format format = mOutputSink->format();
2645 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2646 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2647 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2648 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2649 const NBAIO_Format offers[1] = {format};
2650 size_t numCounterOffers = 0;
2651 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2652 ALOG_ASSERT(index == 0);
2653 monoPipe->setAvgFrames((mScreenState & 1) ?
2654 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2655 mPipeSink = monoPipe;
2656
Glenn Kasten46909e72013-02-26 09:20:22 -08002657#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002658 if (mTeeSinkOutputEnabled) {
2659 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2660 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2661 numCounterOffers = 0;
2662 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2663 ALOG_ASSERT(index == 0);
2664 mTeeSink = teeSink;
2665 PipeReader *teeSource = new PipeReader(*teeSink);
2666 numCounterOffers = 0;
2667 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2668 ALOG_ASSERT(index == 0);
2669 mTeeSource = teeSource;
2670 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002671#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002672
2673 // create fast mixer and configure it initially with just one fast track for our submix
2674 mFastMixer = new FastMixer();
2675 FastMixerStateQueue *sq = mFastMixer->sq();
2676#ifdef STATE_QUEUE_DUMP
2677 sq->setObserverDump(&mStateQueueObserverDump);
2678 sq->setMutatorDump(&mStateQueueMutatorDump);
2679#endif
2680 FastMixerState *state = sq->begin();
2681 FastTrack *fastTrack = &state->mFastTracks[0];
2682 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2683 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2684 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07002685 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
2686 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08002687 fastTrack->mGeneration++;
2688 state->mFastTracksGen++;
2689 state->mTrackMask = 1;
2690 // fast mixer will use the HAL output sink
2691 state->mOutputSink = mOutputSink.get();
2692 state->mOutputSinkGen++;
2693 state->mFrameCount = mFrameCount;
2694 state->mCommand = FastMixerState::COLD_IDLE;
2695 // already done in constructor initialization list
2696 //mFastMixerFutex = 0;
2697 state->mColdFutexAddr = &mFastMixerFutex;
2698 state->mColdGen++;
2699 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002700#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002701 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002702#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002703 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2704 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002705 sq->end();
2706 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2707
2708 // start the fast mixer
2709 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2710 pid_t tid = mFastMixer->getTid();
2711 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2712 if (err != 0) {
2713 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2714 kPriorityFastMixer, getpid_cached, tid, err);
2715 }
2716
2717#ifdef AUDIO_WATCHDOG
2718 // create and start the watchdog
2719 mAudioWatchdog = new AudioWatchdog();
2720 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2721 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2722 tid = mAudioWatchdog->getTid();
2723 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2724 if (err != 0) {
2725 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2726 kPriorityFastMixer, getpid_cached, tid, err);
2727 }
2728#endif
2729
2730 } else {
2731 mFastMixer = NULL;
2732 }
2733
2734 switch (kUseFastMixer) {
2735 case FastMixer_Never:
2736 case FastMixer_Dynamic:
2737 mNormalSink = mOutputSink;
2738 break;
2739 case FastMixer_Always:
2740 mNormalSink = mPipeSink;
2741 break;
2742 case FastMixer_Static:
2743 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2744 break;
2745 }
2746}
2747
2748AudioFlinger::MixerThread::~MixerThread()
2749{
2750 if (mFastMixer != NULL) {
2751 FastMixerStateQueue *sq = mFastMixer->sq();
2752 FastMixerState *state = sq->begin();
2753 if (state->mCommand == FastMixerState::COLD_IDLE) {
2754 int32_t old = android_atomic_inc(&mFastMixerFutex);
2755 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002756 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002757 }
2758 }
2759 state->mCommand = FastMixerState::EXIT;
2760 sq->end();
2761 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2762 mFastMixer->join();
2763 // Though the fast mixer thread has exited, it's state queue is still valid.
2764 // We'll use that extract the final state which contains one remaining fast track
2765 // corresponding to our sub-mix.
2766 state = sq->begin();
2767 ALOG_ASSERT(state->mTrackMask == 1);
2768 FastTrack *fastTrack = &state->mFastTracks[0];
2769 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2770 delete fastTrack->mBufferProvider;
2771 sq->end(false /*didModify*/);
2772 delete mFastMixer;
2773#ifdef AUDIO_WATCHDOG
2774 if (mAudioWatchdog != 0) {
2775 mAudioWatchdog->requestExit();
2776 mAudioWatchdog->requestExitAndWait();
2777 mAudioWatchdog.clear();
2778 }
2779#endif
2780 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002781 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002782 delete mAudioMixer;
2783}
2784
2785
2786uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2787{
2788 if (mFastMixer != NULL) {
2789 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2790 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2791 }
2792 return latency;
2793}
2794
2795
2796void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2797{
2798 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2799}
2800
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
2803 // FIXME we should only do one push per cycle; confirm this is true
2804 // Start the fast mixer if it's not already running
2805 if (mFastMixer != NULL) {
2806 FastMixerStateQueue *sq = mFastMixer->sq();
2807 FastMixerState *state = sq->begin();
2808 if (state->mCommand != FastMixerState::MIX_WRITE &&
2809 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2810 if (state->mCommand == FastMixerState::COLD_IDLE) {
2811 int32_t old = android_atomic_inc(&mFastMixerFutex);
2812 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07002813 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002814 }
2815#ifdef AUDIO_WATCHDOG
2816 if (mAudioWatchdog != 0) {
2817 mAudioWatchdog->resume();
2818 }
2819#endif
2820 }
2821 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002822 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2823 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002824 sq->end();
2825 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2826 if (kUseFastMixer == FastMixer_Dynamic) {
2827 mNormalSink = mPipeSink;
2828 }
2829 } else {
2830 sq->end(false /*didModify*/);
2831 }
2832 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002833 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002834}
2835
2836void AudioFlinger::MixerThread::threadLoop_standby()
2837{
2838 // Idle the fast mixer if it's currently running
2839 if (mFastMixer != NULL) {
2840 FastMixerStateQueue *sq = mFastMixer->sq();
2841 FastMixerState *state = sq->begin();
2842 if (!(state->mCommand & FastMixerState::IDLE)) {
2843 state->mCommand = FastMixerState::COLD_IDLE;
2844 state->mColdFutexAddr = &mFastMixerFutex;
2845 state->mColdGen++;
2846 mFastMixerFutex = 0;
2847 sq->end();
2848 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2849 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2850 if (kUseFastMixer == FastMixer_Dynamic) {
2851 mNormalSink = mOutputSink;
2852 }
2853#ifdef AUDIO_WATCHDOG
2854 if (mAudioWatchdog != 0) {
2855 mAudioWatchdog->pause();
2856 }
2857#endif
2858 } else {
2859 sq->end(false /*didModify*/);
2860 }
2861 }
2862 PlaybackThread::threadLoop_standby();
2863}
2864
Eric Laurentbfb1b832013-01-07 09:53:42 -08002865bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2866{
2867 return false;
2868}
2869
2870bool AudioFlinger::PlaybackThread::shouldStandby_l()
2871{
2872 return !mStandby;
2873}
2874
2875bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2876{
2877 Mutex::Autolock _l(mLock);
2878 return waitingAsyncCallback_l();
2879}
2880
Eric Laurent81784c32012-11-19 14:55:58 -08002881// shared by MIXER and DIRECT, overridden by DUPLICATING
2882void AudioFlinger::PlaybackThread::threadLoop_standby()
2883{
2884 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2885 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002887 // discard any pending drain or write ack by incrementing sequence
2888 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2889 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002891 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2892 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 }
Eric Laurent81784c32012-11-19 14:55:58 -08002894}
2895
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002896void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2897{
2898 ALOGV("signal playback thread");
2899 broadcast_l();
2900}
2901
Eric Laurent81784c32012-11-19 14:55:58 -08002902void AudioFlinger::MixerThread::threadLoop_mix()
2903{
2904 // obtain the presentation timestamp of the next output buffer
2905 int64_t pts;
2906 status_t status = INVALID_OPERATION;
2907
2908 if (mNormalSink != 0) {
2909 status = mNormalSink->getNextWriteTimestamp(&pts);
2910 } else {
2911 status = mOutputSink->getNextWriteTimestamp(&pts);
2912 }
2913
2914 if (status != NO_ERROR) {
2915 pts = AudioBufferProvider::kInvalidPTS;
2916 }
2917
2918 // mix buffers...
2919 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002920 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002921 // increase sleep time progressively when application underrun condition clears.
2922 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2923 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2924 // such that we would underrun the audio HAL.
2925 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2926 sleepTimeShift--;
2927 }
2928 sleepTime = 0;
2929 standbyTime = systemTime() + standbyDelay;
2930 //TODO: delay standby when effects have a tail
2931}
2932
2933void AudioFlinger::MixerThread::threadLoop_sleepTime()
2934{
2935 // If no tracks are ready, sleep once for the duration of an output
2936 // buffer size, then write 0s to the output
2937 if (sleepTime == 0) {
2938 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2939 sleepTime = activeSleepTime >> sleepTimeShift;
2940 if (sleepTime < kMinThreadSleepTimeUs) {
2941 sleepTime = kMinThreadSleepTimeUs;
2942 }
2943 // reduce sleep time in case of consecutive application underruns to avoid
2944 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2945 // duration we would end up writing less data than needed by the audio HAL if
2946 // the condition persists.
2947 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2948 sleepTimeShift++;
2949 }
2950 } else {
2951 sleepTime = idleSleepTime;
2952 }
2953 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002954 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2955 // before effects processing or output.
2956 if (mMixerBufferValid) {
2957 memset(mMixerBuffer, 0, mMixerBufferSize);
2958 } else {
2959 memset(mSinkBuffer, 0, mSinkBufferSize);
2960 }
Eric Laurent81784c32012-11-19 14:55:58 -08002961 sleepTime = 0;
2962 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2963 "anticipated start");
2964 }
2965 // TODO add standby time extension fct of effect tail
2966}
2967
2968// prepareTracks_l() must be called with ThreadBase::mLock held
2969AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2970 Vector< sp<Track> > *tracksToRemove)
2971{
2972
2973 mixer_state mixerStatus = MIXER_IDLE;
2974 // find out which tracks need to be processed
2975 size_t count = mActiveTracks.size();
2976 size_t mixedTracks = 0;
2977 size_t tracksWithEffect = 0;
2978 // counts only _active_ fast tracks
2979 size_t fastTracks = 0;
2980 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2981
2982 float masterVolume = mMasterVolume;
2983 bool masterMute = mMasterMute;
2984
2985 if (masterMute) {
2986 masterVolume = 0;
2987 }
2988 // Delegate master volume control to effect in output mix effect chain if needed
2989 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2990 if (chain != 0) {
2991 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2992 chain->setVolume_l(&v, &v);
2993 masterVolume = (float)((v + (1 << 23)) >> 24);
2994 chain.clear();
2995 }
2996
2997 // prepare a new state to push
2998 FastMixerStateQueue *sq = NULL;
2999 FastMixerState *state = NULL;
3000 bool didModify = false;
3001 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3002 if (mFastMixer != NULL) {
3003 sq = mFastMixer->sq();
3004 state = sq->begin();
3005 }
3006
Andy Hung69aed5f2014-02-25 17:24:40 -08003007 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003008 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003009
Eric Laurent81784c32012-11-19 14:55:58 -08003010 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003011 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003012 if (t == 0) {
3013 continue;
3014 }
3015
3016 // this const just means the local variable doesn't change
3017 Track* const track = t.get();
3018
3019 // process fast tracks
3020 if (track->isFastTrack()) {
3021
3022 // It's theoretically possible (though unlikely) for a fast track to be created
3023 // and then removed within the same normal mix cycle. This is not a problem, as
3024 // the track never becomes active so it's fast mixer slot is never touched.
3025 // The converse, of removing an (active) track and then creating a new track
3026 // at the identical fast mixer slot within the same normal mix cycle,
3027 // is impossible because the slot isn't marked available until the end of each cycle.
3028 int j = track->mFastIndex;
3029 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3030 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3031 FastTrack *fastTrack = &state->mFastTracks[j];
3032
3033 // Determine whether the track is currently in underrun condition,
3034 // and whether it had a recent underrun.
3035 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3036 FastTrackUnderruns underruns = ftDump->mUnderruns;
3037 uint32_t recentFull = (underruns.mBitFields.mFull -
3038 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3039 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3040 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3041 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3042 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3043 uint32_t recentUnderruns = recentPartial + recentEmpty;
3044 track->mObservedUnderruns = underruns;
3045 // don't count underruns that occur while stopping or pausing
3046 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003047 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3048 recentUnderruns > 0) {
3049 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3050 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 }
3052
3053 // This is similar to the state machine for normal tracks,
3054 // with a few modifications for fast tracks.
3055 bool isActive = true;
3056 switch (track->mState) {
3057 case TrackBase::STOPPING_1:
3058 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003059 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003060 track->mState = TrackBase::STOPPING_2;
3061 }
3062 break;
3063 case TrackBase::PAUSING:
3064 // ramp down is not yet implemented
3065 track->setPaused();
3066 break;
3067 case TrackBase::RESUMING:
3068 // ramp up is not yet implemented
3069 track->mState = TrackBase::ACTIVE;
3070 break;
3071 case TrackBase::ACTIVE:
3072 if (recentFull > 0 || recentPartial > 0) {
3073 // track has provided at least some frames recently: reset retry count
3074 track->mRetryCount = kMaxTrackRetries;
3075 }
3076 if (recentUnderruns == 0) {
3077 // no recent underruns: stay active
3078 break;
3079 }
3080 // there has recently been an underrun of some kind
3081 if (track->sharedBuffer() == 0) {
3082 // were any of the recent underruns "empty" (no frames available)?
3083 if (recentEmpty == 0) {
3084 // no, then ignore the partial underruns as they are allowed indefinitely
3085 break;
3086 }
3087 // there has recently been an "empty" underrun: decrement the retry counter
3088 if (--(track->mRetryCount) > 0) {
3089 break;
3090 }
3091 // indicate to client process that the track was disabled because of underrun;
3092 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003093 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003094 // remove from active list, but state remains ACTIVE [confusing but true]
3095 isActive = false;
3096 break;
3097 }
3098 // fall through
3099 case TrackBase::STOPPING_2:
3100 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003101 case TrackBase::STOPPED:
3102 case TrackBase::FLUSHED: // flush() while active
3103 // Check for presentation complete if track is inactive
3104 // We have consumed all the buffers of this track.
3105 // This would be incomplete if we auto-paused on underrun
3106 {
3107 size_t audioHALFrames =
3108 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3109 size_t framesWritten = mBytesWritten / mFrameSize;
3110 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3111 // track stays in active list until presentation is complete
3112 break;
3113 }
3114 }
3115 if (track->isStopping_2()) {
3116 track->mState = TrackBase::STOPPED;
3117 }
3118 if (track->isStopped()) {
3119 // Can't reset directly, as fast mixer is still polling this track
3120 // track->reset();
3121 // So instead mark this track as needing to be reset after push with ack
3122 resetMask |= 1 << i;
3123 }
3124 isActive = false;
3125 break;
3126 case TrackBase::IDLE:
3127 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003128 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003129 }
3130
3131 if (isActive) {
3132 // was it previously inactive?
3133 if (!(state->mTrackMask & (1 << j))) {
3134 ExtendedAudioBufferProvider *eabp = track;
3135 VolumeProvider *vp = track;
3136 fastTrack->mBufferProvider = eabp;
3137 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003138 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003139 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003140 fastTrack->mGeneration++;
3141 state->mTrackMask |= 1 << j;
3142 didModify = true;
3143 // no acknowledgement required for newly active tracks
3144 }
3145 // cache the combined master volume and stream type volume for fast mixer; this
3146 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003147 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003148 ++fastTracks;
3149 } else {
3150 // was it previously active?
3151 if (state->mTrackMask & (1 << j)) {
3152 fastTrack->mBufferProvider = NULL;
3153 fastTrack->mGeneration++;
3154 state->mTrackMask &= ~(1 << j);
3155 didModify = true;
3156 // If any fast tracks were removed, we must wait for acknowledgement
3157 // because we're about to decrement the last sp<> on those tracks.
3158 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3159 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003160 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003161 }
3162 tracksToRemove->add(track);
3163 // Avoids a misleading display in dumpsys
3164 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3165 }
3166 continue;
3167 }
3168
3169 { // local variable scope to avoid goto warning
3170
3171 audio_track_cblk_t* cblk = track->cblk();
3172
3173 // The first time a track is added we wait
3174 // for all its buffers to be filled before processing it
3175 int name = track->name();
3176 // make sure that we have enough frames to mix one full buffer.
3177 // enforce this condition only once to enable draining the buffer in case the client
3178 // app does not call stop() and relies on underrun to stop:
3179 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3180 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003181 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003182 uint32_t sr = track->sampleRate();
3183 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003184 desiredFrames = mNormalFrameCount;
3185 } else {
3186 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003187 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003188 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003189 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003190 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003191#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003192 // the minimum track buffer size is normally twice the number of frames necessary
3193 // to fill one buffer and the resampler should not leave more than one buffer worth
3194 // of unreleased frames after each pass, but just in case...
3195 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003196#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003197 }
Eric Laurent81784c32012-11-19 14:55:58 -08003198 uint32_t minFrames = 1;
3199 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3200 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003201 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003202 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003203
3204 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003205 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003206 !track->isPaused() && !track->isTerminated())
3207 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003208 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003209
3210 mixedTracks++;
3211
Andy Hung69aed5f2014-02-25 17:24:40 -08003212 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3213 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003214 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003215 if (track->mainBuffer() != mSinkBuffer &&
3216 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003217 if (mEffectBufferEnabled) {
3218 mEffectBufferValid = true; // Later can set directly.
3219 }
Eric Laurent81784c32012-11-19 14:55:58 -08003220 chain = getEffectChain_l(track->sessionId());
3221 // Delegate volume control to effect in track effect chain if needed
3222 if (chain != 0) {
3223 tracksWithEffect++;
3224 } else {
3225 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3226 "session %d",
3227 name, track->sessionId());
3228 }
3229 }
3230
3231
3232 int param = AudioMixer::VOLUME;
3233 if (track->mFillingUpStatus == Track::FS_FILLED) {
3234 // no ramp for the first volume setting
3235 track->mFillingUpStatus = Track::FS_ACTIVE;
3236 if (track->mState == TrackBase::RESUMING) {
3237 track->mState = TrackBase::ACTIVE;
3238 param = AudioMixer::RAMP_VOLUME;
3239 }
3240 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003241 // FIXME should not make a decision based on mServer
3242 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003243 // If the track is stopped before the first frame was mixed,
3244 // do not apply ramp
3245 param = AudioMixer::RAMP_VOLUME;
3246 }
3247
3248 // compute volume for this track
3249 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003250 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003251 vl = vr = va = 0;
3252 if (track->isPausing()) {
3253 track->setPaused();
3254 }
3255 } else {
3256
3257 // read original volumes with volume control
3258 float typeVolume = mStreamTypes[track->streamType()].volume;
3259 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003260 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003261 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3262 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3263 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003264 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003265 if (vlf > GAIN_FLOAT_UNITY) {
3266 ALOGV("Track left volume out of range: %.3g", vlf);
3267 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003268 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003269 if (vrf > GAIN_FLOAT_UNITY) {
3270 ALOGV("Track right volume out of range: %.3g", vrf);
3271 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003272 }
3273 // now apply the master volume and stream type volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07003274 // FIXME we're losing the wonderful dynamic range in the minifloat representation
3275 float v8_24 = v * (MAX_GAIN_INT * MAX_GAIN_INT);
3276 vl = (uint32_t) (v8_24 * vlf);
3277 vr = (uint32_t) (v8_24 * vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08003278 // assuming master volume and stream type volume each go up to 1.0,
3279 // vl and vr are now in 8.24 format
3280
Glenn Kastene3aa6592012-12-04 12:22:46 -08003281 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003282 // send level comes from shared memory and so may be corrupt
3283 if (sendLevel > MAX_GAIN_INT) {
3284 ALOGV("Track send level out of range: %04X", sendLevel);
3285 sendLevel = MAX_GAIN_INT;
3286 }
3287 va = (uint32_t)(v * sendLevel);
3288 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003289
Eric Laurent81784c32012-11-19 14:55:58 -08003290 // Delegate volume control to effect in track effect chain if needed
3291 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3292 // Do not ramp volume if volume is controlled by effect
3293 param = AudioMixer::VOLUME;
3294 track->mHasVolumeController = true;
3295 } else {
3296 // force no volume ramp when volume controller was just disabled or removed
3297 // from effect chain to avoid volume spike
3298 if (track->mHasVolumeController) {
3299 param = AudioMixer::VOLUME;
3300 }
3301 track->mHasVolumeController = false;
3302 }
3303
Glenn Kastenc56f3422014-03-21 17:53:17 -07003304 // FIXME Use float
Eric Laurent81784c32012-11-19 14:55:58 -08003305 // Convert volumes from 8.24 to 4.12 format
3306 // This additional clamping is needed in case chain->setVolume_l() overshot
3307 vl = (vl + (1 << 11)) >> 12;
3308 if (vl > MAX_GAIN_INT) {
3309 vl = MAX_GAIN_INT;
3310 }
3311 vr = (vr + (1 << 11)) >> 12;
3312 if (vr > MAX_GAIN_INT) {
3313 vr = MAX_GAIN_INT;
3314 }
3315
3316 if (va > MAX_GAIN_INT) {
3317 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3318 }
3319
3320 // XXX: these things DON'T need to be done each time
3321 mAudioMixer->setBufferProvider(name, track);
3322 mAudioMixer->enable(name);
3323
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003324 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3325 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3326 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003327 mAudioMixer->setParameter(
3328 name,
3329 AudioMixer::TRACK,
3330 AudioMixer::FORMAT, (void *)track->format());
3331 mAudioMixer->setParameter(
3332 name,
3333 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003334 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003335 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3336 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003337 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003338 if (reqSampleRate == 0) {
3339 reqSampleRate = mSampleRate;
3340 } else if (reqSampleRate > maxSampleRate) {
3341 reqSampleRate = maxSampleRate;
3342 }
Eric Laurent81784c32012-11-19 14:55:58 -08003343 mAudioMixer->setParameter(
3344 name,
3345 AudioMixer::RESAMPLE,
3346 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003347 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003348 /*
3349 * Select the appropriate output buffer for the track.
3350 *
Andy Hung98ef9782014-03-04 14:46:50 -08003351 * Tracks with effects go into their own effects chain buffer
3352 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003353 *
3354 * Other tracks can use mMixerBuffer for higher precision
3355 * channel accumulation. If this buffer is enabled
3356 * (mMixerBufferEnabled true), then selected tracks will accumulate
3357 * into it.
3358 *
3359 */
3360 if (mMixerBufferEnabled
3361 && (track->mainBuffer() == mSinkBuffer
3362 || track->mainBuffer() == mMixerBuffer)) {
3363 mAudioMixer->setParameter(
3364 name,
3365 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003366 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003367 mAudioMixer->setParameter(
3368 name,
3369 AudioMixer::TRACK,
3370 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3371 // TODO: override track->mainBuffer()?
3372 mMixerBufferValid = true;
3373 } else {
3374 mAudioMixer->setParameter(
3375 name,
3376 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003377 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003378 mAudioMixer->setParameter(
3379 name,
3380 AudioMixer::TRACK,
3381 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3382 }
Eric Laurent81784c32012-11-19 14:55:58 -08003383 mAudioMixer->setParameter(
3384 name,
3385 AudioMixer::TRACK,
3386 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3387
3388 // reset retry count
3389 track->mRetryCount = kMaxTrackRetries;
3390
3391 // If one track is ready, set the mixer ready if:
3392 // - the mixer was not ready during previous round OR
3393 // - no other track is not ready
3394 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3395 mixerStatus != MIXER_TRACKS_ENABLED) {
3396 mixerStatus = MIXER_TRACKS_READY;
3397 }
3398 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003399 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003400 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003401 }
Eric Laurent81784c32012-11-19 14:55:58 -08003402 // clear effect chain input buffer if an active track underruns to avoid sending
3403 // previous audio buffer again to effects
3404 chain = getEffectChain_l(track->sessionId());
3405 if (chain != 0) {
3406 chain->clearInputBuffer();
3407 }
3408
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003409 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003410 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3411 track->isStopped() || track->isPaused()) {
3412 // We have consumed all the buffers of this track.
3413 // Remove it from the list of active tracks.
3414 // TODO: use actual buffer filling status instead of latency when available from
3415 // audio HAL
3416 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3417 size_t framesWritten = mBytesWritten / mFrameSize;
3418 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3419 if (track->isStopped()) {
3420 track->reset();
3421 }
3422 tracksToRemove->add(track);
3423 }
3424 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003425 // No buffers for this track. Give it a few chances to
3426 // fill a buffer, then remove it from active list.
3427 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003428 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003429 tracksToRemove->add(track);
3430 // indicate to client process that the track was disabled because of underrun;
3431 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003432 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003433 // If one track is not ready, mark the mixer also not ready if:
3434 // - the mixer was ready during previous round OR
3435 // - no other track is ready
3436 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3437 mixerStatus != MIXER_TRACKS_READY) {
3438 mixerStatus = MIXER_TRACKS_ENABLED;
3439 }
3440 }
3441 mAudioMixer->disable(name);
3442 }
3443
3444 } // local variable scope to avoid goto warning
3445track_is_ready: ;
3446
3447 }
3448
3449 // Push the new FastMixer state if necessary
3450 bool pauseAudioWatchdog = false;
3451 if (didModify) {
3452 state->mFastTracksGen++;
3453 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3454 if (kUseFastMixer == FastMixer_Dynamic &&
3455 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3456 state->mCommand = FastMixerState::COLD_IDLE;
3457 state->mColdFutexAddr = &mFastMixerFutex;
3458 state->mColdGen++;
3459 mFastMixerFutex = 0;
3460 if (kUseFastMixer == FastMixer_Dynamic) {
3461 mNormalSink = mOutputSink;
3462 }
3463 // If we go into cold idle, need to wait for acknowledgement
3464 // so that fast mixer stops doing I/O.
3465 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3466 pauseAudioWatchdog = true;
3467 }
Eric Laurent81784c32012-11-19 14:55:58 -08003468 }
3469 if (sq != NULL) {
3470 sq->end(didModify);
3471 sq->push(block);
3472 }
3473#ifdef AUDIO_WATCHDOG
3474 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3475 mAudioWatchdog->pause();
3476 }
3477#endif
3478
3479 // Now perform the deferred reset on fast tracks that have stopped
3480 while (resetMask != 0) {
3481 size_t i = __builtin_ctz(resetMask);
3482 ALOG_ASSERT(i < count);
3483 resetMask &= ~(1 << i);
3484 sp<Track> t = mActiveTracks[i].promote();
3485 if (t == 0) {
3486 continue;
3487 }
3488 Track* track = t.get();
3489 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3490 track->reset();
3491 }
3492
3493 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003495
Andy Hung69aed5f2014-02-25 17:24:40 -08003496 // sink or mix buffer must be cleared if all tracks are connected to an
3497 // effect chain as in this case the mixer will not write to the sink or mix buffer
3498 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003499 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3500 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003501 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003502 if (mMixerBufferValid) {
3503 memset(mMixerBuffer, 0, mMixerBufferSize);
3504 // TODO: In testing, mSinkBuffer below need not be cleared because
3505 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3506 // after mixing.
3507 //
3508 // To enforce this guarantee:
3509 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3510 // (mixedTracks == 0 && fastTracks > 0))
3511 // must imply MIXER_TRACKS_READY.
3512 // Later, we may clear buffers regardless, and skip much of this logic.
3513 }
Andy Hung98ef9782014-03-04 14:46:50 -08003514 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3515 if (mEffectBufferValid) {
3516 memset(mEffectBuffer, 0, mEffectBufferSize);
3517 }
3518 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003519 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003520 }
3521
3522 // if any fast tracks, then status is ready
3523 mMixerStatusIgnoringFastTracks = mixerStatus;
3524 if (fastTracks > 0) {
3525 mixerStatus = MIXER_TRACKS_READY;
3526 }
3527 return mixerStatus;
3528}
3529
3530// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003531int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3532 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003533{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003534 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003535}
3536
3537// deleteTrackName_l() must be called with ThreadBase::mLock held
3538void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3539{
3540 ALOGV("remove track (%d) and delete from mixer", name);
3541 mAudioMixer->deleteTrackName(name);
3542}
3543
Eric Laurent10351942014-05-08 18:49:52 -07003544// checkForNewParameter_l() must be called with ThreadBase::mLock held
3545bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3546 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003547{
Eric Laurent81784c32012-11-19 14:55:58 -08003548 bool reconfig = false;
3549
Eric Laurent10351942014-05-08 18:49:52 -07003550 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003551
Eric Laurent10351942014-05-08 18:49:52 -07003552 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3553 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3554 if (mFastMixer != NULL) {
3555 FastMixerStateQueue *sq = mFastMixer->sq();
3556 FastMixerState *state = sq->begin();
3557 if (!(state->mCommand & FastMixerState::IDLE)) {
3558 previousCommand = state->mCommand;
3559 state->mCommand = FastMixerState::HOT_IDLE;
3560 sq->end();
3561 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3562 } else {
3563 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003564 }
Eric Laurent10351942014-05-08 18:49:52 -07003565 }
Eric Laurent81784c32012-11-19 14:55:58 -08003566
Eric Laurent10351942014-05-08 18:49:52 -07003567 AudioParameter param = AudioParameter(keyValuePair);
3568 int value;
3569 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3570 reconfig = true;
3571 }
3572 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3573 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3574 status = BAD_VALUE;
3575 } else {
3576 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003577 reconfig = true;
3578 }
Eric Laurent10351942014-05-08 18:49:52 -07003579 }
3580 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3581 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3582 status = BAD_VALUE;
3583 } else {
3584 // no need to save value, since it's constant
3585 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003586 }
Eric Laurent10351942014-05-08 18:49:52 -07003587 }
3588 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3589 // do not accept frame count changes if tracks are open as the track buffer
3590 // size depends on frame count and correct behavior would not be guaranteed
3591 // if frame count is changed after track creation
3592 if (!mTracks.isEmpty()) {
3593 status = INVALID_OPERATION;
3594 } else {
3595 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003596 }
Eric Laurent10351942014-05-08 18:49:52 -07003597 }
3598 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003599#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003600 // when changing the audio output device, call addBatteryData to notify
3601 // the change
3602 if (mOutDevice != value) {
3603 uint32_t params = 0;
3604 // check whether speaker is on
3605 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3606 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003607 }
Eric Laurent10351942014-05-08 18:49:52 -07003608
3609 audio_devices_t deviceWithoutSpeaker
3610 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3611 // check if any other device (except speaker) is on
3612 if (value & deviceWithoutSpeaker ) {
3613 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3614 }
3615
3616 if (params != 0) {
3617 addBatteryData(params);
3618 }
3619 }
Eric Laurent81784c32012-11-19 14:55:58 -08003620#endif
3621
Eric Laurent10351942014-05-08 18:49:52 -07003622 // forward device change to effects that have requested to be
3623 // aware of attached audio device.
3624 if (value != AUDIO_DEVICE_NONE) {
3625 mOutDevice = value;
3626 for (size_t i = 0; i < mEffectChains.size(); i++) {
3627 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003628 }
3629 }
Eric Laurent10351942014-05-08 18:49:52 -07003630 }
Eric Laurent81784c32012-11-19 14:55:58 -08003631
Eric Laurent10351942014-05-08 18:49:52 -07003632 if (status == NO_ERROR) {
3633 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3634 keyValuePair.string());
3635 if (!mStandby && status == INVALID_OPERATION) {
3636 mOutput->stream->common.standby(&mOutput->stream->common);
3637 mStandby = true;
3638 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003639 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003640 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003641 }
Eric Laurent10351942014-05-08 18:49:52 -07003642 if (status == NO_ERROR && reconfig) {
3643 readOutputParameters_l();
3644 delete mAudioMixer;
3645 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3646 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07003647 int name = getTrackName_l(mTracks[i]->mChannelMask,
3648 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07003649 if (name < 0) {
3650 break;
3651 }
3652 mTracks[i]->mName = name;
3653 }
3654 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656 }
3657
3658 if (!(previousCommand & FastMixerState::IDLE)) {
3659 ALOG_ASSERT(mFastMixer != NULL);
3660 FastMixerStateQueue *sq = mFastMixer->sq();
3661 FastMixerState *state = sq->begin();
3662 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3663 state->mCommand = previousCommand;
3664 sq->end();
3665 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3666 }
3667
3668 return reconfig;
3669}
3670
3671
3672void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3673{
3674 const size_t SIZE = 256;
3675 char buffer[SIZE];
3676 String8 result;
3677
3678 PlaybackThread::dumpInternals(fd, args);
3679
Elliott Hughes87cebad2014-05-22 10:14:43 -07003680 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003681
3682 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003683 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003684 copy.dump(fd);
3685
3686#ifdef STATE_QUEUE_DUMP
3687 // Similar for state queue
3688 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3689 observerCopy.dump(fd);
3690 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3691 mutatorCopy.dump(fd);
3692#endif
3693
Glenn Kasten46909e72013-02-26 09:20:22 -08003694#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // Write the tee output to a .wav file
3696 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003697#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003698
3699#ifdef AUDIO_WATCHDOG
3700 if (mAudioWatchdog != 0) {
3701 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3702 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3703 wdCopy.dump(fd);
3704 }
3705#endif
3706}
3707
3708uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3709{
3710 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3711}
3712
3713uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3714{
3715 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3716}
3717
3718void AudioFlinger::MixerThread::cacheParameters_l()
3719{
3720 PlaybackThread::cacheParameters_l();
3721
3722 // FIXME: Relaxed timing because of a certain device that can't meet latency
3723 // Should be reduced to 2x after the vendor fixes the driver issue
3724 // increase threshold again due to low power audio mode. The way this warning
3725 // threshold is calculated and its usefulness should be reconsidered anyway.
3726 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3727}
3728
3729// ----------------------------------------------------------------------------
3730
3731AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3732 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3733 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3734 // mLeftVolFloat, mRightVolFloat
3735{
3736}
3737
Eric Laurentbfb1b832013-01-07 09:53:42 -08003738AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3739 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3740 ThreadBase::type_t type)
3741 : PlaybackThread(audioFlinger, output, id, device, type)
3742 // mLeftVolFloat, mRightVolFloat
3743{
3744}
3745
Eric Laurent81784c32012-11-19 14:55:58 -08003746AudioFlinger::DirectOutputThread::~DirectOutputThread()
3747{
3748}
3749
Eric Laurentbfb1b832013-01-07 09:53:42 -08003750void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3751{
3752 audio_track_cblk_t* cblk = track->cblk();
3753 float left, right;
3754
3755 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3756 left = right = 0;
3757 } else {
3758 float typeVolume = mStreamTypes[track->streamType()].volume;
3759 float v = mMasterVolume * typeVolume;
3760 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003761 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3762 left = float_from_gain(gain_minifloat_unpack_left(vlr));
3763 if (left > GAIN_FLOAT_UNITY) {
3764 left = GAIN_FLOAT_UNITY;
3765 }
3766 left *= v;
3767 right = float_from_gain(gain_minifloat_unpack_right(vlr));
3768 if (right > GAIN_FLOAT_UNITY) {
3769 right = GAIN_FLOAT_UNITY;
3770 }
3771 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003772 }
3773
3774 if (lastTrack) {
3775 if (left != mLeftVolFloat || right != mRightVolFloat) {
3776 mLeftVolFloat = left;
3777 mRightVolFloat = right;
3778
3779 // Convert volumes from float to 8.24
3780 uint32_t vl = (uint32_t)(left * (1 << 24));
3781 uint32_t vr = (uint32_t)(right * (1 << 24));
3782
3783 // Delegate volume control to effect in track effect chain if needed
3784 // only one effect chain can be present on DirectOutputThread, so if
3785 // there is one, the track is connected to it
3786 if (!mEffectChains.isEmpty()) {
3787 mEffectChains[0]->setVolume_l(&vl, &vr);
3788 left = (float)vl / (1 << 24);
3789 right = (float)vr / (1 << 24);
3790 }
3791 if (mOutput->stream->set_volume) {
3792 mOutput->stream->set_volume(mOutput->stream, left, right);
3793 }
3794 }
3795 }
3796}
3797
3798
Eric Laurent81784c32012-11-19 14:55:58 -08003799AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3800 Vector< sp<Track> > *tracksToRemove
3801)
3802{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003803 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003804 mixer_state mixerStatus = MIXER_IDLE;
3805
3806 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003807 for (size_t i = 0; i < count; i++) {
3808 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003809 // The track died recently
3810 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003811 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003812 }
3813
3814 Track* const track = t.get();
3815 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003816 // Only consider last track started for volume and mixer state control.
3817 // In theory an older track could underrun and restart after the new one starts
3818 // but as we only care about the transition phase between two tracks on a
3819 // direct output, it is not a problem to ignore the underrun case.
3820 sp<Track> l = mLatestActiveTrack.promote();
3821 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003822
3823 // The first time a track is added we wait
3824 // for all its buffers to be filled before processing it
3825 uint32_t minFrames;
3826 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3827 minFrames = mNormalFrameCount;
3828 } else {
3829 minFrames = 1;
3830 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831
Eric Laurent81784c32012-11-19 14:55:58 -08003832 if ((track->framesReady() >= minFrames) && track->isReady() &&
3833 !track->isPaused() && !track->isTerminated())
3834 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003835 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003836
3837 if (track->mFillingUpStatus == Track::FS_FILLED) {
3838 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003839 // make sure processVolume_l() will apply new volume even if 0
3840 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003841 if (track->mState == TrackBase::RESUMING) {
3842 track->mState = TrackBase::ACTIVE;
3843 }
3844 }
3845
3846 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 processVolume_l(track, last);
3848 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003849 // reset retry count
3850 track->mRetryCount = kMaxTrackRetriesDirect;
3851 mActiveTrack = t;
3852 mixerStatus = MIXER_TRACKS_READY;
3853 }
Eric Laurent81784c32012-11-19 14:55:58 -08003854 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003855 // clear effect chain input buffer if the last active track started underruns
3856 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003857 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003858 mEffectChains[0]->clearInputBuffer();
3859 }
3860
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003861 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003862 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3863 track->isStopped() || track->isPaused()) {
3864 // We have consumed all the buffers of this track.
3865 // Remove it from the list of active tracks.
3866 // TODO: implement behavior for compressed audio
3867 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3868 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003869 if (mStandby || !last ||
3870 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003871 if (track->isStopped()) {
3872 track->reset();
3873 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003874 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 }
3876 } else {
3877 // No buffers for this track. Give it a few chances to
3878 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003879 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003880 if (--(track->mRetryCount) <= 0) {
3881 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003882 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003883 // indicate to client process that the track was disabled because of underrun;
3884 // it will then automatically call start() when data is available
3885 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003887 mixerStatus = MIXER_TRACKS_ENABLED;
3888 }
3889 }
3890 }
3891 }
3892
Eric Laurent81784c32012-11-19 14:55:58 -08003893 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003895
3896 return mixerStatus;
3897}
3898
3899void AudioFlinger::DirectOutputThread::threadLoop_mix()
3900{
Eric Laurent81784c32012-11-19 14:55:58 -08003901 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003902 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003903 // output audio to hardware
3904 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003905 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003906 buffer.frameCount = frameCount;
3907 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003908 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003909 memset(curBuf, 0, frameCount * mFrameSize);
3910 break;
3911 }
3912 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3913 frameCount -= buffer.frameCount;
3914 curBuf += buffer.frameCount * mFrameSize;
3915 mActiveTrack->releaseBuffer(&buffer);
3916 }
Andy Hung2098f272014-02-27 14:00:06 -08003917 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003918 sleepTime = 0;
3919 standbyTime = systemTime() + standbyDelay;
3920 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003921}
3922
3923void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3924{
3925 if (sleepTime == 0) {
3926 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3927 sleepTime = activeSleepTime;
3928 } else {
3929 sleepTime = idleSleepTime;
3930 }
3931 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003932 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003933 sleepTime = 0;
3934 }
3935}
3936
3937// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003938int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07003939 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003940{
3941 return 0;
3942}
3943
3944// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003945void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003946{
3947}
3948
Eric Laurent10351942014-05-08 18:49:52 -07003949// checkForNewParameter_l() must be called with ThreadBase::mLock held
3950bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
3951 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003952{
3953 bool reconfig = false;
3954
Eric Laurent10351942014-05-08 18:49:52 -07003955 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003956
Eric Laurent10351942014-05-08 18:49:52 -07003957 AudioParameter param = AudioParameter(keyValuePair);
3958 int value;
3959 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3960 // forward device change to effects that have requested to be
3961 // aware of attached audio device.
3962 if (value != AUDIO_DEVICE_NONE) {
3963 mOutDevice = value;
3964 for (size_t i = 0; i < mEffectChains.size(); i++) {
3965 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07003966 }
3967 }
Eric Laurent81784c32012-11-19 14:55:58 -08003968 }
Eric Laurent10351942014-05-08 18:49:52 -07003969 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3970 // do not accept frame count changes if tracks are open as the track buffer
3971 // size depends on frame count and correct behavior would not be garantied
3972 // if frame count is changed after track creation
3973 if (!mTracks.isEmpty()) {
3974 status = INVALID_OPERATION;
3975 } else {
3976 reconfig = true;
3977 }
3978 }
3979 if (status == NO_ERROR) {
3980 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3981 keyValuePair.string());
3982 if (!mStandby && status == INVALID_OPERATION) {
3983 mOutput->stream->common.standby(&mOutput->stream->common);
3984 mStandby = true;
3985 mBytesWritten = 0;
3986 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3987 keyValuePair.string());
3988 }
3989 if (status == NO_ERROR && reconfig) {
3990 readOutputParameters_l();
3991 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3992 }
3993 }
3994
Eric Laurent81784c32012-11-19 14:55:58 -08003995 return reconfig;
3996}
3997
3998uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3999{
4000 uint32_t time;
4001 if (audio_is_linear_pcm(mFormat)) {
4002 time = PlaybackThread::activeSleepTimeUs();
4003 } else {
4004 time = 10000;
4005 }
4006 return time;
4007}
4008
4009uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4010{
4011 uint32_t time;
4012 if (audio_is_linear_pcm(mFormat)) {
4013 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4014 } else {
4015 time = 10000;
4016 }
4017 return time;
4018}
4019
4020uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4021{
4022 uint32_t time;
4023 if (audio_is_linear_pcm(mFormat)) {
4024 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4025 } else {
4026 time = 10000;
4027 }
4028 return time;
4029}
4030
4031void AudioFlinger::DirectOutputThread::cacheParameters_l()
4032{
4033 PlaybackThread::cacheParameters_l();
4034
4035 // use shorter standby delay as on normal output to release
4036 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004037 if (audio_is_linear_pcm(mFormat)) {
4038 standbyDelay = microseconds(activeSleepTime*2);
4039 } else {
4040 standbyDelay = kOffloadStandbyDelayNs;
4041 }
Eric Laurent81784c32012-11-19 14:55:58 -08004042}
4043
4044// ----------------------------------------------------------------------------
4045
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004047 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004048 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004049 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004050 mWriteAckSequence(0),
4051 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004052{
4053}
4054
4055AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4056{
4057}
4058
4059void AudioFlinger::AsyncCallbackThread::onFirstRef()
4060{
4061 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4062}
4063
4064bool AudioFlinger::AsyncCallbackThread::threadLoop()
4065{
4066 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004067 uint32_t writeAckSequence;
4068 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069
4070 {
4071 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004072 while (!((mWriteAckSequence & 1) ||
4073 (mDrainSequence & 1) ||
4074 exitPending())) {
4075 mWaitWorkCV.wait(mLock);
4076 }
4077
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 if (exitPending()) {
4079 break;
4080 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004081 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4082 mWriteAckSequence, mDrainSequence);
4083 writeAckSequence = mWriteAckSequence;
4084 mWriteAckSequence &= ~1;
4085 drainSequence = mDrainSequence;
4086 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004087 }
4088 {
Eric Laurent4de95592013-09-26 15:28:21 -07004089 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4090 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004091 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004092 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004093 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004094 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004095 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 }
4097 }
4098 }
4099 }
4100 return false;
4101}
4102
4103void AudioFlinger::AsyncCallbackThread::exit()
4104{
4105 ALOGV("AsyncCallbackThread::exit");
4106 Mutex::Autolock _l(mLock);
4107 requestExit();
4108 mWaitWorkCV.broadcast();
4109}
4110
Eric Laurent3b4529e2013-09-05 18:09:19 -07004111void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004112{
4113 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004114 // bit 0 is cleared
4115 mWriteAckSequence = sequence << 1;
4116}
4117
4118void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4119{
4120 Mutex::Autolock _l(mLock);
4121 // ignore unexpected callbacks
4122 if (mWriteAckSequence & 2) {
4123 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004124 mWaitWorkCV.signal();
4125 }
4126}
4127
Eric Laurent3b4529e2013-09-05 18:09:19 -07004128void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004129{
4130 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004131 // bit 0 is cleared
4132 mDrainSequence = sequence << 1;
4133}
4134
4135void AudioFlinger::AsyncCallbackThread::resetDraining()
4136{
4137 Mutex::Autolock _l(mLock);
4138 // ignore unexpected callbacks
4139 if (mDrainSequence & 2) {
4140 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004141 mWaitWorkCV.signal();
4142 }
4143}
4144
4145
4146// ----------------------------------------------------------------------------
4147AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4148 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4149 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4150 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004151 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004152 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153{
Eric Laurentfd477972013-10-25 18:10:40 -07004154 //FIXME: mStandby should be set to true by ThreadBase constructor
4155 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156}
4157
Eric Laurentbfb1b832013-01-07 09:53:42 -08004158void AudioFlinger::OffloadThread::threadLoop_exit()
4159{
4160 if (mFlushPending || mHwPaused) {
4161 // If a flush is pending or track was paused, just discard buffered data
4162 flushHw_l();
4163 } else {
4164 mMixerStatus = MIXER_DRAIN_ALL;
4165 threadLoop_drain();
4166 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004167 if (mUseAsyncWrite) {
4168 ALOG_ASSERT(mCallbackThread != 0);
4169 mCallbackThread->exit();
4170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 PlaybackThread::threadLoop_exit();
4172}
4173
4174AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4175 Vector< sp<Track> > *tracksToRemove
4176)
4177{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178 size_t count = mActiveTracks.size();
4179
4180 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004181 bool doHwPause = false;
4182 bool doHwResume = false;
4183
Eric Laurentede6c3b2013-09-19 14:37:46 -07004184 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4185
Eric Laurentbfb1b832013-01-07 09:53:42 -08004186 // find out which tracks need to be processed
4187 for (size_t i = 0; i < count; i++) {
4188 sp<Track> t = mActiveTracks[i].promote();
4189 // The track died recently
4190 if (t == 0) {
4191 continue;
4192 }
4193 Track* const track = t.get();
4194 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004195 // Only consider last track started for volume and mixer state control.
4196 // In theory an older track could underrun and restart after the new one starts
4197 // but as we only care about the transition phase between two tracks on a
4198 // direct output, it is not a problem to ignore the underrun case.
4199 sp<Track> l = mLatestActiveTrack.promote();
4200 bool last = l.get() == track;
4201
Haynes Mathew George7844f672014-01-15 12:32:55 -08004202 if (track->isInvalid()) {
4203 ALOGW("An invalidated track shouldn't be in active list");
4204 tracksToRemove->add(track);
4205 continue;
4206 }
4207
4208 if (track->mState == TrackBase::IDLE) {
4209 ALOGW("An idle track shouldn't be in active list");
4210 continue;
4211 }
4212
Eric Laurentbfb1b832013-01-07 09:53:42 -08004213 if (track->isPausing()) {
4214 track->setPaused();
4215 if (last) {
4216 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004217 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004218 mHwPaused = true;
4219 }
4220 // If we were part way through writing the mixbuffer to
4221 // the HAL we must save this until we resume
4222 // BUG - this will be wrong if a different track is made active,
4223 // in that case we want to discard the pending data in the
4224 // mixbuffer and tell the client to present it again when the
4225 // track is resumed
4226 mPausedWriteLength = mCurrentWriteLength;
4227 mPausedBytesRemaining = mBytesRemaining;
4228 mBytesRemaining = 0; // stop writing
4229 }
4230 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004231 } else if (track->isFlushPending()) {
4232 track->flushAck();
4233 if (last) {
4234 mFlushPending = true;
4235 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004236 } else if (track->isResumePending()){
4237 track->resumeAck();
4238 if (last) {
4239 if (mPausedBytesRemaining) {
4240 // Need to continue write that was interrupted
4241 mCurrentWriteLength = mPausedWriteLength;
4242 mBytesRemaining = mPausedBytesRemaining;
4243 mPausedBytesRemaining = 0;
4244 }
4245 if (mHwPaused) {
4246 doHwResume = true;
4247 mHwPaused = false;
4248 // threadLoop_mix() will handle the case that we need to
4249 // resume an interrupted write
4250 }
4251 // enable write to audio HAL
4252 sleepTime = 0;
4253
4254 // Do not handle new data in this iteration even if track->framesReady()
4255 mixerStatus = MIXER_TRACKS_ENABLED;
4256 }
4257 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004258 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004259 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004260 if (track->mFillingUpStatus == Track::FS_FILLED) {
4261 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004262 // make sure processVolume_l() will apply new volume even if 0
4263 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004264 }
4265
4266 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004267 sp<Track> previousTrack = mPreviousTrack.promote();
4268 if (previousTrack != 0) {
4269 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004270 // Flush any data still being written from last track
4271 mBytesRemaining = 0;
4272 if (mPausedBytesRemaining) {
4273 // Last track was paused so we also need to flush saved
4274 // mixbuffer state and invalidate track so that it will
4275 // re-submit that unwritten data when it is next resumed
4276 mPausedBytesRemaining = 0;
4277 // Invalidate is a bit drastic - would be more efficient
4278 // to have a flag to tell client that some of the
4279 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004280 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004281 }
4282 // flush data already sent to the DSP if changing audio session as audio
4283 // comes from a different source. Also invalidate previous track to force a
4284 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004285 if (previousTrack->sessionId() != track->sessionId()) {
4286 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004287 }
4288 }
4289 }
4290 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004291 // reset retry count
4292 track->mRetryCount = kMaxTrackRetriesOffload;
4293 mActiveTrack = t;
4294 mixerStatus = MIXER_TRACKS_READY;
4295 }
4296 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004297 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004298 if (track->isStopping_1()) {
4299 // Hardware buffer can hold a large amount of audio so we must
4300 // wait for all current track's data to drain before we say
4301 // that the track is stopped.
4302 if (mBytesRemaining == 0) {
4303 // Only start draining when all data in mixbuffer
4304 // has been written
4305 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4306 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004307 // do not drain if no data was ever sent to HAL (mStandby == true)
4308 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004309 // do not modify drain sequence if we are already draining. This happens
4310 // when resuming from pause after drain.
4311 if ((mDrainSequence & 1) == 0) {
4312 sleepTime = 0;
4313 standbyTime = systemTime() + standbyDelay;
4314 mixerStatus = MIXER_DRAIN_TRACK;
4315 mDrainSequence += 2;
4316 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004317 if (mHwPaused) {
4318 // It is possible to move from PAUSED to STOPPING_1 without
4319 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004320 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321 mHwPaused = false;
4322 }
4323 }
4324 }
4325 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004326 // Drain has completed or we are in standby, signal presentation complete
4327 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328 track->mState = TrackBase::STOPPED;
4329 size_t audioHALFrames =
4330 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4331 size_t framesWritten =
4332 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4333 track->presentationComplete(framesWritten, audioHALFrames);
4334 track->reset();
4335 tracksToRemove->add(track);
4336 }
4337 } else {
4338 // No buffers for this track. Give it a few chances to
4339 // fill a buffer, then remove it from active list.
4340 if (--(track->mRetryCount) <= 0) {
4341 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4342 track->name());
4343 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004344 // indicate to client process that the track was disabled because of underrun;
4345 // it will then automatically call start() when data is available
4346 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004347 } else if (last){
4348 mixerStatus = MIXER_TRACKS_ENABLED;
4349 }
4350 }
4351 }
4352 // compute volume for this track
4353 processVolume_l(track, last);
4354 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004355
Eric Laurentea0fade2013-10-04 16:23:48 -07004356 // make sure the pause/flush/resume sequence is executed in the right order.
4357 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4358 // before flush and then resume HW. This can happen in case of pause/flush/resume
4359 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004360 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004361 mOutput->stream->pause(mOutput->stream);
4362 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004363 if (mFlushPending) {
4364 flushHw_l();
4365 mFlushPending = false;
4366 }
Eric Laurentfd477972013-10-25 18:10:40 -07004367 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004368 mOutput->stream->resume(mOutput->stream);
4369 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004370
Eric Laurentbfb1b832013-01-07 09:53:42 -08004371 // remove all the tracks that need to be...
4372 removeTracks_l(*tracksToRemove);
4373
4374 return mixerStatus;
4375}
4376
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377// must be called with thread mutex locked
4378bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4379{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004380 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4381 mWriteAckSequence, mDrainSequence);
4382 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383 return true;
4384 }
4385 return false;
4386}
4387
4388// must be called with thread mutex locked
4389bool AudioFlinger::OffloadThread::shouldStandby_l()
4390{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004391 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392
4393 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4394 // after a timeout and we will enter standby then.
4395 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004396 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004397 }
4398
Glenn Kastene6f35b12013-08-19 09:58:50 -07004399 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004400}
4401
4402
4403bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4404{
4405 Mutex::Autolock _l(mLock);
4406 return waitingAsyncCallback_l();
4407}
4408
4409void AudioFlinger::OffloadThread::flushHw_l()
4410{
4411 mOutput->stream->flush(mOutput->stream);
4412 // Flush anything still waiting in the mixbuffer
4413 mCurrentWriteLength = 0;
4414 mBytesRemaining = 0;
4415 mPausedWriteLength = 0;
4416 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004417 mHwPaused = false;
4418
Eric Laurentbfb1b832013-01-07 09:53:42 -08004419 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004420 // discard any pending drain or write ack by incrementing sequence
4421 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4422 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004423 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004424 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4425 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426 }
4427}
4428
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004429void AudioFlinger::OffloadThread::onAddNewTrack_l()
4430{
4431 sp<Track> previousTrack = mPreviousTrack.promote();
4432 sp<Track> latestTrack = mLatestActiveTrack.promote();
4433
4434 if (previousTrack != 0 && latestTrack != 0 &&
4435 (previousTrack->sessionId() != latestTrack->sessionId())) {
4436 mFlushPending = true;
4437 }
4438 PlaybackThread::onAddNewTrack_l();
4439}
4440
Eric Laurentbfb1b832013-01-07 09:53:42 -08004441// ----------------------------------------------------------------------------
4442
Eric Laurent81784c32012-11-19 14:55:58 -08004443AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4444 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4445 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4446 DUPLICATING),
4447 mWaitTimeMs(UINT_MAX)
4448{
4449 addOutputTrack(mainThread);
4450}
4451
4452AudioFlinger::DuplicatingThread::~DuplicatingThread()
4453{
4454 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4455 mOutputTracks[i]->destroy();
4456 }
4457}
4458
4459void AudioFlinger::DuplicatingThread::threadLoop_mix()
4460{
4461 // mix buffers...
4462 if (outputsReady(outputTracks)) {
4463 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4464 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004465 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004466 }
4467 sleepTime = 0;
4468 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004469 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004470 standbyTime = systemTime() + standbyDelay;
4471}
4472
4473void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4474{
4475 if (sleepTime == 0) {
4476 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4477 sleepTime = activeSleepTime;
4478 } else {
4479 sleepTime = idleSleepTime;
4480 }
4481 } else if (mBytesWritten != 0) {
4482 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4483 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004484 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004485 } else {
4486 // flush remaining overflow buffers in output tracks
4487 writeFrames = 0;
4488 }
4489 sleepTime = 0;
4490 }
4491}
4492
Eric Laurentbfb1b832013-01-07 09:53:42 -08004493ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004494{
4495 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004496 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4497 // for delivery downstream as needed. This in-place conversion is safe as
4498 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4499 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4500 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4501 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4502 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4503 }
4504 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004505 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004506 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004507 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004508}
4509
4510void AudioFlinger::DuplicatingThread::threadLoop_standby()
4511{
4512 // DuplicatingThread implements standby by stopping all tracks
4513 for (size_t i = 0; i < outputTracks.size(); i++) {
4514 outputTracks[i]->stop();
4515 }
4516}
4517
4518void AudioFlinger::DuplicatingThread::saveOutputTracks()
4519{
4520 outputTracks = mOutputTracks;
4521}
4522
4523void AudioFlinger::DuplicatingThread::clearOutputTracks()
4524{
4525 outputTracks.clear();
4526}
4527
4528void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4529{
4530 Mutex::Autolock _l(mLock);
4531 // FIXME explain this formula
4532 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004533 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4534 // due to current usage case and restrictions on the AudioBufferProvider.
4535 // Actual buffer conversion is done in threadLoop_write().
4536 //
4537 // TODO: This may change in the future, depending on multichannel
4538 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004539 OutputTrack *outputTrack = new OutputTrack(thread,
4540 this,
4541 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004542 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004543 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004544 frameCount,
4545 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004546 if (outputTrack->cblk() != NULL) {
4547 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4548 mOutputTracks.add(outputTrack);
4549 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4550 updateWaitTime_l();
4551 }
4552}
4553
4554void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4555{
4556 Mutex::Autolock _l(mLock);
4557 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4558 if (mOutputTracks[i]->thread() == thread) {
4559 mOutputTracks[i]->destroy();
4560 mOutputTracks.removeAt(i);
4561 updateWaitTime_l();
4562 return;
4563 }
4564 }
4565 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4566}
4567
4568// caller must hold mLock
4569void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4570{
4571 mWaitTimeMs = UINT_MAX;
4572 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4573 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4574 if (strong != 0) {
4575 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4576 if (waitTimeMs < mWaitTimeMs) {
4577 mWaitTimeMs = waitTimeMs;
4578 }
4579 }
4580 }
4581}
4582
4583
4584bool AudioFlinger::DuplicatingThread::outputsReady(
4585 const SortedVector< sp<OutputTrack> > &outputTracks)
4586{
4587 for (size_t i = 0; i < outputTracks.size(); i++) {
4588 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4589 if (thread == 0) {
4590 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4591 outputTracks[i].get());
4592 return false;
4593 }
4594 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4595 // see note at standby() declaration
4596 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4597 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4598 thread.get());
4599 return false;
4600 }
4601 }
4602 return true;
4603}
4604
4605uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4606{
4607 return (mWaitTimeMs * 1000) / 2;
4608}
4609
4610void AudioFlinger::DuplicatingThread::cacheParameters_l()
4611{
4612 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4613 updateWaitTime_l();
4614
4615 MixerThread::cacheParameters_l();
4616}
4617
4618// ----------------------------------------------------------------------------
4619// Record
4620// ----------------------------------------------------------------------------
4621
4622AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4623 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004624 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004625 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004626 audio_devices_t inDevice
4627#ifdef TEE_SINK
4628 , const sp<NBAIO_Sink>& teeSink
4629#endif
4630 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004631 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004632 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004633 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004634 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004635#ifdef TEE_SINK
4636 , mTeeSink(teeSink)
4637#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004638 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4639 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004640{
4641 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004642 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004643
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004644 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004645}
4646
4647
4648AudioFlinger::RecordThread::~RecordThread()
4649{
Glenn Kasten481fb672013-09-30 14:39:28 -07004650 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004651 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004652}
4653
4654void AudioFlinger::RecordThread::onFirstRef()
4655{
4656 run(mName, PRIORITY_URGENT_AUDIO);
4657}
4658
Eric Laurent81784c32012-11-19 14:55:58 -08004659bool AudioFlinger::RecordThread::threadLoop()
4660{
Eric Laurent81784c32012-11-19 14:55:58 -08004661 nsecs_t lastWarning = 0;
4662
4663 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004664
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004665reacquire_wakelock:
4666 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004667 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004668 {
4669 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004670 size_t size = mActiveTracks.size();
4671 activeTracksGen = mActiveTracksGen;
4672 if (size > 0) {
4673 // FIXME an arbitrary choice
4674 activeTrack = mActiveTracks[0];
4675 acquireWakeLock_l(activeTrack->uid());
4676 if (size > 1) {
4677 SortedVector<int> tmp;
4678 for (size_t i = 0; i < size; i++) {
4679 tmp.add(mActiveTracks[i]->uid());
4680 }
4681 updateWakeLockUids_l(tmp);
4682 }
4683 } else {
4684 acquireWakeLock_l(-1);
4685 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004686 }
4687
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004688 // used to request a deferred sleep, to be executed later while mutex is unlocked
4689 uint32_t sleepUs = 0;
4690
4691 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004692 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004693 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004694
Glenn Kasten5edadd42013-08-14 16:30:49 -07004695 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004696 if (sleepUs > 0) {
4697 usleep(sleepUs);
4698 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004699 }
4700
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004701 // activeTracks accumulates a copy of a subset of mActiveTracks
4702 Vector< sp<RecordTrack> > activeTracks;
4703
Eric Laurent10351942014-05-08 18:49:52 -07004704
Eric Laurent81784c32012-11-19 14:55:58 -08004705 { // scope for mLock
4706 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004707
Eric Laurent021cf962014-05-13 10:18:14 -07004708 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004709
Eric Laurent000a4192014-01-29 15:17:32 -08004710 // check exitPending here because checkForNewParameters_l() and
4711 // checkForNewParameters_l() can temporarily release mLock
4712 if (exitPending()) {
4713 break;
4714 }
4715
Glenn Kasten2b806402013-11-20 16:37:38 -08004716 // if no active track(s), then standby and release wakelock
4717 size_t size = mActiveTracks.size();
4718 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004719 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004720 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004721 releaseWakeLock_l();
4722 ALOGV("RecordThread: loop stopping");
4723 // go to sleep
4724 mWaitWorkCV.wait(mLock);
4725 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004726 goto reacquire_wakelock;
4727 }
4728
Glenn Kasten2b806402013-11-20 16:37:38 -08004729 if (mActiveTracksGen != activeTracksGen) {
4730 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004731 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004732 for (size_t i = 0; i < size; i++) {
4733 tmp.add(mActiveTracks[i]->uid());
4734 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004735 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004736 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004737
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004738 bool doBroadcast = false;
4739 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004740
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004741 activeTrack = mActiveTracks[i];
4742 if (activeTrack->isTerminated()) {
4743 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004744 mActiveTracks.remove(activeTrack);
4745 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004746 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004747 continue;
4748 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004749
4750 TrackBase::track_state activeTrackState = activeTrack->mState;
4751 switch (activeTrackState) {
4752
4753 case TrackBase::PAUSING:
4754 mActiveTracks.remove(activeTrack);
4755 mActiveTracksGen++;
4756 doBroadcast = true;
4757 size--;
4758 continue;
4759
4760 case TrackBase::STARTING_1:
4761 sleepUs = 10000;
4762 i++;
4763 continue;
4764
4765 case TrackBase::STARTING_2:
4766 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004767 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004768 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004769 break;
4770
4771 case TrackBase::ACTIVE:
4772 break;
4773
4774 case TrackBase::IDLE:
4775 i++;
4776 continue;
4777
4778 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004779 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004780 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004781
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004782 activeTracks.add(activeTrack);
4783 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004784
Glenn Kasten9e982352013-08-14 14:39:50 -07004785 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004786 if (doBroadcast) {
4787 mStartStopCond.broadcast();
4788 }
4789
4790 // sleep if there are no active tracks to process
4791 if (activeTracks.size() == 0) {
4792 if (sleepUs == 0) {
4793 sleepUs = kRecordThreadSleepUs;
4794 }
4795 continue;
4796 }
4797 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004798
Eric Laurent81784c32012-11-19 14:55:58 -08004799 lockEffectChains_l(effectChains);
4800 }
4801
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004802 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004803
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004804 size_t size = effectChains.size();
4805 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004806 // thread mutex is not locked, but effect chain is locked
4807 effectChains[i]->process_l();
4808 }
4809
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004810 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4811 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4812 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4813 // If destination is non-contiguous, first read past the nominal end of buffer, then
4814 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004815
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004816 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4817 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4818 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4819 if (bytesRead <= 0) {
4820 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4821 // Force input into standby so that it tries to recover at next read attempt
4822 inputStandBy();
4823 sleepUs = kRecordThreadSleepUs;
4824 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004825 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004826 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4827 size_t framesRead = bytesRead / mFrameSize;
4828 ALOG_ASSERT(framesRead > 0);
4829 if (mTeeSink != 0) {
4830 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4831 }
4832 // If destination is non-contiguous, we now correct for reading past end of buffer.
4833 size_t part1 = mRsmpInFramesP2 - rear;
4834 if (framesRead > part1) {
4835 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4836 (framesRead - part1) * mFrameSize);
4837 }
4838 rear = mRsmpInRear += framesRead;
4839
4840 size = activeTracks.size();
4841 // loop over each active track
4842 for (size_t i = 0; i < size; i++) {
4843 activeTrack = activeTracks[i];
4844
4845 enum {
4846 OVERRUN_UNKNOWN,
4847 OVERRUN_TRUE,
4848 OVERRUN_FALSE
4849 } overrun = OVERRUN_UNKNOWN;
4850
4851 // loop over getNextBuffer to handle circular sink
4852 for (;;) {
4853
4854 activeTrack->mSink.frameCount = ~0;
4855 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4856 size_t framesOut = activeTrack->mSink.frameCount;
4857 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4858
4859 int32_t front = activeTrack->mRsmpInFront;
4860 ssize_t filled = rear - front;
4861 size_t framesIn;
4862
4863 if (filled < 0) {
4864 // should not happen, but treat like a massive overrun and re-sync
4865 framesIn = 0;
4866 activeTrack->mRsmpInFront = rear;
4867 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004868 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004869 framesIn = (size_t) filled;
4870 } else {
4871 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004872 framesIn = mRsmpInFrames;
4873 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004874 overrun = OVERRUN_TRUE;
4875 }
4876
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004877 if (framesOut == 0 || framesIn == 0) {
4878 break;
4879 }
4880
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004881 if (activeTrack->mResampler == NULL) {
4882 // no resampling
4883 if (framesIn > framesOut) {
4884 framesIn = framesOut;
4885 } else {
4886 framesOut = framesIn;
4887 }
4888 int8_t *dst = activeTrack->mSink.i8;
4889 while (framesIn > 0) {
4890 front &= mRsmpInFramesP2 - 1;
4891 size_t part1 = mRsmpInFramesP2 - front;
4892 if (part1 > framesIn) {
4893 part1 = framesIn;
4894 }
4895 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004896 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004897 memcpy(dst, src, part1 * mFrameSize);
4898 } else if (mChannelCount == 1) {
4899 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4900 part1);
4901 } else {
4902 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4903 part1);
4904 }
4905 dst += part1 * activeTrack->mFrameSize;
4906 front += part1;
4907 framesIn -= part1;
4908 }
4909 activeTrack->mRsmpInFront += framesOut;
4910
4911 } else {
4912 // resampling
4913 // FIXME framesInNeeded should really be part of resampler API, and should
4914 // depend on the SRC ratio
4915 // to keep mRsmpInBuffer full so resampler always has sufficient input
4916 size_t framesInNeeded;
4917 // FIXME only re-calculate when it changes, and optimize for common ratios
4918 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4919 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004920 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004921 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4922 framesInNeeded, framesOut, inOverOut);
4923 // Although we theoretically have framesIn in circular buffer, some of those are
4924 // unreleased frames, and thus must be discounted for purpose of budgeting.
4925 size_t unreleased = activeTrack->mRsmpInUnrel;
4926 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004927 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004928 ALOGV("not enough to resample: have %u frames in but need %u in to "
4929 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004930 framesIn, framesInNeeded, framesOut, inOverOut);
4931 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004932 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4933 if (newFramesOut == 0) {
4934 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004935 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004936 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4937 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4938 framesInNeeded, newFramesOut, outOverIn);
4939 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4940 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4941 "given in/out ratio of %.4g",
4942 framesIn, framesInNeeded, newFramesOut, inOverOut);
4943 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004944 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004945 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004946 "given in/out ratio of %.4g",
4947 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004948 }
4949
4950 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4951 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004952 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004953 delete[] activeTrack->mRsmpOutBuffer;
4954 // resampler always outputs stereo
4955 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4956 activeTrack->mRsmpOutFrameCount = framesOut;
4957 }
4958
4959 // resampler accumulates, but we only have one source track
4960 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4961 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004962 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004963 activeTrack->mResamplerBufferProvider
4964 /*this*/ /* AudioBufferProvider* */);
4965 // ditherAndClamp() works as long as all buffers returned by
4966 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004967 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07004968 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004969 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4970 framesOut);
4971 // the resampler always outputs stereo samples:
4972 // do post stereo to mono conversion
4973 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4974 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4975 } else {
4976 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4977 activeTrack->mRsmpOutBuffer, framesOut);
4978 }
4979 // now done with mRsmpOutBuffer
4980
4981 }
4982
4983 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4984 overrun = OVERRUN_FALSE;
4985 }
4986
4987 if (activeTrack->mFramesToDrop == 0) {
4988 if (framesOut > 0) {
4989 activeTrack->mSink.frameCount = framesOut;
4990 activeTrack->releaseBuffer(&activeTrack->mSink);
4991 }
4992 } else {
4993 // FIXME could do a partial drop of framesOut
4994 if (activeTrack->mFramesToDrop > 0) {
4995 activeTrack->mFramesToDrop -= framesOut;
4996 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004997 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004998 }
4999 } else {
5000 activeTrack->mFramesToDrop += framesOut;
5001 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5002 activeTrack->mSyncStartEvent->isCancelled()) {
5003 ALOGW("Synced record %s, session %d, trigger session %d",
5004 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5005 activeTrack->sessionId(),
5006 (activeTrack->mSyncStartEvent != 0) ?
5007 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005008 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005009 }
5010 }
5011 }
5012
5013 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005014 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005015 }
5016 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005017
5018 switch (overrun) {
5019 case OVERRUN_TRUE:
5020 // client isn't retrieving buffers fast enough
5021 if (!activeTrack->setOverflow()) {
5022 nsecs_t now = systemTime();
5023 // FIXME should lastWarning per track?
5024 if ((now - lastWarning) > kWarningThrottleNs) {
5025 ALOGW("RecordThread: buffer overflow");
5026 lastWarning = now;
5027 }
5028 }
5029 break;
5030 case OVERRUN_FALSE:
5031 activeTrack->clearOverflow();
5032 break;
5033 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005034 break;
5035 }
5036
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005037 }
5038
Eric Laurent81784c32012-11-19 14:55:58 -08005039 // enable changes in effect chain
5040 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005041 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005042 }
5043
Glenn Kasten93e471f2013-08-19 08:40:07 -07005044 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005045
5046 {
5047 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005048 for (size_t i = 0; i < mTracks.size(); i++) {
5049 sp<RecordTrack> track = mTracks[i];
5050 track->invalidate();
5051 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005052 mActiveTracks.clear();
5053 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005054 mStartStopCond.broadcast();
5055 }
5056
5057 releaseWakeLock();
5058
5059 ALOGV("RecordThread %p exiting", this);
5060 return false;
5061}
5062
Glenn Kasten93e471f2013-08-19 08:40:07 -07005063void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005064{
5065 if (!mStandby) {
5066 inputStandBy();
5067 mStandby = true;
5068 }
5069}
5070
5071void AudioFlinger::RecordThread::inputStandBy()
5072{
5073 mInput->stream->common.standby(&mInput->stream->common);
5074}
5075
Glenn Kasten05997e22014-03-13 15:08:33 -07005076// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005077sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005078 const sp<AudioFlinger::Client>& client,
5079 uint32_t sampleRate,
5080 audio_format_t format,
5081 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005082 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005083 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005084 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005085 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005086 pid_t tid,
5087 status_t *status)
5088{
Glenn Kasten74935e42013-12-19 08:56:45 -08005089 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005090 sp<RecordTrack> track;
5091 status_t lStatus;
5092
Glenn Kasten90e58b12013-07-31 16:16:02 -07005093 // client expresses a preference for FAST, but we get the final say
5094 if (*flags & IAudioFlinger::TRACK_FAST) {
5095 if (
5096 // use case: callback handler and frame count is default or at least as large as HAL
5097 (
5098 (tid != -1) &&
5099 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005100 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005101 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005102 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005103 // PCM data
5104 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005105 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005106 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5107 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005108 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005109 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005110 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005111 // record thread has an associated fast capture
5112 hasFastCapture()
5113 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005114 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005115 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005116 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005117 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005118 frameCount = mFrameCount * kFastTrackMultiplier;
5119 }
5120 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5121 frameCount, mFrameCount);
5122 } else {
5123 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5124 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005125 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005126 frameCount, mFrameCount, format,
5127 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005128 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005129 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005130 // 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 -07005131 // For compatibility with AudioRecord calculation, buffer depth is forced
5132 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5133 // This is probably too conservative, but legacy application code may depend on it.
5134 // If you change this calculation, also review the start threshold which is related.
Glenn Kasten29b703e2014-05-12 11:06:26 -07005135 // FIXME It's not clear how input latency actually matters. Perhaps this should be 0.
Glenn Kasten90e58b12013-07-31 16:16:02 -07005136 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5137 size_t mNormalFrameCount = 2048; // FIXME
5138 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5139 if (minBufCount < 2) {
5140 minBufCount = 2;
5141 }
5142 size_t minFrameCount = mNormalFrameCount * minBufCount;
5143 if (frameCount < minFrameCount) {
5144 frameCount = minFrameCount;
5145 }
5146 }
5147 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005148 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005149
Glenn Kasten15e57982013-09-24 11:52:37 -07005150 lStatus = initCheck();
5151 if (lStatus != NO_ERROR) {
5152 ALOGE("createRecordTrack_l() audio driver not initialized");
5153 goto Exit;
5154 }
Eric Laurent81784c32012-11-19 14:55:58 -08005155
5156 { // scope for mLock
5157 Mutex::Autolock _l(mLock);
5158
5159 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005160 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005161 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005162
Glenn Kasten03003332013-08-06 15:40:54 -07005163 lStatus = track->initCheck();
5164 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005165 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005166 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005167 goto Exit;
5168 }
5169 mTracks.add(track);
5170
5171 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5172 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5173 mAudioFlinger->btNrecIsOff();
5174 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5175 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005176
5177 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5178 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5179 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5180 // so ask activity manager to do this on our behalf
5181 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5182 }
Eric Laurent81784c32012-11-19 14:55:58 -08005183 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005184
Eric Laurent81784c32012-11-19 14:55:58 -08005185 lStatus = NO_ERROR;
5186
5187Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005188 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005189 return track;
5190}
5191
5192status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5193 AudioSystem::sync_event_t event,
5194 int triggerSession)
5195{
5196 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5197 sp<ThreadBase> strongMe = this;
5198 status_t status = NO_ERROR;
5199
5200 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005201 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005202 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005203 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005204 triggerSession,
5205 recordTrack->sessionId(),
5206 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005207 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005208 // Sync event can be cancelled by the trigger session if the track is not in a
5209 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005210 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005211 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005212 } else {
5213 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005214 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005215 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005216 }
5217 }
5218
5219 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005220 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005221 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005222 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5223 if (recordTrack->mState == TrackBase::PAUSING) {
5224 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005225 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005226 } else {
5227 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005228 }
5229 return status;
5230 }
5231
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005232 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5233 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5234 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005235 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005236 mActiveTracks.add(recordTrack);
5237 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005238 mLock.unlock();
5239 status_t status = AudioSystem::startInput(mId);
5240 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005242 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005243 mActiveTracks.remove(recordTrack);
5244 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005245 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005246 return status;
5247 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005248 // Catch up with current buffer indices if thread is already running.
5249 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5250 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5251 // see previously buffered data before it called start(), but with greater risk of overrun.
5252
5253 recordTrack->mRsmpInFront = mRsmpInRear;
5254 recordTrack->mRsmpInUnrel = 0;
5255 // FIXME why reset?
5256 if (recordTrack->mResampler != NULL) {
5257 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005258 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005259 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005260 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005261 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005262 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005263 ALOGV("Record failed to start");
5264 status = BAD_VALUE;
5265 goto startError;
5266 }
Eric Laurent81784c32012-11-19 14:55:58 -08005267 return status;
5268 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005269
Eric Laurent81784c32012-11-19 14:55:58 -08005270startError:
5271 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005272 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005273 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005274 return status;
5275}
5276
Eric Laurent81784c32012-11-19 14:55:58 -08005277void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5278{
5279 sp<SyncEvent> strongEvent = event.promote();
5280
5281 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005282 sp<RefBase> ptr = strongEvent->cookie().promote();
5283 if (ptr != 0) {
5284 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5285 recordTrack->handleSyncStartEvent(strongEvent);
5286 }
Eric Laurent81784c32012-11-19 14:55:58 -08005287 }
5288}
5289
Glenn Kastena8356f62013-07-25 14:37:52 -07005290bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005291 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005292 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005293 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005294 return false;
5295 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005296 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005297 recordTrack->mState = TrackBase::PAUSING;
5298 // do not wait for mStartStopCond if exiting
5299 if (exitPending()) {
5300 return true;
5301 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005302 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005303 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005304 // if we have been restarted, recordTrack is in mActiveTracks here
5305 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005306 ALOGV("Record stopped OK");
5307 return true;
5308 }
5309 return false;
5310}
5311
Glenn Kasten0f11b512014-01-31 16:18:54 -08005312bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005313{
5314 return false;
5315}
5316
Glenn Kasten0f11b512014-01-31 16:18:54 -08005317status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005318{
5319#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5320 if (!isValidSyncEvent(event)) {
5321 return BAD_VALUE;
5322 }
5323
5324 int eventSession = event->triggerSession();
5325 status_t ret = NAME_NOT_FOUND;
5326
5327 Mutex::Autolock _l(mLock);
5328
5329 for (size_t i = 0; i < mTracks.size(); i++) {
5330 sp<RecordTrack> track = mTracks[i];
5331 if (eventSession == track->sessionId()) {
5332 (void) track->setSyncEvent(event);
5333 ret = NO_ERROR;
5334 }
5335 }
5336 return ret;
5337#else
5338 return BAD_VALUE;
5339#endif
5340}
5341
5342// destroyTrack_l() must be called with ThreadBase::mLock held
5343void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5344{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 track->terminate();
5346 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005347 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005348 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005349 removeTrack_l(track);
5350 }
5351}
5352
5353void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5354{
5355 mTracks.remove(track);
5356 // need anything related to effects here?
5357}
5358
5359void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5360{
5361 dumpInternals(fd, args);
5362 dumpTracks(fd, args);
5363 dumpEffectChains(fd, args);
5364}
5365
5366void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5367{
Elliott Hughes87cebad2014-05-22 10:14:43 -07005368 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005369
Glenn Kasten2b806402013-11-20 16:37:38 -08005370 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005371 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005372 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005373 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005374 }
5375
Eric Laurent81784c32012-11-19 14:55:58 -08005376 dumpBase(fd, args);
5377}
5378
Glenn Kasten0f11b512014-01-31 16:18:54 -08005379void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005380{
5381 const size_t SIZE = 256;
5382 char buffer[SIZE];
5383 String8 result;
5384
Marco Nelissenb2208842014-02-07 14:00:50 -08005385 size_t numtracks = mTracks.size();
5386 size_t numactive = mActiveTracks.size();
5387 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07005388 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08005389 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005390 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08005391 RecordTrack::appendDumpHeader(result);
5392 for (size_t i = 0; i < numtracks ; ++i) {
5393 sp<RecordTrack> track = mTracks[i];
5394 if (track != 0) {
5395 bool active = mActiveTracks.indexOf(track) >= 0;
5396 if (active) {
5397 numactiveseen++;
5398 }
5399 track->dump(buffer, SIZE, active);
5400 result.append(buffer);
5401 }
Eric Laurent81784c32012-11-19 14:55:58 -08005402 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005403 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07005404 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005405 }
5406
Marco Nelissenb2208842014-02-07 14:00:50 -08005407 if (numactiveseen != numactive) {
5408 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5409 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005410 result.append(buffer);
5411 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005412 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005413 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005414 if (mTracks.indexOf(track) < 0) {
5415 track->dump(buffer, SIZE, true);
5416 result.append(buffer);
5417 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005418 }
Eric Laurent81784c32012-11-19 14:55:58 -08005419
5420 }
5421 write(fd, result.string(), result.size());
5422}
5423
5424// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005425status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5426 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005427{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005428 RecordTrack *activeTrack = mRecordTrack;
5429 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5430 if (threadBase == 0) {
5431 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005432 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005433 return NOT_ENOUGH_DATA;
5434 }
5435 RecordThread *recordThread = (RecordThread *) threadBase.get();
5436 int32_t rear = recordThread->mRsmpInRear;
5437 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005438 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005439 // FIXME should not be P2 (don't want to increase latency)
5440 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005441 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005442 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005443 front &= recordThread->mRsmpInFramesP2 - 1;
5444 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005445 if (part1 > (size_t) filled) {
5446 part1 = filled;
5447 }
5448 size_t ask = buffer->frameCount;
5449 ALOG_ASSERT(ask > 0);
5450 if (part1 > ask) {
5451 part1 = ask;
5452 }
5453 if (part1 == 0) {
5454 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005455 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005456 buffer->raw = NULL;
5457 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005459 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 }
5461
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005462 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005463 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005464 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005465 return NO_ERROR;
5466}
5467
5468// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5470 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005471{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005472 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005473 size_t stepCount = buffer->frameCount;
5474 if (stepCount == 0) {
5475 return;
5476 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005477 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5478 activeTrack->mRsmpInUnrel -= stepCount;
5479 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005480 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005481 buffer->frameCount = 0;
5482}
5483
Eric Laurent10351942014-05-08 18:49:52 -07005484bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5485 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005486{
5487 bool reconfig = false;
5488
Eric Laurent10351942014-05-08 18:49:52 -07005489 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005490
Eric Laurent10351942014-05-08 18:49:52 -07005491 audio_format_t reqFormat = mFormat;
5492 uint32_t samplingRate = mSampleRate;
5493 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5494
5495 AudioParameter param = AudioParameter(keyValuePair);
5496 int value;
5497 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5498 // channel count change can be requested. Do we mandate the first client defines the
5499 // HAL sampling rate and channel count or do we allow changes on the fly?
5500 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5501 samplingRate = value;
5502 reconfig = true;
5503 }
5504 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5505 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5506 status = BAD_VALUE;
5507 } else {
5508 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005509 reconfig = true;
5510 }
Eric Laurent10351942014-05-08 18:49:52 -07005511 }
5512 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5513 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5514 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5515 status = BAD_VALUE;
5516 } else {
5517 channelMask = mask;
5518 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005519 }
Eric Laurent10351942014-05-08 18:49:52 -07005520 }
5521 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5522 // do not accept frame count changes if tracks are open as the track buffer
5523 // size depends on frame count and correct behavior would not be guaranteed
5524 // if frame count is changed after track creation
5525 if (mActiveTracks.size() > 0) {
5526 status = INVALID_OPERATION;
5527 } else {
5528 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005529 }
Eric Laurent10351942014-05-08 18:49:52 -07005530 }
5531 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5532 // forward device change to effects that have requested to be
5533 // aware of attached audio device.
5534 for (size_t i = 0; i < mEffectChains.size(); i++) {
5535 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005536 }
Eric Laurent81784c32012-11-19 14:55:58 -08005537
Eric Laurent10351942014-05-08 18:49:52 -07005538 // store input device and output device but do not forward output device to audio HAL.
5539 // Note that status is ignored by the caller for output device
5540 // (see AudioFlinger::setParameters()
5541 if (audio_is_output_devices(value)) {
5542 mOutDevice = value;
5543 status = BAD_VALUE;
5544 } else {
5545 mInDevice = value;
5546 // disable AEC and NS if the device is a BT SCO headset supporting those
5547 // pre processings
5548 if (mTracks.size() > 0) {
5549 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5550 mAudioFlinger->btNrecIsOff();
5551 for (size_t i = 0; i < mTracks.size(); i++) {
5552 sp<RecordTrack> track = mTracks[i];
5553 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5554 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005555 }
5556 }
5557 }
Eric Laurent10351942014-05-08 18:49:52 -07005558 }
5559 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5560 mAudioSource != (audio_source_t)value) {
5561 // forward device change to effects that have requested to be
5562 // aware of attached audio device.
5563 for (size_t i = 0; i < mEffectChains.size(); i++) {
5564 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005565 }
Eric Laurent10351942014-05-08 18:49:52 -07005566 mAudioSource = (audio_source_t)value;
5567 }
Glenn Kastene198c362013-08-13 09:13:36 -07005568
Eric Laurent10351942014-05-08 18:49:52 -07005569 if (status == NO_ERROR) {
5570 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5571 keyValuePair.string());
5572 if (status == INVALID_OPERATION) {
5573 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005574 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5575 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005576 }
5577 if (reconfig) {
5578 if (status == BAD_VALUE &&
5579 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5580 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5581 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5582 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07005583 audio_channel_count_from_in_mask(
5584 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07005585 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5586 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5587 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
Eric Laurent10351942014-05-08 18:49:52 -07005589 if (status == NO_ERROR) {
5590 readInputParameters_l();
5591 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005592 }
5593 }
Eric Laurent81784c32012-11-19 14:55:58 -08005594 }
Eric Laurent10351942014-05-08 18:49:52 -07005595
Eric Laurent81784c32012-11-19 14:55:58 -08005596 return reconfig;
5597}
5598
5599String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5600{
Eric Laurent81784c32012-11-19 14:55:58 -08005601 Mutex::Autolock _l(mLock);
5602 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005603 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005604 }
5605
Glenn Kastend8ea6992013-07-16 14:17:15 -07005606 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5607 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005608 free(s);
5609 return out_s8;
5610}
5611
Eric Laurent021cf962014-05-13 10:18:14 -07005612void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005613 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005614 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005615
5616 switch (event) {
5617 case AudioSystem::INPUT_OPENED:
5618 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005619 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005620 desc.samplingRate = mSampleRate;
5621 desc.format = mFormat;
5622 desc.frameCount = mFrameCount;
5623 desc.latency = 0;
5624 param2 = &desc;
5625 break;
5626
5627 case AudioSystem::INPUT_CLOSED:
5628 default:
5629 break;
5630 }
Eric Laurent021cf962014-05-13 10:18:14 -07005631 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005632}
5633
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005634void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005635{
Eric Laurent81784c32012-11-19 14:55:58 -08005636 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5637 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07005638 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005639 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005640 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005641 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005642 }
Eric Laurent81784c32012-11-19 14:55:58 -08005643 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005644 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5645 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005646 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005647 // 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 -07005648 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005649 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005650 // A larger value should allow more old data to be read after a track calls start(),
5651 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005652 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005653 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005654 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005655 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5656 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005657
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005658 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5659 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005660}
5661
Glenn Kasten5f972c02014-01-13 09:59:31 -08005662uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005663{
5664 Mutex::Autolock _l(mLock);
5665 if (initCheck() != NO_ERROR) {
5666 return 0;
5667 }
5668
5669 return mInput->stream->get_input_frames_lost(mInput->stream);
5670}
5671
5672uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5673{
5674 Mutex::Autolock _l(mLock);
5675 uint32_t result = 0;
5676 if (getEffectChain_l(sessionId) != 0) {
5677 result = EFFECT_SESSION;
5678 }
5679
5680 for (size_t i = 0; i < mTracks.size(); ++i) {
5681 if (sessionId == mTracks[i]->sessionId()) {
5682 result |= TRACK_SESSION;
5683 break;
5684 }
5685 }
5686
5687 return result;
5688}
5689
5690KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5691{
5692 KeyedVector<int, bool> ids;
5693 Mutex::Autolock _l(mLock);
5694 for (size_t j = 0; j < mTracks.size(); ++j) {
5695 sp<RecordThread::RecordTrack> track = mTracks[j];
5696 int sessionId = track->sessionId();
5697 if (ids.indexOfKey(sessionId) < 0) {
5698 ids.add(sessionId, true);
5699 }
5700 }
5701 return ids;
5702}
5703
5704AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5705{
5706 Mutex::Autolock _l(mLock);
5707 AudioStreamIn *input = mInput;
5708 mInput = NULL;
5709 return input;
5710}
5711
5712// this method must always be called either with ThreadBase mLock held or inside the thread loop
5713audio_stream_t* AudioFlinger::RecordThread::stream() const
5714{
5715 if (mInput == NULL) {
5716 return NULL;
5717 }
5718 return &mInput->stream->common;
5719}
5720
5721status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5722{
5723 // only one chain per input thread
5724 if (mEffectChains.size() != 0) {
5725 return INVALID_OPERATION;
5726 }
5727 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5728
5729 chain->setInBuffer(NULL);
5730 chain->setOutBuffer(NULL);
5731
5732 checkSuspendOnAddEffectChain_l(chain);
5733
5734 mEffectChains.add(chain);
5735
5736 return NO_ERROR;
5737}
5738
5739size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5740{
5741 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5742 ALOGW_IF(mEffectChains.size() != 1,
5743 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5744 chain.get(), mEffectChains.size(), this);
5745 if (mEffectChains.size() == 1) {
5746 mEffectChains.removeAt(0);
5747 }
5748 return 0;
5749}
5750
5751}; // namespace android