blob: 470b01887eabdaacf3d2fea534ce0e08d8111ed5 [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 Laurent10351942014-05-08 18:49:52 -0700404void AudioFlinger::ThreadBase::processConfigEvents_l(
405 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients)
Glenn Kastenf7773312013-08-13 16:00:42 -0700406{
Eric Laurent10351942014-05-08 18:49:52 -0700407 bool configChanged = false;
408
Eric Laurent81784c32012-11-19 14:55:58 -0800409 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700410 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
411 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800412 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700413 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700414 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700415 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
416 // FIXME Need to understand why this has to be done asynchronously
417 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700418 true /*asynchronous*/);
419 if (err != 0) {
420 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700421 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700422 }
423 } break;
424 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700425 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
426 audioConfigChanged_l(notificationClients, data->mEvent, data->mParam);
427 } break;
428 case CFG_EVENT_SET_PARAMETER: {
429 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
430 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
431 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700432 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700433 } break;
434 default:
Eric Laurent10351942014-05-08 18:49:52 -0700435 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700436 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800437 }
Eric Laurent10351942014-05-08 18:49:52 -0700438 {
439 Mutex::Autolock _l(event->mLock);
440 if (event->mWaitStatus) {
441 event->mWaitStatus = false;
442 event->mCond.signal();
443 }
444 }
445 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
446 }
447
448 if (configChanged) {
449 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
Eric Laurent81784c32012-11-19 14:55:58 -0800451}
452
Marco Nelissenb2208842014-02-07 14:00:50 -0800453String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
454 String8 s;
455 if (output) {
456 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
457 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
458 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
459 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
460 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
461 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
462 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
463 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
464 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
465 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
466 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
467 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
468 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
469 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
470 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
471 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
472 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
473 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
474 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
475 } else {
476 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
477 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
478 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
479 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
480 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
481 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
482 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
483 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
484 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
485 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
486 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
487 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
488 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
489 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
490 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
491 }
492 int len = s.length();
493 if (s.length() > 2) {
494 char *str = s.lockBuffer(len);
495 s.unlockBuffer(len - 2);
496 }
497 return s;
498}
499
Glenn Kasten0f11b512014-01-31 16:18:54 -0800500void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800501{
502 const size_t SIZE = 256;
503 char buffer[SIZE];
504 String8 result;
505
506 bool locked = AudioFlinger::dumpTryLock(mLock);
507 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800508 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 }
510
Marco Nelissenb2208842014-02-07 14:00:50 -0800511 fdprintf(fd, " I/O handle: %d\n", mId);
512 fdprintf(fd, " TID: %d\n", getTid());
513 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
514 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000515 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800516 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
517 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
518 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
519 channelMaskToString(mChannelMask, mType != RECORD).string());
520 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000521 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800522 fdprintf(fd, " Pending config events:");
523 size_t numConfig = mConfigEvents.size();
524 if (numConfig) {
525 for (size_t i = 0; i < numConfig; i++) {
526 mConfigEvents[i]->dump(buffer, SIZE);
527 fdprintf(fd, "\n %s", buffer);
528 }
529 fdprintf(fd, "\n");
530 } else {
531 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800532 }
Eric Laurent81784c32012-11-19 14:55:58 -0800533
534 if (locked) {
535 mLock.unlock();
536 }
537}
538
539void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
540{
541 const size_t SIZE = 256;
542 char buffer[SIZE];
543 String8 result;
544
Marco Nelissenb2208842014-02-07 14:00:50 -0800545 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000546 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 write(fd, buffer, strlen(buffer));
548
Marco Nelissenb2208842014-02-07 14:00:50 -0800549 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800550 sp<EffectChain> chain = mEffectChains[i];
551 if (chain != 0) {
552 chain->dump(fd, args);
553 }
554 }
555}
556
Marco Nelissene14a5d62013-10-03 08:51:24 -0700557void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800558{
559 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700560 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800561}
562
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100563String16 AudioFlinger::ThreadBase::getWakeLockTag()
564{
565 switch (mType) {
566 case MIXER:
567 return String16("AudioMix");
568 case DIRECT:
569 return String16("AudioDirectOut");
570 case DUPLICATING:
571 return String16("AudioDup");
572 case RECORD:
573 return String16("AudioIn");
574 case OFFLOAD:
575 return String16("AudioOffload");
576 default:
577 ALOG_ASSERT(false);
578 return String16("AudioUnknown");
579 }
580}
581
Marco Nelissene14a5d62013-10-03 08:51:24 -0700582void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800583{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800584 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800585 if (mPowerManager != 0) {
586 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700587 status_t status;
588 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700589 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700590 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100591 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700592 String16("media"),
593 uid);
594 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700595 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700596 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100597 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700598 String16("media"));
599 }
Eric Laurent81784c32012-11-19 14:55:58 -0800600 if (status == NO_ERROR) {
601 mWakeLockToken = binder;
602 }
603 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
604 }
605}
606
607void AudioFlinger::ThreadBase::releaseWakeLock()
608{
609 Mutex::Autolock _l(mLock);
610 releaseWakeLock_l();
611}
612
613void AudioFlinger::ThreadBase::releaseWakeLock_l()
614{
615 if (mWakeLockToken != 0) {
616 ALOGV("releaseWakeLock_l() %s", mName);
617 if (mPowerManager != 0) {
618 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
619 }
620 mWakeLockToken.clear();
621 }
622}
623
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800624void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
625 Mutex::Autolock _l(mLock);
626 updateWakeLockUids_l(uids);
627}
628
629void AudioFlinger::ThreadBase::getPowerManager_l() {
630
631 if (mPowerManager == 0) {
632 // use checkService() to avoid blocking if power service is not up yet
633 sp<IBinder> binder =
634 defaultServiceManager()->checkService(String16("power"));
635 if (binder == 0) {
636 ALOGW("Thread %s cannot connect to the power manager service", mName);
637 } else {
638 mPowerManager = interface_cast<IPowerManager>(binder);
639 binder->linkToDeath(mDeathRecipient);
640 }
641 }
642}
643
644void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
645
646 getPowerManager_l();
647 if (mWakeLockToken == NULL) {
648 ALOGE("no wake lock to update!");
649 return;
650 }
651 if (mPowerManager != 0) {
652 sp<IBinder> binder = new BBinder();
653 status_t status;
654 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
655 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
656 }
657}
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659void AudioFlinger::ThreadBase::clearPowerManager()
660{
661 Mutex::Autolock _l(mLock);
662 releaseWakeLock_l();
663 mPowerManager.clear();
664}
665
Glenn Kasten0f11b512014-01-31 16:18:54 -0800666void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800667{
668 sp<ThreadBase> thread = mThread.promote();
669 if (thread != 0) {
670 thread->clearPowerManager();
671 }
672 ALOGW("power manager service died !!!");
673}
674
675void AudioFlinger::ThreadBase::setEffectSuspended(
676 const effect_uuid_t *type, bool suspend, int sessionId)
677{
678 Mutex::Autolock _l(mLock);
679 setEffectSuspended_l(type, suspend, sessionId);
680}
681
682void AudioFlinger::ThreadBase::setEffectSuspended_l(
683 const effect_uuid_t *type, bool suspend, int sessionId)
684{
685 sp<EffectChain> chain = getEffectChain_l(sessionId);
686 if (chain != 0) {
687 if (type != NULL) {
688 chain->setEffectSuspended_l(type, suspend);
689 } else {
690 chain->setEffectSuspendedAll_l(suspend);
691 }
692 }
693
694 updateSuspendedSessions_l(type, suspend, sessionId);
695}
696
697void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
698{
699 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
700 if (index < 0) {
701 return;
702 }
703
704 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
705 mSuspendedSessions.valueAt(index);
706
707 for (size_t i = 0; i < sessionEffects.size(); i++) {
708 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
709 for (int j = 0; j < desc->mRefCount; j++) {
710 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
711 chain->setEffectSuspendedAll_l(true);
712 } else {
713 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
714 desc->mType.timeLow);
715 chain->setEffectSuspended_l(&desc->mType, true);
716 }
717 }
718 }
719}
720
721void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
722 bool suspend,
723 int sessionId)
724{
725 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
726
727 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
728
729 if (suspend) {
730 if (index >= 0) {
731 sessionEffects = mSuspendedSessions.valueAt(index);
732 } else {
733 mSuspendedSessions.add(sessionId, sessionEffects);
734 }
735 } else {
736 if (index < 0) {
737 return;
738 }
739 sessionEffects = mSuspendedSessions.valueAt(index);
740 }
741
742
743 int key = EffectChain::kKeyForSuspendAll;
744 if (type != NULL) {
745 key = type->timeLow;
746 }
747 index = sessionEffects.indexOfKey(key);
748
749 sp<SuspendedSessionDesc> desc;
750 if (suspend) {
751 if (index >= 0) {
752 desc = sessionEffects.valueAt(index);
753 } else {
754 desc = new SuspendedSessionDesc();
755 if (type != NULL) {
756 desc->mType = *type;
757 }
758 sessionEffects.add(key, desc);
759 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
760 }
761 desc->mRefCount++;
762 } else {
763 if (index < 0) {
764 return;
765 }
766 desc = sessionEffects.valueAt(index);
767 if (--desc->mRefCount == 0) {
768 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
769 sessionEffects.removeItemsAt(index);
770 if (sessionEffects.isEmpty()) {
771 ALOGV("updateSuspendedSessions_l() restore removing session %d",
772 sessionId);
773 mSuspendedSessions.removeItem(sessionId);
774 }
775 }
776 }
777 if (!sessionEffects.isEmpty()) {
778 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
779 }
780}
781
782void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
783 bool enabled,
784 int sessionId)
785{
786 Mutex::Autolock _l(mLock);
787 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
788}
789
790void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
791 bool enabled,
792 int sessionId)
793{
794 if (mType != RECORD) {
795 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
796 // another session. This gives the priority to well behaved effect control panels
797 // and applications not using global effects.
798 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
799 // global effects
800 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
801 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
802 }
803 }
804
805 sp<EffectChain> chain = getEffectChain_l(sessionId);
806 if (chain != 0) {
807 chain->checkSuspendOnEffectEnabled(effect, enabled);
808 }
809}
810
811// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
812sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
813 const sp<AudioFlinger::Client>& client,
814 const sp<IEffectClient>& effectClient,
815 int32_t priority,
816 int sessionId,
817 effect_descriptor_t *desc,
818 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700819 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800820{
821 sp<EffectModule> effect;
822 sp<EffectHandle> handle;
823 status_t lStatus;
824 sp<EffectChain> chain;
825 bool chainCreated = false;
826 bool effectCreated = false;
827 bool effectRegistered = false;
828
829 lStatus = initCheck();
830 if (lStatus != NO_ERROR) {
831 ALOGW("createEffect_l() Audio driver not initialized.");
832 goto Exit;
833 }
834
Andy Hung98ef9782014-03-04 14:46:50 -0800835 // Reject any effect on Direct output threads for now, since the format of
836 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
837 if (mType == DIRECT) {
838 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
839 desc->name, mName);
840 lStatus = BAD_VALUE;
841 goto Exit;
842 }
843
Eric Laurent5baf2af2013-09-12 17:37:00 -0700844 // Allow global effects only on offloaded and mixer threads
845 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
846 switch (mType) {
847 case MIXER:
848 case OFFLOAD:
849 break;
850 case DIRECT:
851 case DUPLICATING:
852 case RECORD:
853 default:
854 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
855 lStatus = BAD_VALUE;
856 goto Exit;
857 }
Eric Laurent81784c32012-11-19 14:55:58 -0800858 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700859
Eric Laurent81784c32012-11-19 14:55:58 -0800860 // Only Pre processor effects are allowed on input threads and only on input threads
861 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
862 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
863 desc->name, desc->flags, mType);
864 lStatus = BAD_VALUE;
865 goto Exit;
866 }
867
868 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
869
870 { // scope for mLock
871 Mutex::Autolock _l(mLock);
872
873 // check for existing effect chain with the requested audio session
874 chain = getEffectChain_l(sessionId);
875 if (chain == 0) {
876 // create a new chain for this session
877 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
878 chain = new EffectChain(this, sessionId);
879 addEffectChain_l(chain);
880 chain->setStrategy(getStrategyForSession_l(sessionId));
881 chainCreated = true;
882 } else {
883 effect = chain->getEffectFromDesc_l(desc);
884 }
885
886 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
887
888 if (effect == 0) {
889 int id = mAudioFlinger->nextUniqueId();
890 // Check CPU and memory usage
891 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
892 if (lStatus != NO_ERROR) {
893 goto Exit;
894 }
895 effectRegistered = true;
896 // create a new effect module if none present in the chain
897 effect = new EffectModule(this, chain, desc, id, sessionId);
898 lStatus = effect->status();
899 if (lStatus != NO_ERROR) {
900 goto Exit;
901 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700902 effect->setOffloaded(mType == OFFLOAD, mId);
903
Eric Laurent81784c32012-11-19 14:55:58 -0800904 lStatus = chain->addEffect_l(effect);
905 if (lStatus != NO_ERROR) {
906 goto Exit;
907 }
908 effectCreated = true;
909
910 effect->setDevice(mOutDevice);
911 effect->setDevice(mInDevice);
912 effect->setMode(mAudioFlinger->getMode());
913 effect->setAudioSource(mAudioSource);
914 }
915 // create effect handle and connect it to effect module
916 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800917 lStatus = handle->initCheck();
918 if (lStatus == OK) {
919 lStatus = effect->addHandle(handle.get());
920 }
Eric Laurent81784c32012-11-19 14:55:58 -0800921 if (enabled != NULL) {
922 *enabled = (int)effect->isEnabled();
923 }
924 }
925
926Exit:
927 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
928 Mutex::Autolock _l(mLock);
929 if (effectCreated) {
930 chain->removeEffect_l(effect);
931 }
932 if (effectRegistered) {
933 AudioSystem::unregisterEffect(effect->id());
934 }
935 if (chainCreated) {
936 removeEffectChain_l(chain);
937 }
938 handle.clear();
939 }
940
Glenn Kasten9156ef32013-08-06 15:39:08 -0700941 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800942 return handle;
943}
944
945sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
946{
947 Mutex::Autolock _l(mLock);
948 return getEffect_l(sessionId, effectId);
949}
950
951sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
952{
953 sp<EffectChain> chain = getEffectChain_l(sessionId);
954 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
955}
956
957// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
958// PlaybackThread::mLock held
959status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
960{
961 // check for existing effect chain with the requested audio session
962 int sessionId = effect->sessionId();
963 sp<EffectChain> chain = getEffectChain_l(sessionId);
964 bool chainCreated = false;
965
Eric Laurent5baf2af2013-09-12 17:37:00 -0700966 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
967 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
968 this, effect->desc().name, effect->desc().flags);
969
Eric Laurent81784c32012-11-19 14:55:58 -0800970 if (chain == 0) {
971 // create a new chain for this session
972 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
973 chain = new EffectChain(this, sessionId);
974 addEffectChain_l(chain);
975 chain->setStrategy(getStrategyForSession_l(sessionId));
976 chainCreated = true;
977 }
978 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
979
980 if (chain->getEffectFromId_l(effect->id()) != 0) {
981 ALOGW("addEffect_l() %p effect %s already present in chain %p",
982 this, effect->desc().name, chain.get());
983 return BAD_VALUE;
984 }
985
Eric Laurent5baf2af2013-09-12 17:37:00 -0700986 effect->setOffloaded(mType == OFFLOAD, mId);
987
Eric Laurent81784c32012-11-19 14:55:58 -0800988 status_t status = chain->addEffect_l(effect);
989 if (status != NO_ERROR) {
990 if (chainCreated) {
991 removeEffectChain_l(chain);
992 }
993 return status;
994 }
995
996 effect->setDevice(mOutDevice);
997 effect->setDevice(mInDevice);
998 effect->setMode(mAudioFlinger->getMode());
999 effect->setAudioSource(mAudioSource);
1000 return NO_ERROR;
1001}
1002
1003void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1004
1005 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1006 effect_descriptor_t desc = effect->desc();
1007 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1008 detachAuxEffect_l(effect->id());
1009 }
1010
1011 sp<EffectChain> chain = effect->chain().promote();
1012 if (chain != 0) {
1013 // remove effect chain if removing last effect
1014 if (chain->removeEffect_l(effect) == 0) {
1015 removeEffectChain_l(chain);
1016 }
1017 } else {
1018 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1019 }
1020}
1021
1022void AudioFlinger::ThreadBase::lockEffectChains_l(
1023 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1024{
1025 effectChains = mEffectChains;
1026 for (size_t i = 0; i < mEffectChains.size(); i++) {
1027 mEffectChains[i]->lock();
1028 }
1029}
1030
1031void AudioFlinger::ThreadBase::unlockEffectChains(
1032 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1033{
1034 for (size_t i = 0; i < effectChains.size(); i++) {
1035 effectChains[i]->unlock();
1036 }
1037}
1038
1039sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1040{
1041 Mutex::Autolock _l(mLock);
1042 return getEffectChain_l(sessionId);
1043}
1044
1045sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1046{
1047 size_t size = mEffectChains.size();
1048 for (size_t i = 0; i < size; i++) {
1049 if (mEffectChains[i]->sessionId() == sessionId) {
1050 return mEffectChains[i];
1051 }
1052 }
1053 return 0;
1054}
1055
1056void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1057{
1058 Mutex::Autolock _l(mLock);
1059 size_t size = mEffectChains.size();
1060 for (size_t i = 0; i < size; i++) {
1061 mEffectChains[i]->setMode_l(mode);
1062 }
1063}
1064
1065void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1066 EffectHandle *handle,
1067 bool unpinIfLast) {
1068
1069 Mutex::Autolock _l(mLock);
1070 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1071 // delete the effect module if removing last handle on it
1072 if (effect->removeHandle(handle) == 0) {
1073 if (!effect->isPinned() || unpinIfLast) {
1074 removeEffect_l(effect);
1075 AudioSystem::unregisterEffect(effect->id());
1076 }
1077 }
1078}
1079
1080// ----------------------------------------------------------------------------
1081// Playback
1082// ----------------------------------------------------------------------------
1083
1084AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1085 AudioStreamOut* output,
1086 audio_io_handle_t id,
1087 audio_devices_t device,
1088 type_t type)
1089 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001090 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001091 mMixerBufferEnabled(false),
1092 mMixerBuffer(NULL),
1093 mMixerBufferSize(0),
1094 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1095 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001096 mEffectBufferEnabled(false),
1097 mEffectBuffer(NULL),
1098 mEffectBufferSize(0),
1099 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1100 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001101 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001103 // mStreamTypes[] initialized in constructor body
1104 mOutput(output),
1105 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1106 mMixerStatus(MIXER_IDLE),
1107 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1108 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001109 mBytesRemaining(0),
1110 mCurrentWriteLength(0),
1111 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001112 mWriteAckSequence(0),
1113 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001114 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001115 mScreenState(AudioFlinger::mScreenState),
1116 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001117 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1118 // mLatchD, mLatchQ,
1119 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001120{
1121 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001122 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001123
1124 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1125 // it would be safer to explicitly pass initial masterVolume/masterMute as
1126 // parameter.
1127 //
1128 // If the HAL we are using has support for master volume or master mute,
1129 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1130 // and the mute set to false).
1131 mMasterVolume = audioFlinger->masterVolume_l();
1132 mMasterMute = audioFlinger->masterMute_l();
1133 if (mOutput && mOutput->audioHwDev) {
1134 if (mOutput->audioHwDev->canSetMasterVolume()) {
1135 mMasterVolume = 1.0;
1136 }
1137
1138 if (mOutput->audioHwDev->canSetMasterMute()) {
1139 mMasterMute = false;
1140 }
1141 }
1142
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001143 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001144
1145 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1146 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001147 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001148 stream = (audio_stream_type_t) (stream + 1)) {
1149 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1150 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1151 }
1152 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1153 // because mAudioFlinger doesn't have one to copy from
1154}
1155
1156AudioFlinger::PlaybackThread::~PlaybackThread()
1157{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001158 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001159 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001160 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001161 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001162}
1163
1164void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1165{
1166 dumpInternals(fd, args);
1167 dumpTracks(fd, args);
1168 dumpEffectChains(fd, args);
1169}
1170
Glenn Kasten0f11b512014-01-31 16:18:54 -08001171void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001172{
1173 const size_t SIZE = 256;
1174 char buffer[SIZE];
1175 String8 result;
1176
Marco Nelissenb2208842014-02-07 14:00:50 -08001177 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001178 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1179 const stream_type_t *st = &mStreamTypes[i];
1180 if (i > 0) {
1181 result.appendFormat(", ");
1182 }
1183 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1184 if (st->mute) {
1185 result.append("M");
1186 }
1187 }
1188 result.append("\n");
1189 write(fd, result.string(), result.length());
1190 result.clear();
1191
Eric Laurent81784c32012-11-19 14:55:58 -08001192 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1193 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001194 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001195 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001196
1197 size_t numtracks = mTracks.size();
1198 size_t numactive = mActiveTracks.size();
1199 fdprintf(fd, " %d Tracks", numtracks);
1200 size_t numactiveseen = 0;
1201 if (numtracks) {
1202 fdprintf(fd, " of which %d are active\n", numactive);
1203 Track::appendDumpHeader(result);
1204 for (size_t i = 0; i < numtracks; ++i) {
1205 sp<Track> track = mTracks[i];
1206 if (track != 0) {
1207 bool active = mActiveTracks.indexOf(track) >= 0;
1208 if (active) {
1209 numactiveseen++;
1210 }
1211 track->dump(buffer, SIZE, active);
1212 result.append(buffer);
1213 }
1214 }
1215 } else {
1216 result.append("\n");
1217 }
1218 if (numactiveseen != numactive) {
1219 // some tracks in the active list were not in the tracks list
1220 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1221 " not in the track list\n");
1222 result.append(buffer);
1223 Track::appendDumpHeader(result);
1224 for (size_t i = 0; i < numactive; ++i) {
1225 sp<Track> track = mActiveTracks[i].promote();
1226 if (track != 0 && mTracks.indexOf(track) < 0) {
1227 track->dump(buffer, SIZE, true);
1228 result.append(buffer);
1229 }
1230 }
1231 }
1232
1233 write(fd, result.string(), result.size());
1234
Eric Laurent81784c32012-11-19 14:55:58 -08001235}
1236
1237void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1238{
Marco Nelissenb2208842014-02-07 14:00:50 -08001239 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001240 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001241 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1242 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1243 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1244 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1245 fdprintf(fd, " Suspend count: %d\n", mSuspended);
Andy Hung2098f272014-02-27 14:00:06 -08001246 fdprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001247 fdprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001248 fdprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001249 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001250
1251 dumpBase(fd, args);
1252}
1253
1254// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001255
1256void AudioFlinger::PlaybackThread::onFirstRef()
1257{
1258 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1259}
1260
1261// ThreadBase virtuals
1262void AudioFlinger::PlaybackThread::preExit()
1263{
1264 ALOGV(" preExit()");
1265 // FIXME this is using hard-coded strings but in the future, this functionality will be
1266 // converted to use audio HAL extensions required to support tunneling
1267 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1268}
1269
1270// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1271sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1272 const sp<AudioFlinger::Client>& client,
1273 audio_stream_type_t streamType,
1274 uint32_t sampleRate,
1275 audio_format_t format,
1276 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001277 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 const sp<IMemory>& sharedBuffer,
1279 int sessionId,
1280 IAudioFlinger::track_flags_t *flags,
1281 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001282 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001283 status_t *status)
1284{
Glenn Kasten74935e42013-12-19 08:56:45 -08001285 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001286 sp<Track> track;
1287 status_t lStatus;
1288
1289 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1290
1291 // client expresses a preference for FAST, but we get the final say
1292 if (*flags & IAudioFlinger::TRACK_FAST) {
1293 if (
1294 // not timed
1295 (!isTimed) &&
1296 // either of these use cases:
1297 (
1298 // use case 1: shared buffer with any frame count
1299 (
1300 (sharedBuffer != 0)
1301 ) ||
1302 // use case 2: callback handler and frame count is default or at least as large as HAL
1303 (
1304 (tid != -1) &&
1305 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001306 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001307 )
1308 ) &&
1309 // PCM data
1310 audio_is_linear_pcm(format) &&
1311 // mono or stereo
1312 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1313 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001314 // hardware sample rate
1315 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001316 // normal mixer has an associated fast mixer
1317 hasFastMixer() &&
1318 // there are sufficient fast track slots available
1319 (mFastTrackAvailMask != 0)
1320 // FIXME test that MixerThread for this fast track has a capable output HAL
1321 // FIXME add a permission test also?
1322 ) {
1323 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1324 if (frameCount == 0) {
1325 frameCount = mFrameCount * kFastTrackMultiplier;
1326 }
1327 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1328 frameCount, mFrameCount);
1329 } else {
1330 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1331 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1332 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1333 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1334 audio_is_linear_pcm(format),
1335 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1336 *flags &= ~IAudioFlinger::TRACK_FAST;
1337 // For compatibility with AudioTrack calculation, buffer depth is forced
1338 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1339 // This is probably too conservative, but legacy application code may depend on it.
1340 // If you change this calculation, also review the start threshold which is related.
1341 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1342 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1343 if (minBufCount < 2) {
1344 minBufCount = 2;
1345 }
1346 size_t minFrameCount = mNormalFrameCount * minBufCount;
1347 if (frameCount < minFrameCount) {
1348 frameCount = minFrameCount;
1349 }
1350 }
1351 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001352 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001353
Glenn Kastenc3df8382014-03-13 15:05:25 -07001354 switch (mType) {
1355
1356 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001357 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001359 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1360 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001361 sampleRate, format, channelMask, mOutput, mFormat);
1362 lStatus = BAD_VALUE;
1363 goto Exit;
1364 }
1365 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001366 break;
1367
1368 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001369 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001370 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1371 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001372 sampleRate, format, channelMask, mOutput, mFormat);
1373 lStatus = BAD_VALUE;
1374 goto Exit;
1375 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001376 break;
1377
1378 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001379 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001380 ALOGE("createTrack_l() Bad parameter: format %#x \""
1381 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001382 format, mOutput, mFormat);
1383 lStatus = BAD_VALUE;
1384 goto Exit;
1385 }
Eric Laurent81784c32012-11-19 14:55:58 -08001386 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1387 if (sampleRate > mSampleRate*2) {
1388 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1389 lStatus = BAD_VALUE;
1390 goto Exit;
1391 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001392 break;
1393
Eric Laurent81784c32012-11-19 14:55:58 -08001394 }
1395
1396 lStatus = initCheck();
1397 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001398 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001399 goto Exit;
1400 }
1401
1402 { // scope for mLock
1403 Mutex::Autolock _l(mLock);
1404
1405 // all tracks in same audio session must share the same routing strategy otherwise
1406 // conflicts will happen when tracks are moved from one output to another by audio policy
1407 // manager
1408 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1409 for (size_t i = 0; i < mTracks.size(); ++i) {
1410 sp<Track> t = mTracks[i];
1411 if (t != 0 && !t->isOutputTrack()) {
1412 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1413 if (sessionId == t->sessionId() && strategy != actual) {
1414 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1415 strategy, actual);
1416 lStatus = BAD_VALUE;
1417 goto Exit;
1418 }
1419 }
1420 }
1421
1422 if (!isTimed) {
1423 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001424 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001425 } else {
1426 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001427 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001428 }
Glenn Kasten03003332013-08-06 15:40:54 -07001429
1430 // new Track always returns non-NULL,
1431 // but TimedTrack::create() is a factory that could fail by returning NULL
1432 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1433 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001434 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001435 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001436 goto Exit;
1437 }
1438 mTracks.add(track);
1439
1440 sp<EffectChain> chain = getEffectChain_l(sessionId);
1441 if (chain != 0) {
1442 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1443 track->setMainBuffer(chain->inBuffer());
1444 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1445 chain->incTrackCnt();
1446 }
1447
1448 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1449 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1450 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1451 // so ask activity manager to do this on our behalf
1452 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1453 }
1454 }
1455
1456 lStatus = NO_ERROR;
1457
1458Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001459 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001460 return track;
1461}
1462
1463uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1464{
1465 return latency;
1466}
1467
1468uint32_t AudioFlinger::PlaybackThread::latency() const
1469{
1470 Mutex::Autolock _l(mLock);
1471 return latency_l();
1472}
1473uint32_t AudioFlinger::PlaybackThread::latency_l() const
1474{
1475 if (initCheck() == NO_ERROR) {
1476 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1477 } else {
1478 return 0;
1479 }
1480}
1481
1482void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1483{
1484 Mutex::Autolock _l(mLock);
1485 // Don't apply master volume in SW if our HAL can do it for us.
1486 if (mOutput && mOutput->audioHwDev &&
1487 mOutput->audioHwDev->canSetMasterVolume()) {
1488 mMasterVolume = 1.0;
1489 } else {
1490 mMasterVolume = value;
1491 }
1492}
1493
1494void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1495{
1496 Mutex::Autolock _l(mLock);
1497 // Don't apply master mute in SW if our HAL can do it for us.
1498 if (mOutput && mOutput->audioHwDev &&
1499 mOutput->audioHwDev->canSetMasterMute()) {
1500 mMasterMute = false;
1501 } else {
1502 mMasterMute = muted;
1503 }
1504}
1505
1506void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1507{
1508 Mutex::Autolock _l(mLock);
1509 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001510 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001511}
1512
1513void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1514{
1515 Mutex::Autolock _l(mLock);
1516 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001517 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001518}
1519
1520float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1521{
1522 Mutex::Autolock _l(mLock);
1523 return mStreamTypes[stream].volume;
1524}
1525
1526// addTrack_l() must be called with ThreadBase::mLock held
1527status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1528{
1529 status_t status = ALREADY_EXISTS;
1530
1531 // set retry count for buffer fill
1532 track->mRetryCount = kMaxTrackStartupRetries;
1533 if (mActiveTracks.indexOf(track) < 0) {
1534 // the track is newly added, make sure it fills up all its
1535 // buffers before playing. This is to ensure the client will
1536 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001537 if (!track->isOutputTrack()) {
1538 TrackBase::track_state state = track->mState;
1539 mLock.unlock();
1540 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1541 mLock.lock();
1542 // abort track was stopped/paused while we released the lock
1543 if (state != track->mState) {
1544 if (status == NO_ERROR) {
1545 mLock.unlock();
1546 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1547 mLock.lock();
1548 }
1549 return INVALID_OPERATION;
1550 }
1551 // abort if start is rejected by audio policy manager
1552 if (status != NO_ERROR) {
1553 return PERMISSION_DENIED;
1554 }
1555#ifdef ADD_BATTERY_DATA
1556 // to track the speaker usage
1557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1558#endif
1559 }
1560
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001561 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001562 track->mResetDone = false;
1563 track->mPresentationCompleteFrames = 0;
1564 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001565 mWakeLockUids.add(track->uid());
1566 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001567 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001568 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1569 if (chain != 0) {
1570 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1571 track->sessionId());
1572 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001573 }
1574
1575 status = NO_ERROR;
1576 }
1577
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001578 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001579 return status;
1580}
1581
Eric Laurentbfb1b832013-01-07 09:53:42 -08001582bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001583{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001584 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001585 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001586 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1587 track->mState = TrackBase::STOPPED;
1588 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001590 } else if (track->isFastTrack() || track->isOffloaded()) {
1591 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001592 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001593
1594 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001595}
1596
1597void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1598{
1599 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1600 mTracks.remove(track);
1601 deleteTrackName_l(track->name());
1602 // redundant as track is about to be destroyed, for dumpsys only
1603 track->mName = -1;
1604 if (track->isFastTrack()) {
1605 int index = track->mFastIndex;
1606 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1607 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1608 mFastTrackAvailMask |= 1 << index;
1609 // redundant as track is about to be destroyed, for dumpsys only
1610 track->mFastIndex = -1;
1611 }
1612 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1613 if (chain != 0) {
1614 chain->decTrackCnt();
1615 }
1616}
1617
Eric Laurentede6c3b2013-09-19 14:37:46 -07001618void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619{
1620 // Thread could be blocked waiting for async
1621 // so signal it to handle state changes immediately
1622 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1623 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1624 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001625 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001626}
1627
Eric Laurent81784c32012-11-19 14:55:58 -08001628String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1629{
Eric Laurent81784c32012-11-19 14:55:58 -08001630 Mutex::Autolock _l(mLock);
1631 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001632 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001633 }
1634
Glenn Kastend8ea6992013-07-16 14:17:15 -07001635 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1636 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001637 free(s);
1638 return out_s8;
1639}
1640
1641// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent10351942014-05-08 18:49:52 -07001642void AudioFlinger::PlaybackThread::audioConfigChanged_l(
1643 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients,
1644 int event,
1645 int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001646 AudioSystem::OutputDescriptor desc;
1647 void *param2 = NULL;
1648
1649 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1650 param);
1651
1652 switch (event) {
1653 case AudioSystem::OUTPUT_OPENED:
1654 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001655 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001656 desc.samplingRate = mSampleRate;
1657 desc.format = mFormat;
1658 desc.frameCount = mNormalFrameCount; // FIXME see
1659 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001660 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001661 param2 = &desc;
1662 break;
1663
1664 case AudioSystem::STREAM_CONFIG_CHANGED:
1665 param2 = &param;
1666 case AudioSystem::OUTPUT_CLOSED:
1667 default:
1668 break;
1669 }
Eric Laurent10351942014-05-08 18:49:52 -07001670 mAudioFlinger->audioConfigChanged_l(notificationClients, event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001671}
1672
Eric Laurentbfb1b832013-01-07 09:53:42 -08001673void AudioFlinger::PlaybackThread::writeCallback()
1674{
1675 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001676 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001677}
1678
1679void AudioFlinger::PlaybackThread::drainCallback()
1680{
1681 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001682 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001683}
1684
Eric Laurent3b4529e2013-09-05 18:09:19 -07001685void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001686{
1687 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001688 // reject out of sequence requests
1689 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1690 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001691 mWaitWorkCV.signal();
1692 }
1693}
1694
Eric Laurent3b4529e2013-09-05 18:09:19 -07001695void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001696{
1697 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001698 // reject out of sequence requests
1699 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1700 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001701 mWaitWorkCV.signal();
1702 }
1703}
1704
1705// static
1706int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001707 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001708 void *cookie)
1709{
1710 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1711 ALOGV("asyncCallback() event %d", event);
1712 switch (event) {
1713 case STREAM_CBK_EVENT_WRITE_READY:
1714 me->writeCallback();
1715 break;
1716 case STREAM_CBK_EVENT_DRAIN_READY:
1717 me->drainCallback();
1718 break;
1719 default:
1720 ALOGW("asyncCallback() unknown event %d", event);
1721 break;
1722 }
1723 return 0;
1724}
1725
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001726void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001727{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001728 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001729 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1730 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001731 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001732 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001733 }
1734 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001735 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001736 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1737 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001738 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001739 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001740 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001741 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001742 }
1743 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001744 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1745 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001746 }
Eric Laurent81784c32012-11-19 14:55:58 -08001747 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001748 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1749 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001750 if (mFrameCount & 15) {
1751 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1752 mFrameCount);
1753 }
1754
Eric Laurentbfb1b832013-01-07 09:53:42 -08001755 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1756 (mOutput->stream->set_callback != NULL)) {
1757 if (mOutput->stream->set_callback(mOutput->stream,
1758 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1759 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001760 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001761 }
1762 }
1763
Andy Hung09a50072014-02-27 14:30:47 -08001764 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001765 double multiplier = 1.0;
1766 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1767 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001768 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1769 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001770 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1771 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1772 maxNormalFrameCount = maxNormalFrameCount & ~15;
1773 if (maxNormalFrameCount < minNormalFrameCount) {
1774 maxNormalFrameCount = minNormalFrameCount;
1775 }
1776 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1777 if (multiplier <= 1.0) {
1778 multiplier = 1.0;
1779 } else if (multiplier <= 2.0) {
1780 if (2 * mFrameCount <= maxNormalFrameCount) {
1781 multiplier = 2.0;
1782 } else {
1783 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1784 }
1785 } else {
1786 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001787 // 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 -08001788 // track, but we sometimes have to do this to satisfy the maximum frame count
1789 // constraint)
1790 // FIXME this rounding up should not be done if no HAL SRC
1791 uint32_t truncMult = (uint32_t) multiplier;
1792 if ((truncMult & 1)) {
1793 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1794 ++truncMult;
1795 }
1796 }
1797 multiplier = (double) truncMult;
1798 }
1799 }
1800 mNormalFrameCount = multiplier * mFrameCount;
1801 // round up to nearest 16 frames to satisfy AudioMixer
1802 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001803 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001804 mNormalFrameCount);
1805
Andy Hung010a1a12014-03-13 13:57:33 -07001806 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1807 // Originally this was int16_t[] array, need to remove legacy implications.
1808 free(mSinkBuffer);
1809 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001810 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1811 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1812 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001813 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001814
Andy Hung69aed5f2014-02-25 17:24:40 -08001815 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1816 // drives the output.
1817 free(mMixerBuffer);
1818 mMixerBuffer = NULL;
1819 if (mMixerBufferEnabled) {
1820 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1821 mMixerBufferSize = mNormalFrameCount * mChannelCount
1822 * audio_bytes_per_sample(mMixerBufferFormat);
1823 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1824 }
Andy Hung98ef9782014-03-04 14:46:50 -08001825 free(mEffectBuffer);
1826 mEffectBuffer = NULL;
1827 if (mEffectBufferEnabled) {
1828 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1829 mEffectBufferSize = mNormalFrameCount * mChannelCount
1830 * audio_bytes_per_sample(mEffectBufferFormat);
1831 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1832 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001833
Eric Laurent81784c32012-11-19 14:55:58 -08001834 // force reconfiguration of effect chains and engines to take new buffer size and audio
1835 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001836 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001837 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1838 // matter.
1839 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1840 Vector< sp<EffectChain> > effectChains = mEffectChains;
1841 for (size_t i = 0; i < effectChains.size(); i ++) {
1842 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1843 }
1844}
1845
1846
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001847status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001848{
1849 if (halFrames == NULL || dspFrames == NULL) {
1850 return BAD_VALUE;
1851 }
1852 Mutex::Autolock _l(mLock);
1853 if (initCheck() != NO_ERROR) {
1854 return INVALID_OPERATION;
1855 }
1856 size_t framesWritten = mBytesWritten / mFrameSize;
1857 *halFrames = framesWritten;
1858
1859 if (isSuspended()) {
1860 // return an estimation of rendered frames when the output is suspended
1861 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1862 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1863 return NO_ERROR;
1864 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001865 status_t status;
1866 uint32_t frames;
1867 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1868 *dspFrames = (size_t)frames;
1869 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
1871}
1872
1873uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1874{
1875 Mutex::Autolock _l(mLock);
1876 uint32_t result = 0;
1877 if (getEffectChain_l(sessionId) != 0) {
1878 result = EFFECT_SESSION;
1879 }
1880
1881 for (size_t i = 0; i < mTracks.size(); ++i) {
1882 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001883 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001884 result |= TRACK_SESSION;
1885 break;
1886 }
1887 }
1888
1889 return result;
1890}
1891
1892uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1893{
1894 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1895 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1896 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1897 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1898 }
1899 for (size_t i = 0; i < mTracks.size(); i++) {
1900 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001901 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001902 return AudioSystem::getStrategyForStream(track->streamType());
1903 }
1904 }
1905 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1906}
1907
1908
1909AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1910{
1911 Mutex::Autolock _l(mLock);
1912 return mOutput;
1913}
1914
1915AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1916{
1917 Mutex::Autolock _l(mLock);
1918 AudioStreamOut *output = mOutput;
1919 mOutput = NULL;
1920 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1921 // must push a NULL and wait for ack
1922 mOutputSink.clear();
1923 mPipeSink.clear();
1924 mNormalSink.clear();
1925 return output;
1926}
1927
1928// this method must always be called either with ThreadBase mLock held or inside the thread loop
1929audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1930{
1931 if (mOutput == NULL) {
1932 return NULL;
1933 }
1934 return &mOutput->stream->common;
1935}
1936
1937uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1938{
1939 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1940}
1941
1942status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1943{
1944 if (!isValidSyncEvent(event)) {
1945 return BAD_VALUE;
1946 }
1947
1948 Mutex::Autolock _l(mLock);
1949
1950 for (size_t i = 0; i < mTracks.size(); ++i) {
1951 sp<Track> track = mTracks[i];
1952 if (event->triggerSession() == track->sessionId()) {
1953 (void) track->setSyncEvent(event);
1954 return NO_ERROR;
1955 }
1956 }
1957
1958 return NAME_NOT_FOUND;
1959}
1960
1961bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1962{
1963 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1964}
1965
1966void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1967 const Vector< sp<Track> >& tracksToRemove)
1968{
1969 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001970 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001971 for (size_t i = 0 ; i < count ; i++) {
1972 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001974 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975#ifdef ADD_BATTERY_DATA
1976 // to track the speaker usage
1977 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1978#endif
1979 if (track->isTerminated()) {
1980 AudioSystem::releaseOutput(mId);
1981 }
Eric Laurent81784c32012-11-19 14:55:58 -08001982 }
1983 }
1984 }
Eric Laurent81784c32012-11-19 14:55:58 -08001985}
1986
1987void AudioFlinger::PlaybackThread::checkSilentMode_l()
1988{
1989 if (!mMasterMute) {
1990 char value[PROPERTY_VALUE_MAX];
1991 if (property_get("ro.audio.silent", value, "0") > 0) {
1992 char *endptr;
1993 unsigned long ul = strtoul(value, &endptr, 0);
1994 if (*endptr == '\0' && ul != 0) {
1995 ALOGD("Silence is golden");
1996 // The setprop command will not allow a property to be changed after
1997 // the first time it is set, so we don't have to worry about un-muting.
1998 setMasterMute_l(true);
1999 }
2000 }
2001 }
2002}
2003
2004// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002005ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002006{
2007 // FIXME rewrite to reduce number of system calls
2008 mLastWriteTime = systemTime();
2009 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002010 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002011 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002012
2013 // If an NBAIO sink is present, use it to write the normal mixer's submix
2014 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002015 const size_t count = mBytesRemaining / mFrameSize;
2016
Simon Wilson2d590962012-11-29 15:18:50 -08002017 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002018 // update the setpoint when AudioFlinger::mScreenState changes
2019 uint32_t screenState = AudioFlinger::mScreenState;
2020 if (screenState != mScreenState) {
2021 mScreenState = screenState;
2022 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2023 if (pipe != NULL) {
2024 pipe->setAvgFrames((mScreenState & 1) ?
2025 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2026 }
2027 }
Andy Hung010a1a12014-03-13 13:57:33 -07002028 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002029 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002030 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002031 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002032 } else {
2033 bytesWritten = framesWritten;
2034 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002035 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002036 if (status == NO_ERROR) {
2037 size_t totalFramesWritten = mNormalSink->framesWritten();
2038 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2039 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2040 mLatchDValid = true;
2041 }
2042 }
Eric Laurent81784c32012-11-19 14:55:58 -08002043 // otherwise use the HAL / AudioStreamOut directly
2044 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002046
Eric Laurentbfb1b832013-01-07 09:53:42 -08002047 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002048 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2049 mWriteAckSequence += 2;
2050 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002051 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002052 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002053 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002054 // FIXME We should have an implementation of timestamps for direct output threads.
2055 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002057 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002058 if (mUseAsyncWrite &&
2059 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2060 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002061 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002062 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002063 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002064 }
Eric Laurent81784c32012-11-19 14:55:58 -08002065 }
2066
Eric Laurent81784c32012-11-19 14:55:58 -08002067 mNumWrites++;
2068 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002069 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002070 return bytesWritten;
2071}
2072
2073void AudioFlinger::PlaybackThread::threadLoop_drain()
2074{
2075 if (mOutput->stream->drain) {
2076 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2077 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002078 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2079 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002081 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082 }
2083 mOutput->stream->drain(mOutput->stream,
2084 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2085 : AUDIO_DRAIN_ALL);
2086 }
2087}
2088
2089void AudioFlinger::PlaybackThread::threadLoop_exit()
2090{
2091 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002092}
2093
2094/*
2095The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002096 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002097 - activeSleepTime from activeSleepTimeUs()
2098 - idleSleepTime from idleSleepTimeUs()
2099 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2100 - maxPeriod from frame count and sample rate (MIXER only)
2101
2102The parameters that affect these derived values are:
2103 - frame count
2104 - frame size
2105 - sample rate
2106 - device type: A2DP or not
2107 - device latency
2108 - format: PCM or not
2109 - active sleep time
2110 - idle sleep time
2111*/
2112
2113void AudioFlinger::PlaybackThread::cacheParameters_l()
2114{
Andy Hung25c2dac2014-02-27 14:56:00 -08002115 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002116 activeSleepTime = activeSleepTimeUs();
2117 idleSleepTime = idleSleepTimeUs();
2118}
2119
2120void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2121{
Glenn Kasten7c027242012-12-26 14:43:16 -08002122 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002123 this, streamType, mTracks.size());
2124 Mutex::Autolock _l(mLock);
2125
2126 size_t size = mTracks.size();
2127 for (size_t i = 0; i < size; i++) {
2128 sp<Track> t = mTracks[i];
2129 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002130 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002131 }
2132 }
2133}
2134
2135status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2136{
2137 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002138 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2139 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002140 bool ownsBuffer = false;
2141
2142 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2143 if (session > 0) {
2144 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002145 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002146 if (mType != DIRECT) {
2147 size_t numSamples = mNormalFrameCount * mChannelCount;
2148 buffer = new int16_t[numSamples];
2149 memset(buffer, 0, numSamples * sizeof(int16_t));
2150 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2151 ownsBuffer = true;
2152 }
2153
2154 // Attach all tracks with same session ID to this chain.
2155 for (size_t i = 0; i < mTracks.size(); ++i) {
2156 sp<Track> track = mTracks[i];
2157 if (session == track->sessionId()) {
2158 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2159 buffer);
2160 track->setMainBuffer(buffer);
2161 chain->incTrackCnt();
2162 }
2163 }
2164
2165 // indicate all active tracks in the chain
2166 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2167 sp<Track> track = mActiveTracks[i].promote();
2168 if (track == 0) {
2169 continue;
2170 }
2171 if (session == track->sessionId()) {
2172 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2173 chain->incActiveTrackCnt();
2174 }
2175 }
2176 }
2177
2178 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002179 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2180 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002181 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2182 // chains list in order to be processed last as it contains output stage effects
2183 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2184 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2185 // after track specific effects and before output stage
2186 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2187 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2188 // Effect chain for other sessions are inserted at beginning of effect
2189 // chains list to be processed before output mix effects. Relative order between other
2190 // sessions is not important
2191 size_t size = mEffectChains.size();
2192 size_t i = 0;
2193 for (i = 0; i < size; i++) {
2194 if (mEffectChains[i]->sessionId() < session) {
2195 break;
2196 }
2197 }
2198 mEffectChains.insertAt(chain, i);
2199 checkSuspendOnAddEffectChain_l(chain);
2200
2201 return NO_ERROR;
2202}
2203
2204size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2205{
2206 int session = chain->sessionId();
2207
2208 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2209
2210 for (size_t i = 0; i < mEffectChains.size(); i++) {
2211 if (chain == mEffectChains[i]) {
2212 mEffectChains.removeAt(i);
2213 // detach all active tracks from the chain
2214 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2215 sp<Track> track = mActiveTracks[i].promote();
2216 if (track == 0) {
2217 continue;
2218 }
2219 if (session == track->sessionId()) {
2220 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2221 chain.get(), session);
2222 chain->decActiveTrackCnt();
2223 }
2224 }
2225
2226 // detach all tracks with same session ID from this chain
2227 for (size_t i = 0; i < mTracks.size(); ++i) {
2228 sp<Track> track = mTracks[i];
2229 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002230 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002231 chain->decTrackCnt();
2232 }
2233 }
2234 break;
2235 }
2236 }
2237 return mEffectChains.size();
2238}
2239
2240status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2241 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2242{
2243 Mutex::Autolock _l(mLock);
2244 return attachAuxEffect_l(track, EffectId);
2245}
2246
2247status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2248 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2249{
2250 status_t status = NO_ERROR;
2251
2252 if (EffectId == 0) {
2253 track->setAuxBuffer(0, NULL);
2254 } else {
2255 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2256 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2257 if (effect != 0) {
2258 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2259 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2260 } else {
2261 status = INVALID_OPERATION;
2262 }
2263 } else {
2264 status = BAD_VALUE;
2265 }
2266 }
2267 return status;
2268}
2269
2270void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2271{
2272 for (size_t i = 0; i < mTracks.size(); ++i) {
2273 sp<Track> track = mTracks[i];
2274 if (track->auxEffectId() == effectId) {
2275 attachAuxEffect_l(track, 0);
2276 }
2277 }
2278}
2279
2280bool AudioFlinger::PlaybackThread::threadLoop()
2281{
2282 Vector< sp<Track> > tracksToRemove;
2283
2284 standbyTime = systemTime();
2285
2286 // MIXER
2287 nsecs_t lastWarning = 0;
2288
2289 // DUPLICATING
2290 // FIXME could this be made local to while loop?
2291 writeFrames = 0;
2292
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002293 int lastGeneration = 0;
2294
Eric Laurent81784c32012-11-19 14:55:58 -08002295 cacheParameters_l();
2296 sleepTime = idleSleepTime;
2297
2298 if (mType == MIXER) {
2299 sleepTimeShift = 0;
2300 }
2301
2302 CpuStats cpuStats;
2303 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2304
2305 acquireWakeLock();
2306
Glenn Kasten9e58b552013-01-18 15:09:48 -08002307 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2308 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2309 // and then that string will be logged at the next convenient opportunity.
2310 const char *logString = NULL;
2311
Eric Laurent664539d2013-09-23 18:24:31 -07002312 checkSilentMode_l();
2313
Eric Laurent81784c32012-11-19 14:55:58 -08002314 while (!exitPending())
2315 {
2316 cpuStats.sample(myName);
2317
2318 Vector< sp<EffectChain> > effectChains;
2319
Eric Laurent10351942014-05-08 18:49:52 -07002320 DefaultKeyedVector< pid_t,sp<NotificationClient> > notificationClients =
2321 mAudioFlinger->notificationClients();
Eric Laurent81784c32012-11-19 14:55:58 -08002322
2323 { // scope for mLock
2324
2325 Mutex::Autolock _l(mLock);
2326
Eric Laurent10351942014-05-08 18:49:52 -07002327 processConfigEvents_l(notificationClients);
2328 notificationClients.clear();
2329
Glenn Kasten9e58b552013-01-18 15:09:48 -08002330 if (logString != NULL) {
2331 mNBLogWriter->logTimestamp();
2332 mNBLogWriter->log(logString);
2333 logString = NULL;
2334 }
2335
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002336 if (mLatchDValid) {
2337 mLatchQ = mLatchD;
2338 mLatchDValid = false;
2339 mLatchQValid = true;
2340 }
2341
Eric Laurent81784c32012-11-19 14:55:58 -08002342 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002343 if (mSignalPending) {
2344 // A signal was raised while we were unlocked
2345 mSignalPending = false;
2346 } else if (waitingAsyncCallback_l()) {
2347 if (exitPending()) {
2348 break;
2349 }
2350 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002351 mWakeLockUids.clear();
2352 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 ALOGV("wait async completion");
2354 mWaitWorkCV.wait(mLock);
2355 ALOGV("async completion/wake");
2356 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002357 standbyTime = systemTime() + standbyDelay;
2358 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002359
2360 continue;
2361 }
2362 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363 isSuspended()) {
2364 // put audio hardware into standby after short delay
2365 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002366
2367 threadLoop_standby();
2368
2369 mStandby = true;
2370 }
2371
2372 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2373 // we're about to wait, flush the binder command buffer
2374 IPCThreadState::self()->flushCommands();
2375
2376 clearOutputTracks();
2377
2378 if (exitPending()) {
2379 break;
2380 }
2381
2382 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002383 mWakeLockUids.clear();
2384 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002385 // wait until we have something to do...
2386 ALOGV("%s going to sleep", myName.string());
2387 mWaitWorkCV.wait(mLock);
2388 ALOGV("%s waking up", myName.string());
2389 acquireWakeLock_l();
2390
2391 mMixerStatus = MIXER_IDLE;
2392 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2393 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002394 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002395 checkSilentMode_l();
2396
2397 standbyTime = systemTime() + standbyDelay;
2398 sleepTime = idleSleepTime;
2399 if (mType == MIXER) {
2400 sleepTimeShift = 0;
2401 }
2402
2403 continue;
2404 }
2405 }
Eric Laurent81784c32012-11-19 14:55:58 -08002406 // mMixerStatusIgnoringFastTracks is also updated internally
2407 mMixerStatus = prepareTracks_l(&tracksToRemove);
2408
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002409 // compare with previously applied list
2410 if (lastGeneration != mActiveTracksGeneration) {
2411 // update wakelock
2412 updateWakeLockUids_l(mWakeLockUids);
2413 lastGeneration = mActiveTracksGeneration;
2414 }
2415
Eric Laurent81784c32012-11-19 14:55:58 -08002416 // prevent any changes in effect chain list and in each effect chain
2417 // during mixing and effect process as the audio buffers could be deleted
2418 // or modified if an effect is created or deleted
2419 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002420 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002421
Eric Laurentbfb1b832013-01-07 09:53:42 -08002422 if (mBytesRemaining == 0) {
2423 mCurrentWriteLength = 0;
2424 if (mMixerStatus == MIXER_TRACKS_READY) {
2425 // threadLoop_mix() sets mCurrentWriteLength
2426 threadLoop_mix();
2427 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2428 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2429 // threadLoop_sleepTime sets sleepTime to 0 if data
2430 // must be written to HAL
2431 threadLoop_sleepTime();
2432 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002433 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002434 }
2435 }
Andy Hung98ef9782014-03-04 14:46:50 -08002436 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2437 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2438 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2439 // or mSinkBuffer (if there are no effects).
2440 //
2441 // This is done pre-effects computation; if effects change to
2442 // support higher precision, this needs to move.
2443 //
2444 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2445 // TODO use sleepTime == 0 as an additional condition.
2446 if (mMixerBufferValid) {
2447 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2448 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2449
2450 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2451 mNormalFrameCount * mChannelCount);
2452 }
2453
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454 mBytesRemaining = mCurrentWriteLength;
2455 if (isSuspended()) {
2456 sleepTime = suspendSleepTimeUs();
2457 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002458 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 mBytesRemaining = 0;
2460 }
Eric Laurent81784c32012-11-19 14:55:58 -08002461
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002463 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464 for (size_t i = 0; i < effectChains.size(); i ++) {
2465 effectChains[i]->process_l();
2466 }
Eric Laurent81784c32012-11-19 14:55:58 -08002467 }
2468 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002469 // Process effect chains for offloaded thread even if no audio
2470 // was read from audio track: process only updates effect state
2471 // and thus does have to be synchronized with audio writes but may have
2472 // to be called while waiting for async write callback
2473 if (mType == OFFLOAD) {
2474 for (size_t i = 0; i < effectChains.size(); i ++) {
2475 effectChains[i]->process_l();
2476 }
2477 }
Eric Laurent81784c32012-11-19 14:55:58 -08002478
Andy Hung98ef9782014-03-04 14:46:50 -08002479 // Only if the Effects buffer is enabled and there is data in the
2480 // Effects buffer (buffer valid), we need to
2481 // copy into the sink buffer.
2482 // TODO use sleepTime == 0 as an additional condition.
2483 if (mEffectBufferValid) {
2484 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2485 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2486 mNormalFrameCount * mChannelCount);
2487 }
2488
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // enable changes in effect chain
2490 unlockEffectChains(effectChains);
2491
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492 if (!waitingAsyncCallback()) {
2493 // sleepTime == 0 means we must write to audio hardware
2494 if (sleepTime == 0) {
2495 if (mBytesRemaining) {
2496 ssize_t ret = threadLoop_write();
2497 if (ret < 0) {
2498 mBytesRemaining = 0;
2499 } else {
2500 mBytesWritten += ret;
2501 mBytesRemaining -= ret;
2502 }
2503 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2504 (mMixerStatus == MIXER_DRAIN_ALL)) {
2505 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002506 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002507 if (mType == MIXER) {
2508 // write blocked detection
2509 nsecs_t now = systemTime();
2510 nsecs_t delta = now - mLastWriteTime;
2511 if (!mStandby && delta > maxPeriod) {
2512 mNumDelayedWrites++;
2513 if ((now - lastWarning) > kWarningThrottleNs) {
2514 ATRACE_NAME("underrun");
2515 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2516 ns2ms(delta), mNumDelayedWrites, this);
2517 lastWarning = now;
2518 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002519 }
2520 }
Eric Laurent81784c32012-11-19 14:55:58 -08002521
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 } else {
2523 usleep(sleepTime);
2524 }
Eric Laurent81784c32012-11-19 14:55:58 -08002525 }
2526
2527 // Finally let go of removed track(s), without the lock held
2528 // since we can't guarantee the destructors won't acquire that
2529 // same lock. This will also mutate and push a new fast mixer state.
2530 threadLoop_removeTracks(tracksToRemove);
2531 tracksToRemove.clear();
2532
2533 // FIXME I don't understand the need for this here;
2534 // it was in the original code but maybe the
2535 // assignment in saveOutputTracks() makes this unnecessary?
2536 clearOutputTracks();
2537
2538 // Effect chains will be actually deleted here if they were removed from
2539 // mEffectChains list during mixing or effects processing
2540 effectChains.clear();
2541
2542 // FIXME Note that the above .clear() is no longer necessary since effectChains
2543 // is now local to this block, but will keep it for now (at least until merge done).
2544 }
2545
Eric Laurentbfb1b832013-01-07 09:53:42 -08002546 threadLoop_exit();
2547
Eric Laurent81784c32012-11-19 14:55:58 -08002548 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002549 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002550 // put output stream into standby mode
2551 if (!mStandby) {
2552 mOutput->stream->common.standby(&mOutput->stream->common);
2553 }
2554 }
2555
2556 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002557 mWakeLockUids.clear();
2558 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002559
2560 ALOGV("Thread %p type %d exiting", this, mType);
2561 return false;
2562}
2563
Eric Laurentbfb1b832013-01-07 09:53:42 -08002564// removeTracks_l() must be called with ThreadBase::mLock held
2565void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2566{
2567 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002568 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002569 for (size_t i=0 ; i<count ; i++) {
2570 const sp<Track>& track = tracksToRemove.itemAt(i);
2571 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002572 mWakeLockUids.remove(track->uid());
2573 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2575 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2576 if (chain != 0) {
2577 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2578 track->sessionId());
2579 chain->decActiveTrackCnt();
2580 }
2581 if (track->isTerminated()) {
2582 removeTrack_l(track);
2583 }
2584 }
2585 }
2586
2587}
Eric Laurent81784c32012-11-19 14:55:58 -08002588
Eric Laurentaccc1472013-09-20 09:36:34 -07002589status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2590{
2591 if (mNormalSink != 0) {
2592 return mNormalSink->getTimestamp(timestamp);
2593 }
2594 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2595 uint64_t position64;
2596 int ret = mOutput->stream->get_presentation_position(
2597 mOutput->stream, &position64, &timestamp.mTime);
2598 if (ret == 0) {
2599 timestamp.mPosition = (uint32_t)position64;
2600 return NO_ERROR;
2601 }
2602 }
2603 return INVALID_OPERATION;
2604}
Eric Laurent81784c32012-11-19 14:55:58 -08002605// ----------------------------------------------------------------------------
2606
2607AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2608 audio_io_handle_t id, audio_devices_t device, type_t type)
2609 : PlaybackThread(audioFlinger, output, id, device, type),
2610 // mAudioMixer below
2611 // mFastMixer below
2612 mFastMixerFutex(0)
2613 // mOutputSink below
2614 // mPipeSink below
2615 // mNormalSink below
2616{
2617 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002618 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002619 "mFrameCount=%d, mNormalFrameCount=%d",
2620 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2621 mNormalFrameCount);
2622 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2623
2624 // FIXME - Current mixer implementation only supports stereo output
2625 if (mChannelCount != FCC_2) {
2626 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2627 }
2628
2629 // create an NBAIO sink for the HAL output stream, and negotiate
2630 mOutputSink = new AudioStreamOutSink(output->stream);
2631 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002632 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002633 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2634 ALOG_ASSERT(index == 0);
2635
2636 // initialize fast mixer depending on configuration
2637 bool initFastMixer;
2638 switch (kUseFastMixer) {
2639 case FastMixer_Never:
2640 initFastMixer = false;
2641 break;
2642 case FastMixer_Always:
2643 initFastMixer = true;
2644 break;
2645 case FastMixer_Static:
2646 case FastMixer_Dynamic:
2647 initFastMixer = mFrameCount < mNormalFrameCount;
2648 break;
2649 }
2650 if (initFastMixer) {
2651
2652 // create a MonoPipe to connect our submix to FastMixer
2653 NBAIO_Format format = mOutputSink->format();
2654 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2655 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2656 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2657 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2658 const NBAIO_Format offers[1] = {format};
2659 size_t numCounterOffers = 0;
2660 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2661 ALOG_ASSERT(index == 0);
2662 monoPipe->setAvgFrames((mScreenState & 1) ?
2663 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2664 mPipeSink = monoPipe;
2665
Glenn Kasten46909e72013-02-26 09:20:22 -08002666#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002667 if (mTeeSinkOutputEnabled) {
2668 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2669 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2670 numCounterOffers = 0;
2671 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2672 ALOG_ASSERT(index == 0);
2673 mTeeSink = teeSink;
2674 PipeReader *teeSource = new PipeReader(*teeSink);
2675 numCounterOffers = 0;
2676 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2677 ALOG_ASSERT(index == 0);
2678 mTeeSource = teeSource;
2679 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002680#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002681
2682 // create fast mixer and configure it initially with just one fast track for our submix
2683 mFastMixer = new FastMixer();
2684 FastMixerStateQueue *sq = mFastMixer->sq();
2685#ifdef STATE_QUEUE_DUMP
2686 sq->setObserverDump(&mStateQueueObserverDump);
2687 sq->setMutatorDump(&mStateQueueMutatorDump);
2688#endif
2689 FastMixerState *state = sq->begin();
2690 FastTrack *fastTrack = &state->mFastTracks[0];
2691 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2692 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2693 fastTrack->mVolumeProvider = NULL;
2694 fastTrack->mGeneration++;
2695 state->mFastTracksGen++;
2696 state->mTrackMask = 1;
2697 // fast mixer will use the HAL output sink
2698 state->mOutputSink = mOutputSink.get();
2699 state->mOutputSinkGen++;
2700 state->mFrameCount = mFrameCount;
2701 state->mCommand = FastMixerState::COLD_IDLE;
2702 // already done in constructor initialization list
2703 //mFastMixerFutex = 0;
2704 state->mColdFutexAddr = &mFastMixerFutex;
2705 state->mColdGen++;
2706 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002707#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002708 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002709#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002710 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2711 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002712 sq->end();
2713 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2714
2715 // start the fast mixer
2716 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2717 pid_t tid = mFastMixer->getTid();
2718 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2719 if (err != 0) {
2720 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2721 kPriorityFastMixer, getpid_cached, tid, err);
2722 }
2723
2724#ifdef AUDIO_WATCHDOG
2725 // create and start the watchdog
2726 mAudioWatchdog = new AudioWatchdog();
2727 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2728 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2729 tid = mAudioWatchdog->getTid();
2730 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2731 if (err != 0) {
2732 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2733 kPriorityFastMixer, getpid_cached, tid, err);
2734 }
2735#endif
2736
2737 } else {
2738 mFastMixer = NULL;
2739 }
2740
2741 switch (kUseFastMixer) {
2742 case FastMixer_Never:
2743 case FastMixer_Dynamic:
2744 mNormalSink = mOutputSink;
2745 break;
2746 case FastMixer_Always:
2747 mNormalSink = mPipeSink;
2748 break;
2749 case FastMixer_Static:
2750 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2751 break;
2752 }
2753}
2754
2755AudioFlinger::MixerThread::~MixerThread()
2756{
2757 if (mFastMixer != NULL) {
2758 FastMixerStateQueue *sq = mFastMixer->sq();
2759 FastMixerState *state = sq->begin();
2760 if (state->mCommand == FastMixerState::COLD_IDLE) {
2761 int32_t old = android_atomic_inc(&mFastMixerFutex);
2762 if (old == -1) {
Glenn Kasten110135b2014-05-09 13:39:04 -07002763 (void) __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002764 }
2765 }
2766 state->mCommand = FastMixerState::EXIT;
2767 sq->end();
2768 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2769 mFastMixer->join();
2770 // Though the fast mixer thread has exited, it's state queue is still valid.
2771 // We'll use that extract the final state which contains one remaining fast track
2772 // corresponding to our sub-mix.
2773 state = sq->begin();
2774 ALOG_ASSERT(state->mTrackMask == 1);
2775 FastTrack *fastTrack = &state->mFastTracks[0];
2776 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2777 delete fastTrack->mBufferProvider;
2778 sq->end(false /*didModify*/);
2779 delete mFastMixer;
2780#ifdef AUDIO_WATCHDOG
2781 if (mAudioWatchdog != 0) {
2782 mAudioWatchdog->requestExit();
2783 mAudioWatchdog->requestExitAndWait();
2784 mAudioWatchdog.clear();
2785 }
2786#endif
2787 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002788 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002789 delete mAudioMixer;
2790}
2791
2792
2793uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2794{
2795 if (mFastMixer != NULL) {
2796 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2797 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2798 }
2799 return latency;
2800}
2801
2802
2803void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2804{
2805 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2806}
2807
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
2810 // FIXME we should only do one push per cycle; confirm this is true
2811 // Start the fast mixer if it's not already running
2812 if (mFastMixer != NULL) {
2813 FastMixerStateQueue *sq = mFastMixer->sq();
2814 FastMixerState *state = sq->begin();
2815 if (state->mCommand != FastMixerState::MIX_WRITE &&
2816 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2817 if (state->mCommand == FastMixerState::COLD_IDLE) {
2818 int32_t old = android_atomic_inc(&mFastMixerFutex);
2819 if (old == -1) {
Glenn Kasten110135b2014-05-09 13:39:04 -07002820 (void) __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08002821 }
2822#ifdef AUDIO_WATCHDOG
2823 if (mAudioWatchdog != 0) {
2824 mAudioWatchdog->resume();
2825 }
2826#endif
2827 }
2828 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002829 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2830 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002831 sq->end();
2832 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2833 if (kUseFastMixer == FastMixer_Dynamic) {
2834 mNormalSink = mPipeSink;
2835 }
2836 } else {
2837 sq->end(false /*didModify*/);
2838 }
2839 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002840 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002841}
2842
2843void AudioFlinger::MixerThread::threadLoop_standby()
2844{
2845 // Idle the fast mixer if it's currently running
2846 if (mFastMixer != NULL) {
2847 FastMixerStateQueue *sq = mFastMixer->sq();
2848 FastMixerState *state = sq->begin();
2849 if (!(state->mCommand & FastMixerState::IDLE)) {
2850 state->mCommand = FastMixerState::COLD_IDLE;
2851 state->mColdFutexAddr = &mFastMixerFutex;
2852 state->mColdGen++;
2853 mFastMixerFutex = 0;
2854 sq->end();
2855 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2856 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2857 if (kUseFastMixer == FastMixer_Dynamic) {
2858 mNormalSink = mOutputSink;
2859 }
2860#ifdef AUDIO_WATCHDOG
2861 if (mAudioWatchdog != 0) {
2862 mAudioWatchdog->pause();
2863 }
2864#endif
2865 } else {
2866 sq->end(false /*didModify*/);
2867 }
2868 }
2869 PlaybackThread::threadLoop_standby();
2870}
2871
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2873{
2874 return false;
2875}
2876
2877bool AudioFlinger::PlaybackThread::shouldStandby_l()
2878{
2879 return !mStandby;
2880}
2881
2882bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2883{
2884 Mutex::Autolock _l(mLock);
2885 return waitingAsyncCallback_l();
2886}
2887
Eric Laurent81784c32012-11-19 14:55:58 -08002888// shared by MIXER and DIRECT, overridden by DUPLICATING
2889void AudioFlinger::PlaybackThread::threadLoop_standby()
2890{
2891 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2892 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 // discard any pending drain or write ack by incrementing sequence
2895 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2896 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002898 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2899 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 }
Eric Laurent81784c32012-11-19 14:55:58 -08002901}
2902
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002903void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2904{
2905 ALOGV("signal playback thread");
2906 broadcast_l();
2907}
2908
Eric Laurent81784c32012-11-19 14:55:58 -08002909void AudioFlinger::MixerThread::threadLoop_mix()
2910{
2911 // obtain the presentation timestamp of the next output buffer
2912 int64_t pts;
2913 status_t status = INVALID_OPERATION;
2914
2915 if (mNormalSink != 0) {
2916 status = mNormalSink->getNextWriteTimestamp(&pts);
2917 } else {
2918 status = mOutputSink->getNextWriteTimestamp(&pts);
2919 }
2920
2921 if (status != NO_ERROR) {
2922 pts = AudioBufferProvider::kInvalidPTS;
2923 }
2924
2925 // mix buffers...
2926 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002927 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002928 // increase sleep time progressively when application underrun condition clears.
2929 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2930 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2931 // such that we would underrun the audio HAL.
2932 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2933 sleepTimeShift--;
2934 }
2935 sleepTime = 0;
2936 standbyTime = systemTime() + standbyDelay;
2937 //TODO: delay standby when effects have a tail
2938}
2939
2940void AudioFlinger::MixerThread::threadLoop_sleepTime()
2941{
2942 // If no tracks are ready, sleep once for the duration of an output
2943 // buffer size, then write 0s to the output
2944 if (sleepTime == 0) {
2945 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2946 sleepTime = activeSleepTime >> sleepTimeShift;
2947 if (sleepTime < kMinThreadSleepTimeUs) {
2948 sleepTime = kMinThreadSleepTimeUs;
2949 }
2950 // reduce sleep time in case of consecutive application underruns to avoid
2951 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2952 // duration we would end up writing less data than needed by the audio HAL if
2953 // the condition persists.
2954 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2955 sleepTimeShift++;
2956 }
2957 } else {
2958 sleepTime = idleSleepTime;
2959 }
2960 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002961 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2962 // before effects processing or output.
2963 if (mMixerBufferValid) {
2964 memset(mMixerBuffer, 0, mMixerBufferSize);
2965 } else {
2966 memset(mSinkBuffer, 0, mSinkBufferSize);
2967 }
Eric Laurent81784c32012-11-19 14:55:58 -08002968 sleepTime = 0;
2969 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2970 "anticipated start");
2971 }
2972 // TODO add standby time extension fct of effect tail
2973}
2974
2975// prepareTracks_l() must be called with ThreadBase::mLock held
2976AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2977 Vector< sp<Track> > *tracksToRemove)
2978{
2979
2980 mixer_state mixerStatus = MIXER_IDLE;
2981 // find out which tracks need to be processed
2982 size_t count = mActiveTracks.size();
2983 size_t mixedTracks = 0;
2984 size_t tracksWithEffect = 0;
2985 // counts only _active_ fast tracks
2986 size_t fastTracks = 0;
2987 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2988
2989 float masterVolume = mMasterVolume;
2990 bool masterMute = mMasterMute;
2991
2992 if (masterMute) {
2993 masterVolume = 0;
2994 }
2995 // Delegate master volume control to effect in output mix effect chain if needed
2996 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2997 if (chain != 0) {
2998 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2999 chain->setVolume_l(&v, &v);
3000 masterVolume = (float)((v + (1 << 23)) >> 24);
3001 chain.clear();
3002 }
3003
3004 // prepare a new state to push
3005 FastMixerStateQueue *sq = NULL;
3006 FastMixerState *state = NULL;
3007 bool didModify = false;
3008 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3009 if (mFastMixer != NULL) {
3010 sq = mFastMixer->sq();
3011 state = sq->begin();
3012 }
3013
Andy Hung69aed5f2014-02-25 17:24:40 -08003014 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003015 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003016
Eric Laurent81784c32012-11-19 14:55:58 -08003017 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003018 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003019 if (t == 0) {
3020 continue;
3021 }
3022
3023 // this const just means the local variable doesn't change
3024 Track* const track = t.get();
3025
3026 // process fast tracks
3027 if (track->isFastTrack()) {
3028
3029 // It's theoretically possible (though unlikely) for a fast track to be created
3030 // and then removed within the same normal mix cycle. This is not a problem, as
3031 // the track never becomes active so it's fast mixer slot is never touched.
3032 // The converse, of removing an (active) track and then creating a new track
3033 // at the identical fast mixer slot within the same normal mix cycle,
3034 // is impossible because the slot isn't marked available until the end of each cycle.
3035 int j = track->mFastIndex;
3036 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3037 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3038 FastTrack *fastTrack = &state->mFastTracks[j];
3039
3040 // Determine whether the track is currently in underrun condition,
3041 // and whether it had a recent underrun.
3042 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3043 FastTrackUnderruns underruns = ftDump->mUnderruns;
3044 uint32_t recentFull = (underruns.mBitFields.mFull -
3045 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3046 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3047 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3048 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3049 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3050 uint32_t recentUnderruns = recentPartial + recentEmpty;
3051 track->mObservedUnderruns = underruns;
3052 // don't count underruns that occur while stopping or pausing
3053 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003054 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3055 recentUnderruns > 0) {
3056 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3057 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003058 }
3059
3060 // This is similar to the state machine for normal tracks,
3061 // with a few modifications for fast tracks.
3062 bool isActive = true;
3063 switch (track->mState) {
3064 case TrackBase::STOPPING_1:
3065 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003067 track->mState = TrackBase::STOPPING_2;
3068 }
3069 break;
3070 case TrackBase::PAUSING:
3071 // ramp down is not yet implemented
3072 track->setPaused();
3073 break;
3074 case TrackBase::RESUMING:
3075 // ramp up is not yet implemented
3076 track->mState = TrackBase::ACTIVE;
3077 break;
3078 case TrackBase::ACTIVE:
3079 if (recentFull > 0 || recentPartial > 0) {
3080 // track has provided at least some frames recently: reset retry count
3081 track->mRetryCount = kMaxTrackRetries;
3082 }
3083 if (recentUnderruns == 0) {
3084 // no recent underruns: stay active
3085 break;
3086 }
3087 // there has recently been an underrun of some kind
3088 if (track->sharedBuffer() == 0) {
3089 // were any of the recent underruns "empty" (no frames available)?
3090 if (recentEmpty == 0) {
3091 // no, then ignore the partial underruns as they are allowed indefinitely
3092 break;
3093 }
3094 // there has recently been an "empty" underrun: decrement the retry counter
3095 if (--(track->mRetryCount) > 0) {
3096 break;
3097 }
3098 // indicate to client process that the track was disabled because of underrun;
3099 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003100 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003101 // remove from active list, but state remains ACTIVE [confusing but true]
3102 isActive = false;
3103 break;
3104 }
3105 // fall through
3106 case TrackBase::STOPPING_2:
3107 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003108 case TrackBase::STOPPED:
3109 case TrackBase::FLUSHED: // flush() while active
3110 // Check for presentation complete if track is inactive
3111 // We have consumed all the buffers of this track.
3112 // This would be incomplete if we auto-paused on underrun
3113 {
3114 size_t audioHALFrames =
3115 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3116 size_t framesWritten = mBytesWritten / mFrameSize;
3117 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3118 // track stays in active list until presentation is complete
3119 break;
3120 }
3121 }
3122 if (track->isStopping_2()) {
3123 track->mState = TrackBase::STOPPED;
3124 }
3125 if (track->isStopped()) {
3126 // Can't reset directly, as fast mixer is still polling this track
3127 // track->reset();
3128 // So instead mark this track as needing to be reset after push with ack
3129 resetMask |= 1 << i;
3130 }
3131 isActive = false;
3132 break;
3133 case TrackBase::IDLE:
3134 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003135 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003136 }
3137
3138 if (isActive) {
3139 // was it previously inactive?
3140 if (!(state->mTrackMask & (1 << j))) {
3141 ExtendedAudioBufferProvider *eabp = track;
3142 VolumeProvider *vp = track;
3143 fastTrack->mBufferProvider = eabp;
3144 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003145 fastTrack->mChannelMask = track->mChannelMask;
3146 fastTrack->mGeneration++;
3147 state->mTrackMask |= 1 << j;
3148 didModify = true;
3149 // no acknowledgement required for newly active tracks
3150 }
3151 // cache the combined master volume and stream type volume for fast mixer; this
3152 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003153 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003154 ++fastTracks;
3155 } else {
3156 // was it previously active?
3157 if (state->mTrackMask & (1 << j)) {
3158 fastTrack->mBufferProvider = NULL;
3159 fastTrack->mGeneration++;
3160 state->mTrackMask &= ~(1 << j);
3161 didModify = true;
3162 // If any fast tracks were removed, we must wait for acknowledgement
3163 // because we're about to decrement the last sp<> on those tracks.
3164 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3165 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003166 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003167 }
3168 tracksToRemove->add(track);
3169 // Avoids a misleading display in dumpsys
3170 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3171 }
3172 continue;
3173 }
3174
3175 { // local variable scope to avoid goto warning
3176
3177 audio_track_cblk_t* cblk = track->cblk();
3178
3179 // The first time a track is added we wait
3180 // for all its buffers to be filled before processing it
3181 int name = track->name();
3182 // make sure that we have enough frames to mix one full buffer.
3183 // enforce this condition only once to enable draining the buffer in case the client
3184 // app does not call stop() and relies on underrun to stop:
3185 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3186 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003187 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003188 uint32_t sr = track->sampleRate();
3189 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003190 desiredFrames = mNormalFrameCount;
3191 } else {
3192 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003193 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003194 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003195 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003196 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003197#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003198 // the minimum track buffer size is normally twice the number of frames necessary
3199 // to fill one buffer and the resampler should not leave more than one buffer worth
3200 // of unreleased frames after each pass, but just in case...
3201 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003202#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003203 }
Eric Laurent81784c32012-11-19 14:55:58 -08003204 uint32_t minFrames = 1;
3205 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3206 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003207 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003208 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003209
3210 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003211 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003212 !track->isPaused() && !track->isTerminated())
3213 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003214 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003215
3216 mixedTracks++;
3217
Andy Hung69aed5f2014-02-25 17:24:40 -08003218 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3219 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003220 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003221 if (track->mainBuffer() != mSinkBuffer &&
3222 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003223 if (mEffectBufferEnabled) {
3224 mEffectBufferValid = true; // Later can set directly.
3225 }
Eric Laurent81784c32012-11-19 14:55:58 -08003226 chain = getEffectChain_l(track->sessionId());
3227 // Delegate volume control to effect in track effect chain if needed
3228 if (chain != 0) {
3229 tracksWithEffect++;
3230 } else {
3231 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3232 "session %d",
3233 name, track->sessionId());
3234 }
3235 }
3236
3237
3238 int param = AudioMixer::VOLUME;
3239 if (track->mFillingUpStatus == Track::FS_FILLED) {
3240 // no ramp for the first volume setting
3241 track->mFillingUpStatus = Track::FS_ACTIVE;
3242 if (track->mState == TrackBase::RESUMING) {
3243 track->mState = TrackBase::ACTIVE;
3244 param = AudioMixer::RAMP_VOLUME;
3245 }
3246 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003247 // FIXME should not make a decision based on mServer
3248 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003249 // If the track is stopped before the first frame was mixed,
3250 // do not apply ramp
3251 param = AudioMixer::RAMP_VOLUME;
3252 }
3253
3254 // compute volume for this track
3255 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003256 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003257 vl = vr = va = 0;
3258 if (track->isPausing()) {
3259 track->setPaused();
3260 }
3261 } else {
3262
3263 // read original volumes with volume control
3264 float typeVolume = mStreamTypes[track->streamType()].volume;
3265 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003266 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003267 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003268 vl = vlr & 0xFFFF;
3269 vr = vlr >> 16;
3270 // track volumes come from shared memory, so can't be trusted and must be clamped
3271 if (vl > MAX_GAIN_INT) {
3272 ALOGV("Track left volume out of range: %04X", vl);
3273 vl = MAX_GAIN_INT;
3274 }
3275 if (vr > MAX_GAIN_INT) {
3276 ALOGV("Track right volume out of range: %04X", vr);
3277 vr = MAX_GAIN_INT;
3278 }
3279 // now apply the master volume and stream type volume
3280 vl = (uint32_t)(v * vl) << 12;
3281 vr = (uint32_t)(v * vr) << 12;
3282 // assuming master volume and stream type volume each go up to 1.0,
3283 // vl and vr are now in 8.24 format
3284
Glenn Kastene3aa6592012-12-04 12:22:46 -08003285 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003286 // send level comes from shared memory and so may be corrupt
3287 if (sendLevel > MAX_GAIN_INT) {
3288 ALOGV("Track send level out of range: %04X", sendLevel);
3289 sendLevel = MAX_GAIN_INT;
3290 }
3291 va = (uint32_t)(v * sendLevel);
3292 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293
Eric Laurent81784c32012-11-19 14:55:58 -08003294 // Delegate volume control to effect in track effect chain if needed
3295 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3296 // Do not ramp volume if volume is controlled by effect
3297 param = AudioMixer::VOLUME;
3298 track->mHasVolumeController = true;
3299 } else {
3300 // force no volume ramp when volume controller was just disabled or removed
3301 // from effect chain to avoid volume spike
3302 if (track->mHasVolumeController) {
3303 param = AudioMixer::VOLUME;
3304 }
3305 track->mHasVolumeController = false;
3306 }
3307
3308 // Convert volumes from 8.24 to 4.12 format
3309 // This additional clamping is needed in case chain->setVolume_l() overshot
3310 vl = (vl + (1 << 11)) >> 12;
3311 if (vl > MAX_GAIN_INT) {
3312 vl = MAX_GAIN_INT;
3313 }
3314 vr = (vr + (1 << 11)) >> 12;
3315 if (vr > MAX_GAIN_INT) {
3316 vr = MAX_GAIN_INT;
3317 }
3318
3319 if (va > MAX_GAIN_INT) {
3320 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3321 }
3322
3323 // XXX: these things DON'T need to be done each time
3324 mAudioMixer->setBufferProvider(name, track);
3325 mAudioMixer->enable(name);
3326
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003327 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3328 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3329 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003330 mAudioMixer->setParameter(
3331 name,
3332 AudioMixer::TRACK,
3333 AudioMixer::FORMAT, (void *)track->format());
3334 mAudioMixer->setParameter(
3335 name,
3336 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003337 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003338 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3339 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003340 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003341 if (reqSampleRate == 0) {
3342 reqSampleRate = mSampleRate;
3343 } else if (reqSampleRate > maxSampleRate) {
3344 reqSampleRate = maxSampleRate;
3345 }
Eric Laurent81784c32012-11-19 14:55:58 -08003346 mAudioMixer->setParameter(
3347 name,
3348 AudioMixer::RESAMPLE,
3349 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003350 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003351 /*
3352 * Select the appropriate output buffer for the track.
3353 *
Andy Hung98ef9782014-03-04 14:46:50 -08003354 * Tracks with effects go into their own effects chain buffer
3355 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003356 *
3357 * Other tracks can use mMixerBuffer for higher precision
3358 * channel accumulation. If this buffer is enabled
3359 * (mMixerBufferEnabled true), then selected tracks will accumulate
3360 * into it.
3361 *
3362 */
3363 if (mMixerBufferEnabled
3364 && (track->mainBuffer() == mSinkBuffer
3365 || track->mainBuffer() == mMixerBuffer)) {
3366 mAudioMixer->setParameter(
3367 name,
3368 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003369 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003370 mAudioMixer->setParameter(
3371 name,
3372 AudioMixer::TRACK,
3373 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3374 // TODO: override track->mainBuffer()?
3375 mMixerBufferValid = true;
3376 } else {
3377 mAudioMixer->setParameter(
3378 name,
3379 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003380 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003381 mAudioMixer->setParameter(
3382 name,
3383 AudioMixer::TRACK,
3384 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3385 }
Eric Laurent81784c32012-11-19 14:55:58 -08003386 mAudioMixer->setParameter(
3387 name,
3388 AudioMixer::TRACK,
3389 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3390
3391 // reset retry count
3392 track->mRetryCount = kMaxTrackRetries;
3393
3394 // If one track is ready, set the mixer ready if:
3395 // - the mixer was not ready during previous round OR
3396 // - no other track is not ready
3397 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3398 mixerStatus != MIXER_TRACKS_ENABLED) {
3399 mixerStatus = MIXER_TRACKS_READY;
3400 }
3401 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003402 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003403 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003404 }
Eric Laurent81784c32012-11-19 14:55:58 -08003405 // clear effect chain input buffer if an active track underruns to avoid sending
3406 // previous audio buffer again to effects
3407 chain = getEffectChain_l(track->sessionId());
3408 if (chain != 0) {
3409 chain->clearInputBuffer();
3410 }
3411
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003412 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003413 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3414 track->isStopped() || track->isPaused()) {
3415 // We have consumed all the buffers of this track.
3416 // Remove it from the list of active tracks.
3417 // TODO: use actual buffer filling status instead of latency when available from
3418 // audio HAL
3419 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3420 size_t framesWritten = mBytesWritten / mFrameSize;
3421 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3422 if (track->isStopped()) {
3423 track->reset();
3424 }
3425 tracksToRemove->add(track);
3426 }
3427 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003428 // No buffers for this track. Give it a few chances to
3429 // fill a buffer, then remove it from active list.
3430 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003431 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003432 tracksToRemove->add(track);
3433 // indicate to client process that the track was disabled because of underrun;
3434 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003435 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003436 // If one track is not ready, mark the mixer also not ready if:
3437 // - the mixer was ready during previous round OR
3438 // - no other track is ready
3439 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3440 mixerStatus != MIXER_TRACKS_READY) {
3441 mixerStatus = MIXER_TRACKS_ENABLED;
3442 }
3443 }
3444 mAudioMixer->disable(name);
3445 }
3446
3447 } // local variable scope to avoid goto warning
3448track_is_ready: ;
3449
3450 }
3451
3452 // Push the new FastMixer state if necessary
3453 bool pauseAudioWatchdog = false;
3454 if (didModify) {
3455 state->mFastTracksGen++;
3456 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3457 if (kUseFastMixer == FastMixer_Dynamic &&
3458 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3459 state->mCommand = FastMixerState::COLD_IDLE;
3460 state->mColdFutexAddr = &mFastMixerFutex;
3461 state->mColdGen++;
3462 mFastMixerFutex = 0;
3463 if (kUseFastMixer == FastMixer_Dynamic) {
3464 mNormalSink = mOutputSink;
3465 }
3466 // If we go into cold idle, need to wait for acknowledgement
3467 // so that fast mixer stops doing I/O.
3468 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3469 pauseAudioWatchdog = true;
3470 }
Eric Laurent81784c32012-11-19 14:55:58 -08003471 }
3472 if (sq != NULL) {
3473 sq->end(didModify);
3474 sq->push(block);
3475 }
3476#ifdef AUDIO_WATCHDOG
3477 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3478 mAudioWatchdog->pause();
3479 }
3480#endif
3481
3482 // Now perform the deferred reset on fast tracks that have stopped
3483 while (resetMask != 0) {
3484 size_t i = __builtin_ctz(resetMask);
3485 ALOG_ASSERT(i < count);
3486 resetMask &= ~(1 << i);
3487 sp<Track> t = mActiveTracks[i].promote();
3488 if (t == 0) {
3489 continue;
3490 }
3491 Track* track = t.get();
3492 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3493 track->reset();
3494 }
3495
3496 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003498
Andy Hung69aed5f2014-02-25 17:24:40 -08003499 // sink or mix buffer must be cleared if all tracks are connected to an
3500 // effect chain as in this case the mixer will not write to the sink or mix buffer
3501 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003502 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3503 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003504 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003505 if (mMixerBufferValid) {
3506 memset(mMixerBuffer, 0, mMixerBufferSize);
3507 // TODO: In testing, mSinkBuffer below need not be cleared because
3508 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3509 // after mixing.
3510 //
3511 // To enforce this guarantee:
3512 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3513 // (mixedTracks == 0 && fastTracks > 0))
3514 // must imply MIXER_TRACKS_READY.
3515 // Later, we may clear buffers regardless, and skip much of this logic.
3516 }
Andy Hung98ef9782014-03-04 14:46:50 -08003517 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3518 if (mEffectBufferValid) {
3519 memset(mEffectBuffer, 0, mEffectBufferSize);
3520 }
3521 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003522 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003523 }
3524
3525 // if any fast tracks, then status is ready
3526 mMixerStatusIgnoringFastTracks = mixerStatus;
3527 if (fastTracks > 0) {
3528 mixerStatus = MIXER_TRACKS_READY;
3529 }
3530 return mixerStatus;
3531}
3532
3533// getTrackName_l() must be called with ThreadBase::mLock held
3534int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3535{
3536 return mAudioMixer->getTrackName(channelMask, sessionId);
3537}
3538
3539// deleteTrackName_l() must be called with ThreadBase::mLock held
3540void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3541{
3542 ALOGV("remove track (%d) and delete from mixer", name);
3543 mAudioMixer->deleteTrackName(name);
3544}
3545
Eric Laurent10351942014-05-08 18:49:52 -07003546// checkForNewParameter_l() must be called with ThreadBase::mLock held
3547bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3548 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003549{
Eric Laurent81784c32012-11-19 14:55:58 -08003550 bool reconfig = false;
3551
Eric Laurent10351942014-05-08 18:49:52 -07003552 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003553
Eric Laurent10351942014-05-08 18:49:52 -07003554 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3555 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3556 if (mFastMixer != NULL) {
3557 FastMixerStateQueue *sq = mFastMixer->sq();
3558 FastMixerState *state = sq->begin();
3559 if (!(state->mCommand & FastMixerState::IDLE)) {
3560 previousCommand = state->mCommand;
3561 state->mCommand = FastMixerState::HOT_IDLE;
3562 sq->end();
3563 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3564 } else {
3565 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003566 }
Eric Laurent10351942014-05-08 18:49:52 -07003567 }
Eric Laurent81784c32012-11-19 14:55:58 -08003568
Eric Laurent10351942014-05-08 18:49:52 -07003569 AudioParameter param = AudioParameter(keyValuePair);
3570 int value;
3571 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3572 reconfig = true;
3573 }
3574 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3575 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3576 status = BAD_VALUE;
3577 } else {
3578 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003579 reconfig = true;
3580 }
Eric Laurent10351942014-05-08 18:49:52 -07003581 }
3582 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3583 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3584 status = BAD_VALUE;
3585 } else {
3586 // no need to save value, since it's constant
3587 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003588 }
Eric Laurent10351942014-05-08 18:49:52 -07003589 }
3590 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3591 // do not accept frame count changes if tracks are open as the track buffer
3592 // size depends on frame count and correct behavior would not be guaranteed
3593 // if frame count is changed after track creation
3594 if (!mTracks.isEmpty()) {
3595 status = INVALID_OPERATION;
3596 } else {
3597 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003598 }
Eric Laurent10351942014-05-08 18:49:52 -07003599 }
3600 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08003601#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07003602 // when changing the audio output device, call addBatteryData to notify
3603 // the change
3604 if (mOutDevice != value) {
3605 uint32_t params = 0;
3606 // check whether speaker is on
3607 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3608 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08003609 }
Eric Laurent10351942014-05-08 18:49:52 -07003610
3611 audio_devices_t deviceWithoutSpeaker
3612 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3613 // check if any other device (except speaker) is on
3614 if (value & deviceWithoutSpeaker ) {
3615 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3616 }
3617
3618 if (params != 0) {
3619 addBatteryData(params);
3620 }
3621 }
Eric Laurent81784c32012-11-19 14:55:58 -08003622#endif
3623
Eric Laurent10351942014-05-08 18:49:52 -07003624 // forward device change to effects that have requested to be
3625 // aware of attached audio device.
3626 if (value != AUDIO_DEVICE_NONE) {
3627 mOutDevice = value;
3628 for (size_t i = 0; i < mEffectChains.size(); i++) {
3629 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08003630 }
3631 }
Eric Laurent10351942014-05-08 18:49:52 -07003632 }
Eric Laurent81784c32012-11-19 14:55:58 -08003633
Eric Laurent10351942014-05-08 18:49:52 -07003634 if (status == NO_ERROR) {
3635 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3636 keyValuePair.string());
3637 if (!mStandby && status == INVALID_OPERATION) {
3638 mOutput->stream->common.standby(&mOutput->stream->common);
3639 mStandby = true;
3640 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003641 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07003642 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08003643 }
Eric Laurent10351942014-05-08 18:49:52 -07003644 if (status == NO_ERROR && reconfig) {
3645 readOutputParameters_l();
3646 delete mAudioMixer;
3647 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3648 for (size_t i = 0; i < mTracks.size() ; i++) {
3649 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3650 if (name < 0) {
3651 break;
3652 }
3653 mTracks[i]->mName = name;
3654 }
3655 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3656 }
Eric Laurent81784c32012-11-19 14:55:58 -08003657 }
3658
3659 if (!(previousCommand & FastMixerState::IDLE)) {
3660 ALOG_ASSERT(mFastMixer != NULL);
3661 FastMixerStateQueue *sq = mFastMixer->sq();
3662 FastMixerState *state = sq->begin();
3663 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3664 state->mCommand = previousCommand;
3665 sq->end();
3666 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3667 }
3668
3669 return reconfig;
3670}
3671
3672
3673void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3674{
3675 const size_t SIZE = 256;
3676 char buffer[SIZE];
3677 String8 result;
3678
3679 PlaybackThread::dumpInternals(fd, args);
3680
Marco Nelissenb2208842014-02-07 14:00:50 -08003681 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003682
3683 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003684 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003685 copy.dump(fd);
3686
3687#ifdef STATE_QUEUE_DUMP
3688 // Similar for state queue
3689 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3690 observerCopy.dump(fd);
3691 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3692 mutatorCopy.dump(fd);
3693#endif
3694
Glenn Kasten46909e72013-02-26 09:20:22 -08003695#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003696 // Write the tee output to a .wav file
3697 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003698#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003699
3700#ifdef AUDIO_WATCHDOG
3701 if (mAudioWatchdog != 0) {
3702 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3703 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3704 wdCopy.dump(fd);
3705 }
3706#endif
3707}
3708
3709uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3710{
3711 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3712}
3713
3714uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3715{
3716 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3717}
3718
3719void AudioFlinger::MixerThread::cacheParameters_l()
3720{
3721 PlaybackThread::cacheParameters_l();
3722
3723 // FIXME: Relaxed timing because of a certain device that can't meet latency
3724 // Should be reduced to 2x after the vendor fixes the driver issue
3725 // increase threshold again due to low power audio mode. The way this warning
3726 // threshold is calculated and its usefulness should be reconsidered anyway.
3727 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3728}
3729
3730// ----------------------------------------------------------------------------
3731
3732AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3733 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3734 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3735 // mLeftVolFloat, mRightVolFloat
3736{
3737}
3738
Eric Laurentbfb1b832013-01-07 09:53:42 -08003739AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3740 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3741 ThreadBase::type_t type)
3742 : PlaybackThread(audioFlinger, output, id, device, type)
3743 // mLeftVolFloat, mRightVolFloat
3744{
3745}
3746
Eric Laurent81784c32012-11-19 14:55:58 -08003747AudioFlinger::DirectOutputThread::~DirectOutputThread()
3748{
3749}
3750
Eric Laurentbfb1b832013-01-07 09:53:42 -08003751void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3752{
3753 audio_track_cblk_t* cblk = track->cblk();
3754 float left, right;
3755
3756 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3757 left = right = 0;
3758 } else {
3759 float typeVolume = mStreamTypes[track->streamType()].volume;
3760 float v = mMasterVolume * typeVolume;
3761 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3762 uint32_t vlr = proxy->getVolumeLR();
3763 float v_clamped = v * (vlr & 0xFFFF);
3764 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3765 left = v_clamped/MAX_GAIN;
3766 v_clamped = v * (vlr >> 16);
3767 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3768 right = v_clamped/MAX_GAIN;
3769 }
3770
3771 if (lastTrack) {
3772 if (left != mLeftVolFloat || right != mRightVolFloat) {
3773 mLeftVolFloat = left;
3774 mRightVolFloat = right;
3775
3776 // Convert volumes from float to 8.24
3777 uint32_t vl = (uint32_t)(left * (1 << 24));
3778 uint32_t vr = (uint32_t)(right * (1 << 24));
3779
3780 // Delegate volume control to effect in track effect chain if needed
3781 // only one effect chain can be present on DirectOutputThread, so if
3782 // there is one, the track is connected to it
3783 if (!mEffectChains.isEmpty()) {
3784 mEffectChains[0]->setVolume_l(&vl, &vr);
3785 left = (float)vl / (1 << 24);
3786 right = (float)vr / (1 << 24);
3787 }
3788 if (mOutput->stream->set_volume) {
3789 mOutput->stream->set_volume(mOutput->stream, left, right);
3790 }
3791 }
3792 }
3793}
3794
3795
Eric Laurent81784c32012-11-19 14:55:58 -08003796AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3797 Vector< sp<Track> > *tracksToRemove
3798)
3799{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003800 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003801 mixer_state mixerStatus = MIXER_IDLE;
3802
3803 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003804 for (size_t i = 0; i < count; i++) {
3805 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003806 // The track died recently
3807 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003808 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003809 }
3810
3811 Track* const track = t.get();
3812 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003813 // Only consider last track started for volume and mixer state control.
3814 // In theory an older track could underrun and restart after the new one starts
3815 // but as we only care about the transition phase between two tracks on a
3816 // direct output, it is not a problem to ignore the underrun case.
3817 sp<Track> l = mLatestActiveTrack.promote();
3818 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003819
3820 // The first time a track is added we wait
3821 // for all its buffers to be filled before processing it
3822 uint32_t minFrames;
3823 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3824 minFrames = mNormalFrameCount;
3825 } else {
3826 minFrames = 1;
3827 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003828
Eric Laurent81784c32012-11-19 14:55:58 -08003829 if ((track->framesReady() >= minFrames) && track->isReady() &&
3830 !track->isPaused() && !track->isTerminated())
3831 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003832 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003833
3834 if (track->mFillingUpStatus == Track::FS_FILLED) {
3835 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003836 // make sure processVolume_l() will apply new volume even if 0
3837 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003838 if (track->mState == TrackBase::RESUMING) {
3839 track->mState = TrackBase::ACTIVE;
3840 }
3841 }
3842
3843 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003844 processVolume_l(track, last);
3845 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003846 // reset retry count
3847 track->mRetryCount = kMaxTrackRetriesDirect;
3848 mActiveTrack = t;
3849 mixerStatus = MIXER_TRACKS_READY;
3850 }
Eric Laurent81784c32012-11-19 14:55:58 -08003851 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003852 // clear effect chain input buffer if the last active track started underruns
3853 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003854 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003855 mEffectChains[0]->clearInputBuffer();
3856 }
3857
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003858 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003859 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3860 track->isStopped() || track->isPaused()) {
3861 // We have consumed all the buffers of this track.
3862 // Remove it from the list of active tracks.
3863 // TODO: implement behavior for compressed audio
3864 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3865 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003866 if (mStandby || !last ||
3867 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003868 if (track->isStopped()) {
3869 track->reset();
3870 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003871 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003872 }
3873 } else {
3874 // No buffers for this track. Give it a few chances to
3875 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003876 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003877 if (--(track->mRetryCount) <= 0) {
3878 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003879 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003880 // indicate to client process that the track was disabled because of underrun;
3881 // it will then automatically call start() when data is available
3882 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003883 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003884 mixerStatus = MIXER_TRACKS_ENABLED;
3885 }
3886 }
3887 }
3888 }
3889
Eric Laurent81784c32012-11-19 14:55:58 -08003890 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003891 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003892
3893 return mixerStatus;
3894}
3895
3896void AudioFlinger::DirectOutputThread::threadLoop_mix()
3897{
Eric Laurent81784c32012-11-19 14:55:58 -08003898 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003899 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003900 // output audio to hardware
3901 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003902 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003903 buffer.frameCount = frameCount;
3904 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003905 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003906 memset(curBuf, 0, frameCount * mFrameSize);
3907 break;
3908 }
3909 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3910 frameCount -= buffer.frameCount;
3911 curBuf += buffer.frameCount * mFrameSize;
3912 mActiveTrack->releaseBuffer(&buffer);
3913 }
Andy Hung2098f272014-02-27 14:00:06 -08003914 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003915 sleepTime = 0;
3916 standbyTime = systemTime() + standbyDelay;
3917 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003918}
3919
3920void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3921{
3922 if (sleepTime == 0) {
3923 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3924 sleepTime = activeSleepTime;
3925 } else {
3926 sleepTime = idleSleepTime;
3927 }
3928 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003929 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003930 sleepTime = 0;
3931 }
3932}
3933
3934// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003935int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3936 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003937{
3938 return 0;
3939}
3940
3941// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003942void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003943{
3944}
3945
Eric Laurent10351942014-05-08 18:49:52 -07003946// checkForNewParameter_l() must be called with ThreadBase::mLock held
3947bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
3948 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003949{
3950 bool reconfig = false;
3951
Eric Laurent10351942014-05-08 18:49:52 -07003952 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003953
Eric Laurent10351942014-05-08 18:49:52 -07003954 AudioParameter param = AudioParameter(keyValuePair);
3955 int value;
3956 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3957 // forward device change to effects that have requested to be
3958 // aware of attached audio device.
3959 if (value != AUDIO_DEVICE_NONE) {
3960 mOutDevice = value;
3961 for (size_t i = 0; i < mEffectChains.size(); i++) {
3962 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07003963 }
3964 }
Eric Laurent81784c32012-11-19 14:55:58 -08003965 }
Eric Laurent10351942014-05-08 18:49:52 -07003966 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3967 // do not accept frame count changes if tracks are open as the track buffer
3968 // size depends on frame count and correct behavior would not be garantied
3969 // if frame count is changed after track creation
3970 if (!mTracks.isEmpty()) {
3971 status = INVALID_OPERATION;
3972 } else {
3973 reconfig = true;
3974 }
3975 }
3976 if (status == NO_ERROR) {
3977 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3978 keyValuePair.string());
3979 if (!mStandby && status == INVALID_OPERATION) {
3980 mOutput->stream->common.standby(&mOutput->stream->common);
3981 mStandby = true;
3982 mBytesWritten = 0;
3983 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3984 keyValuePair.string());
3985 }
3986 if (status == NO_ERROR && reconfig) {
3987 readOutputParameters_l();
3988 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3989 }
3990 }
3991
Eric Laurent81784c32012-11-19 14:55:58 -08003992 return reconfig;
3993}
3994
3995uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3996{
3997 uint32_t time;
3998 if (audio_is_linear_pcm(mFormat)) {
3999 time = PlaybackThread::activeSleepTimeUs();
4000 } else {
4001 time = 10000;
4002 }
4003 return time;
4004}
4005
4006uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4007{
4008 uint32_t time;
4009 if (audio_is_linear_pcm(mFormat)) {
4010 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4011 } else {
4012 time = 10000;
4013 }
4014 return time;
4015}
4016
4017uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4018{
4019 uint32_t time;
4020 if (audio_is_linear_pcm(mFormat)) {
4021 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4022 } else {
4023 time = 10000;
4024 }
4025 return time;
4026}
4027
4028void AudioFlinger::DirectOutputThread::cacheParameters_l()
4029{
4030 PlaybackThread::cacheParameters_l();
4031
4032 // use shorter standby delay as on normal output to release
4033 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004034 if (audio_is_linear_pcm(mFormat)) {
4035 standbyDelay = microseconds(activeSleepTime*2);
4036 } else {
4037 standbyDelay = kOffloadStandbyDelayNs;
4038 }
Eric Laurent81784c32012-11-19 14:55:58 -08004039}
4040
4041// ----------------------------------------------------------------------------
4042
Eric Laurentbfb1b832013-01-07 09:53:42 -08004043AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004044 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004045 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004046 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004047 mWriteAckSequence(0),
4048 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049{
4050}
4051
4052AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4053{
4054}
4055
4056void AudioFlinger::AsyncCallbackThread::onFirstRef()
4057{
4058 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4059}
4060
4061bool AudioFlinger::AsyncCallbackThread::threadLoop()
4062{
4063 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004064 uint32_t writeAckSequence;
4065 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004066
4067 {
4068 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004069 while (!((mWriteAckSequence & 1) ||
4070 (mDrainSequence & 1) ||
4071 exitPending())) {
4072 mWaitWorkCV.wait(mLock);
4073 }
4074
Eric Laurentbfb1b832013-01-07 09:53:42 -08004075 if (exitPending()) {
4076 break;
4077 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004078 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4079 mWriteAckSequence, mDrainSequence);
4080 writeAckSequence = mWriteAckSequence;
4081 mWriteAckSequence &= ~1;
4082 drainSequence = mDrainSequence;
4083 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004084 }
4085 {
Eric Laurent4de95592013-09-26 15:28:21 -07004086 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4087 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004088 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004089 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004090 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004091 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004092 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004093 }
4094 }
4095 }
4096 }
4097 return false;
4098}
4099
4100void AudioFlinger::AsyncCallbackThread::exit()
4101{
4102 ALOGV("AsyncCallbackThread::exit");
4103 Mutex::Autolock _l(mLock);
4104 requestExit();
4105 mWaitWorkCV.broadcast();
4106}
4107
Eric Laurent3b4529e2013-09-05 18:09:19 -07004108void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004109{
4110 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004111 // bit 0 is cleared
4112 mWriteAckSequence = sequence << 1;
4113}
4114
4115void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4116{
4117 Mutex::Autolock _l(mLock);
4118 // ignore unexpected callbacks
4119 if (mWriteAckSequence & 2) {
4120 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121 mWaitWorkCV.signal();
4122 }
4123}
4124
Eric Laurent3b4529e2013-09-05 18:09:19 -07004125void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004126{
4127 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004128 // bit 0 is cleared
4129 mDrainSequence = sequence << 1;
4130}
4131
4132void AudioFlinger::AsyncCallbackThread::resetDraining()
4133{
4134 Mutex::Autolock _l(mLock);
4135 // ignore unexpected callbacks
4136 if (mDrainSequence & 2) {
4137 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138 mWaitWorkCV.signal();
4139 }
4140}
4141
4142
4143// ----------------------------------------------------------------------------
4144AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4145 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4146 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4147 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004148 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004149 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004150{
Eric Laurentfd477972013-10-25 18:10:40 -07004151 //FIXME: mStandby should be set to true by ThreadBase constructor
4152 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153}
4154
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155void AudioFlinger::OffloadThread::threadLoop_exit()
4156{
4157 if (mFlushPending || mHwPaused) {
4158 // If a flush is pending or track was paused, just discard buffered data
4159 flushHw_l();
4160 } else {
4161 mMixerStatus = MIXER_DRAIN_ALL;
4162 threadLoop_drain();
4163 }
4164 mCallbackThread->exit();
4165 PlaybackThread::threadLoop_exit();
4166}
4167
4168AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4169 Vector< sp<Track> > *tracksToRemove
4170)
4171{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004172 size_t count = mActiveTracks.size();
4173
4174 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004175 bool doHwPause = false;
4176 bool doHwResume = false;
4177
Eric Laurentede6c3b2013-09-19 14:37:46 -07004178 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4179
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180 // find out which tracks need to be processed
4181 for (size_t i = 0; i < count; i++) {
4182 sp<Track> t = mActiveTracks[i].promote();
4183 // The track died recently
4184 if (t == 0) {
4185 continue;
4186 }
4187 Track* const track = t.get();
4188 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004189 // Only consider last track started for volume and mixer state control.
4190 // In theory an older track could underrun and restart after the new one starts
4191 // but as we only care about the transition phase between two tracks on a
4192 // direct output, it is not a problem to ignore the underrun case.
4193 sp<Track> l = mLatestActiveTrack.promote();
4194 bool last = l.get() == track;
4195
Haynes Mathew George7844f672014-01-15 12:32:55 -08004196 if (track->isInvalid()) {
4197 ALOGW("An invalidated track shouldn't be in active list");
4198 tracksToRemove->add(track);
4199 continue;
4200 }
4201
4202 if (track->mState == TrackBase::IDLE) {
4203 ALOGW("An idle track shouldn't be in active list");
4204 continue;
4205 }
4206
Eric Laurentbfb1b832013-01-07 09:53:42 -08004207 if (track->isPausing()) {
4208 track->setPaused();
4209 if (last) {
4210 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004211 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004212 mHwPaused = true;
4213 }
4214 // If we were part way through writing the mixbuffer to
4215 // the HAL we must save this until we resume
4216 // BUG - this will be wrong if a different track is made active,
4217 // in that case we want to discard the pending data in the
4218 // mixbuffer and tell the client to present it again when the
4219 // track is resumed
4220 mPausedWriteLength = mCurrentWriteLength;
4221 mPausedBytesRemaining = mBytesRemaining;
4222 mBytesRemaining = 0; // stop writing
4223 }
4224 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004225 } else if (track->isFlushPending()) {
4226 track->flushAck();
4227 if (last) {
4228 mFlushPending = true;
4229 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004230 } else if (track->isResumePending()){
4231 track->resumeAck();
4232 if (last) {
4233 if (mPausedBytesRemaining) {
4234 // Need to continue write that was interrupted
4235 mCurrentWriteLength = mPausedWriteLength;
4236 mBytesRemaining = mPausedBytesRemaining;
4237 mPausedBytesRemaining = 0;
4238 }
4239 if (mHwPaused) {
4240 doHwResume = true;
4241 mHwPaused = false;
4242 // threadLoop_mix() will handle the case that we need to
4243 // resume an interrupted write
4244 }
4245 // enable write to audio HAL
4246 sleepTime = 0;
4247
4248 // Do not handle new data in this iteration even if track->framesReady()
4249 mixerStatus = MIXER_TRACKS_ENABLED;
4250 }
4251 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004252 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004253 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004254 if (track->mFillingUpStatus == Track::FS_FILLED) {
4255 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004256 // make sure processVolume_l() will apply new volume even if 0
4257 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258 }
4259
4260 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004261 sp<Track> previousTrack = mPreviousTrack.promote();
4262 if (previousTrack != 0) {
4263 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004264 // Flush any data still being written from last track
4265 mBytesRemaining = 0;
4266 if (mPausedBytesRemaining) {
4267 // Last track was paused so we also need to flush saved
4268 // mixbuffer state and invalidate track so that it will
4269 // re-submit that unwritten data when it is next resumed
4270 mPausedBytesRemaining = 0;
4271 // Invalidate is a bit drastic - would be more efficient
4272 // to have a flag to tell client that some of the
4273 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004274 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004275 }
4276 // flush data already sent to the DSP if changing audio session as audio
4277 // comes from a different source. Also invalidate previous track to force a
4278 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004279 if (previousTrack->sessionId() != track->sessionId()) {
4280 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004281 }
4282 }
4283 }
4284 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 // reset retry count
4286 track->mRetryCount = kMaxTrackRetriesOffload;
4287 mActiveTrack = t;
4288 mixerStatus = MIXER_TRACKS_READY;
4289 }
4290 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004291 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004292 if (track->isStopping_1()) {
4293 // Hardware buffer can hold a large amount of audio so we must
4294 // wait for all current track's data to drain before we say
4295 // that the track is stopped.
4296 if (mBytesRemaining == 0) {
4297 // Only start draining when all data in mixbuffer
4298 // has been written
4299 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4300 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004301 // do not drain if no data was ever sent to HAL (mStandby == true)
4302 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004303 // do not modify drain sequence if we are already draining. This happens
4304 // when resuming from pause after drain.
4305 if ((mDrainSequence & 1) == 0) {
4306 sleepTime = 0;
4307 standbyTime = systemTime() + standbyDelay;
4308 mixerStatus = MIXER_DRAIN_TRACK;
4309 mDrainSequence += 2;
4310 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004311 if (mHwPaused) {
4312 // It is possible to move from PAUSED to STOPPING_1 without
4313 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004314 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315 mHwPaused = false;
4316 }
4317 }
4318 }
4319 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004320 // Drain has completed or we are in standby, signal presentation complete
4321 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004322 track->mState = TrackBase::STOPPED;
4323 size_t audioHALFrames =
4324 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4325 size_t framesWritten =
4326 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4327 track->presentationComplete(framesWritten, audioHALFrames);
4328 track->reset();
4329 tracksToRemove->add(track);
4330 }
4331 } else {
4332 // No buffers for this track. Give it a few chances to
4333 // fill a buffer, then remove it from active list.
4334 if (--(track->mRetryCount) <= 0) {
4335 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4336 track->name());
4337 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004338 // indicate to client process that the track was disabled because of underrun;
4339 // it will then automatically call start() when data is available
4340 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004341 } else if (last){
4342 mixerStatus = MIXER_TRACKS_ENABLED;
4343 }
4344 }
4345 }
4346 // compute volume for this track
4347 processVolume_l(track, last);
4348 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004349
Eric Laurentea0fade2013-10-04 16:23:48 -07004350 // make sure the pause/flush/resume sequence is executed in the right order.
4351 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4352 // before flush and then resume HW. This can happen in case of pause/flush/resume
4353 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004354 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004355 mOutput->stream->pause(mOutput->stream);
4356 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004357 if (mFlushPending) {
4358 flushHw_l();
4359 mFlushPending = false;
4360 }
Eric Laurentfd477972013-10-25 18:10:40 -07004361 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004362 mOutput->stream->resume(mOutput->stream);
4363 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004364
Eric Laurentbfb1b832013-01-07 09:53:42 -08004365 // remove all the tracks that need to be...
4366 removeTracks_l(*tracksToRemove);
4367
4368 return mixerStatus;
4369}
4370
Eric Laurentbfb1b832013-01-07 09:53:42 -08004371// must be called with thread mutex locked
4372bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4373{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004374 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4375 mWriteAckSequence, mDrainSequence);
4376 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 return true;
4378 }
4379 return false;
4380}
4381
4382// must be called with thread mutex locked
4383bool AudioFlinger::OffloadThread::shouldStandby_l()
4384{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004385 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004386
4387 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4388 // after a timeout and we will enter standby then.
4389 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004390 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 }
4392
Glenn Kastene6f35b12013-08-19 09:58:50 -07004393 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004394}
4395
4396
4397bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4398{
4399 Mutex::Autolock _l(mLock);
4400 return waitingAsyncCallback_l();
4401}
4402
4403void AudioFlinger::OffloadThread::flushHw_l()
4404{
4405 mOutput->stream->flush(mOutput->stream);
4406 // Flush anything still waiting in the mixbuffer
4407 mCurrentWriteLength = 0;
4408 mBytesRemaining = 0;
4409 mPausedWriteLength = 0;
4410 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004411 mHwPaused = false;
4412
Eric Laurentbfb1b832013-01-07 09:53:42 -08004413 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004414 // discard any pending drain or write ack by incrementing sequence
4415 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4416 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004417 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004418 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4419 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004420 }
4421}
4422
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004423void AudioFlinger::OffloadThread::onAddNewTrack_l()
4424{
4425 sp<Track> previousTrack = mPreviousTrack.promote();
4426 sp<Track> latestTrack = mLatestActiveTrack.promote();
4427
4428 if (previousTrack != 0 && latestTrack != 0 &&
4429 (previousTrack->sessionId() != latestTrack->sessionId())) {
4430 mFlushPending = true;
4431 }
4432 PlaybackThread::onAddNewTrack_l();
4433}
4434
Eric Laurentbfb1b832013-01-07 09:53:42 -08004435// ----------------------------------------------------------------------------
4436
Eric Laurent81784c32012-11-19 14:55:58 -08004437AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4438 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4439 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4440 DUPLICATING),
4441 mWaitTimeMs(UINT_MAX)
4442{
4443 addOutputTrack(mainThread);
4444}
4445
4446AudioFlinger::DuplicatingThread::~DuplicatingThread()
4447{
4448 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4449 mOutputTracks[i]->destroy();
4450 }
4451}
4452
4453void AudioFlinger::DuplicatingThread::threadLoop_mix()
4454{
4455 // mix buffers...
4456 if (outputsReady(outputTracks)) {
4457 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4458 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004459 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004460 }
4461 sleepTime = 0;
4462 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004463 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004464 standbyTime = systemTime() + standbyDelay;
4465}
4466
4467void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4468{
4469 if (sleepTime == 0) {
4470 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4471 sleepTime = activeSleepTime;
4472 } else {
4473 sleepTime = idleSleepTime;
4474 }
4475 } else if (mBytesWritten != 0) {
4476 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4477 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004478 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004479 } else {
4480 // flush remaining overflow buffers in output tracks
4481 writeFrames = 0;
4482 }
4483 sleepTime = 0;
4484 }
4485}
4486
Eric Laurentbfb1b832013-01-07 09:53:42 -08004487ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004488{
4489 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004490 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4491 // for delivery downstream as needed. This in-place conversion is safe as
4492 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4493 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4494 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4495 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4496 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4497 }
4498 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004499 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004500 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004501 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004502}
4503
4504void AudioFlinger::DuplicatingThread::threadLoop_standby()
4505{
4506 // DuplicatingThread implements standby by stopping all tracks
4507 for (size_t i = 0; i < outputTracks.size(); i++) {
4508 outputTracks[i]->stop();
4509 }
4510}
4511
4512void AudioFlinger::DuplicatingThread::saveOutputTracks()
4513{
4514 outputTracks = mOutputTracks;
4515}
4516
4517void AudioFlinger::DuplicatingThread::clearOutputTracks()
4518{
4519 outputTracks.clear();
4520}
4521
4522void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4523{
4524 Mutex::Autolock _l(mLock);
4525 // FIXME explain this formula
4526 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004527 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4528 // due to current usage case and restrictions on the AudioBufferProvider.
4529 // Actual buffer conversion is done in threadLoop_write().
4530 //
4531 // TODO: This may change in the future, depending on multichannel
4532 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004533 OutputTrack *outputTrack = new OutputTrack(thread,
4534 this,
4535 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004536 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004537 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004538 frameCount,
4539 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004540 if (outputTrack->cblk() != NULL) {
4541 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4542 mOutputTracks.add(outputTrack);
4543 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4544 updateWaitTime_l();
4545 }
4546}
4547
4548void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4549{
4550 Mutex::Autolock _l(mLock);
4551 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4552 if (mOutputTracks[i]->thread() == thread) {
4553 mOutputTracks[i]->destroy();
4554 mOutputTracks.removeAt(i);
4555 updateWaitTime_l();
4556 return;
4557 }
4558 }
4559 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4560}
4561
4562// caller must hold mLock
4563void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4564{
4565 mWaitTimeMs = UINT_MAX;
4566 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4567 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4568 if (strong != 0) {
4569 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4570 if (waitTimeMs < mWaitTimeMs) {
4571 mWaitTimeMs = waitTimeMs;
4572 }
4573 }
4574 }
4575}
4576
4577
4578bool AudioFlinger::DuplicatingThread::outputsReady(
4579 const SortedVector< sp<OutputTrack> > &outputTracks)
4580{
4581 for (size_t i = 0; i < outputTracks.size(); i++) {
4582 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4583 if (thread == 0) {
4584 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4585 outputTracks[i].get());
4586 return false;
4587 }
4588 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4589 // see note at standby() declaration
4590 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4591 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4592 thread.get());
4593 return false;
4594 }
4595 }
4596 return true;
4597}
4598
4599uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4600{
4601 return (mWaitTimeMs * 1000) / 2;
4602}
4603
4604void AudioFlinger::DuplicatingThread::cacheParameters_l()
4605{
4606 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4607 updateWaitTime_l();
4608
4609 MixerThread::cacheParameters_l();
4610}
4611
4612// ----------------------------------------------------------------------------
4613// Record
4614// ----------------------------------------------------------------------------
4615
4616AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4617 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004618 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004619 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004620 audio_devices_t inDevice
4621#ifdef TEE_SINK
4622 , const sp<NBAIO_Sink>& teeSink
4623#endif
4624 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004625 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004626 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004627 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004628 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004629#ifdef TEE_SINK
4630 , mTeeSink(teeSink)
4631#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004632 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4633 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004634{
4635 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004636 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004637
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004638 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004639}
4640
4641
4642AudioFlinger::RecordThread::~RecordThread()
4643{
Glenn Kasten481fb672013-09-30 14:39:28 -07004644 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004645 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004646}
4647
4648void AudioFlinger::RecordThread::onFirstRef()
4649{
4650 run(mName, PRIORITY_URGENT_AUDIO);
4651}
4652
Eric Laurent81784c32012-11-19 14:55:58 -08004653bool AudioFlinger::RecordThread::threadLoop()
4654{
Eric Laurent81784c32012-11-19 14:55:58 -08004655 nsecs_t lastWarning = 0;
4656
4657 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004658
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004659reacquire_wakelock:
4660 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004661 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004662 {
4663 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004664 size_t size = mActiveTracks.size();
4665 activeTracksGen = mActiveTracksGen;
4666 if (size > 0) {
4667 // FIXME an arbitrary choice
4668 activeTrack = mActiveTracks[0];
4669 acquireWakeLock_l(activeTrack->uid());
4670 if (size > 1) {
4671 SortedVector<int> tmp;
4672 for (size_t i = 0; i < size; i++) {
4673 tmp.add(mActiveTracks[i]->uid());
4674 }
4675 updateWakeLockUids_l(tmp);
4676 }
4677 } else {
4678 acquireWakeLock_l(-1);
4679 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004680 }
4681
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004682 // used to request a deferred sleep, to be executed later while mutex is unlocked
4683 uint32_t sleepUs = 0;
4684
4685 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004686 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004687 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004688
Glenn Kasten5edadd42013-08-14 16:30:49 -07004689 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004690 if (sleepUs > 0) {
4691 usleep(sleepUs);
4692 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004693 }
4694
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004695 // activeTracks accumulates a copy of a subset of mActiveTracks
4696 Vector< sp<RecordTrack> > activeTracks;
4697
Eric Laurent10351942014-05-08 18:49:52 -07004698 DefaultKeyedVector< pid_t,sp<NotificationClient> > notificationClients =
4699 mAudioFlinger->notificationClients();
4700
Eric Laurent81784c32012-11-19 14:55:58 -08004701 { // scope for mLock
4702 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004703
Eric Laurent10351942014-05-08 18:49:52 -07004704 processConfigEvents_l(notificationClients);
4705 notificationClients.clear();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004706
Eric Laurent000a4192014-01-29 15:17:32 -08004707 // check exitPending here because checkForNewParameters_l() and
4708 // checkForNewParameters_l() can temporarily release mLock
4709 if (exitPending()) {
4710 break;
4711 }
4712
Glenn Kasten2b806402013-11-20 16:37:38 -08004713 // if no active track(s), then standby and release wakelock
4714 size_t size = mActiveTracks.size();
4715 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004716 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004717 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004718 releaseWakeLock_l();
4719 ALOGV("RecordThread: loop stopping");
4720 // go to sleep
4721 mWaitWorkCV.wait(mLock);
4722 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004723 goto reacquire_wakelock;
4724 }
4725
Glenn Kasten2b806402013-11-20 16:37:38 -08004726 if (mActiveTracksGen != activeTracksGen) {
4727 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004728 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004729 for (size_t i = 0; i < size; i++) {
4730 tmp.add(mActiveTracks[i]->uid());
4731 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004732 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004733 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004734
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004735 bool doBroadcast = false;
4736 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004737
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004738 activeTrack = mActiveTracks[i];
4739 if (activeTrack->isTerminated()) {
4740 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004741 mActiveTracks.remove(activeTrack);
4742 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004743 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004744 continue;
4745 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004746
4747 TrackBase::track_state activeTrackState = activeTrack->mState;
4748 switch (activeTrackState) {
4749
4750 case TrackBase::PAUSING:
4751 mActiveTracks.remove(activeTrack);
4752 mActiveTracksGen++;
4753 doBroadcast = true;
4754 size--;
4755 continue;
4756
4757 case TrackBase::STARTING_1:
4758 sleepUs = 10000;
4759 i++;
4760 continue;
4761
4762 case TrackBase::STARTING_2:
4763 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004764 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004765 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004766 break;
4767
4768 case TrackBase::ACTIVE:
4769 break;
4770
4771 case TrackBase::IDLE:
4772 i++;
4773 continue;
4774
4775 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004776 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004777 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004778
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004779 activeTracks.add(activeTrack);
4780 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004781
Glenn Kasten9e982352013-08-14 14:39:50 -07004782 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004783 if (doBroadcast) {
4784 mStartStopCond.broadcast();
4785 }
4786
4787 // sleep if there are no active tracks to process
4788 if (activeTracks.size() == 0) {
4789 if (sleepUs == 0) {
4790 sleepUs = kRecordThreadSleepUs;
4791 }
4792 continue;
4793 }
4794 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004795
Eric Laurent81784c32012-11-19 14:55:58 -08004796 lockEffectChains_l(effectChains);
4797 }
4798
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004799 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004800
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004801 size_t size = effectChains.size();
4802 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004803 // thread mutex is not locked, but effect chain is locked
4804 effectChains[i]->process_l();
4805 }
4806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004807 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4808 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4809 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4810 // If destination is non-contiguous, first read past the nominal end of buffer, then
4811 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004812
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004813 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4814 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4815 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4816 if (bytesRead <= 0) {
4817 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4818 // Force input into standby so that it tries to recover at next read attempt
4819 inputStandBy();
4820 sleepUs = kRecordThreadSleepUs;
4821 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004822 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004823 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4824 size_t framesRead = bytesRead / mFrameSize;
4825 ALOG_ASSERT(framesRead > 0);
4826 if (mTeeSink != 0) {
4827 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4828 }
4829 // If destination is non-contiguous, we now correct for reading past end of buffer.
4830 size_t part1 = mRsmpInFramesP2 - rear;
4831 if (framesRead > part1) {
4832 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4833 (framesRead - part1) * mFrameSize);
4834 }
4835 rear = mRsmpInRear += framesRead;
4836
4837 size = activeTracks.size();
4838 // loop over each active track
4839 for (size_t i = 0; i < size; i++) {
4840 activeTrack = activeTracks[i];
4841
4842 enum {
4843 OVERRUN_UNKNOWN,
4844 OVERRUN_TRUE,
4845 OVERRUN_FALSE
4846 } overrun = OVERRUN_UNKNOWN;
4847
4848 // loop over getNextBuffer to handle circular sink
4849 for (;;) {
4850
4851 activeTrack->mSink.frameCount = ~0;
4852 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4853 size_t framesOut = activeTrack->mSink.frameCount;
4854 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4855
4856 int32_t front = activeTrack->mRsmpInFront;
4857 ssize_t filled = rear - front;
4858 size_t framesIn;
4859
4860 if (filled < 0) {
4861 // should not happen, but treat like a massive overrun and re-sync
4862 framesIn = 0;
4863 activeTrack->mRsmpInFront = rear;
4864 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004865 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004866 framesIn = (size_t) filled;
4867 } else {
4868 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004869 framesIn = mRsmpInFrames;
4870 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004871 overrun = OVERRUN_TRUE;
4872 }
4873
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004874 if (framesOut == 0 || framesIn == 0) {
4875 break;
4876 }
4877
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004878 if (activeTrack->mResampler == NULL) {
4879 // no resampling
4880 if (framesIn > framesOut) {
4881 framesIn = framesOut;
4882 } else {
4883 framesOut = framesIn;
4884 }
4885 int8_t *dst = activeTrack->mSink.i8;
4886 while (framesIn > 0) {
4887 front &= mRsmpInFramesP2 - 1;
4888 size_t part1 = mRsmpInFramesP2 - front;
4889 if (part1 > framesIn) {
4890 part1 = framesIn;
4891 }
4892 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004893 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004894 memcpy(dst, src, part1 * mFrameSize);
4895 } else if (mChannelCount == 1) {
4896 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4897 part1);
4898 } else {
4899 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4900 part1);
4901 }
4902 dst += part1 * activeTrack->mFrameSize;
4903 front += part1;
4904 framesIn -= part1;
4905 }
4906 activeTrack->mRsmpInFront += framesOut;
4907
4908 } else {
4909 // resampling
4910 // FIXME framesInNeeded should really be part of resampler API, and should
4911 // depend on the SRC ratio
4912 // to keep mRsmpInBuffer full so resampler always has sufficient input
4913 size_t framesInNeeded;
4914 // FIXME only re-calculate when it changes, and optimize for common ratios
4915 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4916 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004917 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004918 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4919 framesInNeeded, framesOut, inOverOut);
4920 // Although we theoretically have framesIn in circular buffer, some of those are
4921 // unreleased frames, and thus must be discounted for purpose of budgeting.
4922 size_t unreleased = activeTrack->mRsmpInUnrel;
4923 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004924 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004925 ALOGV("not enough to resample: have %u frames in but need %u in to "
4926 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004927 framesIn, framesInNeeded, framesOut, inOverOut);
4928 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004929 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4930 if (newFramesOut == 0) {
4931 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004932 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004933 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4934 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4935 framesInNeeded, newFramesOut, outOverIn);
4936 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4937 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4938 "given in/out ratio of %.4g",
4939 framesIn, framesInNeeded, newFramesOut, inOverOut);
4940 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004941 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004942 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004943 "given in/out ratio of %.4g",
4944 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004945 }
4946
4947 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4948 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004949 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004950 delete[] activeTrack->mRsmpOutBuffer;
4951 // resampler always outputs stereo
4952 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4953 activeTrack->mRsmpOutFrameCount = framesOut;
4954 }
4955
4956 // resampler accumulates, but we only have one source track
4957 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4958 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004959 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004960 activeTrack->mResamplerBufferProvider
4961 /*this*/ /* AudioBufferProvider* */);
4962 // ditherAndClamp() works as long as all buffers returned by
4963 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004964 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07004965 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004966 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4967 framesOut);
4968 // the resampler always outputs stereo samples:
4969 // do post stereo to mono conversion
4970 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4971 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4972 } else {
4973 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4974 activeTrack->mRsmpOutBuffer, framesOut);
4975 }
4976 // now done with mRsmpOutBuffer
4977
4978 }
4979
4980 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4981 overrun = OVERRUN_FALSE;
4982 }
4983
4984 if (activeTrack->mFramesToDrop == 0) {
4985 if (framesOut > 0) {
4986 activeTrack->mSink.frameCount = framesOut;
4987 activeTrack->releaseBuffer(&activeTrack->mSink);
4988 }
4989 } else {
4990 // FIXME could do a partial drop of framesOut
4991 if (activeTrack->mFramesToDrop > 0) {
4992 activeTrack->mFramesToDrop -= framesOut;
4993 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08004994 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004995 }
4996 } else {
4997 activeTrack->mFramesToDrop += framesOut;
4998 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
4999 activeTrack->mSyncStartEvent->isCancelled()) {
5000 ALOGW("Synced record %s, session %d, trigger session %d",
5001 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5002 activeTrack->sessionId(),
5003 (activeTrack->mSyncStartEvent != 0) ?
5004 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005005 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005006 }
5007 }
5008 }
5009
5010 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005011 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005012 }
5013 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005014
5015 switch (overrun) {
5016 case OVERRUN_TRUE:
5017 // client isn't retrieving buffers fast enough
5018 if (!activeTrack->setOverflow()) {
5019 nsecs_t now = systemTime();
5020 // FIXME should lastWarning per track?
5021 if ((now - lastWarning) > kWarningThrottleNs) {
5022 ALOGW("RecordThread: buffer overflow");
5023 lastWarning = now;
5024 }
5025 }
5026 break;
5027 case OVERRUN_FALSE:
5028 activeTrack->clearOverflow();
5029 break;
5030 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005031 break;
5032 }
5033
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005034 }
5035
Eric Laurent81784c32012-11-19 14:55:58 -08005036 // enable changes in effect chain
5037 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005038 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005039 }
5040
Glenn Kasten93e471f2013-08-19 08:40:07 -07005041 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005042
5043 {
5044 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005045 for (size_t i = 0; i < mTracks.size(); i++) {
5046 sp<RecordTrack> track = mTracks[i];
5047 track->invalidate();
5048 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005049 mActiveTracks.clear();
5050 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005051 mStartStopCond.broadcast();
5052 }
5053
5054 releaseWakeLock();
5055
5056 ALOGV("RecordThread %p exiting", this);
5057 return false;
5058}
5059
Glenn Kasten93e471f2013-08-19 08:40:07 -07005060void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005061{
5062 if (!mStandby) {
5063 inputStandBy();
5064 mStandby = true;
5065 }
5066}
5067
5068void AudioFlinger::RecordThread::inputStandBy()
5069{
5070 mInput->stream->common.standby(&mInput->stream->common);
5071}
5072
Glenn Kasten05997e22014-03-13 15:08:33 -07005073// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005074sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005075 const sp<AudioFlinger::Client>& client,
5076 uint32_t sampleRate,
5077 audio_format_t format,
5078 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005079 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005080 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005081 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005082 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005083 pid_t tid,
5084 status_t *status)
5085{
Glenn Kasten74935e42013-12-19 08:56:45 -08005086 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005087 sp<RecordTrack> track;
5088 status_t lStatus;
5089
Glenn Kasten90e58b12013-07-31 16:16:02 -07005090 // client expresses a preference for FAST, but we get the final say
5091 if (*flags & IAudioFlinger::TRACK_FAST) {
5092 if (
5093 // use case: callback handler and frame count is default or at least as large as HAL
5094 (
5095 (tid != -1) &&
5096 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005097 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005098 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005099 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005100 // PCM data
5101 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005102 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005103 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5104 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005105 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005106 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005107 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005108 // record thread has an associated fast capture
5109 hasFastCapture()
5110 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005111 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005112 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005113 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005114 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005115 frameCount = mFrameCount * kFastTrackMultiplier;
5116 }
5117 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5118 frameCount, mFrameCount);
5119 } else {
5120 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5121 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005122 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005123 frameCount, mFrameCount, format,
5124 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005125 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005126 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005127 // 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 -07005128 // For compatibility with AudioRecord calculation, buffer depth is forced
5129 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5130 // This is probably too conservative, but legacy application code may depend on it.
5131 // If you change this calculation, also review the start threshold which is related.
5132 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5133 size_t mNormalFrameCount = 2048; // FIXME
5134 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5135 if (minBufCount < 2) {
5136 minBufCount = 2;
5137 }
5138 size_t minFrameCount = mNormalFrameCount * minBufCount;
5139 if (frameCount < minFrameCount) {
5140 frameCount = minFrameCount;
5141 }
5142 }
5143 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005144 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005145
Glenn Kasten15e57982013-09-24 11:52:37 -07005146 lStatus = initCheck();
5147 if (lStatus != NO_ERROR) {
5148 ALOGE("createRecordTrack_l() audio driver not initialized");
5149 goto Exit;
5150 }
Eric Laurent81784c32012-11-19 14:55:58 -08005151
5152 { // scope for mLock
5153 Mutex::Autolock _l(mLock);
5154
5155 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005156 format, channelMask, frameCount, sessionId, uid,
5157 (*flags & IAudioFlinger::TRACK_FAST) != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08005158
Glenn Kasten03003332013-08-06 15:40:54 -07005159 lStatus = track->initCheck();
5160 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005161 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005162 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005163 goto Exit;
5164 }
5165 mTracks.add(track);
5166
5167 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5168 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5169 mAudioFlinger->btNrecIsOff();
5170 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5171 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005172
5173 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5174 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5175 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5176 // so ask activity manager to do this on our behalf
5177 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005180
Eric Laurent81784c32012-11-19 14:55:58 -08005181 lStatus = NO_ERROR;
5182
5183Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005184 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005185 return track;
5186}
5187
5188status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5189 AudioSystem::sync_event_t event,
5190 int triggerSession)
5191{
5192 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5193 sp<ThreadBase> strongMe = this;
5194 status_t status = NO_ERROR;
5195
5196 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005197 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005198 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005199 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005200 triggerSession,
5201 recordTrack->sessionId(),
5202 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005203 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005204 // Sync event can be cancelled by the trigger session if the track is not in a
5205 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005206 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005207 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005208 } else {
5209 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005210 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005211 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005212 }
5213 }
5214
5215 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005216 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005217 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005218 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5219 if (recordTrack->mState == TrackBase::PAUSING) {
5220 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005221 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005222 } else {
5223 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005224 }
5225 return status;
5226 }
5227
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005228 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5229 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5230 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005231 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005232 mActiveTracks.add(recordTrack);
5233 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005234 mLock.unlock();
5235 status_t status = AudioSystem::startInput(mId);
5236 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005237 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005238 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005239 mActiveTracks.remove(recordTrack);
5240 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005241 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005242 return status;
5243 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005244 // Catch up with current buffer indices if thread is already running.
5245 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5246 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5247 // see previously buffered data before it called start(), but with greater risk of overrun.
5248
5249 recordTrack->mRsmpInFront = mRsmpInRear;
5250 recordTrack->mRsmpInUnrel = 0;
5251 // FIXME why reset?
5252 if (recordTrack->mResampler != NULL) {
5253 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005254 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005255 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005256 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005257 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005258 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005259 ALOGV("Record failed to start");
5260 status = BAD_VALUE;
5261 goto startError;
5262 }
Eric Laurent81784c32012-11-19 14:55:58 -08005263 return status;
5264 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005265
Eric Laurent81784c32012-11-19 14:55:58 -08005266startError:
5267 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005268 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005269 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005270 return status;
5271}
5272
Eric Laurent81784c32012-11-19 14:55:58 -08005273void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5274{
5275 sp<SyncEvent> strongEvent = event.promote();
5276
5277 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005278 sp<RefBase> ptr = strongEvent->cookie().promote();
5279 if (ptr != 0) {
5280 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5281 recordTrack->handleSyncStartEvent(strongEvent);
5282 }
Eric Laurent81784c32012-11-19 14:55:58 -08005283 }
5284}
5285
Glenn Kastena8356f62013-07-25 14:37:52 -07005286bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005287 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005288 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005289 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005290 return false;
5291 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005292 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005293 recordTrack->mState = TrackBase::PAUSING;
5294 // do not wait for mStartStopCond if exiting
5295 if (exitPending()) {
5296 return true;
5297 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005298 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005299 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005300 // if we have been restarted, recordTrack is in mActiveTracks here
5301 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005302 ALOGV("Record stopped OK");
5303 return true;
5304 }
5305 return false;
5306}
5307
Glenn Kasten0f11b512014-01-31 16:18:54 -08005308bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005309{
5310 return false;
5311}
5312
Glenn Kasten0f11b512014-01-31 16:18:54 -08005313status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005314{
5315#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5316 if (!isValidSyncEvent(event)) {
5317 return BAD_VALUE;
5318 }
5319
5320 int eventSession = event->triggerSession();
5321 status_t ret = NAME_NOT_FOUND;
5322
5323 Mutex::Autolock _l(mLock);
5324
5325 for (size_t i = 0; i < mTracks.size(); i++) {
5326 sp<RecordTrack> track = mTracks[i];
5327 if (eventSession == track->sessionId()) {
5328 (void) track->setSyncEvent(event);
5329 ret = NO_ERROR;
5330 }
5331 }
5332 return ret;
5333#else
5334 return BAD_VALUE;
5335#endif
5336}
5337
5338// destroyTrack_l() must be called with ThreadBase::mLock held
5339void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5340{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 track->terminate();
5342 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005343 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005344 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005345 removeTrack_l(track);
5346 }
5347}
5348
5349void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5350{
5351 mTracks.remove(track);
5352 // need anything related to effects here?
5353}
5354
5355void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5356{
5357 dumpInternals(fd, args);
5358 dumpTracks(fd, args);
5359 dumpEffectChains(fd, args);
5360}
5361
5362void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5363{
Marco Nelissenb2208842014-02-07 14:00:50 -08005364 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005365
Glenn Kasten2b806402013-11-20 16:37:38 -08005366 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005367 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005368 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005369 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005370 }
5371
Eric Laurent81784c32012-11-19 14:55:58 -08005372 dumpBase(fd, args);
5373}
5374
Glenn Kasten0f11b512014-01-31 16:18:54 -08005375void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005376{
5377 const size_t SIZE = 256;
5378 char buffer[SIZE];
5379 String8 result;
5380
Marco Nelissenb2208842014-02-07 14:00:50 -08005381 size_t numtracks = mTracks.size();
5382 size_t numactive = mActiveTracks.size();
5383 size_t numactiveseen = 0;
5384 fdprintf(fd, " %d Tracks", numtracks);
5385 if (numtracks) {
5386 fdprintf(fd, " of which %d are active\n", numactive);
5387 RecordTrack::appendDumpHeader(result);
5388 for (size_t i = 0; i < numtracks ; ++i) {
5389 sp<RecordTrack> track = mTracks[i];
5390 if (track != 0) {
5391 bool active = mActiveTracks.indexOf(track) >= 0;
5392 if (active) {
5393 numactiveseen++;
5394 }
5395 track->dump(buffer, SIZE, active);
5396 result.append(buffer);
5397 }
Eric Laurent81784c32012-11-19 14:55:58 -08005398 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005399 } else {
5400 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005401 }
5402
Marco Nelissenb2208842014-02-07 14:00:50 -08005403 if (numactiveseen != numactive) {
5404 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5405 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005406 result.append(buffer);
5407 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005408 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005409 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005410 if (mTracks.indexOf(track) < 0) {
5411 track->dump(buffer, SIZE, true);
5412 result.append(buffer);
5413 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005414 }
Eric Laurent81784c32012-11-19 14:55:58 -08005415
5416 }
5417 write(fd, result.string(), result.size());
5418}
5419
5420// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005421status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5422 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005423{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005424 RecordTrack *activeTrack = mRecordTrack;
5425 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5426 if (threadBase == 0) {
5427 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005428 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005429 return NOT_ENOUGH_DATA;
5430 }
5431 RecordThread *recordThread = (RecordThread *) threadBase.get();
5432 int32_t rear = recordThread->mRsmpInRear;
5433 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005434 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005435 // FIXME should not be P2 (don't want to increase latency)
5436 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005437 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005438 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005439 front &= recordThread->mRsmpInFramesP2 - 1;
5440 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005441 if (part1 > (size_t) filled) {
5442 part1 = filled;
5443 }
5444 size_t ask = buffer->frameCount;
5445 ALOG_ASSERT(ask > 0);
5446 if (part1 > ask) {
5447 part1 = ask;
5448 }
5449 if (part1 == 0) {
5450 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005451 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005452 buffer->raw = NULL;
5453 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005454 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005455 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 }
5457
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005458 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005459 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005460 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005461 return NO_ERROR;
5462}
5463
5464// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005465void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5466 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005467{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005468 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005469 size_t stepCount = buffer->frameCount;
5470 if (stepCount == 0) {
5471 return;
5472 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005473 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5474 activeTrack->mRsmpInUnrel -= stepCount;
5475 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005476 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 buffer->frameCount = 0;
5478}
5479
Eric Laurent10351942014-05-08 18:49:52 -07005480bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
5481 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005482{
5483 bool reconfig = false;
5484
Eric Laurent10351942014-05-08 18:49:52 -07005485 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005486
Eric Laurent10351942014-05-08 18:49:52 -07005487 audio_format_t reqFormat = mFormat;
5488 uint32_t samplingRate = mSampleRate;
5489 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5490
5491 AudioParameter param = AudioParameter(keyValuePair);
5492 int value;
5493 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5494 // channel count change can be requested. Do we mandate the first client defines the
5495 // HAL sampling rate and channel count or do we allow changes on the fly?
5496 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5497 samplingRate = value;
5498 reconfig = true;
5499 }
5500 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5501 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5502 status = BAD_VALUE;
5503 } else {
5504 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08005505 reconfig = true;
5506 }
Eric Laurent10351942014-05-08 18:49:52 -07005507 }
5508 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5509 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5510 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5511 status = BAD_VALUE;
5512 } else {
5513 channelMask = mask;
5514 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005515 }
Eric Laurent10351942014-05-08 18:49:52 -07005516 }
5517 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5518 // do not accept frame count changes if tracks are open as the track buffer
5519 // size depends on frame count and correct behavior would not be guaranteed
5520 // if frame count is changed after track creation
5521 if (mActiveTracks.size() > 0) {
5522 status = INVALID_OPERATION;
5523 } else {
5524 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005525 }
Eric Laurent10351942014-05-08 18:49:52 -07005526 }
5527 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5528 // forward device change to effects that have requested to be
5529 // aware of attached audio device.
5530 for (size_t i = 0; i < mEffectChains.size(); i++) {
5531 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08005532 }
Eric Laurent81784c32012-11-19 14:55:58 -08005533
Eric Laurent10351942014-05-08 18:49:52 -07005534 // store input device and output device but do not forward output device to audio HAL.
5535 // Note that status is ignored by the caller for output device
5536 // (see AudioFlinger::setParameters()
5537 if (audio_is_output_devices(value)) {
5538 mOutDevice = value;
5539 status = BAD_VALUE;
5540 } else {
5541 mInDevice = value;
5542 // disable AEC and NS if the device is a BT SCO headset supporting those
5543 // pre processings
5544 if (mTracks.size() > 0) {
5545 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5546 mAudioFlinger->btNrecIsOff();
5547 for (size_t i = 0; i < mTracks.size(); i++) {
5548 sp<RecordTrack> track = mTracks[i];
5549 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5550 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005551 }
5552 }
5553 }
Eric Laurent10351942014-05-08 18:49:52 -07005554 }
5555 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5556 mAudioSource != (audio_source_t)value) {
5557 // forward device change to effects that have requested to be
5558 // aware of attached audio device.
5559 for (size_t i = 0; i < mEffectChains.size(); i++) {
5560 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08005561 }
Eric Laurent10351942014-05-08 18:49:52 -07005562 mAudioSource = (audio_source_t)value;
5563 }
Glenn Kastene198c362013-08-13 09:13:36 -07005564
Eric Laurent10351942014-05-08 18:49:52 -07005565 if (status == NO_ERROR) {
5566 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5567 keyValuePair.string());
5568 if (status == INVALID_OPERATION) {
5569 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005570 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5571 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07005572 }
5573 if (reconfig) {
5574 if (status == BAD_VALUE &&
5575 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5576 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5577 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5578 <= (2 * samplingRate)) &&
5579 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5580 <= FCC_2 &&
5581 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5582 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5583 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 }
Eric Laurent10351942014-05-08 18:49:52 -07005585 if (status == NO_ERROR) {
5586 readInputParameters_l();
5587 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
5589 }
Eric Laurent81784c32012-11-19 14:55:58 -08005590 }
Eric Laurent10351942014-05-08 18:49:52 -07005591
Eric Laurent81784c32012-11-19 14:55:58 -08005592 return reconfig;
5593}
5594
5595String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5596{
Eric Laurent81784c32012-11-19 14:55:58 -08005597 Mutex::Autolock _l(mLock);
5598 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005599 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005600 }
5601
Glenn Kastend8ea6992013-07-16 14:17:15 -07005602 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5603 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005604 free(s);
5605 return out_s8;
5606}
5607
Eric Laurent10351942014-05-08 18:49:52 -07005608void AudioFlinger::RecordThread::audioConfigChanged_l(
5609 const DefaultKeyedVector< pid_t,sp<NotificationClient> >& notificationClients,
5610 int event,
5611 int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005612 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005613 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005614
5615 switch (event) {
5616 case AudioSystem::INPUT_OPENED:
5617 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005618 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005619 desc.samplingRate = mSampleRate;
5620 desc.format = mFormat;
5621 desc.frameCount = mFrameCount;
5622 desc.latency = 0;
5623 param2 = &desc;
5624 break;
5625
5626 case AudioSystem::INPUT_CLOSED:
5627 default:
5628 break;
5629 }
Eric Laurent10351942014-05-08 18:49:52 -07005630 mAudioFlinger->audioConfigChanged_l(notificationClients, event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08005631}
5632
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005633void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005634{
Eric Laurent81784c32012-11-19 14:55:58 -08005635 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5636 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005637 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005638 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005639 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005640 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005641 }
Eric Laurent81784c32012-11-19 14:55:58 -08005642 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005643 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5644 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005645 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005646 // 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 -07005647 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005648 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005649 // A larger value should allow more old data to be read after a track calls start(),
5650 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005651 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005652 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005653 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005654 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5655 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005656
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005657 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5658 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005659}
5660
Glenn Kasten5f972c02014-01-13 09:59:31 -08005661uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005662{
5663 Mutex::Autolock _l(mLock);
5664 if (initCheck() != NO_ERROR) {
5665 return 0;
5666 }
5667
5668 return mInput->stream->get_input_frames_lost(mInput->stream);
5669}
5670
5671uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5672{
5673 Mutex::Autolock _l(mLock);
5674 uint32_t result = 0;
5675 if (getEffectChain_l(sessionId) != 0) {
5676 result = EFFECT_SESSION;
5677 }
5678
5679 for (size_t i = 0; i < mTracks.size(); ++i) {
5680 if (sessionId == mTracks[i]->sessionId()) {
5681 result |= TRACK_SESSION;
5682 break;
5683 }
5684 }
5685
5686 return result;
5687}
5688
5689KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5690{
5691 KeyedVector<int, bool> ids;
5692 Mutex::Autolock _l(mLock);
5693 for (size_t j = 0; j < mTracks.size(); ++j) {
5694 sp<RecordThread::RecordTrack> track = mTracks[j];
5695 int sessionId = track->sessionId();
5696 if (ids.indexOfKey(sessionId) < 0) {
5697 ids.add(sessionId, true);
5698 }
5699 }
5700 return ids;
5701}
5702
5703AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5704{
5705 Mutex::Autolock _l(mLock);
5706 AudioStreamIn *input = mInput;
5707 mInput = NULL;
5708 return input;
5709}
5710
5711// this method must always be called either with ThreadBase mLock held or inside the thread loop
5712audio_stream_t* AudioFlinger::RecordThread::stream() const
5713{
5714 if (mInput == NULL) {
5715 return NULL;
5716 }
5717 return &mInput->stream->common;
5718}
5719
5720status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5721{
5722 // only one chain per input thread
5723 if (mEffectChains.size() != 0) {
5724 return INVALID_OPERATION;
5725 }
5726 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5727
5728 chain->setInBuffer(NULL);
5729 chain->setOutBuffer(NULL);
5730
5731 checkSuspendOnAddEffectChain_l(chain);
5732
5733 mEffectChains.add(chain);
5734
5735 return NO_ERROR;
5736}
5737
5738size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5739{
5740 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5741 ALOGW_IF(mEffectChains.size() != 1,
5742 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5743 chain.get(), mEffectChains.size(), this);
5744 if (mEffectChains.size() == 1) {
5745 mEffectChains.removeAt(0);
5746 }
5747 return 0;
5748}
5749
5750}; // namespace android