blob: 2d4e025ba05169ffa859374f8cfa8b741a73e4c9 [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>
Eric Laurent81784c32012-11-19 14:55:58 -080038
39// NBAIO implementations
40#include <media/nbaio/AudioStreamOutSink.h>
41#include <media/nbaio/MonoPipe.h>
42#include <media/nbaio/MonoPipeReader.h>
43#include <media/nbaio/Pipe.h>
44#include <media/nbaio/PipeReader.h>
45#include <media/nbaio/SourceAudioBufferProvider.h>
46
47#include <powermanager/PowerManager.h>
48
49#include <common_time/cc_helper.h>
50#include <common_time/local_clock.h>
51
52#include "AudioFlinger.h"
53#include "AudioMixer.h"
54#include "FastMixer.h"
55#include "ServiceUtilities.h"
56#include "SchedulingPolicyService.h"
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62
Eric Laurent81784c32012-11-19 14:55:58 -080063#ifdef DEBUG_CPU_USAGE
64#include <cpustats/CentralTendencyStatistics.h>
65#include <cpustats/ThreadCpuUsage.h>
66#endif
67
68// ----------------------------------------------------------------------------
69
70// Note: the following macro is used for extremely verbose logging message. In
71// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72// 0; but one side effect of this is to turn all LOGV's as well. Some messages
73// are so verbose that we want to suppress them even when we have ALOG_ASSERT
74// turned on. Do not uncomment the #def below unless you really know what you
75// are doing and want to see all of the extremely verbose messages.
76//#define VERY_VERY_VERBOSE_LOGGING
77#ifdef VERY_VERY_VERBOSE_LOGGING
78#define ALOGVV ALOGV
79#else
80#define ALOGVV(a...) do { } while(0)
81#endif
82
83namespace android {
84
85// retry counts for buffer fill timeout
86// 50 * ~20msecs = 1 second
87static const int8_t kMaxTrackRetries = 50;
88static const int8_t kMaxTrackStartupRetries = 50;
89// allow less retry attempts on direct output thread.
90// direct outputs can be a scarce resource in audio hardware and should
91// be released as quickly as possible.
92static const int8_t kMaxTrackRetriesDirect = 2;
93
94// don't warn about blocked writes or record buffer overflows more often than this
95static const nsecs_t kWarningThrottleNs = seconds(5);
96
97// RecordThread loop sleep time upon application overrun or audio HAL read error
98static const int kRecordThreadSleepUs = 5000;
99
Eric Laurent10351942014-05-08 18:49:52 -0700100// maximum time to wait in sendConfigEvent_l() for a status to be received
101static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800102
103// minimum sleep time for the mixer thread loop when tracks are active but in underrun
104static const uint32_t kMinThreadSleepTimeUs = 5000;
105// maximum divider applied to the active sleep time in the mixer thread loop
106static const uint32_t kMaxThreadSleepTimeShift = 2;
107
Andy Hung09a50072014-02-27 14:30:47 -0800108// minimum normal sink buffer size, expressed in milliseconds rather than frames
109static const uint32_t kMinNormalSinkBufferSizeMs = 20;
110// maximum normal sink buffer size
111static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800112
Eric Laurent972a1732013-09-04 09:42:59 -0700113// Offloaded output thread standby delay: allows track transition without going to standby
114static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
115
Eric Laurent81784c32012-11-19 14:55:58 -0800116// Whether to use fast mixer
117static const enum {
118 FastMixer_Never, // never initialize or use: for debugging only
119 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
120 // normal mixer multiplier is 1
121 FastMixer_Static, // initialize if needed, then use all the time if initialized,
122 // multiplier is calculated based on min & max normal mixer buffer size
123 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
124 // multiplier is calculated based on min & max normal mixer buffer size
125 // FIXME for FastMixer_Dynamic:
126 // Supporting this option will require fixing HALs that can't handle large writes.
127 // For example, one HAL implementation returns an error from a large write,
128 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
129 // We could either fix the HAL implementations, or provide a wrapper that breaks
130 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
131} kUseFastMixer = FastMixer_Static;
132
133// Priorities for requestPriority
134static const int kPriorityAudioApp = 2;
135static const int kPriorityFastMixer = 3;
136
137// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
138// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800139// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
140// So for now we just assume that client is double-buffered for fast tracks.
141// FIXME It would be better for client to tell AudioFlinger the value of N,
142// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800143// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800144static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800145
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700146// See Thread::readOnlyHeap().
147// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
148// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
149// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
150static const size_t kRecordThreadReadOnlyHeapSize = 0x1000;
151
Eric Laurent81784c32012-11-19 14:55:58 -0800152// ----------------------------------------------------------------------------
153
154#ifdef ADD_BATTERY_DATA
155// To collect the amplifier usage
156static void addBatteryData(uint32_t params) {
157 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
158 if (service == NULL) {
159 // it already logged
160 return;
161 }
162
163 service->addBatteryData(params);
164}
165#endif
166
167
168// ----------------------------------------------------------------------------
169// CPU Stats
170// ----------------------------------------------------------------------------
171
172class CpuStats {
173public:
174 CpuStats();
175 void sample(const String8 &title);
176#ifdef DEBUG_CPU_USAGE
177private:
178 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
179 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
180
181 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
182
183 int mCpuNum; // thread's current CPU number
184 int mCpukHz; // frequency of thread's current CPU in kHz
185#endif
186};
187
188CpuStats::CpuStats()
189#ifdef DEBUG_CPU_USAGE
190 : mCpuNum(-1), mCpukHz(-1)
191#endif
192{
193}
194
Glenn Kasten0f11b512014-01-31 16:18:54 -0800195void CpuStats::sample(const String8 &title
196#ifndef DEBUG_CPU_USAGE
197 __unused
198#endif
199 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800200#ifdef DEBUG_CPU_USAGE
201 // get current thread's delta CPU time in wall clock ns
202 double wcNs;
203 bool valid = mCpuUsage.sampleAndEnable(wcNs);
204
205 // record sample for wall clock statistics
206 if (valid) {
207 mWcStats.sample(wcNs);
208 }
209
210 // get the current CPU number
211 int cpuNum = sched_getcpu();
212
213 // get the current CPU frequency in kHz
214 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
215
216 // check if either CPU number or frequency changed
217 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
218 mCpuNum = cpuNum;
219 mCpukHz = cpukHz;
220 // ignore sample for purposes of cycles
221 valid = false;
222 }
223
224 // if no change in CPU number or frequency, then record sample for cycle statistics
225 if (valid && mCpukHz > 0) {
226 double cycles = wcNs * cpukHz * 0.000001;
227 mHzStats.sample(cycles);
228 }
229
230 unsigned n = mWcStats.n();
231 // mCpuUsage.elapsed() is expensive, so don't call it every loop
232 if ((n & 127) == 1) {
233 long long elapsed = mCpuUsage.elapsed();
234 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
235 double perLoop = elapsed / (double) n;
236 double perLoop100 = perLoop * 0.01;
237 double perLoop1k = perLoop * 0.001;
238 double mean = mWcStats.mean();
239 double stddev = mWcStats.stddev();
240 double minimum = mWcStats.minimum();
241 double maximum = mWcStats.maximum();
242 double meanCycles = mHzStats.mean();
243 double stddevCycles = mHzStats.stddev();
244 double minCycles = mHzStats.minimum();
245 double maxCycles = mHzStats.maximum();
246 mCpuUsage.resetElapsed();
247 mWcStats.reset();
248 mHzStats.reset();
249 ALOGD("CPU usage for %s over past %.1f secs\n"
250 " (%u mixer loops at %.1f mean ms per loop):\n"
251 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
252 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
253 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
254 title.string(),
255 elapsed * .000000001, n, perLoop * .000001,
256 mean * .001,
257 stddev * .001,
258 minimum * .001,
259 maximum * .001,
260 mean / perLoop100,
261 stddev / perLoop100,
262 minimum / perLoop100,
263 maximum / perLoop100,
264 meanCycles / perLoop1k,
265 stddevCycles / perLoop1k,
266 minCycles / perLoop1k,
267 maxCycles / perLoop1k);
268
269 }
270 }
271#endif
272};
273
274// ----------------------------------------------------------------------------
275// ThreadBase
276// ----------------------------------------------------------------------------
277
278AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
279 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
280 : Thread(false /*canCallJava*/),
281 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700282 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700283 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800284 // are set by PlaybackThread::readOutputParameters_l() or
285 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700286 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800287 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
288 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
289 // mName will be set by concrete (non-virtual) subclass
290 mDeathRecipient(new PMDeathRecipient(this))
291{
292}
293
294AudioFlinger::ThreadBase::~ThreadBase()
295{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700296 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700297 mConfigEvents.clear();
298
Eric Laurent81784c32012-11-19 14:55:58 -0800299 // do not lock the mutex in destructor
300 releaseWakeLock_l();
301 if (mPowerManager != 0) {
302 sp<IBinder> binder = mPowerManager->asBinder();
303 binder->unlinkToDeath(mDeathRecipient);
304 }
305}
306
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700307status_t AudioFlinger::ThreadBase::readyToRun()
308{
309 status_t status = initCheck();
310 if (status == NO_ERROR) {
311 ALOGI("AudioFlinger's thread %p ready to run", this);
312 } else {
313 ALOGE("No working audio driver found.");
314 }
315 return status;
316}
317
Eric Laurent81784c32012-11-19 14:55:58 -0800318void AudioFlinger::ThreadBase::exit()
319{
320 ALOGV("ThreadBase::exit");
321 // do any cleanup required for exit to succeed
322 preExit();
323 {
324 // This lock prevents the following race in thread (uniprocessor for illustration):
325 // if (!exitPending()) {
326 // // context switch from here to exit()
327 // // exit() calls requestExit(), what exitPending() observes
328 // // exit() calls signal(), which is dropped since no waiters
329 // // context switch back from exit() to here
330 // mWaitWorkCV.wait(...);
331 // // now thread is hung
332 // }
333 AutoMutex lock(mLock);
334 requestExit();
335 mWaitWorkCV.broadcast();
336 }
337 // When Thread::requestExitAndWait is made virtual and this method is renamed to
338 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
339 requestExitAndWait();
340}
341
342status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
343{
344 status_t status;
345
346 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
347 Mutex::Autolock _l(mLock);
348
Eric Laurent10351942014-05-08 18:49:52 -0700349 return sendSetParameterConfigEvent_l(keyValuePairs);
350}
351
352// sendConfigEvent_l() must be called with ThreadBase::mLock held
353// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
354status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
355{
356 status_t status = NO_ERROR;
357
358 mConfigEvents.add(event);
359 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800360 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700361 mLock.unlock();
362 {
363 Mutex::Autolock _l(event->mLock);
364 while (event->mWaitStatus) {
365 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
366 event->mStatus = TIMED_OUT;
367 event->mWaitStatus = false;
368 }
369 }
370 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800371 }
Eric Laurent10351942014-05-08 18:49:52 -0700372 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800373 return status;
374}
375
376void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
377{
378 Mutex::Autolock _l(mLock);
379 sendIoConfigEvent_l(event, param);
380}
381
382// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
383void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
384{
Eric Laurent10351942014-05-08 18:49:52 -0700385 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
386 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800387}
388
389// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
390void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
391{
Eric Laurent10351942014-05-08 18:49:52 -0700392 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
393 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800394}
395
Eric Laurent10351942014-05-08 18:49:52 -0700396// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
397status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800398{
Eric Laurent10351942014-05-08 18:49:52 -0700399 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
400 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700401}
402
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700403// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700404void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700405{
Eric Laurent10351942014-05-08 18:49:52 -0700406 bool configChanged = false;
407
Eric Laurent81784c32012-11-19 14:55:58 -0800408 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700409 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
410 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800411 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700412 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700413 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700414 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
415 // FIXME Need to understand why this has to be done asynchronously
416 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700417 true /*asynchronous*/);
418 if (err != 0) {
419 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700420 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700421 }
422 } break;
423 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700424 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700425 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700426 } break;
427 case CFG_EVENT_SET_PARAMETER: {
428 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
429 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
430 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700431 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700432 } break;
433 default:
Eric Laurent10351942014-05-08 18:49:52 -0700434 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700435 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800436 }
Eric Laurent10351942014-05-08 18:49:52 -0700437 {
438 Mutex::Autolock _l(event->mLock);
439 if (event->mWaitStatus) {
440 event->mWaitStatus = false;
441 event->mCond.signal();
442 }
443 }
444 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
445 }
446
447 if (configChanged) {
448 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800449 }
Eric Laurent81784c32012-11-19 14:55:58 -0800450}
451
Marco Nelissenb2208842014-02-07 14:00:50 -0800452String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
453 String8 s;
454 if (output) {
455 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
456 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
457 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
458 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
459 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
460 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
461 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
462 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
463 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
464 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
465 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
466 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
467 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
468 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
469 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
470 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
471 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
472 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
473 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
474 } else {
475 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
476 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
477 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
478 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
479 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
480 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
481 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
482 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
483 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
484 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
485 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
486 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
487 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
488 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
489 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
490 }
491 int len = s.length();
492 if (s.length() > 2) {
493 char *str = s.lockBuffer(len);
494 s.unlockBuffer(len - 2);
495 }
496 return s;
497}
498
Glenn Kasten0f11b512014-01-31 16:18:54 -0800499void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800500{
501 const size_t SIZE = 256;
502 char buffer[SIZE];
503 String8 result;
504
505 bool locked = AudioFlinger::dumpTryLock(mLock);
506 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800507 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800508 }
509
Marco Nelissenb2208842014-02-07 14:00:50 -0800510 fdprintf(fd, " I/O handle: %d\n", mId);
511 fdprintf(fd, " TID: %d\n", getTid());
512 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
513 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000514 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800515 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
516 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
517 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
518 channelMaskToString(mChannelMask, mType != RECORD).string());
519 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000520 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800521 fdprintf(fd, " Pending config events:");
522 size_t numConfig = mConfigEvents.size();
523 if (numConfig) {
524 for (size_t i = 0; i < numConfig; i++) {
525 mConfigEvents[i]->dump(buffer, SIZE);
526 fdprintf(fd, "\n %s", buffer);
527 }
528 fdprintf(fd, "\n");
529 } else {
530 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800531 }
Eric Laurent81784c32012-11-19 14:55:58 -0800532
533 if (locked) {
534 mLock.unlock();
535 }
536}
537
538void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
539{
540 const size_t SIZE = 256;
541 char buffer[SIZE];
542 String8 result;
543
Marco Nelissenb2208842014-02-07 14:00:50 -0800544 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000545 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800546 write(fd, buffer, strlen(buffer));
547
Marco Nelissenb2208842014-02-07 14:00:50 -0800548 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800549 sp<EffectChain> chain = mEffectChains[i];
550 if (chain != 0) {
551 chain->dump(fd, args);
552 }
553 }
554}
555
Marco Nelissene14a5d62013-10-03 08:51:24 -0700556void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800557{
558 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700559 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800560}
561
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100562String16 AudioFlinger::ThreadBase::getWakeLockTag()
563{
564 switch (mType) {
565 case MIXER:
566 return String16("AudioMix");
567 case DIRECT:
568 return String16("AudioDirectOut");
569 case DUPLICATING:
570 return String16("AudioDup");
571 case RECORD:
572 return String16("AudioIn");
573 case OFFLOAD:
574 return String16("AudioOffload");
575 default:
576 ALOG_ASSERT(false);
577 return String16("AudioUnknown");
578 }
579}
580
Marco Nelissene14a5d62013-10-03 08:51:24 -0700581void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800582{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800583 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800584 if (mPowerManager != 0) {
585 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700586 status_t status;
587 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700588 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700589 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100590 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700591 String16("media"),
592 uid);
593 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700594 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700595 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100596 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700597 String16("media"));
598 }
Eric Laurent81784c32012-11-19 14:55:58 -0800599 if (status == NO_ERROR) {
600 mWakeLockToken = binder;
601 }
602 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
603 }
604}
605
606void AudioFlinger::ThreadBase::releaseWakeLock()
607{
608 Mutex::Autolock _l(mLock);
609 releaseWakeLock_l();
610}
611
612void AudioFlinger::ThreadBase::releaseWakeLock_l()
613{
614 if (mWakeLockToken != 0) {
615 ALOGV("releaseWakeLock_l() %s", mName);
616 if (mPowerManager != 0) {
617 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
618 }
619 mWakeLockToken.clear();
620 }
621}
622
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800623void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
624 Mutex::Autolock _l(mLock);
625 updateWakeLockUids_l(uids);
626}
627
628void AudioFlinger::ThreadBase::getPowerManager_l() {
629
630 if (mPowerManager == 0) {
631 // use checkService() to avoid blocking if power service is not up yet
632 sp<IBinder> binder =
633 defaultServiceManager()->checkService(String16("power"));
634 if (binder == 0) {
635 ALOGW("Thread %s cannot connect to the power manager service", mName);
636 } else {
637 mPowerManager = interface_cast<IPowerManager>(binder);
638 binder->linkToDeath(mDeathRecipient);
639 }
640 }
641}
642
643void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
644
645 getPowerManager_l();
646 if (mWakeLockToken == NULL) {
647 ALOGE("no wake lock to update!");
648 return;
649 }
650 if (mPowerManager != 0) {
651 sp<IBinder> binder = new BBinder();
652 status_t status;
653 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
654 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
655 }
656}
657
Eric Laurent81784c32012-11-19 14:55:58 -0800658void AudioFlinger::ThreadBase::clearPowerManager()
659{
660 Mutex::Autolock _l(mLock);
661 releaseWakeLock_l();
662 mPowerManager.clear();
663}
664
Glenn Kasten0f11b512014-01-31 16:18:54 -0800665void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800666{
667 sp<ThreadBase> thread = mThread.promote();
668 if (thread != 0) {
669 thread->clearPowerManager();
670 }
671 ALOGW("power manager service died !!!");
672}
673
674void AudioFlinger::ThreadBase::setEffectSuspended(
675 const effect_uuid_t *type, bool suspend, int sessionId)
676{
677 Mutex::Autolock _l(mLock);
678 setEffectSuspended_l(type, suspend, sessionId);
679}
680
681void AudioFlinger::ThreadBase::setEffectSuspended_l(
682 const effect_uuid_t *type, bool suspend, int sessionId)
683{
684 sp<EffectChain> chain = getEffectChain_l(sessionId);
685 if (chain != 0) {
686 if (type != NULL) {
687 chain->setEffectSuspended_l(type, suspend);
688 } else {
689 chain->setEffectSuspendedAll_l(suspend);
690 }
691 }
692
693 updateSuspendedSessions_l(type, suspend, sessionId);
694}
695
696void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
697{
698 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
699 if (index < 0) {
700 return;
701 }
702
703 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
704 mSuspendedSessions.valueAt(index);
705
706 for (size_t i = 0; i < sessionEffects.size(); i++) {
707 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
708 for (int j = 0; j < desc->mRefCount; j++) {
709 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
710 chain->setEffectSuspendedAll_l(true);
711 } else {
712 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
713 desc->mType.timeLow);
714 chain->setEffectSuspended_l(&desc->mType, true);
715 }
716 }
717 }
718}
719
720void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
721 bool suspend,
722 int sessionId)
723{
724 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
725
726 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
727
728 if (suspend) {
729 if (index >= 0) {
730 sessionEffects = mSuspendedSessions.valueAt(index);
731 } else {
732 mSuspendedSessions.add(sessionId, sessionEffects);
733 }
734 } else {
735 if (index < 0) {
736 return;
737 }
738 sessionEffects = mSuspendedSessions.valueAt(index);
739 }
740
741
742 int key = EffectChain::kKeyForSuspendAll;
743 if (type != NULL) {
744 key = type->timeLow;
745 }
746 index = sessionEffects.indexOfKey(key);
747
748 sp<SuspendedSessionDesc> desc;
749 if (suspend) {
750 if (index >= 0) {
751 desc = sessionEffects.valueAt(index);
752 } else {
753 desc = new SuspendedSessionDesc();
754 if (type != NULL) {
755 desc->mType = *type;
756 }
757 sessionEffects.add(key, desc);
758 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
759 }
760 desc->mRefCount++;
761 } else {
762 if (index < 0) {
763 return;
764 }
765 desc = sessionEffects.valueAt(index);
766 if (--desc->mRefCount == 0) {
767 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
768 sessionEffects.removeItemsAt(index);
769 if (sessionEffects.isEmpty()) {
770 ALOGV("updateSuspendedSessions_l() restore removing session %d",
771 sessionId);
772 mSuspendedSessions.removeItem(sessionId);
773 }
774 }
775 }
776 if (!sessionEffects.isEmpty()) {
777 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
778 }
779}
780
781void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
782 bool enabled,
783 int sessionId)
784{
785 Mutex::Autolock _l(mLock);
786 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
787}
788
789void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
790 bool enabled,
791 int sessionId)
792{
793 if (mType != RECORD) {
794 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
795 // another session. This gives the priority to well behaved effect control panels
796 // and applications not using global effects.
797 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
798 // global effects
799 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
800 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
801 }
802 }
803
804 sp<EffectChain> chain = getEffectChain_l(sessionId);
805 if (chain != 0) {
806 chain->checkSuspendOnEffectEnabled(effect, enabled);
807 }
808}
809
810// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
811sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
812 const sp<AudioFlinger::Client>& client,
813 const sp<IEffectClient>& effectClient,
814 int32_t priority,
815 int sessionId,
816 effect_descriptor_t *desc,
817 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700818 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800819{
820 sp<EffectModule> effect;
821 sp<EffectHandle> handle;
822 status_t lStatus;
823 sp<EffectChain> chain;
824 bool chainCreated = false;
825 bool effectCreated = false;
826 bool effectRegistered = false;
827
828 lStatus = initCheck();
829 if (lStatus != NO_ERROR) {
830 ALOGW("createEffect_l() Audio driver not initialized.");
831 goto Exit;
832 }
833
Andy Hung98ef9782014-03-04 14:46:50 -0800834 // Reject any effect on Direct output threads for now, since the format of
835 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
836 if (mType == DIRECT) {
837 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
838 desc->name, mName);
839 lStatus = BAD_VALUE;
840 goto Exit;
841 }
842
Eric Laurent5baf2af2013-09-12 17:37:00 -0700843 // Allow global effects only on offloaded and mixer threads
844 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
845 switch (mType) {
846 case MIXER:
847 case OFFLOAD:
848 break;
849 case DIRECT:
850 case DUPLICATING:
851 case RECORD:
852 default:
853 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
854 lStatus = BAD_VALUE;
855 goto Exit;
856 }
Eric Laurent81784c32012-11-19 14:55:58 -0800857 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700858
Eric Laurent81784c32012-11-19 14:55:58 -0800859 // Only Pre processor effects are allowed on input threads and only on input threads
860 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
861 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
862 desc->name, desc->flags, mType);
863 lStatus = BAD_VALUE;
864 goto Exit;
865 }
866
867 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
868
869 { // scope for mLock
870 Mutex::Autolock _l(mLock);
871
872 // check for existing effect chain with the requested audio session
873 chain = getEffectChain_l(sessionId);
874 if (chain == 0) {
875 // create a new chain for this session
876 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
877 chain = new EffectChain(this, sessionId);
878 addEffectChain_l(chain);
879 chain->setStrategy(getStrategyForSession_l(sessionId));
880 chainCreated = true;
881 } else {
882 effect = chain->getEffectFromDesc_l(desc);
883 }
884
885 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
886
887 if (effect == 0) {
888 int id = mAudioFlinger->nextUniqueId();
889 // Check CPU and memory usage
890 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
891 if (lStatus != NO_ERROR) {
892 goto Exit;
893 }
894 effectRegistered = true;
895 // create a new effect module if none present in the chain
896 effect = new EffectModule(this, chain, desc, id, sessionId);
897 lStatus = effect->status();
898 if (lStatus != NO_ERROR) {
899 goto Exit;
900 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700901 effect->setOffloaded(mType == OFFLOAD, mId);
902
Eric Laurent81784c32012-11-19 14:55:58 -0800903 lStatus = chain->addEffect_l(effect);
904 if (lStatus != NO_ERROR) {
905 goto Exit;
906 }
907 effectCreated = true;
908
909 effect->setDevice(mOutDevice);
910 effect->setDevice(mInDevice);
911 effect->setMode(mAudioFlinger->getMode());
912 effect->setAudioSource(mAudioSource);
913 }
914 // create effect handle and connect it to effect module
915 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800916 lStatus = handle->initCheck();
917 if (lStatus == OK) {
918 lStatus = effect->addHandle(handle.get());
919 }
Eric Laurent81784c32012-11-19 14:55:58 -0800920 if (enabled != NULL) {
921 *enabled = (int)effect->isEnabled();
922 }
923 }
924
925Exit:
926 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
927 Mutex::Autolock _l(mLock);
928 if (effectCreated) {
929 chain->removeEffect_l(effect);
930 }
931 if (effectRegistered) {
932 AudioSystem::unregisterEffect(effect->id());
933 }
934 if (chainCreated) {
935 removeEffectChain_l(chain);
936 }
937 handle.clear();
938 }
939
Glenn Kasten9156ef32013-08-06 15:39:08 -0700940 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800941 return handle;
942}
943
944sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
945{
946 Mutex::Autolock _l(mLock);
947 return getEffect_l(sessionId, effectId);
948}
949
950sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
951{
952 sp<EffectChain> chain = getEffectChain_l(sessionId);
953 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
954}
955
956// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
957// PlaybackThread::mLock held
958status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
959{
960 // check for existing effect chain with the requested audio session
961 int sessionId = effect->sessionId();
962 sp<EffectChain> chain = getEffectChain_l(sessionId);
963 bool chainCreated = false;
964
Eric Laurent5baf2af2013-09-12 17:37:00 -0700965 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
966 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
967 this, effect->desc().name, effect->desc().flags);
968
Eric Laurent81784c32012-11-19 14:55:58 -0800969 if (chain == 0) {
970 // create a new chain for this session
971 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
972 chain = new EffectChain(this, sessionId);
973 addEffectChain_l(chain);
974 chain->setStrategy(getStrategyForSession_l(sessionId));
975 chainCreated = true;
976 }
977 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
978
979 if (chain->getEffectFromId_l(effect->id()) != 0) {
980 ALOGW("addEffect_l() %p effect %s already present in chain %p",
981 this, effect->desc().name, chain.get());
982 return BAD_VALUE;
983 }
984
Eric Laurent5baf2af2013-09-12 17:37:00 -0700985 effect->setOffloaded(mType == OFFLOAD, mId);
986
Eric Laurent81784c32012-11-19 14:55:58 -0800987 status_t status = chain->addEffect_l(effect);
988 if (status != NO_ERROR) {
989 if (chainCreated) {
990 removeEffectChain_l(chain);
991 }
992 return status;
993 }
994
995 effect->setDevice(mOutDevice);
996 effect->setDevice(mInDevice);
997 effect->setMode(mAudioFlinger->getMode());
998 effect->setAudioSource(mAudioSource);
999 return NO_ERROR;
1000}
1001
1002void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1003
1004 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1005 effect_descriptor_t desc = effect->desc();
1006 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1007 detachAuxEffect_l(effect->id());
1008 }
1009
1010 sp<EffectChain> chain = effect->chain().promote();
1011 if (chain != 0) {
1012 // remove effect chain if removing last effect
1013 if (chain->removeEffect_l(effect) == 0) {
1014 removeEffectChain_l(chain);
1015 }
1016 } else {
1017 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1018 }
1019}
1020
1021void AudioFlinger::ThreadBase::lockEffectChains_l(
1022 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1023{
1024 effectChains = mEffectChains;
1025 for (size_t i = 0; i < mEffectChains.size(); i++) {
1026 mEffectChains[i]->lock();
1027 }
1028}
1029
1030void AudioFlinger::ThreadBase::unlockEffectChains(
1031 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1032{
1033 for (size_t i = 0; i < effectChains.size(); i++) {
1034 effectChains[i]->unlock();
1035 }
1036}
1037
1038sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1039{
1040 Mutex::Autolock _l(mLock);
1041 return getEffectChain_l(sessionId);
1042}
1043
1044sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1045{
1046 size_t size = mEffectChains.size();
1047 for (size_t i = 0; i < size; i++) {
1048 if (mEffectChains[i]->sessionId() == sessionId) {
1049 return mEffectChains[i];
1050 }
1051 }
1052 return 0;
1053}
1054
1055void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1056{
1057 Mutex::Autolock _l(mLock);
1058 size_t size = mEffectChains.size();
1059 for (size_t i = 0; i < size; i++) {
1060 mEffectChains[i]->setMode_l(mode);
1061 }
1062}
1063
1064void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1065 EffectHandle *handle,
1066 bool unpinIfLast) {
1067
1068 Mutex::Autolock _l(mLock);
1069 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1070 // delete the effect module if removing last handle on it
1071 if (effect->removeHandle(handle) == 0) {
1072 if (!effect->isPinned() || unpinIfLast) {
1073 removeEffect_l(effect);
1074 AudioSystem::unregisterEffect(effect->id());
1075 }
1076 }
1077}
1078
1079// ----------------------------------------------------------------------------
1080// Playback
1081// ----------------------------------------------------------------------------
1082
1083AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1084 AudioStreamOut* output,
1085 audio_io_handle_t id,
1086 audio_devices_t device,
1087 type_t type)
1088 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001089 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001090 mMixerBufferEnabled(false),
1091 mMixerBuffer(NULL),
1092 mMixerBufferSize(0),
1093 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1094 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001095 mEffectBufferEnabled(false),
1096 mEffectBuffer(NULL),
1097 mEffectBufferSize(0),
1098 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1099 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001100 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001101 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001102 // mStreamTypes[] initialized in constructor body
1103 mOutput(output),
1104 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1105 mMixerStatus(MIXER_IDLE),
1106 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1107 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001108 mBytesRemaining(0),
1109 mCurrentWriteLength(0),
1110 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001111 mWriteAckSequence(0),
1112 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001113 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001114 mScreenState(AudioFlinger::mScreenState),
1115 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001116 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1117 // mLatchD, mLatchQ,
1118 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001119{
1120 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001121 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001122
1123 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1124 // it would be safer to explicitly pass initial masterVolume/masterMute as
1125 // parameter.
1126 //
1127 // If the HAL we are using has support for master volume or master mute,
1128 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1129 // and the mute set to false).
1130 mMasterVolume = audioFlinger->masterVolume_l();
1131 mMasterMute = audioFlinger->masterMute_l();
1132 if (mOutput && mOutput->audioHwDev) {
1133 if (mOutput->audioHwDev->canSetMasterVolume()) {
1134 mMasterVolume = 1.0;
1135 }
1136
1137 if (mOutput->audioHwDev->canSetMasterMute()) {
1138 mMasterMute = false;
1139 }
1140 }
1141
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001142 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001143
1144 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1145 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001146 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001147 stream = (audio_stream_type_t) (stream + 1)) {
1148 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1149 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1150 }
1151 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1152 // because mAudioFlinger doesn't have one to copy from
1153}
1154
1155AudioFlinger::PlaybackThread::~PlaybackThread()
1156{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001157 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001158 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001159 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001160 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001161}
1162
1163void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1164{
1165 dumpInternals(fd, args);
1166 dumpTracks(fd, args);
1167 dumpEffectChains(fd, args);
1168}
1169
Glenn Kasten0f11b512014-01-31 16:18:54 -08001170void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001171{
1172 const size_t SIZE = 256;
1173 char buffer[SIZE];
1174 String8 result;
1175
Marco Nelissenb2208842014-02-07 14:00:50 -08001176 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001177 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1178 const stream_type_t *st = &mStreamTypes[i];
1179 if (i > 0) {
1180 result.appendFormat(", ");
1181 }
1182 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1183 if (st->mute) {
1184 result.append("M");
1185 }
1186 }
1187 result.append("\n");
1188 write(fd, result.string(), result.length());
1189 result.clear();
1190
Eric Laurent81784c32012-11-19 14:55:58 -08001191 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1192 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001193 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001194 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001195
1196 size_t numtracks = mTracks.size();
1197 size_t numactive = mActiveTracks.size();
1198 fdprintf(fd, " %d Tracks", numtracks);
1199 size_t numactiveseen = 0;
1200 if (numtracks) {
1201 fdprintf(fd, " of which %d are active\n", numactive);
1202 Track::appendDumpHeader(result);
1203 for (size_t i = 0; i < numtracks; ++i) {
1204 sp<Track> track = mTracks[i];
1205 if (track != 0) {
1206 bool active = mActiveTracks.indexOf(track) >= 0;
1207 if (active) {
1208 numactiveseen++;
1209 }
1210 track->dump(buffer, SIZE, active);
1211 result.append(buffer);
1212 }
1213 }
1214 } else {
1215 result.append("\n");
1216 }
1217 if (numactiveseen != numactive) {
1218 // some tracks in the active list were not in the tracks list
1219 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1220 " not in the track list\n");
1221 result.append(buffer);
1222 Track::appendDumpHeader(result);
1223 for (size_t i = 0; i < numactive; ++i) {
1224 sp<Track> track = mActiveTracks[i].promote();
1225 if (track != 0 && mTracks.indexOf(track) < 0) {
1226 track->dump(buffer, SIZE, true);
1227 result.append(buffer);
1228 }
1229 }
1230 }
1231
1232 write(fd, result.string(), result.size());
1233
Eric Laurent81784c32012-11-19 14:55:58 -08001234}
1235
1236void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1237{
Marco Nelissenb2208842014-02-07 14:00:50 -08001238 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001239 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001240 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1241 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1242 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1243 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1244 fdprintf(fd, " Suspend count: %d\n", mSuspended);
Andy Hung2098f272014-02-27 14:00:06 -08001245 fdprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001246 fdprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001247 fdprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001248 fdprintf(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 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001733 mChannelCount = popcount(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;
2685 fastTrack->mGeneration++;
2686 state->mFastTracksGen++;
2687 state->mTrackMask = 1;
2688 // fast mixer will use the HAL output sink
2689 state->mOutputSink = mOutputSink.get();
2690 state->mOutputSinkGen++;
2691 state->mFrameCount = mFrameCount;
2692 state->mCommand = FastMixerState::COLD_IDLE;
2693 // already done in constructor initialization list
2694 //mFastMixerFutex = 0;
2695 state->mColdFutexAddr = &mFastMixerFutex;
2696 state->mColdGen++;
2697 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002698#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002699 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002700#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002701 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2702 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002703 sq->end();
2704 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2705
2706 // start the fast mixer
2707 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2708 pid_t tid = mFastMixer->getTid();
2709 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2710 if (err != 0) {
2711 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2712 kPriorityFastMixer, getpid_cached, tid, err);
2713 }
2714
2715#ifdef AUDIO_WATCHDOG
2716 // create and start the watchdog
2717 mAudioWatchdog = new AudioWatchdog();
2718 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2719 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2720 tid = mAudioWatchdog->getTid();
2721 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2722 if (err != 0) {
2723 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2724 kPriorityFastMixer, getpid_cached, tid, err);
2725 }
2726#endif
2727
2728 } else {
2729 mFastMixer = NULL;
2730 }
2731
2732 switch (kUseFastMixer) {
2733 case FastMixer_Never:
2734 case FastMixer_Dynamic:
2735 mNormalSink = mOutputSink;
2736 break;
2737 case FastMixer_Always:
2738 mNormalSink = mPipeSink;
2739 break;
2740 case FastMixer_Static:
2741 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2742 break;
2743 }
2744}
2745
2746AudioFlinger::MixerThread::~MixerThread()
2747{
2748 if (mFastMixer != NULL) {
2749 FastMixerStateQueue *sq = mFastMixer->sq();
2750 FastMixerState *state = sq->begin();
2751 if (state->mCommand == FastMixerState::COLD_IDLE) {
2752 int32_t old = android_atomic_inc(&mFastMixerFutex);
2753 if (old == -1) {
Glenn Kasten110135b2014-05-09 13:39:04 -07002754 (void) __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002755 }
2756 }
2757 state->mCommand = FastMixerState::EXIT;
2758 sq->end();
2759 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2760 mFastMixer->join();
2761 // Though the fast mixer thread has exited, it's state queue is still valid.
2762 // We'll use that extract the final state which contains one remaining fast track
2763 // corresponding to our sub-mix.
2764 state = sq->begin();
2765 ALOG_ASSERT(state->mTrackMask == 1);
2766 FastTrack *fastTrack = &state->mFastTracks[0];
2767 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2768 delete fastTrack->mBufferProvider;
2769 sq->end(false /*didModify*/);
2770 delete mFastMixer;
2771#ifdef AUDIO_WATCHDOG
2772 if (mAudioWatchdog != 0) {
2773 mAudioWatchdog->requestExit();
2774 mAudioWatchdog->requestExitAndWait();
2775 mAudioWatchdog.clear();
2776 }
2777#endif
2778 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002779 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002780 delete mAudioMixer;
2781}
2782
2783
2784uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2785{
2786 if (mFastMixer != NULL) {
2787 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2788 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2789 }
2790 return latency;
2791}
2792
2793
2794void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2795{
2796 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2797}
2798
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
2801 // FIXME we should only do one push per cycle; confirm this is true
2802 // Start the fast mixer if it's not already running
2803 if (mFastMixer != NULL) {
2804 FastMixerStateQueue *sq = mFastMixer->sq();
2805 FastMixerState *state = sq->begin();
2806 if (state->mCommand != FastMixerState::MIX_WRITE &&
2807 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2808 if (state->mCommand == FastMixerState::COLD_IDLE) {
2809 int32_t old = android_atomic_inc(&mFastMixerFutex);
2810 if (old == -1) {
Glenn Kasten110135b2014-05-09 13:39:04 -07002811 (void) __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
2813#ifdef AUDIO_WATCHDOG
2814 if (mAudioWatchdog != 0) {
2815 mAudioWatchdog->resume();
2816 }
2817#endif
2818 }
2819 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002820 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2821 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002822 sq->end();
2823 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2824 if (kUseFastMixer == FastMixer_Dynamic) {
2825 mNormalSink = mPipeSink;
2826 }
2827 } else {
2828 sq->end(false /*didModify*/);
2829 }
2830 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002831 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002832}
2833
2834void AudioFlinger::MixerThread::threadLoop_standby()
2835{
2836 // Idle the fast mixer if it's currently running
2837 if (mFastMixer != NULL) {
2838 FastMixerStateQueue *sq = mFastMixer->sq();
2839 FastMixerState *state = sq->begin();
2840 if (!(state->mCommand & FastMixerState::IDLE)) {
2841 state->mCommand = FastMixerState::COLD_IDLE;
2842 state->mColdFutexAddr = &mFastMixerFutex;
2843 state->mColdGen++;
2844 mFastMixerFutex = 0;
2845 sq->end();
2846 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2847 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2848 if (kUseFastMixer == FastMixer_Dynamic) {
2849 mNormalSink = mOutputSink;
2850 }
2851#ifdef AUDIO_WATCHDOG
2852 if (mAudioWatchdog != 0) {
2853 mAudioWatchdog->pause();
2854 }
2855#endif
2856 } else {
2857 sq->end(false /*didModify*/);
2858 }
2859 }
2860 PlaybackThread::threadLoop_standby();
2861}
2862
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2864{
2865 return false;
2866}
2867
2868bool AudioFlinger::PlaybackThread::shouldStandby_l()
2869{
2870 return !mStandby;
2871}
2872
2873bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2874{
2875 Mutex::Autolock _l(mLock);
2876 return waitingAsyncCallback_l();
2877}
2878
Eric Laurent81784c32012-11-19 14:55:58 -08002879// shared by MIXER and DIRECT, overridden by DUPLICATING
2880void AudioFlinger::PlaybackThread::threadLoop_standby()
2881{
2882 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2883 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002885 // discard any pending drain or write ack by incrementing sequence
2886 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2887 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002889 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2890 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 }
Eric Laurent81784c32012-11-19 14:55:58 -08002892}
2893
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002894void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2895{
2896 ALOGV("signal playback thread");
2897 broadcast_l();
2898}
2899
Eric Laurent81784c32012-11-19 14:55:58 -08002900void AudioFlinger::MixerThread::threadLoop_mix()
2901{
2902 // obtain the presentation timestamp of the next output buffer
2903 int64_t pts;
2904 status_t status = INVALID_OPERATION;
2905
2906 if (mNormalSink != 0) {
2907 status = mNormalSink->getNextWriteTimestamp(&pts);
2908 } else {
2909 status = mOutputSink->getNextWriteTimestamp(&pts);
2910 }
2911
2912 if (status != NO_ERROR) {
2913 pts = AudioBufferProvider::kInvalidPTS;
2914 }
2915
2916 // mix buffers...
2917 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002918 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002919 // increase sleep time progressively when application underrun condition clears.
2920 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2921 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2922 // such that we would underrun the audio HAL.
2923 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2924 sleepTimeShift--;
2925 }
2926 sleepTime = 0;
2927 standbyTime = systemTime() + standbyDelay;
2928 //TODO: delay standby when effects have a tail
2929}
2930
2931void AudioFlinger::MixerThread::threadLoop_sleepTime()
2932{
2933 // If no tracks are ready, sleep once for the duration of an output
2934 // buffer size, then write 0s to the output
2935 if (sleepTime == 0) {
2936 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2937 sleepTime = activeSleepTime >> sleepTimeShift;
2938 if (sleepTime < kMinThreadSleepTimeUs) {
2939 sleepTime = kMinThreadSleepTimeUs;
2940 }
2941 // reduce sleep time in case of consecutive application underruns to avoid
2942 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2943 // duration we would end up writing less data than needed by the audio HAL if
2944 // the condition persists.
2945 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2946 sleepTimeShift++;
2947 }
2948 } else {
2949 sleepTime = idleSleepTime;
2950 }
2951 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002952 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2953 // before effects processing or output.
2954 if (mMixerBufferValid) {
2955 memset(mMixerBuffer, 0, mMixerBufferSize);
2956 } else {
2957 memset(mSinkBuffer, 0, mSinkBufferSize);
2958 }
Eric Laurent81784c32012-11-19 14:55:58 -08002959 sleepTime = 0;
2960 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2961 "anticipated start");
2962 }
2963 // TODO add standby time extension fct of effect tail
2964}
2965
2966// prepareTracks_l() must be called with ThreadBase::mLock held
2967AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2968 Vector< sp<Track> > *tracksToRemove)
2969{
2970
2971 mixer_state mixerStatus = MIXER_IDLE;
2972 // find out which tracks need to be processed
2973 size_t count = mActiveTracks.size();
2974 size_t mixedTracks = 0;
2975 size_t tracksWithEffect = 0;
2976 // counts only _active_ fast tracks
2977 size_t fastTracks = 0;
2978 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2979
2980 float masterVolume = mMasterVolume;
2981 bool masterMute = mMasterMute;
2982
2983 if (masterMute) {
2984 masterVolume = 0;
2985 }
2986 // Delegate master volume control to effect in output mix effect chain if needed
2987 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2988 if (chain != 0) {
2989 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2990 chain->setVolume_l(&v, &v);
2991 masterVolume = (float)((v + (1 << 23)) >> 24);
2992 chain.clear();
2993 }
2994
2995 // prepare a new state to push
2996 FastMixerStateQueue *sq = NULL;
2997 FastMixerState *state = NULL;
2998 bool didModify = false;
2999 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3000 if (mFastMixer != NULL) {
3001 sq = mFastMixer->sq();
3002 state = sq->begin();
3003 }
3004
Andy Hung69aed5f2014-02-25 17:24:40 -08003005 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003006 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003007
Eric Laurent81784c32012-11-19 14:55:58 -08003008 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003009 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003010 if (t == 0) {
3011 continue;
3012 }
3013
3014 // this const just means the local variable doesn't change
3015 Track* const track = t.get();
3016
3017 // process fast tracks
3018 if (track->isFastTrack()) {
3019
3020 // It's theoretically possible (though unlikely) for a fast track to be created
3021 // and then removed within the same normal mix cycle. This is not a problem, as
3022 // the track never becomes active so it's fast mixer slot is never touched.
3023 // The converse, of removing an (active) track and then creating a new track
3024 // at the identical fast mixer slot within the same normal mix cycle,
3025 // is impossible because the slot isn't marked available until the end of each cycle.
3026 int j = track->mFastIndex;
3027 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3028 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3029 FastTrack *fastTrack = &state->mFastTracks[j];
3030
3031 // Determine whether the track is currently in underrun condition,
3032 // and whether it had a recent underrun.
3033 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3034 FastTrackUnderruns underruns = ftDump->mUnderruns;
3035 uint32_t recentFull = (underruns.mBitFields.mFull -
3036 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3037 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3038 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3039 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3040 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3041 uint32_t recentUnderruns = recentPartial + recentEmpty;
3042 track->mObservedUnderruns = underruns;
3043 // don't count underruns that occur while stopping or pausing
3044 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003045 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3046 recentUnderruns > 0) {
3047 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3048 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003049 }
3050
3051 // This is similar to the state machine for normal tracks,
3052 // with a few modifications for fast tracks.
3053 bool isActive = true;
3054 switch (track->mState) {
3055 case TrackBase::STOPPING_1:
3056 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003058 track->mState = TrackBase::STOPPING_2;
3059 }
3060 break;
3061 case TrackBase::PAUSING:
3062 // ramp down is not yet implemented
3063 track->setPaused();
3064 break;
3065 case TrackBase::RESUMING:
3066 // ramp up is not yet implemented
3067 track->mState = TrackBase::ACTIVE;
3068 break;
3069 case TrackBase::ACTIVE:
3070 if (recentFull > 0 || recentPartial > 0) {
3071 // track has provided at least some frames recently: reset retry count
3072 track->mRetryCount = kMaxTrackRetries;
3073 }
3074 if (recentUnderruns == 0) {
3075 // no recent underruns: stay active
3076 break;
3077 }
3078 // there has recently been an underrun of some kind
3079 if (track->sharedBuffer() == 0) {
3080 // were any of the recent underruns "empty" (no frames available)?
3081 if (recentEmpty == 0) {
3082 // no, then ignore the partial underruns as they are allowed indefinitely
3083 break;
3084 }
3085 // there has recently been an "empty" underrun: decrement the retry counter
3086 if (--(track->mRetryCount) > 0) {
3087 break;
3088 }
3089 // indicate to client process that the track was disabled because of underrun;
3090 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003091 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003092 // remove from active list, but state remains ACTIVE [confusing but true]
3093 isActive = false;
3094 break;
3095 }
3096 // fall through
3097 case TrackBase::STOPPING_2:
3098 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003099 case TrackBase::STOPPED:
3100 case TrackBase::FLUSHED: // flush() while active
3101 // Check for presentation complete if track is inactive
3102 // We have consumed all the buffers of this track.
3103 // This would be incomplete if we auto-paused on underrun
3104 {
3105 size_t audioHALFrames =
3106 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3107 size_t framesWritten = mBytesWritten / mFrameSize;
3108 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3109 // track stays in active list until presentation is complete
3110 break;
3111 }
3112 }
3113 if (track->isStopping_2()) {
3114 track->mState = TrackBase::STOPPED;
3115 }
3116 if (track->isStopped()) {
3117 // Can't reset directly, as fast mixer is still polling this track
3118 // track->reset();
3119 // So instead mark this track as needing to be reset after push with ack
3120 resetMask |= 1 << i;
3121 }
3122 isActive = false;
3123 break;
3124 case TrackBase::IDLE:
3125 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003126 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003127 }
3128
3129 if (isActive) {
3130 // was it previously inactive?
3131 if (!(state->mTrackMask & (1 << j))) {
3132 ExtendedAudioBufferProvider *eabp = track;
3133 VolumeProvider *vp = track;
3134 fastTrack->mBufferProvider = eabp;
3135 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003136 fastTrack->mChannelMask = track->mChannelMask;
3137 fastTrack->mGeneration++;
3138 state->mTrackMask |= 1 << j;
3139 didModify = true;
3140 // no acknowledgement required for newly active tracks
3141 }
3142 // cache the combined master volume and stream type volume for fast mixer; this
3143 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003144 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003145 ++fastTracks;
3146 } else {
3147 // was it previously active?
3148 if (state->mTrackMask & (1 << j)) {
3149 fastTrack->mBufferProvider = NULL;
3150 fastTrack->mGeneration++;
3151 state->mTrackMask &= ~(1 << j);
3152 didModify = true;
3153 // If any fast tracks were removed, we must wait for acknowledgement
3154 // because we're about to decrement the last sp<> on those tracks.
3155 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3156 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003157 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003158 }
3159 tracksToRemove->add(track);
3160 // Avoids a misleading display in dumpsys
3161 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3162 }
3163 continue;
3164 }
3165
3166 { // local variable scope to avoid goto warning
3167
3168 audio_track_cblk_t* cblk = track->cblk();
3169
3170 // The first time a track is added we wait
3171 // for all its buffers to be filled before processing it
3172 int name = track->name();
3173 // make sure that we have enough frames to mix one full buffer.
3174 // enforce this condition only once to enable draining the buffer in case the client
3175 // app does not call stop() and relies on underrun to stop:
3176 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3177 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003178 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003179 uint32_t sr = track->sampleRate();
3180 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003181 desiredFrames = mNormalFrameCount;
3182 } else {
3183 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003184 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003185 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003186 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003187 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003188#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003189 // the minimum track buffer size is normally twice the number of frames necessary
3190 // to fill one buffer and the resampler should not leave more than one buffer worth
3191 // of unreleased frames after each pass, but just in case...
3192 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003193#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003194 }
Eric Laurent81784c32012-11-19 14:55:58 -08003195 uint32_t minFrames = 1;
3196 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3197 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003198 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003199 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003200
3201 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003202 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003203 !track->isPaused() && !track->isTerminated())
3204 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003205 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003206
3207 mixedTracks++;
3208
Andy Hung69aed5f2014-02-25 17:24:40 -08003209 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3210 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003211 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003212 if (track->mainBuffer() != mSinkBuffer &&
3213 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003214 if (mEffectBufferEnabled) {
3215 mEffectBufferValid = true; // Later can set directly.
3216 }
Eric Laurent81784c32012-11-19 14:55:58 -08003217 chain = getEffectChain_l(track->sessionId());
3218 // Delegate volume control to effect in track effect chain if needed
3219 if (chain != 0) {
3220 tracksWithEffect++;
3221 } else {
3222 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3223 "session %d",
3224 name, track->sessionId());
3225 }
3226 }
3227
3228
3229 int param = AudioMixer::VOLUME;
3230 if (track->mFillingUpStatus == Track::FS_FILLED) {
3231 // no ramp for the first volume setting
3232 track->mFillingUpStatus = Track::FS_ACTIVE;
3233 if (track->mState == TrackBase::RESUMING) {
3234 track->mState = TrackBase::ACTIVE;
3235 param = AudioMixer::RAMP_VOLUME;
3236 }
3237 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003238 // FIXME should not make a decision based on mServer
3239 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003240 // If the track is stopped before the first frame was mixed,
3241 // do not apply ramp
3242 param = AudioMixer::RAMP_VOLUME;
3243 }
3244
3245 // compute volume for this track
3246 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003247 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003248 vl = vr = va = 0;
3249 if (track->isPausing()) {
3250 track->setPaused();
3251 }
3252 } else {
3253
3254 // read original volumes with volume control
3255 float typeVolume = mStreamTypes[track->streamType()].volume;
3256 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003257 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003258 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003259 vl = vlr & 0xFFFF;
3260 vr = vlr >> 16;
3261 // track volumes come from shared memory, so can't be trusted and must be clamped
3262 if (vl > MAX_GAIN_INT) {
3263 ALOGV("Track left volume out of range: %04X", vl);
3264 vl = MAX_GAIN_INT;
3265 }
3266 if (vr > MAX_GAIN_INT) {
3267 ALOGV("Track right volume out of range: %04X", vr);
3268 vr = MAX_GAIN_INT;
3269 }
3270 // now apply the master volume and stream type volume
3271 vl = (uint32_t)(v * vl) << 12;
3272 vr = (uint32_t)(v * vr) << 12;
3273 // assuming master volume and stream type volume each go up to 1.0,
3274 // vl and vr are now in 8.24 format
3275
Glenn Kastene3aa6592012-12-04 12:22:46 -08003276 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // send level comes from shared memory and so may be corrupt
3278 if (sendLevel > MAX_GAIN_INT) {
3279 ALOGV("Track send level out of range: %04X", sendLevel);
3280 sendLevel = MAX_GAIN_INT;
3281 }
3282 va = (uint32_t)(v * sendLevel);
3283 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284
Eric Laurent81784c32012-11-19 14:55:58 -08003285 // Delegate volume control to effect in track effect chain if needed
3286 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3287 // Do not ramp volume if volume is controlled by effect
3288 param = AudioMixer::VOLUME;
3289 track->mHasVolumeController = true;
3290 } else {
3291 // force no volume ramp when volume controller was just disabled or removed
3292 // from effect chain to avoid volume spike
3293 if (track->mHasVolumeController) {
3294 param = AudioMixer::VOLUME;
3295 }
3296 track->mHasVolumeController = false;
3297 }
3298
3299 // Convert volumes from 8.24 to 4.12 format
3300 // This additional clamping is needed in case chain->setVolume_l() overshot
3301 vl = (vl + (1 << 11)) >> 12;
3302 if (vl > MAX_GAIN_INT) {
3303 vl = MAX_GAIN_INT;
3304 }
3305 vr = (vr + (1 << 11)) >> 12;
3306 if (vr > MAX_GAIN_INT) {
3307 vr = MAX_GAIN_INT;
3308 }
3309
3310 if (va > MAX_GAIN_INT) {
3311 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3312 }
3313
3314 // XXX: these things DON'T need to be done each time
3315 mAudioMixer->setBufferProvider(name, track);
3316 mAudioMixer->enable(name);
3317
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003318 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3319 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3320 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003321 mAudioMixer->setParameter(
3322 name,
3323 AudioMixer::TRACK,
3324 AudioMixer::FORMAT, (void *)track->format());
3325 mAudioMixer->setParameter(
3326 name,
3327 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003328 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003329 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3330 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003331 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003332 if (reqSampleRate == 0) {
3333 reqSampleRate = mSampleRate;
3334 } else if (reqSampleRate > maxSampleRate) {
3335 reqSampleRate = maxSampleRate;
3336 }
Eric Laurent81784c32012-11-19 14:55:58 -08003337 mAudioMixer->setParameter(
3338 name,
3339 AudioMixer::RESAMPLE,
3340 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003341 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003342 /*
3343 * Select the appropriate output buffer for the track.
3344 *
Andy Hung98ef9782014-03-04 14:46:50 -08003345 * Tracks with effects go into their own effects chain buffer
3346 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003347 *
3348 * Other tracks can use mMixerBuffer for higher precision
3349 * channel accumulation. If this buffer is enabled
3350 * (mMixerBufferEnabled true), then selected tracks will accumulate
3351 * into it.
3352 *
3353 */
3354 if (mMixerBufferEnabled
3355 && (track->mainBuffer() == mSinkBuffer
3356 || track->mainBuffer() == mMixerBuffer)) {
3357 mAudioMixer->setParameter(
3358 name,
3359 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003360 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003361 mAudioMixer->setParameter(
3362 name,
3363 AudioMixer::TRACK,
3364 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3365 // TODO: override track->mainBuffer()?
3366 mMixerBufferValid = true;
3367 } else {
3368 mAudioMixer->setParameter(
3369 name,
3370 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003371 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003372 mAudioMixer->setParameter(
3373 name,
3374 AudioMixer::TRACK,
3375 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3376 }
Eric Laurent81784c32012-11-19 14:55:58 -08003377 mAudioMixer->setParameter(
3378 name,
3379 AudioMixer::TRACK,
3380 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3381
3382 // reset retry count
3383 track->mRetryCount = kMaxTrackRetries;
3384
3385 // If one track is ready, set the mixer ready if:
3386 // - the mixer was not ready during previous round OR
3387 // - no other track is not ready
3388 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3389 mixerStatus != MIXER_TRACKS_ENABLED) {
3390 mixerStatus = MIXER_TRACKS_READY;
3391 }
3392 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003393 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003394 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003395 }
Eric Laurent81784c32012-11-19 14:55:58 -08003396 // clear effect chain input buffer if an active track underruns to avoid sending
3397 // previous audio buffer again to effects
3398 chain = getEffectChain_l(track->sessionId());
3399 if (chain != 0) {
3400 chain->clearInputBuffer();
3401 }
3402
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003403 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003404 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3405 track->isStopped() || track->isPaused()) {
3406 // We have consumed all the buffers of this track.
3407 // Remove it from the list of active tracks.
3408 // TODO: use actual buffer filling status instead of latency when available from
3409 // audio HAL
3410 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3411 size_t framesWritten = mBytesWritten / mFrameSize;
3412 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3413 if (track->isStopped()) {
3414 track->reset();
3415 }
3416 tracksToRemove->add(track);
3417 }
3418 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003419 // No buffers for this track. Give it a few chances to
3420 // fill a buffer, then remove it from active list.
3421 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003422 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003423 tracksToRemove->add(track);
3424 // indicate to client process that the track was disabled because of underrun;
3425 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003426 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003427 // If one track is not ready, mark the mixer also not ready if:
3428 // - the mixer was ready during previous round OR
3429 // - no other track is ready
3430 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3431 mixerStatus != MIXER_TRACKS_READY) {
3432 mixerStatus = MIXER_TRACKS_ENABLED;
3433 }
3434 }
3435 mAudioMixer->disable(name);
3436 }
3437
3438 } // local variable scope to avoid goto warning
3439track_is_ready: ;
3440
3441 }
3442
3443 // Push the new FastMixer state if necessary
3444 bool pauseAudioWatchdog = false;
3445 if (didModify) {
3446 state->mFastTracksGen++;
3447 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3448 if (kUseFastMixer == FastMixer_Dynamic &&
3449 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3450 state->mCommand = FastMixerState::COLD_IDLE;
3451 state->mColdFutexAddr = &mFastMixerFutex;
3452 state->mColdGen++;
3453 mFastMixerFutex = 0;
3454 if (kUseFastMixer == FastMixer_Dynamic) {
3455 mNormalSink = mOutputSink;
3456 }
3457 // If we go into cold idle, need to wait for acknowledgement
3458 // so that fast mixer stops doing I/O.
3459 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3460 pauseAudioWatchdog = true;
3461 }
Eric Laurent81784c32012-11-19 14:55:58 -08003462 }
3463 if (sq != NULL) {
3464 sq->end(didModify);
3465 sq->push(block);
3466 }
3467#ifdef AUDIO_WATCHDOG
3468 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3469 mAudioWatchdog->pause();
3470 }
3471#endif
3472
3473 // Now perform the deferred reset on fast tracks that have stopped
3474 while (resetMask != 0) {
3475 size_t i = __builtin_ctz(resetMask);
3476 ALOG_ASSERT(i < count);
3477 resetMask &= ~(1 << i);
3478 sp<Track> t = mActiveTracks[i].promote();
3479 if (t == 0) {
3480 continue;
3481 }
3482 Track* track = t.get();
3483 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3484 track->reset();
3485 }
3486
3487 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003488 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003489
Andy Hung69aed5f2014-02-25 17:24:40 -08003490 // sink or mix buffer must be cleared if all tracks are connected to an
3491 // effect chain as in this case the mixer will not write to the sink or mix buffer
3492 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003493 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3494 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003495 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003496 if (mMixerBufferValid) {
3497 memset(mMixerBuffer, 0, mMixerBufferSize);
3498 // TODO: In testing, mSinkBuffer below need not be cleared because
3499 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3500 // after mixing.
3501 //
3502 // To enforce this guarantee:
3503 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3504 // (mixedTracks == 0 && fastTracks > 0))
3505 // must imply MIXER_TRACKS_READY.
3506 // Later, we may clear buffers regardless, and skip much of this logic.
3507 }
Andy Hung98ef9782014-03-04 14:46:50 -08003508 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3509 if (mEffectBufferValid) {
3510 memset(mEffectBuffer, 0, mEffectBufferSize);
3511 }
3512 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003513 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003514 }
3515
3516 // if any fast tracks, then status is ready
3517 mMixerStatusIgnoringFastTracks = mixerStatus;
3518 if (fastTracks > 0) {
3519 mixerStatus = MIXER_TRACKS_READY;
3520 }
3521 return mixerStatus;
3522}
3523
3524// getTrackName_l() must be called with ThreadBase::mLock held
3525int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3526{
3527 return mAudioMixer->getTrackName(channelMask, sessionId);
3528}
3529
3530// deleteTrackName_l() must be called with ThreadBase::mLock held
3531void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3532{
3533 ALOGV("remove track (%d) and delete from mixer", name);
3534 mAudioMixer->deleteTrackName(name);
3535}
3536
Eric Laurent10351942014-05-08 18:49:52 -07003537// checkForNewParameter_l() must be called with ThreadBase::mLock held
3538bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3539 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003540{
Eric Laurent81784c32012-11-19 14:55:58 -08003541 bool reconfig = false;
3542
Eric Laurent10351942014-05-08 18:49:52 -07003543 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003544
Eric Laurent10351942014-05-08 18:49:52 -07003545 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3546 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3547 if (mFastMixer != NULL) {
3548 FastMixerStateQueue *sq = mFastMixer->sq();
3549 FastMixerState *state = sq->begin();
3550 if (!(state->mCommand & FastMixerState::IDLE)) {
3551 previousCommand = state->mCommand;
3552 state->mCommand = FastMixerState::HOT_IDLE;
3553 sq->end();
3554 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3555 } else {
3556 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003557 }
Eric Laurent10351942014-05-08 18:49:52 -07003558 }
Eric Laurent81784c32012-11-19 14:55:58 -08003559
Eric Laurent10351942014-05-08 18:49:52 -07003560 AudioParameter param = AudioParameter(keyValuePair);
3561 int value;
3562 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3563 reconfig = true;
3564 }
3565 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3566 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3567 status = BAD_VALUE;
3568 } else {
3569 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003570 reconfig = true;
3571 }
Eric Laurent10351942014-05-08 18:49:52 -07003572 }
3573 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3574 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3575 status = BAD_VALUE;
3576 } else {
3577 // no need to save value, since it's constant
3578 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003579 }
Eric Laurent10351942014-05-08 18:49:52 -07003580 }
3581 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3582 // do not accept frame count changes if tracks are open as the track buffer
3583 // size depends on frame count and correct behavior would not be guaranteed
3584 // if frame count is changed after track creation
3585 if (!mTracks.isEmpty()) {
3586 status = INVALID_OPERATION;
3587 } else {
3588 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003589 }
Eric Laurent10351942014-05-08 18:49:52 -07003590 }
3591 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003592#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003593 // when changing the audio output device, call addBatteryData to notify
3594 // the change
3595 if (mOutDevice != value) {
3596 uint32_t params = 0;
3597 // check whether speaker is on
3598 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3599 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003600 }
Eric Laurent10351942014-05-08 18:49:52 -07003601
3602 audio_devices_t deviceWithoutSpeaker
3603 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3604 // check if any other device (except speaker) is on
3605 if (value & deviceWithoutSpeaker ) {
3606 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3607 }
3608
3609 if (params != 0) {
3610 addBatteryData(params);
3611 }
3612 }
Eric Laurent81784c32012-11-19 14:55:58 -08003613#endif
3614
Eric Laurent10351942014-05-08 18:49:52 -07003615 // forward device change to effects that have requested to be
3616 // aware of attached audio device.
3617 if (value != AUDIO_DEVICE_NONE) {
3618 mOutDevice = value;
3619 for (size_t i = 0; i < mEffectChains.size(); i++) {
3620 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003621 }
3622 }
Eric Laurent10351942014-05-08 18:49:52 -07003623 }
Eric Laurent81784c32012-11-19 14:55:58 -08003624
Eric Laurent10351942014-05-08 18:49:52 -07003625 if (status == NO_ERROR) {
3626 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3627 keyValuePair.string());
3628 if (!mStandby && status == INVALID_OPERATION) {
3629 mOutput->stream->common.standby(&mOutput->stream->common);
3630 mStandby = true;
3631 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003632 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003633 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003634 }
Eric Laurent10351942014-05-08 18:49:52 -07003635 if (status == NO_ERROR && reconfig) {
3636 readOutputParameters_l();
3637 delete mAudioMixer;
3638 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3639 for (size_t i = 0; i < mTracks.size() ; i++) {
3640 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3641 if (name < 0) {
3642 break;
3643 }
3644 mTracks[i]->mName = name;
3645 }
3646 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3647 }
Eric Laurent81784c32012-11-19 14:55:58 -08003648 }
3649
3650 if (!(previousCommand & FastMixerState::IDLE)) {
3651 ALOG_ASSERT(mFastMixer != NULL);
3652 FastMixerStateQueue *sq = mFastMixer->sq();
3653 FastMixerState *state = sq->begin();
3654 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3655 state->mCommand = previousCommand;
3656 sq->end();
3657 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3658 }
3659
3660 return reconfig;
3661}
3662
3663
3664void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3665{
3666 const size_t SIZE = 256;
3667 char buffer[SIZE];
3668 String8 result;
3669
3670 PlaybackThread::dumpInternals(fd, args);
3671
Marco Nelissenb2208842014-02-07 14:00:50 -08003672 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003673
3674 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003675 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003676 copy.dump(fd);
3677
3678#ifdef STATE_QUEUE_DUMP
3679 // Similar for state queue
3680 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3681 observerCopy.dump(fd);
3682 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3683 mutatorCopy.dump(fd);
3684#endif
3685
Glenn Kasten46909e72013-02-26 09:20:22 -08003686#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003687 // Write the tee output to a .wav file
3688 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003689#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003690
3691#ifdef AUDIO_WATCHDOG
3692 if (mAudioWatchdog != 0) {
3693 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3694 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3695 wdCopy.dump(fd);
3696 }
3697#endif
3698}
3699
3700uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3701{
3702 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3703}
3704
3705uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3706{
3707 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3708}
3709
3710void AudioFlinger::MixerThread::cacheParameters_l()
3711{
3712 PlaybackThread::cacheParameters_l();
3713
3714 // FIXME: Relaxed timing because of a certain device that can't meet latency
3715 // Should be reduced to 2x after the vendor fixes the driver issue
3716 // increase threshold again due to low power audio mode. The way this warning
3717 // threshold is calculated and its usefulness should be reconsidered anyway.
3718 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3719}
3720
3721// ----------------------------------------------------------------------------
3722
3723AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3724 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3725 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3726 // mLeftVolFloat, mRightVolFloat
3727{
3728}
3729
Eric Laurentbfb1b832013-01-07 09:53:42 -08003730AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3731 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3732 ThreadBase::type_t type)
3733 : PlaybackThread(audioFlinger, output, id, device, type)
3734 // mLeftVolFloat, mRightVolFloat
3735{
3736}
3737
Eric Laurent81784c32012-11-19 14:55:58 -08003738AudioFlinger::DirectOutputThread::~DirectOutputThread()
3739{
3740}
3741
Eric Laurentbfb1b832013-01-07 09:53:42 -08003742void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3743{
3744 audio_track_cblk_t* cblk = track->cblk();
3745 float left, right;
3746
3747 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3748 left = right = 0;
3749 } else {
3750 float typeVolume = mStreamTypes[track->streamType()].volume;
3751 float v = mMasterVolume * typeVolume;
3752 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3753 uint32_t vlr = proxy->getVolumeLR();
3754 float v_clamped = v * (vlr & 0xFFFF);
3755 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3756 left = v_clamped/MAX_GAIN;
3757 v_clamped = v * (vlr >> 16);
3758 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3759 right = v_clamped/MAX_GAIN;
3760 }
3761
3762 if (lastTrack) {
3763 if (left != mLeftVolFloat || right != mRightVolFloat) {
3764 mLeftVolFloat = left;
3765 mRightVolFloat = right;
3766
3767 // Convert volumes from float to 8.24
3768 uint32_t vl = (uint32_t)(left * (1 << 24));
3769 uint32_t vr = (uint32_t)(right * (1 << 24));
3770
3771 // Delegate volume control to effect in track effect chain if needed
3772 // only one effect chain can be present on DirectOutputThread, so if
3773 // there is one, the track is connected to it
3774 if (!mEffectChains.isEmpty()) {
3775 mEffectChains[0]->setVolume_l(&vl, &vr);
3776 left = (float)vl / (1 << 24);
3777 right = (float)vr / (1 << 24);
3778 }
3779 if (mOutput->stream->set_volume) {
3780 mOutput->stream->set_volume(mOutput->stream, left, right);
3781 }
3782 }
3783 }
3784}
3785
3786
Eric Laurent81784c32012-11-19 14:55:58 -08003787AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3788 Vector< sp<Track> > *tracksToRemove
3789)
3790{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003791 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003792 mixer_state mixerStatus = MIXER_IDLE;
3793
3794 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003795 for (size_t i = 0; i < count; i++) {
3796 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003797 // The track died recently
3798 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003799 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003800 }
3801
3802 Track* const track = t.get();
3803 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003804 // Only consider last track started for volume and mixer state control.
3805 // In theory an older track could underrun and restart after the new one starts
3806 // but as we only care about the transition phase between two tracks on a
3807 // direct output, it is not a problem to ignore the underrun case.
3808 sp<Track> l = mLatestActiveTrack.promote();
3809 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003810
3811 // The first time a track is added we wait
3812 // for all its buffers to be filled before processing it
3813 uint32_t minFrames;
3814 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3815 minFrames = mNormalFrameCount;
3816 } else {
3817 minFrames = 1;
3818 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819
Eric Laurent81784c32012-11-19 14:55:58 -08003820 if ((track->framesReady() >= minFrames) && track->isReady() &&
3821 !track->isPaused() && !track->isTerminated())
3822 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003823 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003824
3825 if (track->mFillingUpStatus == Track::FS_FILLED) {
3826 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003827 // make sure processVolume_l() will apply new volume even if 0
3828 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003829 if (track->mState == TrackBase::RESUMING) {
3830 track->mState = TrackBase::ACTIVE;
3831 }
3832 }
3833
3834 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003835 processVolume_l(track, last);
3836 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003837 // reset retry count
3838 track->mRetryCount = kMaxTrackRetriesDirect;
3839 mActiveTrack = t;
3840 mixerStatus = MIXER_TRACKS_READY;
3841 }
Eric Laurent81784c32012-11-19 14:55:58 -08003842 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003843 // clear effect chain input buffer if the last active track started underruns
3844 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003845 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003846 mEffectChains[0]->clearInputBuffer();
3847 }
3848
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003849 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003850 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3851 track->isStopped() || track->isPaused()) {
3852 // We have consumed all the buffers of this track.
3853 // Remove it from the list of active tracks.
3854 // TODO: implement behavior for compressed audio
3855 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3856 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003857 if (mStandby || !last ||
3858 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003859 if (track->isStopped()) {
3860 track->reset();
3861 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003862 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003863 }
3864 } else {
3865 // No buffers for this track. Give it a few chances to
3866 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003867 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003868 if (--(track->mRetryCount) <= 0) {
3869 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003870 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003871 // indicate to client process that the track was disabled because of underrun;
3872 // it will then automatically call start() when data is available
3873 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003875 mixerStatus = MIXER_TRACKS_ENABLED;
3876 }
3877 }
3878 }
3879 }
3880
Eric Laurent81784c32012-11-19 14:55:58 -08003881 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003882 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003883
3884 return mixerStatus;
3885}
3886
3887void AudioFlinger::DirectOutputThread::threadLoop_mix()
3888{
Eric Laurent81784c32012-11-19 14:55:58 -08003889 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003890 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003891 // output audio to hardware
3892 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003893 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003894 buffer.frameCount = frameCount;
3895 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003896 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003897 memset(curBuf, 0, frameCount * mFrameSize);
3898 break;
3899 }
3900 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3901 frameCount -= buffer.frameCount;
3902 curBuf += buffer.frameCount * mFrameSize;
3903 mActiveTrack->releaseBuffer(&buffer);
3904 }
Andy Hung2098f272014-02-27 14:00:06 -08003905 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003906 sleepTime = 0;
3907 standbyTime = systemTime() + standbyDelay;
3908 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003909}
3910
3911void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3912{
3913 if (sleepTime == 0) {
3914 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3915 sleepTime = activeSleepTime;
3916 } else {
3917 sleepTime = idleSleepTime;
3918 }
3919 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003920 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003921 sleepTime = 0;
3922 }
3923}
3924
3925// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003926int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3927 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003928{
3929 return 0;
3930}
3931
3932// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003933void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003934{
3935}
3936
Eric Laurent10351942014-05-08 18:49:52 -07003937// checkForNewParameter_l() must be called with ThreadBase::mLock held
3938bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
3939 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003940{
3941 bool reconfig = false;
3942
Eric Laurent10351942014-05-08 18:49:52 -07003943 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003944
Eric Laurent10351942014-05-08 18:49:52 -07003945 AudioParameter param = AudioParameter(keyValuePair);
3946 int value;
3947 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3948 // forward device change to effects that have requested to be
3949 // aware of attached audio device.
3950 if (value != AUDIO_DEVICE_NONE) {
3951 mOutDevice = value;
3952 for (size_t i = 0; i < mEffectChains.size(); i++) {
3953 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07003954 }
3955 }
Eric Laurent81784c32012-11-19 14:55:58 -08003956 }
Eric Laurent10351942014-05-08 18:49:52 -07003957 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3958 // do not accept frame count changes if tracks are open as the track buffer
3959 // size depends on frame count and correct behavior would not be garantied
3960 // if frame count is changed after track creation
3961 if (!mTracks.isEmpty()) {
3962 status = INVALID_OPERATION;
3963 } else {
3964 reconfig = true;
3965 }
3966 }
3967 if (status == NO_ERROR) {
3968 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3969 keyValuePair.string());
3970 if (!mStandby && status == INVALID_OPERATION) {
3971 mOutput->stream->common.standby(&mOutput->stream->common);
3972 mStandby = true;
3973 mBytesWritten = 0;
3974 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3975 keyValuePair.string());
3976 }
3977 if (status == NO_ERROR && reconfig) {
3978 readOutputParameters_l();
3979 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3980 }
3981 }
3982
Eric Laurent81784c32012-11-19 14:55:58 -08003983 return reconfig;
3984}
3985
3986uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3987{
3988 uint32_t time;
3989 if (audio_is_linear_pcm(mFormat)) {
3990 time = PlaybackThread::activeSleepTimeUs();
3991 } else {
3992 time = 10000;
3993 }
3994 return time;
3995}
3996
3997uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3998{
3999 uint32_t time;
4000 if (audio_is_linear_pcm(mFormat)) {
4001 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4002 } else {
4003 time = 10000;
4004 }
4005 return time;
4006}
4007
4008uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4009{
4010 uint32_t time;
4011 if (audio_is_linear_pcm(mFormat)) {
4012 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4013 } else {
4014 time = 10000;
4015 }
4016 return time;
4017}
4018
4019void AudioFlinger::DirectOutputThread::cacheParameters_l()
4020{
4021 PlaybackThread::cacheParameters_l();
4022
4023 // use shorter standby delay as on normal output to release
4024 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004025 if (audio_is_linear_pcm(mFormat)) {
4026 standbyDelay = microseconds(activeSleepTime*2);
4027 } else {
4028 standbyDelay = kOffloadStandbyDelayNs;
4029 }
Eric Laurent81784c32012-11-19 14:55:58 -08004030}
4031
4032// ----------------------------------------------------------------------------
4033
Eric Laurentbfb1b832013-01-07 09:53:42 -08004034AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004035 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004036 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004037 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004038 mWriteAckSequence(0),
4039 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004040{
4041}
4042
4043AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4044{
4045}
4046
4047void AudioFlinger::AsyncCallbackThread::onFirstRef()
4048{
4049 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4050}
4051
4052bool AudioFlinger::AsyncCallbackThread::threadLoop()
4053{
4054 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004055 uint32_t writeAckSequence;
4056 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057
4058 {
4059 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004060 while (!((mWriteAckSequence & 1) ||
4061 (mDrainSequence & 1) ||
4062 exitPending())) {
4063 mWaitWorkCV.wait(mLock);
4064 }
4065
Eric Laurentbfb1b832013-01-07 09:53:42 -08004066 if (exitPending()) {
4067 break;
4068 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004069 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4070 mWriteAckSequence, mDrainSequence);
4071 writeAckSequence = mWriteAckSequence;
4072 mWriteAckSequence &= ~1;
4073 drainSequence = mDrainSequence;
4074 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004075 }
4076 {
Eric Laurent4de95592013-09-26 15:28:21 -07004077 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4078 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004079 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004080 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004082 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004083 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 }
4085 }
4086 }
4087 }
4088 return false;
4089}
4090
4091void AudioFlinger::AsyncCallbackThread::exit()
4092{
4093 ALOGV("AsyncCallbackThread::exit");
4094 Mutex::Autolock _l(mLock);
4095 requestExit();
4096 mWaitWorkCV.broadcast();
4097}
4098
Eric Laurent3b4529e2013-09-05 18:09:19 -07004099void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100{
4101 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004102 // bit 0 is cleared
4103 mWriteAckSequence = sequence << 1;
4104}
4105
4106void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4107{
4108 Mutex::Autolock _l(mLock);
4109 // ignore unexpected callbacks
4110 if (mWriteAckSequence & 2) {
4111 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004112 mWaitWorkCV.signal();
4113 }
4114}
4115
Eric Laurent3b4529e2013-09-05 18:09:19 -07004116void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004117{
4118 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004119 // bit 0 is cleared
4120 mDrainSequence = sequence << 1;
4121}
4122
4123void AudioFlinger::AsyncCallbackThread::resetDraining()
4124{
4125 Mutex::Autolock _l(mLock);
4126 // ignore unexpected callbacks
4127 if (mDrainSequence & 2) {
4128 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004129 mWaitWorkCV.signal();
4130 }
4131}
4132
4133
4134// ----------------------------------------------------------------------------
4135AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4136 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4137 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4138 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004139 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004140 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004141{
Eric Laurentfd477972013-10-25 18:10:40 -07004142 //FIXME: mStandby should be set to true by ThreadBase constructor
4143 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004144}
4145
Eric Laurentbfb1b832013-01-07 09:53:42 -08004146void AudioFlinger::OffloadThread::threadLoop_exit()
4147{
4148 if (mFlushPending || mHwPaused) {
4149 // If a flush is pending or track was paused, just discard buffered data
4150 flushHw_l();
4151 } else {
4152 mMixerStatus = MIXER_DRAIN_ALL;
4153 threadLoop_drain();
4154 }
4155 mCallbackThread->exit();
4156 PlaybackThread::threadLoop_exit();
4157}
4158
4159AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4160 Vector< sp<Track> > *tracksToRemove
4161)
4162{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163 size_t count = mActiveTracks.size();
4164
4165 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004166 bool doHwPause = false;
4167 bool doHwResume = false;
4168
Eric Laurentede6c3b2013-09-19 14:37:46 -07004169 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4170
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 // find out which tracks need to be processed
4172 for (size_t i = 0; i < count; i++) {
4173 sp<Track> t = mActiveTracks[i].promote();
4174 // The track died recently
4175 if (t == 0) {
4176 continue;
4177 }
4178 Track* const track = t.get();
4179 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004180 // Only consider last track started for volume and mixer state control.
4181 // In theory an older track could underrun and restart after the new one starts
4182 // but as we only care about the transition phase between two tracks on a
4183 // direct output, it is not a problem to ignore the underrun case.
4184 sp<Track> l = mLatestActiveTrack.promote();
4185 bool last = l.get() == track;
4186
Haynes Mathew George7844f672014-01-15 12:32:55 -08004187 if (track->isInvalid()) {
4188 ALOGW("An invalidated track shouldn't be in active list");
4189 tracksToRemove->add(track);
4190 continue;
4191 }
4192
4193 if (track->mState == TrackBase::IDLE) {
4194 ALOGW("An idle track shouldn't be in active list");
4195 continue;
4196 }
4197
Eric Laurentbfb1b832013-01-07 09:53:42 -08004198 if (track->isPausing()) {
4199 track->setPaused();
4200 if (last) {
4201 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004202 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004203 mHwPaused = true;
4204 }
4205 // If we were part way through writing the mixbuffer to
4206 // the HAL we must save this until we resume
4207 // BUG - this will be wrong if a different track is made active,
4208 // in that case we want to discard the pending data in the
4209 // mixbuffer and tell the client to present it again when the
4210 // track is resumed
4211 mPausedWriteLength = mCurrentWriteLength;
4212 mPausedBytesRemaining = mBytesRemaining;
4213 mBytesRemaining = 0; // stop writing
4214 }
4215 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004216 } else if (track->isFlushPending()) {
4217 track->flushAck();
4218 if (last) {
4219 mFlushPending = true;
4220 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004221 } else if (track->isResumePending()){
4222 track->resumeAck();
4223 if (last) {
4224 if (mPausedBytesRemaining) {
4225 // Need to continue write that was interrupted
4226 mCurrentWriteLength = mPausedWriteLength;
4227 mBytesRemaining = mPausedBytesRemaining;
4228 mPausedBytesRemaining = 0;
4229 }
4230 if (mHwPaused) {
4231 doHwResume = true;
4232 mHwPaused = false;
4233 // threadLoop_mix() will handle the case that we need to
4234 // resume an interrupted write
4235 }
4236 // enable write to audio HAL
4237 sleepTime = 0;
4238
4239 // Do not handle new data in this iteration even if track->framesReady()
4240 mixerStatus = MIXER_TRACKS_ENABLED;
4241 }
4242 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004243 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004244 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004245 if (track->mFillingUpStatus == Track::FS_FILLED) {
4246 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004247 // make sure processVolume_l() will apply new volume even if 0
4248 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004249 }
4250
4251 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004252 sp<Track> previousTrack = mPreviousTrack.promote();
4253 if (previousTrack != 0) {
4254 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004255 // Flush any data still being written from last track
4256 mBytesRemaining = 0;
4257 if (mPausedBytesRemaining) {
4258 // Last track was paused so we also need to flush saved
4259 // mixbuffer state and invalidate track so that it will
4260 // re-submit that unwritten data when it is next resumed
4261 mPausedBytesRemaining = 0;
4262 // Invalidate is a bit drastic - would be more efficient
4263 // to have a flag to tell client that some of the
4264 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004265 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004266 }
4267 // flush data already sent to the DSP if changing audio session as audio
4268 // comes from a different source. Also invalidate previous track to force a
4269 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004270 if (previousTrack->sessionId() != track->sessionId()) {
4271 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004272 }
4273 }
4274 }
4275 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276 // reset retry count
4277 track->mRetryCount = kMaxTrackRetriesOffload;
4278 mActiveTrack = t;
4279 mixerStatus = MIXER_TRACKS_READY;
4280 }
4281 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004282 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004283 if (track->isStopping_1()) {
4284 // Hardware buffer can hold a large amount of audio so we must
4285 // wait for all current track's data to drain before we say
4286 // that the track is stopped.
4287 if (mBytesRemaining == 0) {
4288 // Only start draining when all data in mixbuffer
4289 // has been written
4290 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4291 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004292 // do not drain if no data was ever sent to HAL (mStandby == true)
4293 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004294 // do not modify drain sequence if we are already draining. This happens
4295 // when resuming from pause after drain.
4296 if ((mDrainSequence & 1) == 0) {
4297 sleepTime = 0;
4298 standbyTime = systemTime() + standbyDelay;
4299 mixerStatus = MIXER_DRAIN_TRACK;
4300 mDrainSequence += 2;
4301 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004302 if (mHwPaused) {
4303 // It is possible to move from PAUSED to STOPPING_1 without
4304 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004305 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 mHwPaused = false;
4307 }
4308 }
4309 }
4310 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004311 // Drain has completed or we are in standby, signal presentation complete
4312 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004313 track->mState = TrackBase::STOPPED;
4314 size_t audioHALFrames =
4315 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4316 size_t framesWritten =
4317 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4318 track->presentationComplete(framesWritten, audioHALFrames);
4319 track->reset();
4320 tracksToRemove->add(track);
4321 }
4322 } else {
4323 // No buffers for this track. Give it a few chances to
4324 // fill a buffer, then remove it from active list.
4325 if (--(track->mRetryCount) <= 0) {
4326 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4327 track->name());
4328 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004329 // indicate to client process that the track was disabled because of underrun;
4330 // it will then automatically call start() when data is available
4331 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004332 } else if (last){
4333 mixerStatus = MIXER_TRACKS_ENABLED;
4334 }
4335 }
4336 }
4337 // compute volume for this track
4338 processVolume_l(track, last);
4339 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004340
Eric Laurentea0fade2013-10-04 16:23:48 -07004341 // make sure the pause/flush/resume sequence is executed in the right order.
4342 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4343 // before flush and then resume HW. This can happen in case of pause/flush/resume
4344 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004345 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004346 mOutput->stream->pause(mOutput->stream);
4347 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004348 if (mFlushPending) {
4349 flushHw_l();
4350 mFlushPending = false;
4351 }
Eric Laurentfd477972013-10-25 18:10:40 -07004352 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004353 mOutput->stream->resume(mOutput->stream);
4354 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004355
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 // remove all the tracks that need to be...
4357 removeTracks_l(*tracksToRemove);
4358
4359 return mixerStatus;
4360}
4361
Eric Laurentbfb1b832013-01-07 09:53:42 -08004362// must be called with thread mutex locked
4363bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4364{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004365 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4366 mWriteAckSequence, mDrainSequence);
4367 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004368 return true;
4369 }
4370 return false;
4371}
4372
4373// must be called with thread mutex locked
4374bool AudioFlinger::OffloadThread::shouldStandby_l()
4375{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004376 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377
4378 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4379 // after a timeout and we will enter standby then.
4380 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004381 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004382 }
4383
Glenn Kastene6f35b12013-08-19 09:58:50 -07004384 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004385}
4386
4387
4388bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4389{
4390 Mutex::Autolock _l(mLock);
4391 return waitingAsyncCallback_l();
4392}
4393
4394void AudioFlinger::OffloadThread::flushHw_l()
4395{
4396 mOutput->stream->flush(mOutput->stream);
4397 // Flush anything still waiting in the mixbuffer
4398 mCurrentWriteLength = 0;
4399 mBytesRemaining = 0;
4400 mPausedWriteLength = 0;
4401 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004402 mHwPaused = false;
4403
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004405 // discard any pending drain or write ack by incrementing sequence
4406 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4407 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004408 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004409 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4410 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004411 }
4412}
4413
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004414void AudioFlinger::OffloadThread::onAddNewTrack_l()
4415{
4416 sp<Track> previousTrack = mPreviousTrack.promote();
4417 sp<Track> latestTrack = mLatestActiveTrack.promote();
4418
4419 if (previousTrack != 0 && latestTrack != 0 &&
4420 (previousTrack->sessionId() != latestTrack->sessionId())) {
4421 mFlushPending = true;
4422 }
4423 PlaybackThread::onAddNewTrack_l();
4424}
4425
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426// ----------------------------------------------------------------------------
4427
Eric Laurent81784c32012-11-19 14:55:58 -08004428AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4429 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4430 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4431 DUPLICATING),
4432 mWaitTimeMs(UINT_MAX)
4433{
4434 addOutputTrack(mainThread);
4435}
4436
4437AudioFlinger::DuplicatingThread::~DuplicatingThread()
4438{
4439 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4440 mOutputTracks[i]->destroy();
4441 }
4442}
4443
4444void AudioFlinger::DuplicatingThread::threadLoop_mix()
4445{
4446 // mix buffers...
4447 if (outputsReady(outputTracks)) {
4448 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4449 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004450 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004451 }
4452 sleepTime = 0;
4453 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004454 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004455 standbyTime = systemTime() + standbyDelay;
4456}
4457
4458void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4459{
4460 if (sleepTime == 0) {
4461 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4462 sleepTime = activeSleepTime;
4463 } else {
4464 sleepTime = idleSleepTime;
4465 }
4466 } else if (mBytesWritten != 0) {
4467 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4468 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004469 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004470 } else {
4471 // flush remaining overflow buffers in output tracks
4472 writeFrames = 0;
4473 }
4474 sleepTime = 0;
4475 }
4476}
4477
Eric Laurentbfb1b832013-01-07 09:53:42 -08004478ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004479{
4480 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004481 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4482 // for delivery downstream as needed. This in-place conversion is safe as
4483 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4484 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4485 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4486 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4487 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4488 }
4489 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004490 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004491 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004492 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004493}
4494
4495void AudioFlinger::DuplicatingThread::threadLoop_standby()
4496{
4497 // DuplicatingThread implements standby by stopping all tracks
4498 for (size_t i = 0; i < outputTracks.size(); i++) {
4499 outputTracks[i]->stop();
4500 }
4501}
4502
4503void AudioFlinger::DuplicatingThread::saveOutputTracks()
4504{
4505 outputTracks = mOutputTracks;
4506}
4507
4508void AudioFlinger::DuplicatingThread::clearOutputTracks()
4509{
4510 outputTracks.clear();
4511}
4512
4513void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4514{
4515 Mutex::Autolock _l(mLock);
4516 // FIXME explain this formula
4517 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004518 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4519 // due to current usage case and restrictions on the AudioBufferProvider.
4520 // Actual buffer conversion is done in threadLoop_write().
4521 //
4522 // TODO: This may change in the future, depending on multichannel
4523 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004524 OutputTrack *outputTrack = new OutputTrack(thread,
4525 this,
4526 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004527 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004528 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004529 frameCount,
4530 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004531 if (outputTrack->cblk() != NULL) {
4532 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4533 mOutputTracks.add(outputTrack);
4534 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4535 updateWaitTime_l();
4536 }
4537}
4538
4539void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4540{
4541 Mutex::Autolock _l(mLock);
4542 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4543 if (mOutputTracks[i]->thread() == thread) {
4544 mOutputTracks[i]->destroy();
4545 mOutputTracks.removeAt(i);
4546 updateWaitTime_l();
4547 return;
4548 }
4549 }
4550 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4551}
4552
4553// caller must hold mLock
4554void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4555{
4556 mWaitTimeMs = UINT_MAX;
4557 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4558 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4559 if (strong != 0) {
4560 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4561 if (waitTimeMs < mWaitTimeMs) {
4562 mWaitTimeMs = waitTimeMs;
4563 }
4564 }
4565 }
4566}
4567
4568
4569bool AudioFlinger::DuplicatingThread::outputsReady(
4570 const SortedVector< sp<OutputTrack> > &outputTracks)
4571{
4572 for (size_t i = 0; i < outputTracks.size(); i++) {
4573 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4574 if (thread == 0) {
4575 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4576 outputTracks[i].get());
4577 return false;
4578 }
4579 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4580 // see note at standby() declaration
4581 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4582 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4583 thread.get());
4584 return false;
4585 }
4586 }
4587 return true;
4588}
4589
4590uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4591{
4592 return (mWaitTimeMs * 1000) / 2;
4593}
4594
4595void AudioFlinger::DuplicatingThread::cacheParameters_l()
4596{
4597 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4598 updateWaitTime_l();
4599
4600 MixerThread::cacheParameters_l();
4601}
4602
4603// ----------------------------------------------------------------------------
4604// Record
4605// ----------------------------------------------------------------------------
4606
4607AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4608 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004609 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004610 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004611 audio_devices_t inDevice
4612#ifdef TEE_SINK
4613 , const sp<NBAIO_Sink>& teeSink
4614#endif
4615 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004616 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004617 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004618 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004619 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004620#ifdef TEE_SINK
4621 , mTeeSink(teeSink)
4622#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004623 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4624 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004625{
4626 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004627 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004628
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004629 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004630}
4631
4632
4633AudioFlinger::RecordThread::~RecordThread()
4634{
Glenn Kasten481fb672013-09-30 14:39:28 -07004635 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004636 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004637}
4638
4639void AudioFlinger::RecordThread::onFirstRef()
4640{
4641 run(mName, PRIORITY_URGENT_AUDIO);
4642}
4643
Eric Laurent81784c32012-11-19 14:55:58 -08004644bool AudioFlinger::RecordThread::threadLoop()
4645{
Eric Laurent81784c32012-11-19 14:55:58 -08004646 nsecs_t lastWarning = 0;
4647
4648 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004649
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004650reacquire_wakelock:
4651 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004652 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004653 {
4654 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004655 size_t size = mActiveTracks.size();
4656 activeTracksGen = mActiveTracksGen;
4657 if (size > 0) {
4658 // FIXME an arbitrary choice
4659 activeTrack = mActiveTracks[0];
4660 acquireWakeLock_l(activeTrack->uid());
4661 if (size > 1) {
4662 SortedVector<int> tmp;
4663 for (size_t i = 0; i < size; i++) {
4664 tmp.add(mActiveTracks[i]->uid());
4665 }
4666 updateWakeLockUids_l(tmp);
4667 }
4668 } else {
4669 acquireWakeLock_l(-1);
4670 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004671 }
4672
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004673 // used to request a deferred sleep, to be executed later while mutex is unlocked
4674 uint32_t sleepUs = 0;
4675
4676 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004677 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004678 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004679
Glenn Kasten5edadd42013-08-14 16:30:49 -07004680 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004681 if (sleepUs > 0) {
4682 usleep(sleepUs);
4683 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004684 }
4685
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004686 // activeTracks accumulates a copy of a subset of mActiveTracks
4687 Vector< sp<RecordTrack> > activeTracks;
4688
Eric Laurent10351942014-05-08 18:49:52 -07004689
Eric Laurent81784c32012-11-19 14:55:58 -08004690 { // scope for mLock
4691 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004692
Eric Laurent021cf962014-05-13 10:18:14 -07004693 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004694
Eric Laurent000a4192014-01-29 15:17:32 -08004695 // check exitPending here because checkForNewParameters_l() and
4696 // checkForNewParameters_l() can temporarily release mLock
4697 if (exitPending()) {
4698 break;
4699 }
4700
Glenn Kasten2b806402013-11-20 16:37:38 -08004701 // if no active track(s), then standby and release wakelock
4702 size_t size = mActiveTracks.size();
4703 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004704 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004705 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004706 releaseWakeLock_l();
4707 ALOGV("RecordThread: loop stopping");
4708 // go to sleep
4709 mWaitWorkCV.wait(mLock);
4710 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004711 goto reacquire_wakelock;
4712 }
4713
Glenn Kasten2b806402013-11-20 16:37:38 -08004714 if (mActiveTracksGen != activeTracksGen) {
4715 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004716 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004717 for (size_t i = 0; i < size; i++) {
4718 tmp.add(mActiveTracks[i]->uid());
4719 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004720 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004721 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004722
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004723 bool doBroadcast = false;
4724 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004725
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004726 activeTrack = mActiveTracks[i];
4727 if (activeTrack->isTerminated()) {
4728 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004729 mActiveTracks.remove(activeTrack);
4730 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004731 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004732 continue;
4733 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004734
4735 TrackBase::track_state activeTrackState = activeTrack->mState;
4736 switch (activeTrackState) {
4737
4738 case TrackBase::PAUSING:
4739 mActiveTracks.remove(activeTrack);
4740 mActiveTracksGen++;
4741 doBroadcast = true;
4742 size--;
4743 continue;
4744
4745 case TrackBase::STARTING_1:
4746 sleepUs = 10000;
4747 i++;
4748 continue;
4749
4750 case TrackBase::STARTING_2:
4751 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004752 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004753 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004754 break;
4755
4756 case TrackBase::ACTIVE:
4757 break;
4758
4759 case TrackBase::IDLE:
4760 i++;
4761 continue;
4762
4763 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004764 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004765 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004766
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004767 activeTracks.add(activeTrack);
4768 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004769
Glenn Kasten9e982352013-08-14 14:39:50 -07004770 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004771 if (doBroadcast) {
4772 mStartStopCond.broadcast();
4773 }
4774
4775 // sleep if there are no active tracks to process
4776 if (activeTracks.size() == 0) {
4777 if (sleepUs == 0) {
4778 sleepUs = kRecordThreadSleepUs;
4779 }
4780 continue;
4781 }
4782 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004783
Eric Laurent81784c32012-11-19 14:55:58 -08004784 lockEffectChains_l(effectChains);
4785 }
4786
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004787 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004789 size_t size = effectChains.size();
4790 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004791 // thread mutex is not locked, but effect chain is locked
4792 effectChains[i]->process_l();
4793 }
4794
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004795 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4796 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4797 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4798 // If destination is non-contiguous, first read past the nominal end of buffer, then
4799 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004800
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004801 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4802 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4803 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4804 if (bytesRead <= 0) {
4805 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4806 // Force input into standby so that it tries to recover at next read attempt
4807 inputStandBy();
4808 sleepUs = kRecordThreadSleepUs;
4809 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004810 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004811 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4812 size_t framesRead = bytesRead / mFrameSize;
4813 ALOG_ASSERT(framesRead > 0);
4814 if (mTeeSink != 0) {
4815 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4816 }
4817 // If destination is non-contiguous, we now correct for reading past end of buffer.
4818 size_t part1 = mRsmpInFramesP2 - rear;
4819 if (framesRead > part1) {
4820 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4821 (framesRead - part1) * mFrameSize);
4822 }
4823 rear = mRsmpInRear += framesRead;
4824
4825 size = activeTracks.size();
4826 // loop over each active track
4827 for (size_t i = 0; i < size; i++) {
4828 activeTrack = activeTracks[i];
4829
4830 enum {
4831 OVERRUN_UNKNOWN,
4832 OVERRUN_TRUE,
4833 OVERRUN_FALSE
4834 } overrun = OVERRUN_UNKNOWN;
4835
4836 // loop over getNextBuffer to handle circular sink
4837 for (;;) {
4838
4839 activeTrack->mSink.frameCount = ~0;
4840 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4841 size_t framesOut = activeTrack->mSink.frameCount;
4842 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4843
4844 int32_t front = activeTrack->mRsmpInFront;
4845 ssize_t filled = rear - front;
4846 size_t framesIn;
4847
4848 if (filled < 0) {
4849 // should not happen, but treat like a massive overrun and re-sync
4850 framesIn = 0;
4851 activeTrack->mRsmpInFront = rear;
4852 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004853 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004854 framesIn = (size_t) filled;
4855 } else {
4856 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004857 framesIn = mRsmpInFrames;
4858 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004859 overrun = OVERRUN_TRUE;
4860 }
4861
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004862 if (framesOut == 0 || framesIn == 0) {
4863 break;
4864 }
4865
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004866 if (activeTrack->mResampler == NULL) {
4867 // no resampling
4868 if (framesIn > framesOut) {
4869 framesIn = framesOut;
4870 } else {
4871 framesOut = framesIn;
4872 }
4873 int8_t *dst = activeTrack->mSink.i8;
4874 while (framesIn > 0) {
4875 front &= mRsmpInFramesP2 - 1;
4876 size_t part1 = mRsmpInFramesP2 - front;
4877 if (part1 > framesIn) {
4878 part1 = framesIn;
4879 }
4880 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004881 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004882 memcpy(dst, src, part1 * mFrameSize);
4883 } else if (mChannelCount == 1) {
4884 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4885 part1);
4886 } else {
4887 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4888 part1);
4889 }
4890 dst += part1 * activeTrack->mFrameSize;
4891 front += part1;
4892 framesIn -= part1;
4893 }
4894 activeTrack->mRsmpInFront += framesOut;
4895
4896 } else {
4897 // resampling
4898 // FIXME framesInNeeded should really be part of resampler API, and should
4899 // depend on the SRC ratio
4900 // to keep mRsmpInBuffer full so resampler always has sufficient input
4901 size_t framesInNeeded;
4902 // FIXME only re-calculate when it changes, and optimize for common ratios
4903 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4904 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004905 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004906 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4907 framesInNeeded, framesOut, inOverOut);
4908 // Although we theoretically have framesIn in circular buffer, some of those are
4909 // unreleased frames, and thus must be discounted for purpose of budgeting.
4910 size_t unreleased = activeTrack->mRsmpInUnrel;
4911 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004912 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004913 ALOGV("not enough to resample: have %u frames in but need %u in to "
4914 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004915 framesIn, framesInNeeded, framesOut, inOverOut);
4916 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004917 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4918 if (newFramesOut == 0) {
4919 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004920 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004921 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4922 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4923 framesInNeeded, newFramesOut, outOverIn);
4924 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4925 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4926 "given in/out ratio of %.4g",
4927 framesIn, framesInNeeded, newFramesOut, inOverOut);
4928 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004929 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004930 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004931 "given in/out ratio of %.4g",
4932 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004933 }
4934
4935 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4936 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004937 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004938 delete[] activeTrack->mRsmpOutBuffer;
4939 // resampler always outputs stereo
4940 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4941 activeTrack->mRsmpOutFrameCount = framesOut;
4942 }
4943
4944 // resampler accumulates, but we only have one source track
4945 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4946 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004947 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004948 activeTrack->mResamplerBufferProvider
4949 /*this*/ /* AudioBufferProvider* */);
4950 // ditherAndClamp() works as long as all buffers returned by
4951 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004952 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07004953 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004954 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4955 framesOut);
4956 // the resampler always outputs stereo samples:
4957 // do post stereo to mono conversion
4958 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4959 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4960 } else {
4961 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4962 activeTrack->mRsmpOutBuffer, framesOut);
4963 }
4964 // now done with mRsmpOutBuffer
4965
4966 }
4967
4968 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4969 overrun = OVERRUN_FALSE;
4970 }
4971
4972 if (activeTrack->mFramesToDrop == 0) {
4973 if (framesOut > 0) {
4974 activeTrack->mSink.frameCount = framesOut;
4975 activeTrack->releaseBuffer(&activeTrack->mSink);
4976 }
4977 } else {
4978 // FIXME could do a partial drop of framesOut
4979 if (activeTrack->mFramesToDrop > 0) {
4980 activeTrack->mFramesToDrop -= framesOut;
4981 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004982 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004983 }
4984 } else {
4985 activeTrack->mFramesToDrop += framesOut;
4986 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
4987 activeTrack->mSyncStartEvent->isCancelled()) {
4988 ALOGW("Synced record %s, session %d, trigger session %d",
4989 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
4990 activeTrack->sessionId(),
4991 (activeTrack->mSyncStartEvent != 0) ?
4992 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004993 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004994 }
4995 }
4996 }
4997
4998 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004999 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005000 }
5001 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005002
5003 switch (overrun) {
5004 case OVERRUN_TRUE:
5005 // client isn't retrieving buffers fast enough
5006 if (!activeTrack->setOverflow()) {
5007 nsecs_t now = systemTime();
5008 // FIXME should lastWarning per track?
5009 if ((now - lastWarning) > kWarningThrottleNs) {
5010 ALOGW("RecordThread: buffer overflow");
5011 lastWarning = now;
5012 }
5013 }
5014 break;
5015 case OVERRUN_FALSE:
5016 activeTrack->clearOverflow();
5017 break;
5018 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005019 break;
5020 }
5021
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005022 }
5023
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // enable changes in effect chain
5025 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005026 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005027 }
5028
Glenn Kasten93e471f2013-08-19 08:40:07 -07005029 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005030
5031 {
5032 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005033 for (size_t i = 0; i < mTracks.size(); i++) {
5034 sp<RecordTrack> track = mTracks[i];
5035 track->invalidate();
5036 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005037 mActiveTracks.clear();
5038 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005039 mStartStopCond.broadcast();
5040 }
5041
5042 releaseWakeLock();
5043
5044 ALOGV("RecordThread %p exiting", this);
5045 return false;
5046}
5047
Glenn Kasten93e471f2013-08-19 08:40:07 -07005048void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005049{
5050 if (!mStandby) {
5051 inputStandBy();
5052 mStandby = true;
5053 }
5054}
5055
5056void AudioFlinger::RecordThread::inputStandBy()
5057{
5058 mInput->stream->common.standby(&mInput->stream->common);
5059}
5060
Glenn Kasten05997e22014-03-13 15:08:33 -07005061// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005062sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005063 const sp<AudioFlinger::Client>& client,
5064 uint32_t sampleRate,
5065 audio_format_t format,
5066 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005067 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005068 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005069 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005070 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005071 pid_t tid,
5072 status_t *status)
5073{
Glenn Kasten74935e42013-12-19 08:56:45 -08005074 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005075 sp<RecordTrack> track;
5076 status_t lStatus;
5077
Glenn Kasten90e58b12013-07-31 16:16:02 -07005078 // client expresses a preference for FAST, but we get the final say
5079 if (*flags & IAudioFlinger::TRACK_FAST) {
5080 if (
5081 // use case: callback handler and frame count is default or at least as large as HAL
5082 (
5083 (tid != -1) &&
5084 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005085 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005086 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005087 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005088 // PCM data
5089 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005090 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005091 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5092 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005093 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005094 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005095 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005096 // record thread has an associated fast capture
5097 hasFastCapture()
5098 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005099 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005100 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005101 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005102 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005103 frameCount = mFrameCount * kFastTrackMultiplier;
5104 }
5105 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5106 frameCount, mFrameCount);
5107 } else {
5108 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5109 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005110 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005111 frameCount, mFrameCount, format,
5112 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005113 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005114 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005115 // 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 -07005116 // For compatibility with AudioRecord calculation, buffer depth is forced
5117 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5118 // This is probably too conservative, but legacy application code may depend on it.
5119 // If you change this calculation, also review the start threshold which is related.
5120 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5121 size_t mNormalFrameCount = 2048; // FIXME
5122 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5123 if (minBufCount < 2) {
5124 minBufCount = 2;
5125 }
5126 size_t minFrameCount = mNormalFrameCount * minBufCount;
5127 if (frameCount < minFrameCount) {
5128 frameCount = minFrameCount;
5129 }
5130 }
5131 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005132 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005133
Glenn Kasten15e57982013-09-24 11:52:37 -07005134 lStatus = initCheck();
5135 if (lStatus != NO_ERROR) {
5136 ALOGE("createRecordTrack_l() audio driver not initialized");
5137 goto Exit;
5138 }
Eric Laurent81784c32012-11-19 14:55:58 -08005139
5140 { // scope for mLock
5141 Mutex::Autolock _l(mLock);
5142
5143 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005144 format, channelMask, frameCount, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07005145 *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08005146
Glenn Kasten03003332013-08-06 15:40:54 -07005147 lStatus = track->initCheck();
5148 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005149 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005150 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005151 goto Exit;
5152 }
5153 mTracks.add(track);
5154
5155 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5156 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5157 mAudioFlinger->btNrecIsOff();
5158 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5159 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005160
5161 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5162 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5163 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5164 // so ask activity manager to do this on our behalf
5165 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5166 }
Eric Laurent81784c32012-11-19 14:55:58 -08005167 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005168
Eric Laurent81784c32012-11-19 14:55:58 -08005169 lStatus = NO_ERROR;
5170
5171Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005172 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005173 return track;
5174}
5175
5176status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5177 AudioSystem::sync_event_t event,
5178 int triggerSession)
5179{
5180 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5181 sp<ThreadBase> strongMe = this;
5182 status_t status = NO_ERROR;
5183
5184 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005185 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005186 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005187 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005188 triggerSession,
5189 recordTrack->sessionId(),
5190 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005191 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005192 // Sync event can be cancelled by the trigger session if the track is not in a
5193 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005194 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005195 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005196 } else {
5197 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005198 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005199 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005200 }
5201 }
5202
5203 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005204 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005205 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005206 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5207 if (recordTrack->mState == TrackBase::PAUSING) {
5208 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005209 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005210 } else {
5211 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005212 }
5213 return status;
5214 }
5215
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005216 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5217 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5218 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005219 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005220 mActiveTracks.add(recordTrack);
5221 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005222 mLock.unlock();
5223 status_t status = AudioSystem::startInput(mId);
5224 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005225 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005226 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005227 mActiveTracks.remove(recordTrack);
5228 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005229 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005230 return status;
5231 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005232 // Catch up with current buffer indices if thread is already running.
5233 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5234 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5235 // see previously buffered data before it called start(), but with greater risk of overrun.
5236
5237 recordTrack->mRsmpInFront = mRsmpInRear;
5238 recordTrack->mRsmpInUnrel = 0;
5239 // FIXME why reset?
5240 if (recordTrack->mResampler != NULL) {
5241 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005242 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005243 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005244 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005245 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005246 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005247 ALOGV("Record failed to start");
5248 status = BAD_VALUE;
5249 goto startError;
5250 }
Eric Laurent81784c32012-11-19 14:55:58 -08005251 return status;
5252 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005253
Eric Laurent81784c32012-11-19 14:55:58 -08005254startError:
5255 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005256 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005257 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005258 return status;
5259}
5260
Eric Laurent81784c32012-11-19 14:55:58 -08005261void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5262{
5263 sp<SyncEvent> strongEvent = event.promote();
5264
5265 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005266 sp<RefBase> ptr = strongEvent->cookie().promote();
5267 if (ptr != 0) {
5268 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5269 recordTrack->handleSyncStartEvent(strongEvent);
5270 }
Eric Laurent81784c32012-11-19 14:55:58 -08005271 }
5272}
5273
Glenn Kastena8356f62013-07-25 14:37:52 -07005274bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005275 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005276 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005277 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005278 return false;
5279 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005280 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005281 recordTrack->mState = TrackBase::PAUSING;
5282 // do not wait for mStartStopCond if exiting
5283 if (exitPending()) {
5284 return true;
5285 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005286 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005287 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005288 // if we have been restarted, recordTrack is in mActiveTracks here
5289 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005290 ALOGV("Record stopped OK");
5291 return true;
5292 }
5293 return false;
5294}
5295
Glenn Kasten0f11b512014-01-31 16:18:54 -08005296bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005297{
5298 return false;
5299}
5300
Glenn Kasten0f11b512014-01-31 16:18:54 -08005301status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005302{
5303#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5304 if (!isValidSyncEvent(event)) {
5305 return BAD_VALUE;
5306 }
5307
5308 int eventSession = event->triggerSession();
5309 status_t ret = NAME_NOT_FOUND;
5310
5311 Mutex::Autolock _l(mLock);
5312
5313 for (size_t i = 0; i < mTracks.size(); i++) {
5314 sp<RecordTrack> track = mTracks[i];
5315 if (eventSession == track->sessionId()) {
5316 (void) track->setSyncEvent(event);
5317 ret = NO_ERROR;
5318 }
5319 }
5320 return ret;
5321#else
5322 return BAD_VALUE;
5323#endif
5324}
5325
5326// destroyTrack_l() must be called with ThreadBase::mLock held
5327void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5328{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 track->terminate();
5330 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005331 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005332 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005333 removeTrack_l(track);
5334 }
5335}
5336
5337void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5338{
5339 mTracks.remove(track);
5340 // need anything related to effects here?
5341}
5342
5343void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5344{
5345 dumpInternals(fd, args);
5346 dumpTracks(fd, args);
5347 dumpEffectChains(fd, args);
5348}
5349
5350void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5351{
Marco Nelissenb2208842014-02-07 14:00:50 -08005352 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005353
Glenn Kasten2b806402013-11-20 16:37:38 -08005354 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005355 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005356 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005357 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005358 }
5359
Eric Laurent81784c32012-11-19 14:55:58 -08005360 dumpBase(fd, args);
5361}
5362
Glenn Kasten0f11b512014-01-31 16:18:54 -08005363void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005364{
5365 const size_t SIZE = 256;
5366 char buffer[SIZE];
5367 String8 result;
5368
Marco Nelissenb2208842014-02-07 14:00:50 -08005369 size_t numtracks = mTracks.size();
5370 size_t numactive = mActiveTracks.size();
5371 size_t numactiveseen = 0;
5372 fdprintf(fd, " %d Tracks", numtracks);
5373 if (numtracks) {
5374 fdprintf(fd, " of which %d are active\n", numactive);
5375 RecordTrack::appendDumpHeader(result);
5376 for (size_t i = 0; i < numtracks ; ++i) {
5377 sp<RecordTrack> track = mTracks[i];
5378 if (track != 0) {
5379 bool active = mActiveTracks.indexOf(track) >= 0;
5380 if (active) {
5381 numactiveseen++;
5382 }
5383 track->dump(buffer, SIZE, active);
5384 result.append(buffer);
5385 }
Eric Laurent81784c32012-11-19 14:55:58 -08005386 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005387 } else {
5388 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005389 }
5390
Marco Nelissenb2208842014-02-07 14:00:50 -08005391 if (numactiveseen != numactive) {
5392 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5393 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005394 result.append(buffer);
5395 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005396 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005397 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005398 if (mTracks.indexOf(track) < 0) {
5399 track->dump(buffer, SIZE, true);
5400 result.append(buffer);
5401 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005402 }
Eric Laurent81784c32012-11-19 14:55:58 -08005403
5404 }
5405 write(fd, result.string(), result.size());
5406}
5407
5408// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005409status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5410 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005411{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005412 RecordTrack *activeTrack = mRecordTrack;
5413 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5414 if (threadBase == 0) {
5415 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005416 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005417 return NOT_ENOUGH_DATA;
5418 }
5419 RecordThread *recordThread = (RecordThread *) threadBase.get();
5420 int32_t rear = recordThread->mRsmpInRear;
5421 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005422 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005423 // FIXME should not be P2 (don't want to increase latency)
5424 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005425 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005426 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005427 front &= recordThread->mRsmpInFramesP2 - 1;
5428 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005429 if (part1 > (size_t) filled) {
5430 part1 = filled;
5431 }
5432 size_t ask = buffer->frameCount;
5433 ALOG_ASSERT(ask > 0);
5434 if (part1 > ask) {
5435 part1 = ask;
5436 }
5437 if (part1 == 0) {
5438 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005439 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005440 buffer->raw = NULL;
5441 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005442 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005443 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005444 }
5445
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005446 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005447 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005448 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005449 return NO_ERROR;
5450}
5451
5452// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005453void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5454 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005455{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005456 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005457 size_t stepCount = buffer->frameCount;
5458 if (stepCount == 0) {
5459 return;
5460 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005461 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5462 activeTrack->mRsmpInUnrel -= stepCount;
5463 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005464 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005465 buffer->frameCount = 0;
5466}
5467
Eric Laurent10351942014-05-08 18:49:52 -07005468bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5469 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005470{
5471 bool reconfig = false;
5472
Eric Laurent10351942014-05-08 18:49:52 -07005473 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005474
Eric Laurent10351942014-05-08 18:49:52 -07005475 audio_format_t reqFormat = mFormat;
5476 uint32_t samplingRate = mSampleRate;
5477 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5478
5479 AudioParameter param = AudioParameter(keyValuePair);
5480 int value;
5481 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5482 // channel count change can be requested. Do we mandate the first client defines the
5483 // HAL sampling rate and channel count or do we allow changes on the fly?
5484 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5485 samplingRate = value;
5486 reconfig = true;
5487 }
5488 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5489 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5490 status = BAD_VALUE;
5491 } else {
5492 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005493 reconfig = true;
5494 }
Eric Laurent10351942014-05-08 18:49:52 -07005495 }
5496 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5497 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5498 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5499 status = BAD_VALUE;
5500 } else {
5501 channelMask = mask;
5502 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005503 }
Eric Laurent10351942014-05-08 18:49:52 -07005504 }
5505 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5506 // do not accept frame count changes if tracks are open as the track buffer
5507 // size depends on frame count and correct behavior would not be guaranteed
5508 // if frame count is changed after track creation
5509 if (mActiveTracks.size() > 0) {
5510 status = INVALID_OPERATION;
5511 } else {
5512 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005513 }
Eric Laurent10351942014-05-08 18:49:52 -07005514 }
5515 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5516 // forward device change to effects that have requested to be
5517 // aware of attached audio device.
5518 for (size_t i = 0; i < mEffectChains.size(); i++) {
5519 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005520 }
Eric Laurent81784c32012-11-19 14:55:58 -08005521
Eric Laurent10351942014-05-08 18:49:52 -07005522 // store input device and output device but do not forward output device to audio HAL.
5523 // Note that status is ignored by the caller for output device
5524 // (see AudioFlinger::setParameters()
5525 if (audio_is_output_devices(value)) {
5526 mOutDevice = value;
5527 status = BAD_VALUE;
5528 } else {
5529 mInDevice = value;
5530 // disable AEC and NS if the device is a BT SCO headset supporting those
5531 // pre processings
5532 if (mTracks.size() > 0) {
5533 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5534 mAudioFlinger->btNrecIsOff();
5535 for (size_t i = 0; i < mTracks.size(); i++) {
5536 sp<RecordTrack> track = mTracks[i];
5537 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5538 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005539 }
5540 }
5541 }
Eric Laurent10351942014-05-08 18:49:52 -07005542 }
5543 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5544 mAudioSource != (audio_source_t)value) {
5545 // forward device change to effects that have requested to be
5546 // aware of attached audio device.
5547 for (size_t i = 0; i < mEffectChains.size(); i++) {
5548 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005549 }
Eric Laurent10351942014-05-08 18:49:52 -07005550 mAudioSource = (audio_source_t)value;
5551 }
Glenn Kastene198c362013-08-13 09:13:36 -07005552
Eric Laurent10351942014-05-08 18:49:52 -07005553 if (status == NO_ERROR) {
5554 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5555 keyValuePair.string());
5556 if (status == INVALID_OPERATION) {
5557 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005558 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5559 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005560 }
5561 if (reconfig) {
5562 if (status == BAD_VALUE &&
5563 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5564 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5565 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5566 <= (2 * samplingRate)) &&
5567 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5568 <= FCC_2 &&
5569 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5570 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5571 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005572 }
Eric Laurent10351942014-05-08 18:49:52 -07005573 if (status == NO_ERROR) {
5574 readInputParameters_l();
5575 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005576 }
5577 }
Eric Laurent81784c32012-11-19 14:55:58 -08005578 }
Eric Laurent10351942014-05-08 18:49:52 -07005579
Eric Laurent81784c32012-11-19 14:55:58 -08005580 return reconfig;
5581}
5582
5583String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5584{
Eric Laurent81784c32012-11-19 14:55:58 -08005585 Mutex::Autolock _l(mLock);
5586 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005587 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
5589
Glenn Kastend8ea6992013-07-16 14:17:15 -07005590 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5591 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005592 free(s);
5593 return out_s8;
5594}
5595
Eric Laurent021cf962014-05-13 10:18:14 -07005596void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005597 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005598 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005599
5600 switch (event) {
5601 case AudioSystem::INPUT_OPENED:
5602 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005603 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005604 desc.samplingRate = mSampleRate;
5605 desc.format = mFormat;
5606 desc.frameCount = mFrameCount;
5607 desc.latency = 0;
5608 param2 = &desc;
5609 break;
5610
5611 case AudioSystem::INPUT_CLOSED:
5612 default:
5613 break;
5614 }
Eric Laurent021cf962014-05-13 10:18:14 -07005615 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005616}
5617
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005618void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005619{
Eric Laurent81784c32012-11-19 14:55:58 -08005620 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5621 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005622 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005624 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005625 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005626 }
Eric Laurent81784c32012-11-19 14:55:58 -08005627 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005628 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5629 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005630 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005631 // 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 -07005632 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005633 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 // A larger value should allow more old data to be read after a track calls start(),
5635 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005636 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005637 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005638 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005639 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5640 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005641
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005642 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5643 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005644}
5645
Glenn Kasten5f972c02014-01-13 09:59:31 -08005646uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005647{
5648 Mutex::Autolock _l(mLock);
5649 if (initCheck() != NO_ERROR) {
5650 return 0;
5651 }
5652
5653 return mInput->stream->get_input_frames_lost(mInput->stream);
5654}
5655
5656uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5657{
5658 Mutex::Autolock _l(mLock);
5659 uint32_t result = 0;
5660 if (getEffectChain_l(sessionId) != 0) {
5661 result = EFFECT_SESSION;
5662 }
5663
5664 for (size_t i = 0; i < mTracks.size(); ++i) {
5665 if (sessionId == mTracks[i]->sessionId()) {
5666 result |= TRACK_SESSION;
5667 break;
5668 }
5669 }
5670
5671 return result;
5672}
5673
5674KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5675{
5676 KeyedVector<int, bool> ids;
5677 Mutex::Autolock _l(mLock);
5678 for (size_t j = 0; j < mTracks.size(); ++j) {
5679 sp<RecordThread::RecordTrack> track = mTracks[j];
5680 int sessionId = track->sessionId();
5681 if (ids.indexOfKey(sessionId) < 0) {
5682 ids.add(sessionId, true);
5683 }
5684 }
5685 return ids;
5686}
5687
5688AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5689{
5690 Mutex::Autolock _l(mLock);
5691 AudioStreamIn *input = mInput;
5692 mInput = NULL;
5693 return input;
5694}
5695
5696// this method must always be called either with ThreadBase mLock held or inside the thread loop
5697audio_stream_t* AudioFlinger::RecordThread::stream() const
5698{
5699 if (mInput == NULL) {
5700 return NULL;
5701 }
5702 return &mInput->stream->common;
5703}
5704
5705status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5706{
5707 // only one chain per input thread
5708 if (mEffectChains.size() != 0) {
5709 return INVALID_OPERATION;
5710 }
5711 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5712
5713 chain->setInBuffer(NULL);
5714 chain->setOutBuffer(NULL);
5715
5716 checkSuspendOnAddEffectChain_l(chain);
5717
5718 mEffectChains.add(chain);
5719
5720 return NO_ERROR;
5721}
5722
5723size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5724{
5725 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5726 ALOGW_IF(mEffectChains.size() != 1,
5727 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5728 chain.get(), mEffectChains.size(), this);
5729 if (mEffectChains.size() == 1) {
5730 mEffectChains.removeAt(0);
5731 }
5732 return 0;
5733}
5734
5735}; // namespace android