blob: be7d7253a1416a160f678b65661eba0f0ea8a7d2 [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
100// maximum time to wait for setParameters to complete
101static const nsecs_t kSetParametersTimeoutNs = seconds(2);
102
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 Laurent81784c32012-11-19 14:55:58 -0800286 mParamStatus(NO_ERROR),
Eric Laurentfd477972013-10-25 18:10:40 -0700287 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800288 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
289 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
290 // mName will be set by concrete (non-virtual) subclass
291 mDeathRecipient(new PMDeathRecipient(this))
292{
293}
294
295AudioFlinger::ThreadBase::~ThreadBase()
296{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700297 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
298 for (size_t i = 0; i < mConfigEvents.size(); i++) {
299 delete mConfigEvents[i];
300 }
301 mConfigEvents.clear();
302
Eric Laurent81784c32012-11-19 14:55:58 -0800303 mParamCond.broadcast();
304 // do not lock the mutex in destructor
305 releaseWakeLock_l();
306 if (mPowerManager != 0) {
307 sp<IBinder> binder = mPowerManager->asBinder();
308 binder->unlinkToDeath(mDeathRecipient);
309 }
310}
311
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700312status_t AudioFlinger::ThreadBase::readyToRun()
313{
314 status_t status = initCheck();
315 if (status == NO_ERROR) {
316 ALOGI("AudioFlinger's thread %p ready to run", this);
317 } else {
318 ALOGE("No working audio driver found.");
319 }
320 return status;
321}
322
Eric Laurent81784c32012-11-19 14:55:58 -0800323void AudioFlinger::ThreadBase::exit()
324{
325 ALOGV("ThreadBase::exit");
326 // do any cleanup required for exit to succeed
327 preExit();
328 {
329 // This lock prevents the following race in thread (uniprocessor for illustration):
330 // if (!exitPending()) {
331 // // context switch from here to exit()
332 // // exit() calls requestExit(), what exitPending() observes
333 // // exit() calls signal(), which is dropped since no waiters
334 // // context switch back from exit() to here
335 // mWaitWorkCV.wait(...);
336 // // now thread is hung
337 // }
338 AutoMutex lock(mLock);
339 requestExit();
340 mWaitWorkCV.broadcast();
341 }
342 // When Thread::requestExitAndWait is made virtual and this method is renamed to
343 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
344 requestExitAndWait();
345}
346
347status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
348{
349 status_t status;
350
351 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
352 Mutex::Autolock _l(mLock);
353
354 mNewParameters.add(keyValuePairs);
355 mWaitWorkCV.signal();
356 // wait condition with timeout in case the thread loop has exited
357 // before the request could be processed
358 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
359 status = mParamStatus;
360 mWaitWorkCV.signal();
361 } else {
362 status = TIMED_OUT;
363 }
364 return status;
365}
366
367void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
368{
369 Mutex::Autolock _l(mLock);
370 sendIoConfigEvent_l(event, param);
371}
372
373// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
374void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
375{
376 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
377 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
378 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
379 param);
380 mWaitWorkCV.signal();
381}
382
383// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
384void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
385{
386 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
387 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
388 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
389 mConfigEvents.size(), pid, tid, prio);
390 mWaitWorkCV.signal();
391}
392
393void AudioFlinger::ThreadBase::processConfigEvents()
394{
Glenn Kastenf7773312013-08-13 16:00:42 -0700395 Mutex::Autolock _l(mLock);
396 processConfigEvents_l();
397}
398
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700399// post condition: mConfigEvents.isEmpty()
Glenn Kastenf7773312013-08-13 16:00:42 -0700400void AudioFlinger::ThreadBase::processConfigEvents_l()
401{
Eric Laurent81784c32012-11-19 14:55:58 -0800402 while (!mConfigEvents.isEmpty()) {
403 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
404 ConfigEvent *event = mConfigEvents[0];
405 mConfigEvents.removeAt(0);
406 // release mLock before locking AudioFlinger mLock: lock order is always
407 // AudioFlinger then ThreadBase to avoid cross deadlock
408 mLock.unlock();
Glenn Kastene198c362013-08-13 09:13:36 -0700409 switch (event->type()) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700410 case CFG_EVENT_PRIO: {
411 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
412 // FIXME Need to understand why this has be done asynchronously
413 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
414 true /*asynchronous*/);
415 if (err != 0) {
416 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
417 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
418 }
419 } break;
420 case CFG_EVENT_IO: {
421 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
Glenn Kastend5418eb2013-08-14 13:11:06 -0700422 {
423 Mutex::Autolock _l(mAudioFlinger->mLock);
424 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
425 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700426 } break;
427 default:
428 ALOGE("processConfigEvents() unknown event type %d", event->type());
429 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800430 }
431 delete event;
432 mLock.lock();
433 }
Eric Laurent81784c32012-11-19 14:55:58 -0800434}
435
Marco Nelissenb2208842014-02-07 14:00:50 -0800436String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
437 String8 s;
438 if (output) {
439 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
440 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
441 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
442 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
443 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
444 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
445 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
446 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
447 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
448 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
449 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
450 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
451 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
452 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
453 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
454 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
455 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
456 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
457 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
458 } else {
459 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
460 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
461 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
462 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
463 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
464 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
465 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
466 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
467 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
468 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
469 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
470 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
471 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
472 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
473 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
474 }
475 int len = s.length();
476 if (s.length() > 2) {
477 char *str = s.lockBuffer(len);
478 s.unlockBuffer(len - 2);
479 }
480 return s;
481}
482
Glenn Kasten0f11b512014-01-31 16:18:54 -0800483void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800484{
485 const size_t SIZE = 256;
486 char buffer[SIZE];
487 String8 result;
488
489 bool locked = AudioFlinger::dumpTryLock(mLock);
490 if (!locked) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800491 fdprintf(fd, "thread %p maybe dead locked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 }
493
Marco Nelissenb2208842014-02-07 14:00:50 -0800494 fdprintf(fd, " I/O handle: %d\n", mId);
495 fdprintf(fd, " TID: %d\n", getTid());
496 fdprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
497 fdprintf(fd, " Sample rate: %u\n", mSampleRate);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000498 fdprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -0800499 fdprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
500 fdprintf(fd, " Channel Count: %u\n", mChannelCount);
501 fdprintf(fd, " Channel Mask: 0x%08x (%s)\n", mChannelMask,
502 channelMaskToString(mChannelMask, mType != RECORD).string());
503 fdprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000504 fdprintf(fd, " Frame size: %zu\n", mFrameSize);
Marco Nelissenb2208842014-02-07 14:00:50 -0800505 fdprintf(fd, " Pending setParameters commands:");
506 size_t numParams = mNewParameters.size();
507 if (numParams) {
508 fdprintf(fd, "\n Index Command");
509 for (size_t i = 0; i < numParams; ++i) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000510 fdprintf(fd, "\n %02zu ", i);
Marco Nelissenb2208842014-02-07 14:00:50 -0800511 fdprintf(fd, mNewParameters[i]);
512 }
513 fdprintf(fd, "\n");
514 } else {
515 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800516 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800517 fdprintf(fd, " Pending config events:");
518 size_t numConfig = mConfigEvents.size();
519 if (numConfig) {
520 for (size_t i = 0; i < numConfig; i++) {
521 mConfigEvents[i]->dump(buffer, SIZE);
522 fdprintf(fd, "\n %s", buffer);
523 }
524 fdprintf(fd, "\n");
525 } else {
526 fdprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800527 }
Eric Laurent81784c32012-11-19 14:55:58 -0800528
529 if (locked) {
530 mLock.unlock();
531 }
532}
533
534void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
535{
536 const size_t SIZE = 256;
537 char buffer[SIZE];
538 String8 result;
539
Marco Nelissenb2208842014-02-07 14:00:50 -0800540 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000541 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800542 write(fd, buffer, strlen(buffer));
543
Marco Nelissenb2208842014-02-07 14:00:50 -0800544 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800545 sp<EffectChain> chain = mEffectChains[i];
546 if (chain != 0) {
547 chain->dump(fd, args);
548 }
549 }
550}
551
Marco Nelissene14a5d62013-10-03 08:51:24 -0700552void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800553{
554 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700555 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800556}
557
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100558String16 AudioFlinger::ThreadBase::getWakeLockTag()
559{
560 switch (mType) {
561 case MIXER:
562 return String16("AudioMix");
563 case DIRECT:
564 return String16("AudioDirectOut");
565 case DUPLICATING:
566 return String16("AudioDup");
567 case RECORD:
568 return String16("AudioIn");
569 case OFFLOAD:
570 return String16("AudioOffload");
571 default:
572 ALOG_ASSERT(false);
573 return String16("AudioUnknown");
574 }
575}
576
Marco Nelissene14a5d62013-10-03 08:51:24 -0700577void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800578{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800579 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800580 if (mPowerManager != 0) {
581 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700582 status_t status;
583 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700584 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700585 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100586 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700587 String16("media"),
588 uid);
589 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700590 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700591 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100592 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700593 String16("media"));
594 }
Eric Laurent81784c32012-11-19 14:55:58 -0800595 if (status == NO_ERROR) {
596 mWakeLockToken = binder;
597 }
598 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
599 }
600}
601
602void AudioFlinger::ThreadBase::releaseWakeLock()
603{
604 Mutex::Autolock _l(mLock);
605 releaseWakeLock_l();
606}
607
608void AudioFlinger::ThreadBase::releaseWakeLock_l()
609{
610 if (mWakeLockToken != 0) {
611 ALOGV("releaseWakeLock_l() %s", mName);
612 if (mPowerManager != 0) {
613 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
614 }
615 mWakeLockToken.clear();
616 }
617}
618
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800619void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
620 Mutex::Autolock _l(mLock);
621 updateWakeLockUids_l(uids);
622}
623
624void AudioFlinger::ThreadBase::getPowerManager_l() {
625
626 if (mPowerManager == 0) {
627 // use checkService() to avoid blocking if power service is not up yet
628 sp<IBinder> binder =
629 defaultServiceManager()->checkService(String16("power"));
630 if (binder == 0) {
631 ALOGW("Thread %s cannot connect to the power manager service", mName);
632 } else {
633 mPowerManager = interface_cast<IPowerManager>(binder);
634 binder->linkToDeath(mDeathRecipient);
635 }
636 }
637}
638
639void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
640
641 getPowerManager_l();
642 if (mWakeLockToken == NULL) {
643 ALOGE("no wake lock to update!");
644 return;
645 }
646 if (mPowerManager != 0) {
647 sp<IBinder> binder = new BBinder();
648 status_t status;
649 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array());
650 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
651 }
652}
653
Eric Laurent81784c32012-11-19 14:55:58 -0800654void AudioFlinger::ThreadBase::clearPowerManager()
655{
656 Mutex::Autolock _l(mLock);
657 releaseWakeLock_l();
658 mPowerManager.clear();
659}
660
Glenn Kasten0f11b512014-01-31 16:18:54 -0800661void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800662{
663 sp<ThreadBase> thread = mThread.promote();
664 if (thread != 0) {
665 thread->clearPowerManager();
666 }
667 ALOGW("power manager service died !!!");
668}
669
670void AudioFlinger::ThreadBase::setEffectSuspended(
671 const effect_uuid_t *type, bool suspend, int sessionId)
672{
673 Mutex::Autolock _l(mLock);
674 setEffectSuspended_l(type, suspend, sessionId);
675}
676
677void AudioFlinger::ThreadBase::setEffectSuspended_l(
678 const effect_uuid_t *type, bool suspend, int sessionId)
679{
680 sp<EffectChain> chain = getEffectChain_l(sessionId);
681 if (chain != 0) {
682 if (type != NULL) {
683 chain->setEffectSuspended_l(type, suspend);
684 } else {
685 chain->setEffectSuspendedAll_l(suspend);
686 }
687 }
688
689 updateSuspendedSessions_l(type, suspend, sessionId);
690}
691
692void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
693{
694 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
695 if (index < 0) {
696 return;
697 }
698
699 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
700 mSuspendedSessions.valueAt(index);
701
702 for (size_t i = 0; i < sessionEffects.size(); i++) {
703 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
704 for (int j = 0; j < desc->mRefCount; j++) {
705 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
706 chain->setEffectSuspendedAll_l(true);
707 } else {
708 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
709 desc->mType.timeLow);
710 chain->setEffectSuspended_l(&desc->mType, true);
711 }
712 }
713 }
714}
715
716void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
717 bool suspend,
718 int sessionId)
719{
720 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
721
722 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
723
724 if (suspend) {
725 if (index >= 0) {
726 sessionEffects = mSuspendedSessions.valueAt(index);
727 } else {
728 mSuspendedSessions.add(sessionId, sessionEffects);
729 }
730 } else {
731 if (index < 0) {
732 return;
733 }
734 sessionEffects = mSuspendedSessions.valueAt(index);
735 }
736
737
738 int key = EffectChain::kKeyForSuspendAll;
739 if (type != NULL) {
740 key = type->timeLow;
741 }
742 index = sessionEffects.indexOfKey(key);
743
744 sp<SuspendedSessionDesc> desc;
745 if (suspend) {
746 if (index >= 0) {
747 desc = sessionEffects.valueAt(index);
748 } else {
749 desc = new SuspendedSessionDesc();
750 if (type != NULL) {
751 desc->mType = *type;
752 }
753 sessionEffects.add(key, desc);
754 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
755 }
756 desc->mRefCount++;
757 } else {
758 if (index < 0) {
759 return;
760 }
761 desc = sessionEffects.valueAt(index);
762 if (--desc->mRefCount == 0) {
763 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
764 sessionEffects.removeItemsAt(index);
765 if (sessionEffects.isEmpty()) {
766 ALOGV("updateSuspendedSessions_l() restore removing session %d",
767 sessionId);
768 mSuspendedSessions.removeItem(sessionId);
769 }
770 }
771 }
772 if (!sessionEffects.isEmpty()) {
773 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
774 }
775}
776
777void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
778 bool enabled,
779 int sessionId)
780{
781 Mutex::Autolock _l(mLock);
782 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
783}
784
785void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
786 bool enabled,
787 int sessionId)
788{
789 if (mType != RECORD) {
790 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
791 // another session. This gives the priority to well behaved effect control panels
792 // and applications not using global effects.
793 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
794 // global effects
795 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
796 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
797 }
798 }
799
800 sp<EffectChain> chain = getEffectChain_l(sessionId);
801 if (chain != 0) {
802 chain->checkSuspendOnEffectEnabled(effect, enabled);
803 }
804}
805
806// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
807sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
808 const sp<AudioFlinger::Client>& client,
809 const sp<IEffectClient>& effectClient,
810 int32_t priority,
811 int sessionId,
812 effect_descriptor_t *desc,
813 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700814 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -0800815{
816 sp<EffectModule> effect;
817 sp<EffectHandle> handle;
818 status_t lStatus;
819 sp<EffectChain> chain;
820 bool chainCreated = false;
821 bool effectCreated = false;
822 bool effectRegistered = false;
823
824 lStatus = initCheck();
825 if (lStatus != NO_ERROR) {
826 ALOGW("createEffect_l() Audio driver not initialized.");
827 goto Exit;
828 }
829
Andy Hung98ef9782014-03-04 14:46:50 -0800830 // Reject any effect on Direct output threads for now, since the format of
831 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
832 if (mType == DIRECT) {
833 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
834 desc->name, mName);
835 lStatus = BAD_VALUE;
836 goto Exit;
837 }
838
Eric Laurent5baf2af2013-09-12 17:37:00 -0700839 // Allow global effects only on offloaded and mixer threads
840 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
841 switch (mType) {
842 case MIXER:
843 case OFFLOAD:
844 break;
845 case DIRECT:
846 case DUPLICATING:
847 case RECORD:
848 default:
849 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
850 lStatus = BAD_VALUE;
851 goto Exit;
852 }
Eric Laurent81784c32012-11-19 14:55:58 -0800853 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700854
Eric Laurent81784c32012-11-19 14:55:58 -0800855 // Only Pre processor effects are allowed on input threads and only on input threads
856 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
857 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
858 desc->name, desc->flags, mType);
859 lStatus = BAD_VALUE;
860 goto Exit;
861 }
862
863 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
864
865 { // scope for mLock
866 Mutex::Autolock _l(mLock);
867
868 // check for existing effect chain with the requested audio session
869 chain = getEffectChain_l(sessionId);
870 if (chain == 0) {
871 // create a new chain for this session
872 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
873 chain = new EffectChain(this, sessionId);
874 addEffectChain_l(chain);
875 chain->setStrategy(getStrategyForSession_l(sessionId));
876 chainCreated = true;
877 } else {
878 effect = chain->getEffectFromDesc_l(desc);
879 }
880
881 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
882
883 if (effect == 0) {
884 int id = mAudioFlinger->nextUniqueId();
885 // Check CPU and memory usage
886 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
887 if (lStatus != NO_ERROR) {
888 goto Exit;
889 }
890 effectRegistered = true;
891 // create a new effect module if none present in the chain
892 effect = new EffectModule(this, chain, desc, id, sessionId);
893 lStatus = effect->status();
894 if (lStatus != NO_ERROR) {
895 goto Exit;
896 }
Eric Laurent5baf2af2013-09-12 17:37:00 -0700897 effect->setOffloaded(mType == OFFLOAD, mId);
898
Eric Laurent81784c32012-11-19 14:55:58 -0800899 lStatus = chain->addEffect_l(effect);
900 if (lStatus != NO_ERROR) {
901 goto Exit;
902 }
903 effectCreated = true;
904
905 effect->setDevice(mOutDevice);
906 effect->setDevice(mInDevice);
907 effect->setMode(mAudioFlinger->getMode());
908 effect->setAudioSource(mAudioSource);
909 }
910 // create effect handle and connect it to effect module
911 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -0800912 lStatus = handle->initCheck();
913 if (lStatus == OK) {
914 lStatus = effect->addHandle(handle.get());
915 }
Eric Laurent81784c32012-11-19 14:55:58 -0800916 if (enabled != NULL) {
917 *enabled = (int)effect->isEnabled();
918 }
919 }
920
921Exit:
922 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
923 Mutex::Autolock _l(mLock);
924 if (effectCreated) {
925 chain->removeEffect_l(effect);
926 }
927 if (effectRegistered) {
928 AudioSystem::unregisterEffect(effect->id());
929 }
930 if (chainCreated) {
931 removeEffectChain_l(chain);
932 }
933 handle.clear();
934 }
935
Glenn Kasten9156ef32013-08-06 15:39:08 -0700936 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800937 return handle;
938}
939
940sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
941{
942 Mutex::Autolock _l(mLock);
943 return getEffect_l(sessionId, effectId);
944}
945
946sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
947{
948 sp<EffectChain> chain = getEffectChain_l(sessionId);
949 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
950}
951
952// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
953// PlaybackThread::mLock held
954status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
955{
956 // check for existing effect chain with the requested audio session
957 int sessionId = effect->sessionId();
958 sp<EffectChain> chain = getEffectChain_l(sessionId);
959 bool chainCreated = false;
960
Eric Laurent5baf2af2013-09-12 17:37:00 -0700961 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
962 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
963 this, effect->desc().name, effect->desc().flags);
964
Eric Laurent81784c32012-11-19 14:55:58 -0800965 if (chain == 0) {
966 // create a new chain for this session
967 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
968 chain = new EffectChain(this, sessionId);
969 addEffectChain_l(chain);
970 chain->setStrategy(getStrategyForSession_l(sessionId));
971 chainCreated = true;
972 }
973 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
974
975 if (chain->getEffectFromId_l(effect->id()) != 0) {
976 ALOGW("addEffect_l() %p effect %s already present in chain %p",
977 this, effect->desc().name, chain.get());
978 return BAD_VALUE;
979 }
980
Eric Laurent5baf2af2013-09-12 17:37:00 -0700981 effect->setOffloaded(mType == OFFLOAD, mId);
982
Eric Laurent81784c32012-11-19 14:55:58 -0800983 status_t status = chain->addEffect_l(effect);
984 if (status != NO_ERROR) {
985 if (chainCreated) {
986 removeEffectChain_l(chain);
987 }
988 return status;
989 }
990
991 effect->setDevice(mOutDevice);
992 effect->setDevice(mInDevice);
993 effect->setMode(mAudioFlinger->getMode());
994 effect->setAudioSource(mAudioSource);
995 return NO_ERROR;
996}
997
998void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
999
1000 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1001 effect_descriptor_t desc = effect->desc();
1002 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1003 detachAuxEffect_l(effect->id());
1004 }
1005
1006 sp<EffectChain> chain = effect->chain().promote();
1007 if (chain != 0) {
1008 // remove effect chain if removing last effect
1009 if (chain->removeEffect_l(effect) == 0) {
1010 removeEffectChain_l(chain);
1011 }
1012 } else {
1013 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1014 }
1015}
1016
1017void AudioFlinger::ThreadBase::lockEffectChains_l(
1018 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1019{
1020 effectChains = mEffectChains;
1021 for (size_t i = 0; i < mEffectChains.size(); i++) {
1022 mEffectChains[i]->lock();
1023 }
1024}
1025
1026void AudioFlinger::ThreadBase::unlockEffectChains(
1027 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1028{
1029 for (size_t i = 0; i < effectChains.size(); i++) {
1030 effectChains[i]->unlock();
1031 }
1032}
1033
1034sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1035{
1036 Mutex::Autolock _l(mLock);
1037 return getEffectChain_l(sessionId);
1038}
1039
1040sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1041{
1042 size_t size = mEffectChains.size();
1043 for (size_t i = 0; i < size; i++) {
1044 if (mEffectChains[i]->sessionId() == sessionId) {
1045 return mEffectChains[i];
1046 }
1047 }
1048 return 0;
1049}
1050
1051void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1052{
1053 Mutex::Autolock _l(mLock);
1054 size_t size = mEffectChains.size();
1055 for (size_t i = 0; i < size; i++) {
1056 mEffectChains[i]->setMode_l(mode);
1057 }
1058}
1059
1060void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
1061 EffectHandle *handle,
1062 bool unpinIfLast) {
1063
1064 Mutex::Autolock _l(mLock);
1065 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
1066 // delete the effect module if removing last handle on it
1067 if (effect->removeHandle(handle) == 0) {
1068 if (!effect->isPinned() || unpinIfLast) {
1069 removeEffect_l(effect);
1070 AudioSystem::unregisterEffect(effect->id());
1071 }
1072 }
1073}
1074
1075// ----------------------------------------------------------------------------
1076// Playback
1077// ----------------------------------------------------------------------------
1078
1079AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1080 AudioStreamOut* output,
1081 audio_io_handle_t id,
1082 audio_devices_t device,
1083 type_t type)
1084 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001085 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung69aed5f2014-02-25 17:24:40 -08001086 mMixerBufferEnabled(false),
1087 mMixerBuffer(NULL),
1088 mMixerBufferSize(0),
1089 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1090 mMixerBufferValid(false),
Andy Hung98ef9782014-03-04 14:46:50 -08001091 mEffectBufferEnabled(false),
1092 mEffectBuffer(NULL),
1093 mEffectBufferSize(0),
1094 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1095 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001096 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001097 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001098 // mStreamTypes[] initialized in constructor body
1099 mOutput(output),
1100 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1101 mMixerStatus(MIXER_IDLE),
1102 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1103 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001104 mBytesRemaining(0),
1105 mCurrentWriteLength(0),
1106 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001107 mWriteAckSequence(0),
1108 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001109 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001110 mScreenState(AudioFlinger::mScreenState),
1111 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001112 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1113 // mLatchD, mLatchQ,
1114 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001115{
1116 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001117 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001118
1119 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1120 // it would be safer to explicitly pass initial masterVolume/masterMute as
1121 // parameter.
1122 //
1123 // If the HAL we are using has support for master volume or master mute,
1124 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1125 // and the mute set to false).
1126 mMasterVolume = audioFlinger->masterVolume_l();
1127 mMasterMute = audioFlinger->masterMute_l();
1128 if (mOutput && mOutput->audioHwDev) {
1129 if (mOutput->audioHwDev->canSetMasterVolume()) {
1130 mMasterVolume = 1.0;
1131 }
1132
1133 if (mOutput->audioHwDev->canSetMasterMute()) {
1134 mMasterMute = false;
1135 }
1136 }
1137
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001138 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001139
1140 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1141 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001142 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001143 stream = (audio_stream_type_t) (stream + 1)) {
1144 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1145 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1146 }
1147 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1148 // because mAudioFlinger doesn't have one to copy from
1149}
1150
1151AudioFlinger::PlaybackThread::~PlaybackThread()
1152{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001153 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001154 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001155 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001156 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001157}
1158
1159void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1160{
1161 dumpInternals(fd, args);
1162 dumpTracks(fd, args);
1163 dumpEffectChains(fd, args);
1164}
1165
Glenn Kasten0f11b512014-01-31 16:18:54 -08001166void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001167{
1168 const size_t SIZE = 256;
1169 char buffer[SIZE];
1170 String8 result;
1171
Marco Nelissenb2208842014-02-07 14:00:50 -08001172 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001173 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1174 const stream_type_t *st = &mStreamTypes[i];
1175 if (i > 0) {
1176 result.appendFormat(", ");
1177 }
1178 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1179 if (st->mute) {
1180 result.append("M");
1181 }
1182 }
1183 result.append("\n");
1184 write(fd, result.string(), result.length());
1185 result.clear();
1186
Eric Laurent81784c32012-11-19 14:55:58 -08001187 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1188 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Marco Nelissenb2208842014-02-07 14:00:50 -08001189 fdprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001190 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001191
1192 size_t numtracks = mTracks.size();
1193 size_t numactive = mActiveTracks.size();
1194 fdprintf(fd, " %d Tracks", numtracks);
1195 size_t numactiveseen = 0;
1196 if (numtracks) {
1197 fdprintf(fd, " of which %d are active\n", numactive);
1198 Track::appendDumpHeader(result);
1199 for (size_t i = 0; i < numtracks; ++i) {
1200 sp<Track> track = mTracks[i];
1201 if (track != 0) {
1202 bool active = mActiveTracks.indexOf(track) >= 0;
1203 if (active) {
1204 numactiveseen++;
1205 }
1206 track->dump(buffer, SIZE, active);
1207 result.append(buffer);
1208 }
1209 }
1210 } else {
1211 result.append("\n");
1212 }
1213 if (numactiveseen != numactive) {
1214 // some tracks in the active list were not in the tracks list
1215 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1216 " not in the track list\n");
1217 result.append(buffer);
1218 Track::appendDumpHeader(result);
1219 for (size_t i = 0; i < numactive; ++i) {
1220 sp<Track> track = mActiveTracks[i].promote();
1221 if (track != 0 && mTracks.indexOf(track) < 0) {
1222 track->dump(buffer, SIZE, true);
1223 result.append(buffer);
1224 }
1225 }
1226 }
1227
1228 write(fd, result.string(), result.size());
1229
Eric Laurent81784c32012-11-19 14:55:58 -08001230}
1231
1232void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1233{
Marco Nelissenb2208842014-02-07 14:00:50 -08001234 fdprintf(fd, "\nOutput thread %p:\n", this);
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001235 fdprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Marco Nelissenb2208842014-02-07 14:00:50 -08001236 fdprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1237 fdprintf(fd, " Total writes: %d\n", mNumWrites);
1238 fdprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1239 fdprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1240 fdprintf(fd, " Suspend count: %d\n", mSuspended);
Andy Hung2098f272014-02-27 14:00:06 -08001241 fdprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001242 fdprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001243 fdprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001244 fdprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001245
1246 dumpBase(fd, args);
1247}
1248
1249// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001250
1251void AudioFlinger::PlaybackThread::onFirstRef()
1252{
1253 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1254}
1255
1256// ThreadBase virtuals
1257void AudioFlinger::PlaybackThread::preExit()
1258{
1259 ALOGV(" preExit()");
1260 // FIXME this is using hard-coded strings but in the future, this functionality will be
1261 // converted to use audio HAL extensions required to support tunneling
1262 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1263}
1264
1265// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1266sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1267 const sp<AudioFlinger::Client>& client,
1268 audio_stream_type_t streamType,
1269 uint32_t sampleRate,
1270 audio_format_t format,
1271 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001272 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001273 const sp<IMemory>& sharedBuffer,
1274 int sessionId,
1275 IAudioFlinger::track_flags_t *flags,
1276 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001277 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 status_t *status)
1279{
Glenn Kasten74935e42013-12-19 08:56:45 -08001280 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001281 sp<Track> track;
1282 status_t lStatus;
1283
1284 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1285
1286 // client expresses a preference for FAST, but we get the final say
1287 if (*flags & IAudioFlinger::TRACK_FAST) {
1288 if (
1289 // not timed
1290 (!isTimed) &&
1291 // either of these use cases:
1292 (
1293 // use case 1: shared buffer with any frame count
1294 (
1295 (sharedBuffer != 0)
1296 ) ||
1297 // use case 2: callback handler and frame count is default or at least as large as HAL
1298 (
1299 (tid != -1) &&
1300 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001301 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001302 )
1303 ) &&
1304 // PCM data
1305 audio_is_linear_pcm(format) &&
1306 // mono or stereo
1307 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1308 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001309 // hardware sample rate
1310 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001311 // normal mixer has an associated fast mixer
1312 hasFastMixer() &&
1313 // there are sufficient fast track slots available
1314 (mFastTrackAvailMask != 0)
1315 // FIXME test that MixerThread for this fast track has a capable output HAL
1316 // FIXME add a permission test also?
1317 ) {
1318 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1319 if (frameCount == 0) {
1320 frameCount = mFrameCount * kFastTrackMultiplier;
1321 }
1322 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1323 frameCount, mFrameCount);
1324 } else {
1325 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1326 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1327 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1328 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1329 audio_is_linear_pcm(format),
1330 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1331 *flags &= ~IAudioFlinger::TRACK_FAST;
1332 // For compatibility with AudioTrack calculation, buffer depth is forced
1333 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1334 // This is probably too conservative, but legacy application code may depend on it.
1335 // If you change this calculation, also review the start threshold which is related.
1336 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1337 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1338 if (minBufCount < 2) {
1339 minBufCount = 2;
1340 }
1341 size_t minFrameCount = mNormalFrameCount * minBufCount;
1342 if (frameCount < minFrameCount) {
1343 frameCount = minFrameCount;
1344 }
1345 }
1346 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001347 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001348
Glenn Kastenc3df8382014-03-13 15:05:25 -07001349 switch (mType) {
1350
1351 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001352 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001353 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001354 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1355 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001356 sampleRate, format, channelMask, mOutput, mFormat);
1357 lStatus = BAD_VALUE;
1358 goto Exit;
1359 }
1360 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001361 break;
1362
1363 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001364 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001365 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1366 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001367 sampleRate, format, channelMask, mOutput, mFormat);
1368 lStatus = BAD_VALUE;
1369 goto Exit;
1370 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001371 break;
1372
1373 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001374 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001375 ALOGE("createTrack_l() Bad parameter: format %#x \""
1376 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001377 format, mOutput, mFormat);
1378 lStatus = BAD_VALUE;
1379 goto Exit;
1380 }
Eric Laurent81784c32012-11-19 14:55:58 -08001381 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1382 if (sampleRate > mSampleRate*2) {
1383 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1384 lStatus = BAD_VALUE;
1385 goto Exit;
1386 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001387 break;
1388
Eric Laurent81784c32012-11-19 14:55:58 -08001389 }
1390
1391 lStatus = initCheck();
1392 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001393 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001394 goto Exit;
1395 }
1396
1397 { // scope for mLock
1398 Mutex::Autolock _l(mLock);
1399
1400 // all tracks in same audio session must share the same routing strategy otherwise
1401 // conflicts will happen when tracks are moved from one output to another by audio policy
1402 // manager
1403 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1404 for (size_t i = 0; i < mTracks.size(); ++i) {
1405 sp<Track> t = mTracks[i];
1406 if (t != 0 && !t->isOutputTrack()) {
1407 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1408 if (sessionId == t->sessionId() && strategy != actual) {
1409 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1410 strategy, actual);
1411 lStatus = BAD_VALUE;
1412 goto Exit;
1413 }
1414 }
1415 }
1416
1417 if (!isTimed) {
1418 track = new Track(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001419 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
Eric Laurent81784c32012-11-19 14:55:58 -08001420 } else {
1421 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001422 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001423 }
Glenn Kasten03003332013-08-06 15:40:54 -07001424
1425 // new Track always returns non-NULL,
1426 // but TimedTrack::create() is a factory that could fail by returning NULL
1427 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1428 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001429 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001430 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001431 goto Exit;
1432 }
1433 mTracks.add(track);
1434
1435 sp<EffectChain> chain = getEffectChain_l(sessionId);
1436 if (chain != 0) {
1437 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1438 track->setMainBuffer(chain->inBuffer());
1439 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1440 chain->incTrackCnt();
1441 }
1442
1443 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1444 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1445 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1446 // so ask activity manager to do this on our behalf
1447 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1448 }
1449 }
1450
1451 lStatus = NO_ERROR;
1452
1453Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001454 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001455 return track;
1456}
1457
1458uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1459{
1460 return latency;
1461}
1462
1463uint32_t AudioFlinger::PlaybackThread::latency() const
1464{
1465 Mutex::Autolock _l(mLock);
1466 return latency_l();
1467}
1468uint32_t AudioFlinger::PlaybackThread::latency_l() const
1469{
1470 if (initCheck() == NO_ERROR) {
1471 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1472 } else {
1473 return 0;
1474 }
1475}
1476
1477void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1478{
1479 Mutex::Autolock _l(mLock);
1480 // Don't apply master volume in SW if our HAL can do it for us.
1481 if (mOutput && mOutput->audioHwDev &&
1482 mOutput->audioHwDev->canSetMasterVolume()) {
1483 mMasterVolume = 1.0;
1484 } else {
1485 mMasterVolume = value;
1486 }
1487}
1488
1489void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1490{
1491 Mutex::Autolock _l(mLock);
1492 // Don't apply master mute in SW if our HAL can do it for us.
1493 if (mOutput && mOutput->audioHwDev &&
1494 mOutput->audioHwDev->canSetMasterMute()) {
1495 mMasterMute = false;
1496 } else {
1497 mMasterMute = muted;
1498 }
1499}
1500
1501void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1502{
1503 Mutex::Autolock _l(mLock);
1504 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001505 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001506}
1507
1508void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1509{
1510 Mutex::Autolock _l(mLock);
1511 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001512 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001513}
1514
1515float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1516{
1517 Mutex::Autolock _l(mLock);
1518 return mStreamTypes[stream].volume;
1519}
1520
1521// addTrack_l() must be called with ThreadBase::mLock held
1522status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1523{
1524 status_t status = ALREADY_EXISTS;
1525
1526 // set retry count for buffer fill
1527 track->mRetryCount = kMaxTrackStartupRetries;
1528 if (mActiveTracks.indexOf(track) < 0) {
1529 // the track is newly added, make sure it fills up all its
1530 // buffers before playing. This is to ensure the client will
1531 // effectively get the latency it requested.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001532 if (!track->isOutputTrack()) {
1533 TrackBase::track_state state = track->mState;
1534 mLock.unlock();
1535 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1536 mLock.lock();
1537 // abort track was stopped/paused while we released the lock
1538 if (state != track->mState) {
1539 if (status == NO_ERROR) {
1540 mLock.unlock();
1541 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1542 mLock.lock();
1543 }
1544 return INVALID_OPERATION;
1545 }
1546 // abort if start is rejected by audio policy manager
1547 if (status != NO_ERROR) {
1548 return PERMISSION_DENIED;
1549 }
1550#ifdef ADD_BATTERY_DATA
1551 // to track the speaker usage
1552 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1553#endif
1554 }
1555
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001556 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001557 track->mResetDone = false;
1558 track->mPresentationCompleteFrames = 0;
1559 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001560 mWakeLockUids.add(track->uid());
1561 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001562 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001563 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1564 if (chain != 0) {
1565 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1566 track->sessionId());
1567 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001568 }
1569
1570 status = NO_ERROR;
1571 }
1572
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001573 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001574 return status;
1575}
1576
Eric Laurentbfb1b832013-01-07 09:53:42 -08001577bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001578{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001579 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001580 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001581 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1582 track->mState = TrackBase::STOPPED;
1583 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001584 removeTrack_l(track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001585 } else if (track->isFastTrack() || track->isOffloaded()) {
1586 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001587 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001588
1589 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001590}
1591
1592void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1593{
1594 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1595 mTracks.remove(track);
1596 deleteTrackName_l(track->name());
1597 // redundant as track is about to be destroyed, for dumpsys only
1598 track->mName = -1;
1599 if (track->isFastTrack()) {
1600 int index = track->mFastIndex;
1601 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1602 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1603 mFastTrackAvailMask |= 1 << index;
1604 // redundant as track is about to be destroyed, for dumpsys only
1605 track->mFastIndex = -1;
1606 }
1607 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1608 if (chain != 0) {
1609 chain->decTrackCnt();
1610 }
1611}
1612
Eric Laurentede6c3b2013-09-19 14:37:46 -07001613void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001614{
1615 // Thread could be blocked waiting for async
1616 // so signal it to handle state changes immediately
1617 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1618 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1619 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001620 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001621}
1622
Eric Laurent81784c32012-11-19 14:55:58 -08001623String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1624{
Eric Laurent81784c32012-11-19 14:55:58 -08001625 Mutex::Autolock _l(mLock);
1626 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001627 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001628 }
1629
Glenn Kastend8ea6992013-07-16 14:17:15 -07001630 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1631 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001632 free(s);
1633 return out_s8;
1634}
1635
1636// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1637void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1638 AudioSystem::OutputDescriptor desc;
1639 void *param2 = NULL;
1640
1641 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1642 param);
1643
1644 switch (event) {
1645 case AudioSystem::OUTPUT_OPENED:
1646 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001647 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001648 desc.samplingRate = mSampleRate;
1649 desc.format = mFormat;
1650 desc.frameCount = mNormalFrameCount; // FIXME see
1651 // AudioFlinger::frameCount(audio_io_handle_t)
1652 desc.latency = latency();
1653 param2 = &desc;
1654 break;
1655
1656 case AudioSystem::STREAM_CONFIG_CHANGED:
1657 param2 = &param;
1658 case AudioSystem::OUTPUT_CLOSED:
1659 default:
1660 break;
1661 }
1662 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1663}
1664
Eric Laurentbfb1b832013-01-07 09:53:42 -08001665void AudioFlinger::PlaybackThread::writeCallback()
1666{
1667 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001668 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669}
1670
1671void AudioFlinger::PlaybackThread::drainCallback()
1672{
1673 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001674 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001675}
1676
Eric Laurent3b4529e2013-09-05 18:09:19 -07001677void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678{
1679 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001680 // reject out of sequence requests
1681 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1682 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001683 mWaitWorkCV.signal();
1684 }
1685}
1686
Eric Laurent3b4529e2013-09-05 18:09:19 -07001687void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001688{
1689 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001690 // reject out of sequence requests
1691 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1692 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001693 mWaitWorkCV.signal();
1694 }
1695}
1696
1697// static
1698int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001699 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001700 void *cookie)
1701{
1702 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1703 ALOGV("asyncCallback() event %d", event);
1704 switch (event) {
1705 case STREAM_CBK_EVENT_WRITE_READY:
1706 me->writeCallback();
1707 break;
1708 case STREAM_CBK_EVENT_DRAIN_READY:
1709 me->drainCallback();
1710 break;
1711 default:
1712 ALOGW("asyncCallback() unknown event %d", event);
1713 break;
1714 }
1715 return 0;
1716}
1717
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001718void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001719{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001720 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001721 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1722 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001723 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001724 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001725 }
1726 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001727 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001728 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1729 }
Glenn Kastenf6ed4232013-07-16 11:16:27 -07001730 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08001731 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001732 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001733 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001734 }
1735 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001736 LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1737 "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001738 }
Eric Laurent81784c32012-11-19 14:55:58 -08001739 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten70949c42013-08-06 07:40:12 -07001740 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1741 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001742 if (mFrameCount & 15) {
1743 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1744 mFrameCount);
1745 }
1746
Eric Laurentbfb1b832013-01-07 09:53:42 -08001747 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1748 (mOutput->stream->set_callback != NULL)) {
1749 if (mOutput->stream->set_callback(mOutput->stream,
1750 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1751 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07001752 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001753 }
1754 }
1755
Andy Hung09a50072014-02-27 14:30:47 -08001756 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08001757 double multiplier = 1.0;
1758 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1759 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08001760 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1761 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08001762 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1763 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1764 maxNormalFrameCount = maxNormalFrameCount & ~15;
1765 if (maxNormalFrameCount < minNormalFrameCount) {
1766 maxNormalFrameCount = minNormalFrameCount;
1767 }
1768 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1769 if (multiplier <= 1.0) {
1770 multiplier = 1.0;
1771 } else if (multiplier <= 2.0) {
1772 if (2 * mFrameCount <= maxNormalFrameCount) {
1773 multiplier = 2.0;
1774 } else {
1775 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1776 }
1777 } else {
1778 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08001779 // 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 -08001780 // track, but we sometimes have to do this to satisfy the maximum frame count
1781 // constraint)
1782 // FIXME this rounding up should not be done if no HAL SRC
1783 uint32_t truncMult = (uint32_t) multiplier;
1784 if ((truncMult & 1)) {
1785 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1786 ++truncMult;
1787 }
1788 }
1789 multiplier = (double) truncMult;
1790 }
1791 }
1792 mNormalFrameCount = multiplier * mFrameCount;
1793 // round up to nearest 16 frames to satisfy AudioMixer
1794 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Andy Hung09a50072014-02-27 14:30:47 -08001795 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001796 mNormalFrameCount);
1797
Andy Hung010a1a12014-03-13 13:57:33 -07001798 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
1799 // Originally this was int16_t[] array, need to remove legacy implications.
1800 free(mSinkBuffer);
1801 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07001802 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1803 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1804 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07001805 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001806
Andy Hung69aed5f2014-02-25 17:24:40 -08001807 // We resize the mMixerBuffer according to the requirements of the sink buffer which
1808 // drives the output.
1809 free(mMixerBuffer);
1810 mMixerBuffer = NULL;
1811 if (mMixerBufferEnabled) {
1812 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1813 mMixerBufferSize = mNormalFrameCount * mChannelCount
1814 * audio_bytes_per_sample(mMixerBufferFormat);
1815 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1816 }
Andy Hung98ef9782014-03-04 14:46:50 -08001817 free(mEffectBuffer);
1818 mEffectBuffer = NULL;
1819 if (mEffectBufferEnabled) {
1820 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1821 mEffectBufferSize = mNormalFrameCount * mChannelCount
1822 * audio_bytes_per_sample(mEffectBufferFormat);
1823 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1824 }
Andy Hung69aed5f2014-02-25 17:24:40 -08001825
Eric Laurent81784c32012-11-19 14:55:58 -08001826 // force reconfiguration of effect chains and engines to take new buffer size and audio
1827 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001828 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08001829 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1830 // matter.
1831 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1832 Vector< sp<EffectChain> > effectChains = mEffectChains;
1833 for (size_t i = 0; i < effectChains.size(); i ++) {
1834 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1835 }
1836}
1837
1838
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001839status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08001840{
1841 if (halFrames == NULL || dspFrames == NULL) {
1842 return BAD_VALUE;
1843 }
1844 Mutex::Autolock _l(mLock);
1845 if (initCheck() != NO_ERROR) {
1846 return INVALID_OPERATION;
1847 }
1848 size_t framesWritten = mBytesWritten / mFrameSize;
1849 *halFrames = framesWritten;
1850
1851 if (isSuspended()) {
1852 // return an estimation of rendered frames when the output is suspended
1853 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1854 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1855 return NO_ERROR;
1856 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001857 status_t status;
1858 uint32_t frames;
1859 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1860 *dspFrames = (size_t)frames;
1861 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001862 }
1863}
1864
1865uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1866{
1867 Mutex::Autolock _l(mLock);
1868 uint32_t result = 0;
1869 if (getEffectChain_l(sessionId) != 0) {
1870 result = EFFECT_SESSION;
1871 }
1872
1873 for (size_t i = 0; i < mTracks.size(); ++i) {
1874 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001875 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001876 result |= TRACK_SESSION;
1877 break;
1878 }
1879 }
1880
1881 return result;
1882}
1883
1884uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1885{
1886 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1887 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1888 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1889 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1890 }
1891 for (size_t i = 0; i < mTracks.size(); i++) {
1892 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08001893 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001894 return AudioSystem::getStrategyForStream(track->streamType());
1895 }
1896 }
1897 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1898}
1899
1900
1901AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1902{
1903 Mutex::Autolock _l(mLock);
1904 return mOutput;
1905}
1906
1907AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1908{
1909 Mutex::Autolock _l(mLock);
1910 AudioStreamOut *output = mOutput;
1911 mOutput = NULL;
1912 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1913 // must push a NULL and wait for ack
1914 mOutputSink.clear();
1915 mPipeSink.clear();
1916 mNormalSink.clear();
1917 return output;
1918}
1919
1920// this method must always be called either with ThreadBase mLock held or inside the thread loop
1921audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1922{
1923 if (mOutput == NULL) {
1924 return NULL;
1925 }
1926 return &mOutput->stream->common;
1927}
1928
1929uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1930{
1931 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1932}
1933
1934status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1935{
1936 if (!isValidSyncEvent(event)) {
1937 return BAD_VALUE;
1938 }
1939
1940 Mutex::Autolock _l(mLock);
1941
1942 for (size_t i = 0; i < mTracks.size(); ++i) {
1943 sp<Track> track = mTracks[i];
1944 if (event->triggerSession() == track->sessionId()) {
1945 (void) track->setSyncEvent(event);
1946 return NO_ERROR;
1947 }
1948 }
1949
1950 return NAME_NOT_FOUND;
1951}
1952
1953bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1954{
1955 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1956}
1957
1958void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1959 const Vector< sp<Track> >& tracksToRemove)
1960{
1961 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07001962 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001963 for (size_t i = 0 ; i < count ; i++) {
1964 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965 if (!track->isOutputTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001966 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001967#ifdef ADD_BATTERY_DATA
1968 // to track the speaker usage
1969 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1970#endif
1971 if (track->isTerminated()) {
1972 AudioSystem::releaseOutput(mId);
1973 }
Eric Laurent81784c32012-11-19 14:55:58 -08001974 }
1975 }
1976 }
Eric Laurent81784c32012-11-19 14:55:58 -08001977}
1978
1979void AudioFlinger::PlaybackThread::checkSilentMode_l()
1980{
1981 if (!mMasterMute) {
1982 char value[PROPERTY_VALUE_MAX];
1983 if (property_get("ro.audio.silent", value, "0") > 0) {
1984 char *endptr;
1985 unsigned long ul = strtoul(value, &endptr, 0);
1986 if (*endptr == '\0' && ul != 0) {
1987 ALOGD("Silence is golden");
1988 // The setprop command will not allow a property to be changed after
1989 // the first time it is set, so we don't have to worry about un-muting.
1990 setMasterMute_l(true);
1991 }
1992 }
1993 }
1994}
1995
1996// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08001997ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08001998{
1999 // FIXME rewrite to reduce number of system calls
2000 mLastWriteTime = systemTime();
2001 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002002 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002003 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002004
2005 // If an NBAIO sink is present, use it to write the normal mixer's submix
2006 if (mNormalSink != 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002007 const size_t count = mBytesRemaining / mFrameSize;
2008
Simon Wilson2d590962012-11-29 15:18:50 -08002009 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002010 // update the setpoint when AudioFlinger::mScreenState changes
2011 uint32_t screenState = AudioFlinger::mScreenState;
2012 if (screenState != mScreenState) {
2013 mScreenState = screenState;
2014 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2015 if (pipe != NULL) {
2016 pipe->setAvgFrames((mScreenState & 1) ?
2017 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2018 }
2019 }
Andy Hung010a1a12014-03-13 13:57:33 -07002020 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002021 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002022 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002023 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002024 } else {
2025 bytesWritten = framesWritten;
2026 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002027 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002028 if (status == NO_ERROR) {
2029 size_t totalFramesWritten = mNormalSink->framesWritten();
2030 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2031 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2032 mLatchDValid = true;
2033 }
2034 }
Eric Laurent81784c32012-11-19 14:55:58 -08002035 // otherwise use the HAL / AudioStreamOut directly
2036 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002038
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002040 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2041 mWriteAckSequence += 2;
2042 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002044 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002046 // FIXME We should have an implementation of timestamps for direct output threads.
2047 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002049 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050 if (mUseAsyncWrite &&
2051 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2052 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002053 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002054 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002055 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002056 }
Eric Laurent81784c32012-11-19 14:55:58 -08002057 }
2058
Eric Laurent81784c32012-11-19 14:55:58 -08002059 mNumWrites++;
2060 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002061 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002062 return bytesWritten;
2063}
2064
2065void AudioFlinger::PlaybackThread::threadLoop_drain()
2066{
2067 if (mOutput->stream->drain) {
2068 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2069 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002070 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2071 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002072 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002073 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002074 }
2075 mOutput->stream->drain(mOutput->stream,
2076 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2077 : AUDIO_DRAIN_ALL);
2078 }
2079}
2080
2081void AudioFlinger::PlaybackThread::threadLoop_exit()
2082{
2083 // Default implementation has nothing to do
Eric Laurent81784c32012-11-19 14:55:58 -08002084}
2085
2086/*
2087The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002088 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002089 - activeSleepTime from activeSleepTimeUs()
2090 - idleSleepTime from idleSleepTimeUs()
2091 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2092 - maxPeriod from frame count and sample rate (MIXER only)
2093
2094The parameters that affect these derived values are:
2095 - frame count
2096 - frame size
2097 - sample rate
2098 - device type: A2DP or not
2099 - device latency
2100 - format: PCM or not
2101 - active sleep time
2102 - idle sleep time
2103*/
2104
2105void AudioFlinger::PlaybackThread::cacheParameters_l()
2106{
Andy Hung25c2dac2014-02-27 14:56:00 -08002107 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002108 activeSleepTime = activeSleepTimeUs();
2109 idleSleepTime = idleSleepTimeUs();
2110}
2111
2112void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2113{
Glenn Kasten7c027242012-12-26 14:43:16 -08002114 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002115 this, streamType, mTracks.size());
2116 Mutex::Autolock _l(mLock);
2117
2118 size_t size = mTracks.size();
2119 for (size_t i = 0; i < size; i++) {
2120 sp<Track> t = mTracks[i];
2121 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002122 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002123 }
2124 }
2125}
2126
2127status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2128{
2129 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002130 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2131 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002132 bool ownsBuffer = false;
2133
2134 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2135 if (session > 0) {
2136 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002137 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002138 if (mType != DIRECT) {
2139 size_t numSamples = mNormalFrameCount * mChannelCount;
2140 buffer = new int16_t[numSamples];
2141 memset(buffer, 0, numSamples * sizeof(int16_t));
2142 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2143 ownsBuffer = true;
2144 }
2145
2146 // Attach all tracks with same session ID to this chain.
2147 for (size_t i = 0; i < mTracks.size(); ++i) {
2148 sp<Track> track = mTracks[i];
2149 if (session == track->sessionId()) {
2150 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2151 buffer);
2152 track->setMainBuffer(buffer);
2153 chain->incTrackCnt();
2154 }
2155 }
2156
2157 // indicate all active tracks in the chain
2158 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2159 sp<Track> track = mActiveTracks[i].promote();
2160 if (track == 0) {
2161 continue;
2162 }
2163 if (session == track->sessionId()) {
2164 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2165 chain->incActiveTrackCnt();
2166 }
2167 }
2168 }
2169
2170 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002171 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2172 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002173 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2174 // chains list in order to be processed last as it contains output stage effects
2175 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2176 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2177 // after track specific effects and before output stage
2178 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2179 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2180 // Effect chain for other sessions are inserted at beginning of effect
2181 // chains list to be processed before output mix effects. Relative order between other
2182 // sessions is not important
2183 size_t size = mEffectChains.size();
2184 size_t i = 0;
2185 for (i = 0; i < size; i++) {
2186 if (mEffectChains[i]->sessionId() < session) {
2187 break;
2188 }
2189 }
2190 mEffectChains.insertAt(chain, i);
2191 checkSuspendOnAddEffectChain_l(chain);
2192
2193 return NO_ERROR;
2194}
2195
2196size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2197{
2198 int session = chain->sessionId();
2199
2200 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2201
2202 for (size_t i = 0; i < mEffectChains.size(); i++) {
2203 if (chain == mEffectChains[i]) {
2204 mEffectChains.removeAt(i);
2205 // detach all active tracks from the chain
2206 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2207 sp<Track> track = mActiveTracks[i].promote();
2208 if (track == 0) {
2209 continue;
2210 }
2211 if (session == track->sessionId()) {
2212 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2213 chain.get(), session);
2214 chain->decActiveTrackCnt();
2215 }
2216 }
2217
2218 // detach all tracks with same session ID from this chain
2219 for (size_t i = 0; i < mTracks.size(); ++i) {
2220 sp<Track> track = mTracks[i];
2221 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002222 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002223 chain->decTrackCnt();
2224 }
2225 }
2226 break;
2227 }
2228 }
2229 return mEffectChains.size();
2230}
2231
2232status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2233 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2234{
2235 Mutex::Autolock _l(mLock);
2236 return attachAuxEffect_l(track, EffectId);
2237}
2238
2239status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2240 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2241{
2242 status_t status = NO_ERROR;
2243
2244 if (EffectId == 0) {
2245 track->setAuxBuffer(0, NULL);
2246 } else {
2247 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2248 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2249 if (effect != 0) {
2250 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2251 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2252 } else {
2253 status = INVALID_OPERATION;
2254 }
2255 } else {
2256 status = BAD_VALUE;
2257 }
2258 }
2259 return status;
2260}
2261
2262void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2263{
2264 for (size_t i = 0; i < mTracks.size(); ++i) {
2265 sp<Track> track = mTracks[i];
2266 if (track->auxEffectId() == effectId) {
2267 attachAuxEffect_l(track, 0);
2268 }
2269 }
2270}
2271
2272bool AudioFlinger::PlaybackThread::threadLoop()
2273{
2274 Vector< sp<Track> > tracksToRemove;
2275
2276 standbyTime = systemTime();
2277
2278 // MIXER
2279 nsecs_t lastWarning = 0;
2280
2281 // DUPLICATING
2282 // FIXME could this be made local to while loop?
2283 writeFrames = 0;
2284
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002285 int lastGeneration = 0;
2286
Eric Laurent81784c32012-11-19 14:55:58 -08002287 cacheParameters_l();
2288 sleepTime = idleSleepTime;
2289
2290 if (mType == MIXER) {
2291 sleepTimeShift = 0;
2292 }
2293
2294 CpuStats cpuStats;
2295 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2296
2297 acquireWakeLock();
2298
Glenn Kasten9e58b552013-01-18 15:09:48 -08002299 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2300 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2301 // and then that string will be logged at the next convenient opportunity.
2302 const char *logString = NULL;
2303
Eric Laurent664539d2013-09-23 18:24:31 -07002304 checkSilentMode_l();
2305
Eric Laurent81784c32012-11-19 14:55:58 -08002306 while (!exitPending())
2307 {
2308 cpuStats.sample(myName);
2309
2310 Vector< sp<EffectChain> > effectChains;
2311
2312 processConfigEvents();
2313
2314 { // scope for mLock
2315
2316 Mutex::Autolock _l(mLock);
2317
Glenn Kasten9e58b552013-01-18 15:09:48 -08002318 if (logString != NULL) {
2319 mNBLogWriter->logTimestamp();
2320 mNBLogWriter->log(logString);
2321 logString = NULL;
2322 }
2323
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002324 if (mLatchDValid) {
2325 mLatchQ = mLatchD;
2326 mLatchDValid = false;
2327 mLatchQValid = true;
2328 }
2329
Eric Laurent81784c32012-11-19 14:55:58 -08002330 if (checkForNewParameters_l()) {
2331 cacheParameters_l();
2332 }
2333
2334 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 if (mSignalPending) {
2336 // A signal was raised while we were unlocked
2337 mSignalPending = false;
2338 } else if (waitingAsyncCallback_l()) {
2339 if (exitPending()) {
2340 break;
2341 }
2342 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002343 mWakeLockUids.clear();
2344 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345 ALOGV("wait async completion");
2346 mWaitWorkCV.wait(mLock);
2347 ALOGV("async completion/wake");
2348 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002349 standbyTime = systemTime() + standbyDelay;
2350 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002351
2352 continue;
2353 }
2354 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355 isSuspended()) {
2356 // put audio hardware into standby after short delay
2357 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002358
2359 threadLoop_standby();
2360
2361 mStandby = true;
2362 }
2363
2364 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2365 // we're about to wait, flush the binder command buffer
2366 IPCThreadState::self()->flushCommands();
2367
2368 clearOutputTracks();
2369
2370 if (exitPending()) {
2371 break;
2372 }
2373
2374 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002375 mWakeLockUids.clear();
2376 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002377 // wait until we have something to do...
2378 ALOGV("%s going to sleep", myName.string());
2379 mWaitWorkCV.wait(mLock);
2380 ALOGV("%s waking up", myName.string());
2381 acquireWakeLock_l();
2382
2383 mMixerStatus = MIXER_IDLE;
2384 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2385 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002387 checkSilentMode_l();
2388
2389 standbyTime = systemTime() + standbyDelay;
2390 sleepTime = idleSleepTime;
2391 if (mType == MIXER) {
2392 sleepTimeShift = 0;
2393 }
2394
2395 continue;
2396 }
2397 }
Eric Laurent81784c32012-11-19 14:55:58 -08002398 // mMixerStatusIgnoringFastTracks is also updated internally
2399 mMixerStatus = prepareTracks_l(&tracksToRemove);
2400
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002401 // compare with previously applied list
2402 if (lastGeneration != mActiveTracksGeneration) {
2403 // update wakelock
2404 updateWakeLockUids_l(mWakeLockUids);
2405 lastGeneration = mActiveTracksGeneration;
2406 }
2407
Eric Laurent81784c32012-11-19 14:55:58 -08002408 // prevent any changes in effect chain list and in each effect chain
2409 // during mixing and effect process as the audio buffers could be deleted
2410 // or modified if an effect is created or deleted
2411 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002412 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002413
Eric Laurentbfb1b832013-01-07 09:53:42 -08002414 if (mBytesRemaining == 0) {
2415 mCurrentWriteLength = 0;
2416 if (mMixerStatus == MIXER_TRACKS_READY) {
2417 // threadLoop_mix() sets mCurrentWriteLength
2418 threadLoop_mix();
2419 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2420 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2421 // threadLoop_sleepTime sets sleepTime to 0 if data
2422 // must be written to HAL
2423 threadLoop_sleepTime();
2424 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002425 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002426 }
2427 }
Andy Hung98ef9782014-03-04 14:46:50 -08002428 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2429 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2430 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2431 // or mSinkBuffer (if there are no effects).
2432 //
2433 // This is done pre-effects computation; if effects change to
2434 // support higher precision, this needs to move.
2435 //
2436 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2437 // TODO use sleepTime == 0 as an additional condition.
2438 if (mMixerBufferValid) {
2439 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2440 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2441
2442 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2443 mNormalFrameCount * mChannelCount);
2444 }
2445
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446 mBytesRemaining = mCurrentWriteLength;
2447 if (isSuspended()) {
2448 sleepTime = suspendSleepTimeUs();
2449 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002450 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 mBytesRemaining = 0;
2452 }
Eric Laurent81784c32012-11-19 14:55:58 -08002453
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002455 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456 for (size_t i = 0; i < effectChains.size(); i ++) {
2457 effectChains[i]->process_l();
2458 }
Eric Laurent81784c32012-11-19 14:55:58 -08002459 }
2460 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002461 // Process effect chains for offloaded thread even if no audio
2462 // was read from audio track: process only updates effect state
2463 // and thus does have to be synchronized with audio writes but may have
2464 // to be called while waiting for async write callback
2465 if (mType == OFFLOAD) {
2466 for (size_t i = 0; i < effectChains.size(); i ++) {
2467 effectChains[i]->process_l();
2468 }
2469 }
Eric Laurent81784c32012-11-19 14:55:58 -08002470
Andy Hung98ef9782014-03-04 14:46:50 -08002471 // Only if the Effects buffer is enabled and there is data in the
2472 // Effects buffer (buffer valid), we need to
2473 // copy into the sink buffer.
2474 // TODO use sleepTime == 0 as an additional condition.
2475 if (mEffectBufferValid) {
2476 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2477 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2478 mNormalFrameCount * mChannelCount);
2479 }
2480
Eric Laurent81784c32012-11-19 14:55:58 -08002481 // enable changes in effect chain
2482 unlockEffectChains(effectChains);
2483
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484 if (!waitingAsyncCallback()) {
2485 // sleepTime == 0 means we must write to audio hardware
2486 if (sleepTime == 0) {
2487 if (mBytesRemaining) {
2488 ssize_t ret = threadLoop_write();
2489 if (ret < 0) {
2490 mBytesRemaining = 0;
2491 } else {
2492 mBytesWritten += ret;
2493 mBytesRemaining -= ret;
2494 }
2495 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2496 (mMixerStatus == MIXER_DRAIN_ALL)) {
2497 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002499 if (mType == MIXER) {
2500 // write blocked detection
2501 nsecs_t now = systemTime();
2502 nsecs_t delta = now - mLastWriteTime;
2503 if (!mStandby && delta > maxPeriod) {
2504 mNumDelayedWrites++;
2505 if ((now - lastWarning) > kWarningThrottleNs) {
2506 ATRACE_NAME("underrun");
2507 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2508 ns2ms(delta), mNumDelayedWrites, this);
2509 lastWarning = now;
2510 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002511 }
2512 }
Eric Laurent81784c32012-11-19 14:55:58 -08002513
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 } else {
2515 usleep(sleepTime);
2516 }
Eric Laurent81784c32012-11-19 14:55:58 -08002517 }
2518
2519 // Finally let go of removed track(s), without the lock held
2520 // since we can't guarantee the destructors won't acquire that
2521 // same lock. This will also mutate and push a new fast mixer state.
2522 threadLoop_removeTracks(tracksToRemove);
2523 tracksToRemove.clear();
2524
2525 // FIXME I don't understand the need for this here;
2526 // it was in the original code but maybe the
2527 // assignment in saveOutputTracks() makes this unnecessary?
2528 clearOutputTracks();
2529
2530 // Effect chains will be actually deleted here if they were removed from
2531 // mEffectChains list during mixing or effects processing
2532 effectChains.clear();
2533
2534 // FIXME Note that the above .clear() is no longer necessary since effectChains
2535 // is now local to this block, but will keep it for now (at least until merge done).
2536 }
2537
Eric Laurentbfb1b832013-01-07 09:53:42 -08002538 threadLoop_exit();
2539
Eric Laurent81784c32012-11-19 14:55:58 -08002540 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
Eric Laurentbfb1b832013-01-07 09:53:42 -08002541 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08002542 // put output stream into standby mode
2543 if (!mStandby) {
2544 mOutput->stream->common.standby(&mOutput->stream->common);
2545 }
2546 }
2547
2548 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002549 mWakeLockUids.clear();
2550 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002551
2552 ALOGV("Thread %p type %d exiting", this, mType);
2553 return false;
2554}
2555
Eric Laurentbfb1b832013-01-07 09:53:42 -08002556// removeTracks_l() must be called with ThreadBase::mLock held
2557void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2558{
2559 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002560 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002561 for (size_t i=0 ; i<count ; i++) {
2562 const sp<Track>& track = tracksToRemove.itemAt(i);
2563 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002564 mWakeLockUids.remove(track->uid());
2565 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002566 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2567 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2568 if (chain != 0) {
2569 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2570 track->sessionId());
2571 chain->decActiveTrackCnt();
2572 }
2573 if (track->isTerminated()) {
2574 removeTrack_l(track);
2575 }
2576 }
2577 }
2578
2579}
Eric Laurent81784c32012-11-19 14:55:58 -08002580
Eric Laurentaccc1472013-09-20 09:36:34 -07002581status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2582{
2583 if (mNormalSink != 0) {
2584 return mNormalSink->getTimestamp(timestamp);
2585 }
2586 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2587 uint64_t position64;
2588 int ret = mOutput->stream->get_presentation_position(
2589 mOutput->stream, &position64, &timestamp.mTime);
2590 if (ret == 0) {
2591 timestamp.mPosition = (uint32_t)position64;
2592 return NO_ERROR;
2593 }
2594 }
2595 return INVALID_OPERATION;
2596}
Eric Laurent81784c32012-11-19 14:55:58 -08002597// ----------------------------------------------------------------------------
2598
2599AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2600 audio_io_handle_t id, audio_devices_t device, type_t type)
2601 : PlaybackThread(audioFlinger, output, id, device, type),
2602 // mAudioMixer below
2603 // mFastMixer below
2604 mFastMixerFutex(0)
2605 // mOutputSink below
2606 // mPipeSink below
2607 // mNormalSink below
2608{
2609 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002610 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002611 "mFrameCount=%d, mNormalFrameCount=%d",
2612 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2613 mNormalFrameCount);
2614 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2615
2616 // FIXME - Current mixer implementation only supports stereo output
2617 if (mChannelCount != FCC_2) {
2618 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2619 }
2620
2621 // create an NBAIO sink for the HAL output stream, and negotiate
2622 mOutputSink = new AudioStreamOutSink(output->stream);
2623 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08002624 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08002625 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2626 ALOG_ASSERT(index == 0);
2627
2628 // initialize fast mixer depending on configuration
2629 bool initFastMixer;
2630 switch (kUseFastMixer) {
2631 case FastMixer_Never:
2632 initFastMixer = false;
2633 break;
2634 case FastMixer_Always:
2635 initFastMixer = true;
2636 break;
2637 case FastMixer_Static:
2638 case FastMixer_Dynamic:
2639 initFastMixer = mFrameCount < mNormalFrameCount;
2640 break;
2641 }
2642 if (initFastMixer) {
2643
2644 // create a MonoPipe to connect our submix to FastMixer
2645 NBAIO_Format format = mOutputSink->format();
2646 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2647 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2648 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2649 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2650 const NBAIO_Format offers[1] = {format};
2651 size_t numCounterOffers = 0;
2652 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2653 ALOG_ASSERT(index == 0);
2654 monoPipe->setAvgFrames((mScreenState & 1) ?
2655 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2656 mPipeSink = monoPipe;
2657
Glenn Kasten46909e72013-02-26 09:20:22 -08002658#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08002659 if (mTeeSinkOutputEnabled) {
2660 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2661 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2662 numCounterOffers = 0;
2663 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2664 ALOG_ASSERT(index == 0);
2665 mTeeSink = teeSink;
2666 PipeReader *teeSource = new PipeReader(*teeSink);
2667 numCounterOffers = 0;
2668 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2669 ALOG_ASSERT(index == 0);
2670 mTeeSource = teeSource;
2671 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002672#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002673
2674 // create fast mixer and configure it initially with just one fast track for our submix
2675 mFastMixer = new FastMixer();
2676 FastMixerStateQueue *sq = mFastMixer->sq();
2677#ifdef STATE_QUEUE_DUMP
2678 sq->setObserverDump(&mStateQueueObserverDump);
2679 sq->setMutatorDump(&mStateQueueMutatorDump);
2680#endif
2681 FastMixerState *state = sq->begin();
2682 FastTrack *fastTrack = &state->mFastTracks[0];
2683 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2684 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2685 fastTrack->mVolumeProvider = NULL;
2686 fastTrack->mGeneration++;
2687 state->mFastTracksGen++;
2688 state->mTrackMask = 1;
2689 // fast mixer will use the HAL output sink
2690 state->mOutputSink = mOutputSink.get();
2691 state->mOutputSinkGen++;
2692 state->mFrameCount = mFrameCount;
2693 state->mCommand = FastMixerState::COLD_IDLE;
2694 // already done in constructor initialization list
2695 //mFastMixerFutex = 0;
2696 state->mColdFutexAddr = &mFastMixerFutex;
2697 state->mColdGen++;
2698 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08002699#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002700 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08002701#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08002702 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2703 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08002704 sq->end();
2705 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2706
2707 // start the fast mixer
2708 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2709 pid_t tid = mFastMixer->getTid();
2710 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2711 if (err != 0) {
2712 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2713 kPriorityFastMixer, getpid_cached, tid, err);
2714 }
2715
2716#ifdef AUDIO_WATCHDOG
2717 // create and start the watchdog
2718 mAudioWatchdog = new AudioWatchdog();
2719 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2720 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2721 tid = mAudioWatchdog->getTid();
2722 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2723 if (err != 0) {
2724 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2725 kPriorityFastMixer, getpid_cached, tid, err);
2726 }
2727#endif
2728
2729 } else {
2730 mFastMixer = NULL;
2731 }
2732
2733 switch (kUseFastMixer) {
2734 case FastMixer_Never:
2735 case FastMixer_Dynamic:
2736 mNormalSink = mOutputSink;
2737 break;
2738 case FastMixer_Always:
2739 mNormalSink = mPipeSink;
2740 break;
2741 case FastMixer_Static:
2742 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2743 break;
2744 }
2745}
2746
2747AudioFlinger::MixerThread::~MixerThread()
2748{
2749 if (mFastMixer != NULL) {
2750 FastMixerStateQueue *sq = mFastMixer->sq();
2751 FastMixerState *state = sq->begin();
2752 if (state->mCommand == FastMixerState::COLD_IDLE) {
2753 int32_t old = android_atomic_inc(&mFastMixerFutex);
2754 if (old == -1) {
2755 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2756 }
2757 }
2758 state->mCommand = FastMixerState::EXIT;
2759 sq->end();
2760 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2761 mFastMixer->join();
2762 // Though the fast mixer thread has exited, it's state queue is still valid.
2763 // We'll use that extract the final state which contains one remaining fast track
2764 // corresponding to our sub-mix.
2765 state = sq->begin();
2766 ALOG_ASSERT(state->mTrackMask == 1);
2767 FastTrack *fastTrack = &state->mFastTracks[0];
2768 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2769 delete fastTrack->mBufferProvider;
2770 sq->end(false /*didModify*/);
2771 delete mFastMixer;
2772#ifdef AUDIO_WATCHDOG
2773 if (mAudioWatchdog != 0) {
2774 mAudioWatchdog->requestExit();
2775 mAudioWatchdog->requestExitAndWait();
2776 mAudioWatchdog.clear();
2777 }
2778#endif
2779 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08002780 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08002781 delete mAudioMixer;
2782}
2783
2784
2785uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2786{
2787 if (mFastMixer != NULL) {
2788 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2789 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2790 }
2791 return latency;
2792}
2793
2794
2795void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2796{
2797 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2798}
2799
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002801{
2802 // FIXME we should only do one push per cycle; confirm this is true
2803 // Start the fast mixer if it's not already running
2804 if (mFastMixer != NULL) {
2805 FastMixerStateQueue *sq = mFastMixer->sq();
2806 FastMixerState *state = sq->begin();
2807 if (state->mCommand != FastMixerState::MIX_WRITE &&
2808 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2809 if (state->mCommand == FastMixerState::COLD_IDLE) {
2810 int32_t old = android_atomic_inc(&mFastMixerFutex);
2811 if (old == -1) {
2812 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2813 }
2814#ifdef AUDIO_WATCHDOG
2815 if (mAudioWatchdog != 0) {
2816 mAudioWatchdog->resume();
2817 }
2818#endif
2819 }
2820 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002821 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2822 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
Eric Laurent81784c32012-11-19 14:55:58 -08002823 sq->end();
2824 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2825 if (kUseFastMixer == FastMixer_Dynamic) {
2826 mNormalSink = mPipeSink;
2827 }
2828 } else {
2829 sq->end(false /*didModify*/);
2830 }
2831 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08002833}
2834
2835void AudioFlinger::MixerThread::threadLoop_standby()
2836{
2837 // Idle the fast mixer if it's currently running
2838 if (mFastMixer != NULL) {
2839 FastMixerStateQueue *sq = mFastMixer->sq();
2840 FastMixerState *state = sq->begin();
2841 if (!(state->mCommand & FastMixerState::IDLE)) {
2842 state->mCommand = FastMixerState::COLD_IDLE;
2843 state->mColdFutexAddr = &mFastMixerFutex;
2844 state->mColdGen++;
2845 mFastMixerFutex = 0;
2846 sq->end();
2847 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2848 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2849 if (kUseFastMixer == FastMixer_Dynamic) {
2850 mNormalSink = mOutputSink;
2851 }
2852#ifdef AUDIO_WATCHDOG
2853 if (mAudioWatchdog != 0) {
2854 mAudioWatchdog->pause();
2855 }
2856#endif
2857 } else {
2858 sq->end(false /*didModify*/);
2859 }
2860 }
2861 PlaybackThread::threadLoop_standby();
2862}
2863
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2865{
2866 return false;
2867}
2868
2869bool AudioFlinger::PlaybackThread::shouldStandby_l()
2870{
2871 return !mStandby;
2872}
2873
2874bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2875{
2876 Mutex::Autolock _l(mLock);
2877 return waitingAsyncCallback_l();
2878}
2879
Eric Laurent81784c32012-11-19 14:55:58 -08002880// shared by MIXER and DIRECT, overridden by DUPLICATING
2881void AudioFlinger::PlaybackThread::threadLoop_standby()
2882{
2883 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2884 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002886 // discard any pending drain or write ack by incrementing sequence
2887 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2888 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002890 mCallbackThread->setWriteBlocked(mWriteAckSequence);
2891 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 }
Eric Laurent81784c32012-11-19 14:55:58 -08002893}
2894
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002895void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2896{
2897 ALOGV("signal playback thread");
2898 broadcast_l();
2899}
2900
Eric Laurent81784c32012-11-19 14:55:58 -08002901void AudioFlinger::MixerThread::threadLoop_mix()
2902{
2903 // obtain the presentation timestamp of the next output buffer
2904 int64_t pts;
2905 status_t status = INVALID_OPERATION;
2906
2907 if (mNormalSink != 0) {
2908 status = mNormalSink->getNextWriteTimestamp(&pts);
2909 } else {
2910 status = mOutputSink->getNextWriteTimestamp(&pts);
2911 }
2912
2913 if (status != NO_ERROR) {
2914 pts = AudioBufferProvider::kInvalidPTS;
2915 }
2916
2917 // mix buffers...
2918 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08002919 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002920 // increase sleep time progressively when application underrun condition clears.
2921 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2922 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2923 // such that we would underrun the audio HAL.
2924 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2925 sleepTimeShift--;
2926 }
2927 sleepTime = 0;
2928 standbyTime = systemTime() + standbyDelay;
2929 //TODO: delay standby when effects have a tail
2930}
2931
2932void AudioFlinger::MixerThread::threadLoop_sleepTime()
2933{
2934 // If no tracks are ready, sleep once for the duration of an output
2935 // buffer size, then write 0s to the output
2936 if (sleepTime == 0) {
2937 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2938 sleepTime = activeSleepTime >> sleepTimeShift;
2939 if (sleepTime < kMinThreadSleepTimeUs) {
2940 sleepTime = kMinThreadSleepTimeUs;
2941 }
2942 // reduce sleep time in case of consecutive application underruns to avoid
2943 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2944 // duration we would end up writing less data than needed by the audio HAL if
2945 // the condition persists.
2946 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2947 sleepTimeShift++;
2948 }
2949 } else {
2950 sleepTime = idleSleepTime;
2951 }
2952 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08002953 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2954 // before effects processing or output.
2955 if (mMixerBufferValid) {
2956 memset(mMixerBuffer, 0, mMixerBufferSize);
2957 } else {
2958 memset(mSinkBuffer, 0, mSinkBufferSize);
2959 }
Eric Laurent81784c32012-11-19 14:55:58 -08002960 sleepTime = 0;
2961 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2962 "anticipated start");
2963 }
2964 // TODO add standby time extension fct of effect tail
2965}
2966
2967// prepareTracks_l() must be called with ThreadBase::mLock held
2968AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2969 Vector< sp<Track> > *tracksToRemove)
2970{
2971
2972 mixer_state mixerStatus = MIXER_IDLE;
2973 // find out which tracks need to be processed
2974 size_t count = mActiveTracks.size();
2975 size_t mixedTracks = 0;
2976 size_t tracksWithEffect = 0;
2977 // counts only _active_ fast tracks
2978 size_t fastTracks = 0;
2979 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2980
2981 float masterVolume = mMasterVolume;
2982 bool masterMute = mMasterMute;
2983
2984 if (masterMute) {
2985 masterVolume = 0;
2986 }
2987 // Delegate master volume control to effect in output mix effect chain if needed
2988 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2989 if (chain != 0) {
2990 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2991 chain->setVolume_l(&v, &v);
2992 masterVolume = (float)((v + (1 << 23)) >> 24);
2993 chain.clear();
2994 }
2995
2996 // prepare a new state to push
2997 FastMixerStateQueue *sq = NULL;
2998 FastMixerState *state = NULL;
2999 bool didModify = false;
3000 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3001 if (mFastMixer != NULL) {
3002 sq = mFastMixer->sq();
3003 state = sq->begin();
3004 }
3005
Andy Hung69aed5f2014-02-25 17:24:40 -08003006 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003007 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003008
Eric Laurent81784c32012-11-19 14:55:58 -08003009 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003010 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003011 if (t == 0) {
3012 continue;
3013 }
3014
3015 // this const just means the local variable doesn't change
3016 Track* const track = t.get();
3017
3018 // process fast tracks
3019 if (track->isFastTrack()) {
3020
3021 // It's theoretically possible (though unlikely) for a fast track to be created
3022 // and then removed within the same normal mix cycle. This is not a problem, as
3023 // the track never becomes active so it's fast mixer slot is never touched.
3024 // The converse, of removing an (active) track and then creating a new track
3025 // at the identical fast mixer slot within the same normal mix cycle,
3026 // is impossible because the slot isn't marked available until the end of each cycle.
3027 int j = track->mFastIndex;
3028 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3029 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3030 FastTrack *fastTrack = &state->mFastTracks[j];
3031
3032 // Determine whether the track is currently in underrun condition,
3033 // and whether it had a recent underrun.
3034 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3035 FastTrackUnderruns underruns = ftDump->mUnderruns;
3036 uint32_t recentFull = (underruns.mBitFields.mFull -
3037 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3038 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3039 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3040 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3041 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3042 uint32_t recentUnderruns = recentPartial + recentEmpty;
3043 track->mObservedUnderruns = underruns;
3044 // don't count underruns that occur while stopping or pausing
3045 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003046 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3047 recentUnderruns > 0) {
3048 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3049 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003050 }
3051
3052 // This is similar to the state machine for normal tracks,
3053 // with a few modifications for fast tracks.
3054 bool isActive = true;
3055 switch (track->mState) {
3056 case TrackBase::STOPPING_1:
3057 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003058 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003059 track->mState = TrackBase::STOPPING_2;
3060 }
3061 break;
3062 case TrackBase::PAUSING:
3063 // ramp down is not yet implemented
3064 track->setPaused();
3065 break;
3066 case TrackBase::RESUMING:
3067 // ramp up is not yet implemented
3068 track->mState = TrackBase::ACTIVE;
3069 break;
3070 case TrackBase::ACTIVE:
3071 if (recentFull > 0 || recentPartial > 0) {
3072 // track has provided at least some frames recently: reset retry count
3073 track->mRetryCount = kMaxTrackRetries;
3074 }
3075 if (recentUnderruns == 0) {
3076 // no recent underruns: stay active
3077 break;
3078 }
3079 // there has recently been an underrun of some kind
3080 if (track->sharedBuffer() == 0) {
3081 // were any of the recent underruns "empty" (no frames available)?
3082 if (recentEmpty == 0) {
3083 // no, then ignore the partial underruns as they are allowed indefinitely
3084 break;
3085 }
3086 // there has recently been an "empty" underrun: decrement the retry counter
3087 if (--(track->mRetryCount) > 0) {
3088 break;
3089 }
3090 // indicate to client process that the track was disabled because of underrun;
3091 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003092 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // remove from active list, but state remains ACTIVE [confusing but true]
3094 isActive = false;
3095 break;
3096 }
3097 // fall through
3098 case TrackBase::STOPPING_2:
3099 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003100 case TrackBase::STOPPED:
3101 case TrackBase::FLUSHED: // flush() while active
3102 // Check for presentation complete if track is inactive
3103 // We have consumed all the buffers of this track.
3104 // This would be incomplete if we auto-paused on underrun
3105 {
3106 size_t audioHALFrames =
3107 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3108 size_t framesWritten = mBytesWritten / mFrameSize;
3109 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3110 // track stays in active list until presentation is complete
3111 break;
3112 }
3113 }
3114 if (track->isStopping_2()) {
3115 track->mState = TrackBase::STOPPED;
3116 }
3117 if (track->isStopped()) {
3118 // Can't reset directly, as fast mixer is still polling this track
3119 // track->reset();
3120 // So instead mark this track as needing to be reset after push with ack
3121 resetMask |= 1 << i;
3122 }
3123 isActive = false;
3124 break;
3125 case TrackBase::IDLE:
3126 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003127 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003128 }
3129
3130 if (isActive) {
3131 // was it previously inactive?
3132 if (!(state->mTrackMask & (1 << j))) {
3133 ExtendedAudioBufferProvider *eabp = track;
3134 VolumeProvider *vp = track;
3135 fastTrack->mBufferProvider = eabp;
3136 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003137 fastTrack->mChannelMask = track->mChannelMask;
3138 fastTrack->mGeneration++;
3139 state->mTrackMask |= 1 << j;
3140 didModify = true;
3141 // no acknowledgement required for newly active tracks
3142 }
3143 // cache the combined master volume and stream type volume for fast mixer; this
3144 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003145 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003146 ++fastTracks;
3147 } else {
3148 // was it previously active?
3149 if (state->mTrackMask & (1 << j)) {
3150 fastTrack->mBufferProvider = NULL;
3151 fastTrack->mGeneration++;
3152 state->mTrackMask &= ~(1 << j);
3153 didModify = true;
3154 // If any fast tracks were removed, we must wait for acknowledgement
3155 // because we're about to decrement the last sp<> on those tracks.
3156 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3157 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003158 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003159 }
3160 tracksToRemove->add(track);
3161 // Avoids a misleading display in dumpsys
3162 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3163 }
3164 continue;
3165 }
3166
3167 { // local variable scope to avoid goto warning
3168
3169 audio_track_cblk_t* cblk = track->cblk();
3170
3171 // The first time a track is added we wait
3172 // for all its buffers to be filled before processing it
3173 int name = track->name();
3174 // make sure that we have enough frames to mix one full buffer.
3175 // enforce this condition only once to enable draining the buffer in case the client
3176 // app does not call stop() and relies on underrun to stop:
3177 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3178 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003179 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003180 uint32_t sr = track->sampleRate();
3181 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003182 desiredFrames = mNormalFrameCount;
3183 } else {
3184 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003185 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003186 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003187 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003188 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003189#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003190 // the minimum track buffer size is normally twice the number of frames necessary
3191 // to fill one buffer and the resampler should not leave more than one buffer worth
3192 // of unreleased frames after each pass, but just in case...
3193 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003194#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003195 }
Eric Laurent81784c32012-11-19 14:55:58 -08003196 uint32_t minFrames = 1;
3197 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3198 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003199 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003200 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003201
3202 size_t framesReady = track->framesReady();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003203 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003204 !track->isPaused() && !track->isTerminated())
3205 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003206 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003207
3208 mixedTracks++;
3209
Andy Hung69aed5f2014-02-25 17:24:40 -08003210 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3211 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003212 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003213 if (track->mainBuffer() != mSinkBuffer &&
3214 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003215 if (mEffectBufferEnabled) {
3216 mEffectBufferValid = true; // Later can set directly.
3217 }
Eric Laurent81784c32012-11-19 14:55:58 -08003218 chain = getEffectChain_l(track->sessionId());
3219 // Delegate volume control to effect in track effect chain if needed
3220 if (chain != 0) {
3221 tracksWithEffect++;
3222 } else {
3223 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3224 "session %d",
3225 name, track->sessionId());
3226 }
3227 }
3228
3229
3230 int param = AudioMixer::VOLUME;
3231 if (track->mFillingUpStatus == Track::FS_FILLED) {
3232 // no ramp for the first volume setting
3233 track->mFillingUpStatus = Track::FS_ACTIVE;
3234 if (track->mState == TrackBase::RESUMING) {
3235 track->mState = TrackBase::ACTIVE;
3236 param = AudioMixer::RAMP_VOLUME;
3237 }
3238 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003239 // FIXME should not make a decision based on mServer
3240 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003241 // If the track is stopped before the first frame was mixed,
3242 // do not apply ramp
3243 param = AudioMixer::RAMP_VOLUME;
3244 }
3245
3246 // compute volume for this track
3247 uint32_t vl, vr, va;
Glenn Kastene4756fe2012-11-29 13:38:14 -08003248 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Eric Laurent81784c32012-11-19 14:55:58 -08003249 vl = vr = va = 0;
3250 if (track->isPausing()) {
3251 track->setPaused();
3252 }
3253 } else {
3254
3255 // read original volumes with volume control
3256 float typeVolume = mStreamTypes[track->streamType()].volume;
3257 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003258 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -08003259 uint32_t vlr = proxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -08003260 vl = vlr & 0xFFFF;
3261 vr = vlr >> 16;
3262 // track volumes come from shared memory, so can't be trusted and must be clamped
3263 if (vl > MAX_GAIN_INT) {
3264 ALOGV("Track left volume out of range: %04X", vl);
3265 vl = MAX_GAIN_INT;
3266 }
3267 if (vr > MAX_GAIN_INT) {
3268 ALOGV("Track right volume out of range: %04X", vr);
3269 vr = MAX_GAIN_INT;
3270 }
3271 // now apply the master volume and stream type volume
3272 vl = (uint32_t)(v * vl) << 12;
3273 vr = (uint32_t)(v * vr) << 12;
3274 // assuming master volume and stream type volume each go up to 1.0,
3275 // vl and vr are now in 8.24 format
3276
Glenn Kastene3aa6592012-12-04 12:22:46 -08003277 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003278 // send level comes from shared memory and so may be corrupt
3279 if (sendLevel > MAX_GAIN_INT) {
3280 ALOGV("Track send level out of range: %04X", sendLevel);
3281 sendLevel = MAX_GAIN_INT;
3282 }
3283 va = (uint32_t)(v * sendLevel);
3284 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003285
Eric Laurent81784c32012-11-19 14:55:58 -08003286 // Delegate volume control to effect in track effect chain if needed
3287 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3288 // Do not ramp volume if volume is controlled by effect
3289 param = AudioMixer::VOLUME;
3290 track->mHasVolumeController = true;
3291 } else {
3292 // force no volume ramp when volume controller was just disabled or removed
3293 // from effect chain to avoid volume spike
3294 if (track->mHasVolumeController) {
3295 param = AudioMixer::VOLUME;
3296 }
3297 track->mHasVolumeController = false;
3298 }
3299
3300 // Convert volumes from 8.24 to 4.12 format
3301 // This additional clamping is needed in case chain->setVolume_l() overshot
3302 vl = (vl + (1 << 11)) >> 12;
3303 if (vl > MAX_GAIN_INT) {
3304 vl = MAX_GAIN_INT;
3305 }
3306 vr = (vr + (1 << 11)) >> 12;
3307 if (vr > MAX_GAIN_INT) {
3308 vr = MAX_GAIN_INT;
3309 }
3310
3311 if (va > MAX_GAIN_INT) {
3312 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3313 }
3314
3315 // XXX: these things DON'T need to be done each time
3316 mAudioMixer->setBufferProvider(name, track);
3317 mAudioMixer->enable(name);
3318
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003319 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3320 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3321 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
Eric Laurent81784c32012-11-19 14:55:58 -08003322 mAudioMixer->setParameter(
3323 name,
3324 AudioMixer::TRACK,
3325 AudioMixer::FORMAT, (void *)track->format());
3326 mAudioMixer->setParameter(
3327 name,
3328 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003329 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Glenn Kastene3aa6592012-12-04 12:22:46 -08003330 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3331 uint32_t maxSampleRate = mSampleRate * 2;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003332 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003333 if (reqSampleRate == 0) {
3334 reqSampleRate = mSampleRate;
3335 } else if (reqSampleRate > maxSampleRate) {
3336 reqSampleRate = maxSampleRate;
3337 }
Eric Laurent81784c32012-11-19 14:55:58 -08003338 mAudioMixer->setParameter(
3339 name,
3340 AudioMixer::RESAMPLE,
3341 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003342 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003343 /*
3344 * Select the appropriate output buffer for the track.
3345 *
Andy Hung98ef9782014-03-04 14:46:50 -08003346 * Tracks with effects go into their own effects chain buffer
3347 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003348 *
3349 * Other tracks can use mMixerBuffer for higher precision
3350 * channel accumulation. If this buffer is enabled
3351 * (mMixerBufferEnabled true), then selected tracks will accumulate
3352 * into it.
3353 *
3354 */
3355 if (mMixerBufferEnabled
3356 && (track->mainBuffer() == mSinkBuffer
3357 || track->mainBuffer() == mMixerBuffer)) {
3358 mAudioMixer->setParameter(
3359 name,
3360 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003361 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003362 mAudioMixer->setParameter(
3363 name,
3364 AudioMixer::TRACK,
3365 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3366 // TODO: override track->mainBuffer()?
3367 mMixerBufferValid = true;
3368 } else {
3369 mAudioMixer->setParameter(
3370 name,
3371 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003372 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003373 mAudioMixer->setParameter(
3374 name,
3375 AudioMixer::TRACK,
3376 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3377 }
Eric Laurent81784c32012-11-19 14:55:58 -08003378 mAudioMixer->setParameter(
3379 name,
3380 AudioMixer::TRACK,
3381 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3382
3383 // reset retry count
3384 track->mRetryCount = kMaxTrackRetries;
3385
3386 // If one track is ready, set the mixer ready if:
3387 // - the mixer was not ready during previous round OR
3388 // - no other track is not ready
3389 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3390 mixerStatus != MIXER_TRACKS_ENABLED) {
3391 mixerStatus = MIXER_TRACKS_READY;
3392 }
3393 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003394 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003395 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003396 }
Eric Laurent81784c32012-11-19 14:55:58 -08003397 // clear effect chain input buffer if an active track underruns to avoid sending
3398 // previous audio buffer again to effects
3399 chain = getEffectChain_l(track->sessionId());
3400 if (chain != 0) {
3401 chain->clearInputBuffer();
3402 }
3403
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003404 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003405 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3406 track->isStopped() || track->isPaused()) {
3407 // We have consumed all the buffers of this track.
3408 // Remove it from the list of active tracks.
3409 // TODO: use actual buffer filling status instead of latency when available from
3410 // audio HAL
3411 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3412 size_t framesWritten = mBytesWritten / mFrameSize;
3413 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3414 if (track->isStopped()) {
3415 track->reset();
3416 }
3417 tracksToRemove->add(track);
3418 }
3419 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003420 // No buffers for this track. Give it a few chances to
3421 // fill a buffer, then remove it from active list.
3422 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003423 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003424 tracksToRemove->add(track);
3425 // indicate to client process that the track was disabled because of underrun;
3426 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003427 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003428 // If one track is not ready, mark the mixer also not ready if:
3429 // - the mixer was ready during previous round OR
3430 // - no other track is ready
3431 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3432 mixerStatus != MIXER_TRACKS_READY) {
3433 mixerStatus = MIXER_TRACKS_ENABLED;
3434 }
3435 }
3436 mAudioMixer->disable(name);
3437 }
3438
3439 } // local variable scope to avoid goto warning
3440track_is_ready: ;
3441
3442 }
3443
3444 // Push the new FastMixer state if necessary
3445 bool pauseAudioWatchdog = false;
3446 if (didModify) {
3447 state->mFastTracksGen++;
3448 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3449 if (kUseFastMixer == FastMixer_Dynamic &&
3450 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3451 state->mCommand = FastMixerState::COLD_IDLE;
3452 state->mColdFutexAddr = &mFastMixerFutex;
3453 state->mColdGen++;
3454 mFastMixerFutex = 0;
3455 if (kUseFastMixer == FastMixer_Dynamic) {
3456 mNormalSink = mOutputSink;
3457 }
3458 // If we go into cold idle, need to wait for acknowledgement
3459 // so that fast mixer stops doing I/O.
3460 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3461 pauseAudioWatchdog = true;
3462 }
Eric Laurent81784c32012-11-19 14:55:58 -08003463 }
3464 if (sq != NULL) {
3465 sq->end(didModify);
3466 sq->push(block);
3467 }
3468#ifdef AUDIO_WATCHDOG
3469 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3470 mAudioWatchdog->pause();
3471 }
3472#endif
3473
3474 // Now perform the deferred reset on fast tracks that have stopped
3475 while (resetMask != 0) {
3476 size_t i = __builtin_ctz(resetMask);
3477 ALOG_ASSERT(i < count);
3478 resetMask &= ~(1 << i);
3479 sp<Track> t = mActiveTracks[i].promote();
3480 if (t == 0) {
3481 continue;
3482 }
3483 Track* track = t.get();
3484 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3485 track->reset();
3486 }
3487
3488 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003489 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003490
Andy Hung69aed5f2014-02-25 17:24:40 -08003491 // sink or mix buffer must be cleared if all tracks are connected to an
3492 // effect chain as in this case the mixer will not write to the sink or mix buffer
3493 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3495 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003496 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003497 if (mMixerBufferValid) {
3498 memset(mMixerBuffer, 0, mMixerBufferSize);
3499 // TODO: In testing, mSinkBuffer below need not be cleared because
3500 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3501 // after mixing.
3502 //
3503 // To enforce this guarantee:
3504 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3505 // (mixedTracks == 0 && fastTracks > 0))
3506 // must imply MIXER_TRACKS_READY.
3507 // Later, we may clear buffers regardless, and skip much of this logic.
3508 }
Andy Hung98ef9782014-03-04 14:46:50 -08003509 // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3510 if (mEffectBufferValid) {
3511 memset(mEffectBuffer, 0, mEffectBufferSize);
3512 }
3513 // FIXME as a performance optimization, should remember previous zero status
Andy Hung2098f272014-02-27 14:00:06 -08003514 memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Eric Laurent81784c32012-11-19 14:55:58 -08003515 }
3516
3517 // if any fast tracks, then status is ready
3518 mMixerStatusIgnoringFastTracks = mixerStatus;
3519 if (fastTracks > 0) {
3520 mixerStatus = MIXER_TRACKS_READY;
3521 }
3522 return mixerStatus;
3523}
3524
3525// getTrackName_l() must be called with ThreadBase::mLock held
3526int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3527{
3528 return mAudioMixer->getTrackName(channelMask, sessionId);
3529}
3530
3531// deleteTrackName_l() must be called with ThreadBase::mLock held
3532void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3533{
3534 ALOGV("remove track (%d) and delete from mixer", name);
3535 mAudioMixer->deleteTrackName(name);
3536}
3537
3538// checkForNewParameters_l() must be called with ThreadBase::mLock held
3539bool AudioFlinger::MixerThread::checkForNewParameters_l()
3540{
3541 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3542 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3543 bool reconfig = false;
3544
3545 while (!mNewParameters.isEmpty()) {
3546
3547 if (mFastMixer != NULL) {
3548 FastMixerStateQueue *sq = mFastMixer->sq();
3549 FastMixerState *state = sq->begin();
3550 if (!(state->mCommand & FastMixerState::IDLE)) {
3551 previousCommand = state->mCommand;
3552 state->mCommand = FastMixerState::HOT_IDLE;
3553 sq->end();
3554 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3555 } else {
3556 sq->end(false /*didModify*/);
3557 }
3558 }
3559
3560 status_t status = NO_ERROR;
3561 String8 keyValuePair = mNewParameters[0];
3562 AudioParameter param = AudioParameter(keyValuePair);
3563 int value;
3564
3565 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3566 reconfig = true;
3567 }
3568 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3569 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3570 status = BAD_VALUE;
3571 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003572 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003573 reconfig = true;
3574 }
3575 }
3576 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenfad226a2013-07-16 17:19:58 -07003577 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurent81784c32012-11-19 14:55:58 -08003578 status = BAD_VALUE;
3579 } else {
Glenn Kasten2fc14732013-08-05 14:58:14 -07003580 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003581 reconfig = true;
3582 }
3583 }
3584 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3585 // do not accept frame count changes if tracks are open as the track buffer
3586 // size depends on frame count and correct behavior would not be guaranteed
3587 // if frame count is changed after track creation
3588 if (!mTracks.isEmpty()) {
3589 status = INVALID_OPERATION;
3590 } else {
3591 reconfig = true;
3592 }
3593 }
3594 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3595#ifdef ADD_BATTERY_DATA
3596 // when changing the audio output device, call addBatteryData to notify
3597 // the change
3598 if (mOutDevice != value) {
3599 uint32_t params = 0;
3600 // check whether speaker is on
3601 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3602 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3603 }
3604
3605 audio_devices_t deviceWithoutSpeaker
3606 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3607 // check if any other device (except speaker) is on
3608 if (value & deviceWithoutSpeaker ) {
3609 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3610 }
3611
3612 if (params != 0) {
3613 addBatteryData(params);
3614 }
3615 }
3616#endif
3617
3618 // forward device change to effects that have requested to be
3619 // aware of attached audio device.
Eric Laurent7e1139c2013-06-06 18:29:01 -07003620 if (value != AUDIO_DEVICE_NONE) {
3621 mOutDevice = value;
3622 for (size_t i = 0; i < mEffectChains.size(); i++) {
3623 mEffectChains[i]->setDevice_l(mOutDevice);
3624 }
Eric Laurent81784c32012-11-19 14:55:58 -08003625 }
3626 }
3627
3628 if (status == NO_ERROR) {
3629 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3630 keyValuePair.string());
3631 if (!mStandby && status == INVALID_OPERATION) {
3632 mOutput->stream->common.standby(&mOutput->stream->common);
3633 mStandby = true;
3634 mBytesWritten = 0;
3635 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3636 keyValuePair.string());
3637 }
3638 if (status == NO_ERROR && reconfig) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003639 readOutputParameters_l();
Glenn Kasten9e8fcbc2013-07-25 10:09:11 -07003640 delete mAudioMixer;
Eric Laurent81784c32012-11-19 14:55:58 -08003641 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3642 for (size_t i = 0; i < mTracks.size() ; i++) {
3643 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3644 if (name < 0) {
3645 break;
3646 }
3647 mTracks[i]->mName = name;
Eric Laurent81784c32012-11-19 14:55:58 -08003648 }
3649 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3650 }
3651 }
3652
3653 mNewParameters.removeAt(0);
3654
3655 mParamStatus = status;
3656 mParamCond.signal();
3657 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3658 // already timed out waiting for the status and will never signal the condition.
3659 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3660 }
3661
3662 if (!(previousCommand & FastMixerState::IDLE)) {
3663 ALOG_ASSERT(mFastMixer != NULL);
3664 FastMixerStateQueue *sq = mFastMixer->sq();
3665 FastMixerState *state = sq->begin();
3666 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3667 state->mCommand = previousCommand;
3668 sq->end();
3669 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3670 }
3671
3672 return reconfig;
3673}
3674
3675
3676void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3677{
3678 const size_t SIZE = 256;
3679 char buffer[SIZE];
3680 String8 result;
3681
3682 PlaybackThread::dumpInternals(fd, args);
3683
Marco Nelissenb2208842014-02-07 14:00:50 -08003684 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08003685
3686 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003687 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08003688 copy.dump(fd);
3689
3690#ifdef STATE_QUEUE_DUMP
3691 // Similar for state queue
3692 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3693 observerCopy.dump(fd);
3694 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3695 mutatorCopy.dump(fd);
3696#endif
3697
Glenn Kasten46909e72013-02-26 09:20:22 -08003698#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003699 // Write the tee output to a .wav file
3700 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08003701#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003702
3703#ifdef AUDIO_WATCHDOG
3704 if (mAudioWatchdog != 0) {
3705 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3706 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3707 wdCopy.dump(fd);
3708 }
3709#endif
3710}
3711
3712uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3713{
3714 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3715}
3716
3717uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3718{
3719 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3720}
3721
3722void AudioFlinger::MixerThread::cacheParameters_l()
3723{
3724 PlaybackThread::cacheParameters_l();
3725
3726 // FIXME: Relaxed timing because of a certain device that can't meet latency
3727 // Should be reduced to 2x after the vendor fixes the driver issue
3728 // increase threshold again due to low power audio mode. The way this warning
3729 // threshold is calculated and its usefulness should be reconsidered anyway.
3730 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3731}
3732
3733// ----------------------------------------------------------------------------
3734
3735AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3736 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3737 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3738 // mLeftVolFloat, mRightVolFloat
3739{
3740}
3741
Eric Laurentbfb1b832013-01-07 09:53:42 -08003742AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3743 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3744 ThreadBase::type_t type)
3745 : PlaybackThread(audioFlinger, output, id, device, type)
3746 // mLeftVolFloat, mRightVolFloat
3747{
3748}
3749
Eric Laurent81784c32012-11-19 14:55:58 -08003750AudioFlinger::DirectOutputThread::~DirectOutputThread()
3751{
3752}
3753
Eric Laurentbfb1b832013-01-07 09:53:42 -08003754void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3755{
3756 audio_track_cblk_t* cblk = track->cblk();
3757 float left, right;
3758
3759 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3760 left = right = 0;
3761 } else {
3762 float typeVolume = mStreamTypes[track->streamType()].volume;
3763 float v = mMasterVolume * typeVolume;
3764 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3765 uint32_t vlr = proxy->getVolumeLR();
3766 float v_clamped = v * (vlr & 0xFFFF);
3767 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3768 left = v_clamped/MAX_GAIN;
3769 v_clamped = v * (vlr >> 16);
3770 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3771 right = v_clamped/MAX_GAIN;
3772 }
3773
3774 if (lastTrack) {
3775 if (left != mLeftVolFloat || right != mRightVolFloat) {
3776 mLeftVolFloat = left;
3777 mRightVolFloat = right;
3778
3779 // Convert volumes from float to 8.24
3780 uint32_t vl = (uint32_t)(left * (1 << 24));
3781 uint32_t vr = (uint32_t)(right * (1 << 24));
3782
3783 // Delegate volume control to effect in track effect chain if needed
3784 // only one effect chain can be present on DirectOutputThread, so if
3785 // there is one, the track is connected to it
3786 if (!mEffectChains.isEmpty()) {
3787 mEffectChains[0]->setVolume_l(&vl, &vr);
3788 left = (float)vl / (1 << 24);
3789 right = (float)vr / (1 << 24);
3790 }
3791 if (mOutput->stream->set_volume) {
3792 mOutput->stream->set_volume(mOutput->stream, left, right);
3793 }
3794 }
3795 }
3796}
3797
3798
Eric Laurent81784c32012-11-19 14:55:58 -08003799AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3800 Vector< sp<Track> > *tracksToRemove
3801)
3802{
Eric Laurentd595b7c2013-04-03 17:27:56 -07003803 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08003804 mixer_state mixerStatus = MIXER_IDLE;
3805
3806 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07003807 for (size_t i = 0; i < count; i++) {
3808 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003809 // The track died recently
3810 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003811 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08003812 }
3813
3814 Track* const track = t.get();
3815 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07003816 // Only consider last track started for volume and mixer state control.
3817 // In theory an older track could underrun and restart after the new one starts
3818 // but as we only care about the transition phase between two tracks on a
3819 // direct output, it is not a problem to ignore the underrun case.
3820 sp<Track> l = mLatestActiveTrack.promote();
3821 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08003822
3823 // The first time a track is added we wait
3824 // for all its buffers to be filled before processing it
3825 uint32_t minFrames;
3826 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3827 minFrames = mNormalFrameCount;
3828 } else {
3829 minFrames = 1;
3830 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831
Eric Laurent81784c32012-11-19 14:55:58 -08003832 if ((track->framesReady() >= minFrames) && track->isReady() &&
3833 !track->isPaused() && !track->isTerminated())
3834 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003835 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003836
3837 if (track->mFillingUpStatus == Track::FS_FILLED) {
3838 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07003839 // make sure processVolume_l() will apply new volume even if 0
3840 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurent81784c32012-11-19 14:55:58 -08003841 if (track->mState == TrackBase::RESUMING) {
3842 track->mState = TrackBase::ACTIVE;
3843 }
3844 }
3845
3846 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 processVolume_l(track, last);
3848 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003849 // reset retry count
3850 track->mRetryCount = kMaxTrackRetriesDirect;
3851 mActiveTrack = t;
3852 mixerStatus = MIXER_TRACKS_READY;
3853 }
Eric Laurent81784c32012-11-19 14:55:58 -08003854 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07003855 // clear effect chain input buffer if the last active track started underruns
3856 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07003857 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003858 mEffectChains[0]->clearInputBuffer();
3859 }
3860
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003861 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08003862 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3863 track->isStopped() || track->isPaused()) {
3864 // We have consumed all the buffers of this track.
3865 // Remove it from the list of active tracks.
3866 // TODO: implement behavior for compressed audio
3867 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3868 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07003869 if (mStandby || !last ||
3870 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003871 if (track->isStopped()) {
3872 track->reset();
3873 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07003874 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 }
3876 } else {
3877 // No buffers for this track. Give it a few chances to
3878 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07003879 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08003880 if (--(track->mRetryCount) <= 0) {
3881 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07003882 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08003883 // indicate to client process that the track was disabled because of underrun;
3884 // it will then automatically call start() when data is available
3885 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08003887 mixerStatus = MIXER_TRACKS_ENABLED;
3888 }
3889 }
3890 }
3891 }
3892
Eric Laurent81784c32012-11-19 14:55:58 -08003893 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003895
3896 return mixerStatus;
3897}
3898
3899void AudioFlinger::DirectOutputThread::threadLoop_mix()
3900{
Eric Laurent81784c32012-11-19 14:55:58 -08003901 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08003902 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003903 // output audio to hardware
3904 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07003905 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003906 buffer.frameCount = frameCount;
3907 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07003908 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08003909 memset(curBuf, 0, frameCount * mFrameSize);
3910 break;
3911 }
3912 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3913 frameCount -= buffer.frameCount;
3914 curBuf += buffer.frameCount * mFrameSize;
3915 mActiveTrack->releaseBuffer(&buffer);
3916 }
Andy Hung2098f272014-02-27 14:00:06 -08003917 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08003918 sleepTime = 0;
3919 standbyTime = systemTime() + standbyDelay;
3920 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003921}
3922
3923void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3924{
3925 if (sleepTime == 0) {
3926 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3927 sleepTime = activeSleepTime;
3928 } else {
3929 sleepTime = idleSleepTime;
3930 }
3931 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08003932 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003933 sleepTime = 0;
3934 }
3935}
3936
3937// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003938int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3939 int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003940{
3941 return 0;
3942}
3943
3944// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08003945void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08003946{
3947}
3948
3949// checkForNewParameters_l() must be called with ThreadBase::mLock held
3950bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3951{
3952 bool reconfig = false;
3953
3954 while (!mNewParameters.isEmpty()) {
3955 status_t status = NO_ERROR;
3956 String8 keyValuePair = mNewParameters[0];
3957 AudioParameter param = AudioParameter(keyValuePair);
3958 int value;
3959
Glenn Kastenc125f382014-04-11 18:37:33 -07003960 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3961 // forward device change to effects that have requested to be
3962 // aware of attached audio device.
3963 if (value != AUDIO_DEVICE_NONE) {
3964 mOutDevice = value;
3965 for (size_t i = 0; i < mEffectChains.size(); i++) {
3966 mEffectChains[i]->setDevice_l(mOutDevice);
3967 }
3968 }
3969 }
Eric Laurent81784c32012-11-19 14:55:58 -08003970 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3971 // do not accept frame count changes if tracks are open as the track buffer
3972 // size depends on frame count and correct behavior would not be garantied
3973 // if frame count is changed after track creation
3974 if (!mTracks.isEmpty()) {
3975 status = INVALID_OPERATION;
3976 } else {
3977 reconfig = true;
3978 }
3979 }
3980 if (status == NO_ERROR) {
3981 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3982 keyValuePair.string());
3983 if (!mStandby && status == INVALID_OPERATION) {
3984 mOutput->stream->common.standby(&mOutput->stream->common);
3985 mStandby = true;
3986 mBytesWritten = 0;
3987 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3988 keyValuePair.string());
3989 }
3990 if (status == NO_ERROR && reconfig) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003991 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08003992 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3993 }
3994 }
3995
3996 mNewParameters.removeAt(0);
3997
3998 mParamStatus = status;
3999 mParamCond.signal();
4000 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4001 // already timed out waiting for the status and will never signal the condition.
4002 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4003 }
4004 return reconfig;
4005}
4006
4007uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4008{
4009 uint32_t time;
4010 if (audio_is_linear_pcm(mFormat)) {
4011 time = PlaybackThread::activeSleepTimeUs();
4012 } else {
4013 time = 10000;
4014 }
4015 return time;
4016}
4017
4018uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4019{
4020 uint32_t time;
4021 if (audio_is_linear_pcm(mFormat)) {
4022 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4023 } else {
4024 time = 10000;
4025 }
4026 return time;
4027}
4028
4029uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4030{
4031 uint32_t time;
4032 if (audio_is_linear_pcm(mFormat)) {
4033 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4034 } else {
4035 time = 10000;
4036 }
4037 return time;
4038}
4039
4040void AudioFlinger::DirectOutputThread::cacheParameters_l()
4041{
4042 PlaybackThread::cacheParameters_l();
4043
4044 // use shorter standby delay as on normal output to release
4045 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004046 if (audio_is_linear_pcm(mFormat)) {
4047 standbyDelay = microseconds(activeSleepTime*2);
4048 } else {
4049 standbyDelay = kOffloadStandbyDelayNs;
4050 }
Eric Laurent81784c32012-11-19 14:55:58 -08004051}
4052
4053// ----------------------------------------------------------------------------
4054
Eric Laurentbfb1b832013-01-07 09:53:42 -08004055AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004056 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004058 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004059 mWriteAckSequence(0),
4060 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004061{
4062}
4063
4064AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4065{
4066}
4067
4068void AudioFlinger::AsyncCallbackThread::onFirstRef()
4069{
4070 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4071}
4072
4073bool AudioFlinger::AsyncCallbackThread::threadLoop()
4074{
4075 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004076 uint32_t writeAckSequence;
4077 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078
4079 {
4080 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004081 while (!((mWriteAckSequence & 1) ||
4082 (mDrainSequence & 1) ||
4083 exitPending())) {
4084 mWaitWorkCV.wait(mLock);
4085 }
4086
Eric Laurentbfb1b832013-01-07 09:53:42 -08004087 if (exitPending()) {
4088 break;
4089 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004090 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4091 mWriteAckSequence, mDrainSequence);
4092 writeAckSequence = mWriteAckSequence;
4093 mWriteAckSequence &= ~1;
4094 drainSequence = mDrainSequence;
4095 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 }
4097 {
Eric Laurent4de95592013-09-26 15:28:21 -07004098 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4099 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004100 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004101 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004102 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004103 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004104 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004105 }
4106 }
4107 }
4108 }
4109 return false;
4110}
4111
4112void AudioFlinger::AsyncCallbackThread::exit()
4113{
4114 ALOGV("AsyncCallbackThread::exit");
4115 Mutex::Autolock _l(mLock);
4116 requestExit();
4117 mWaitWorkCV.broadcast();
4118}
4119
Eric Laurent3b4529e2013-09-05 18:09:19 -07004120void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121{
4122 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004123 // bit 0 is cleared
4124 mWriteAckSequence = sequence << 1;
4125}
4126
4127void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4128{
4129 Mutex::Autolock _l(mLock);
4130 // ignore unexpected callbacks
4131 if (mWriteAckSequence & 2) {
4132 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004133 mWaitWorkCV.signal();
4134 }
4135}
4136
Eric Laurent3b4529e2013-09-05 18:09:19 -07004137void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138{
4139 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004140 // bit 0 is cleared
4141 mDrainSequence = sequence << 1;
4142}
4143
4144void AudioFlinger::AsyncCallbackThread::resetDraining()
4145{
4146 Mutex::Autolock _l(mLock);
4147 // ignore unexpected callbacks
4148 if (mDrainSequence & 2) {
4149 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004150 mWaitWorkCV.signal();
4151 }
4152}
4153
4154
4155// ----------------------------------------------------------------------------
4156AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4157 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4158 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4159 mHwPaused(false),
Eric Laurentea0fade2013-10-04 16:23:48 -07004160 mFlushPending(false),
Eric Laurentd7e59222013-11-15 12:02:28 -08004161 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162{
Eric Laurentfd477972013-10-25 18:10:40 -07004163 //FIXME: mStandby should be set to true by ThreadBase constructor
4164 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165}
4166
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167void AudioFlinger::OffloadThread::threadLoop_exit()
4168{
4169 if (mFlushPending || mHwPaused) {
4170 // If a flush is pending or track was paused, just discard buffered data
4171 flushHw_l();
4172 } else {
4173 mMixerStatus = MIXER_DRAIN_ALL;
4174 threadLoop_drain();
4175 }
4176 mCallbackThread->exit();
4177 PlaybackThread::threadLoop_exit();
4178}
4179
4180AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4181 Vector< sp<Track> > *tracksToRemove
4182)
4183{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184 size_t count = mActiveTracks.size();
4185
4186 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004187 bool doHwPause = false;
4188 bool doHwResume = false;
4189
Eric Laurentede6c3b2013-09-19 14:37:46 -07004190 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4191
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 // find out which tracks need to be processed
4193 for (size_t i = 0; i < count; i++) {
4194 sp<Track> t = mActiveTracks[i].promote();
4195 // The track died recently
4196 if (t == 0) {
4197 continue;
4198 }
4199 Track* const track = t.get();
4200 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004201 // Only consider last track started for volume and mixer state control.
4202 // In theory an older track could underrun and restart after the new one starts
4203 // but as we only care about the transition phase between two tracks on a
4204 // direct output, it is not a problem to ignore the underrun case.
4205 sp<Track> l = mLatestActiveTrack.promote();
4206 bool last = l.get() == track;
4207
Haynes Mathew George7844f672014-01-15 12:32:55 -08004208 if (track->isInvalid()) {
4209 ALOGW("An invalidated track shouldn't be in active list");
4210 tracksToRemove->add(track);
4211 continue;
4212 }
4213
4214 if (track->mState == TrackBase::IDLE) {
4215 ALOGW("An idle track shouldn't be in active list");
4216 continue;
4217 }
4218
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 if (track->isPausing()) {
4220 track->setPaused();
4221 if (last) {
4222 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004223 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004224 mHwPaused = true;
4225 }
4226 // If we were part way through writing the mixbuffer to
4227 // the HAL we must save this until we resume
4228 // BUG - this will be wrong if a different track is made active,
4229 // in that case we want to discard the pending data in the
4230 // mixbuffer and tell the client to present it again when the
4231 // track is resumed
4232 mPausedWriteLength = mCurrentWriteLength;
4233 mPausedBytesRemaining = mBytesRemaining;
4234 mBytesRemaining = 0; // stop writing
4235 }
4236 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004237 } else if (track->isFlushPending()) {
4238 track->flushAck();
4239 if (last) {
4240 mFlushPending = true;
4241 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004242 } else if (track->isResumePending()){
4243 track->resumeAck();
4244 if (last) {
4245 if (mPausedBytesRemaining) {
4246 // Need to continue write that was interrupted
4247 mCurrentWriteLength = mPausedWriteLength;
4248 mBytesRemaining = mPausedBytesRemaining;
4249 mPausedBytesRemaining = 0;
4250 }
4251 if (mHwPaused) {
4252 doHwResume = true;
4253 mHwPaused = false;
4254 // threadLoop_mix() will handle the case that we need to
4255 // resume an interrupted write
4256 }
4257 // enable write to audio HAL
4258 sleepTime = 0;
4259
4260 // Do not handle new data in this iteration even if track->framesReady()
4261 mixerStatus = MIXER_TRACKS_ENABLED;
4262 }
4263 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004264 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004265 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004266 if (track->mFillingUpStatus == Track::FS_FILLED) {
4267 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004268 // make sure processVolume_l() will apply new volume even if 0
4269 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004270 }
4271
4272 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004273 sp<Track> previousTrack = mPreviousTrack.promote();
4274 if (previousTrack != 0) {
4275 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004276 // Flush any data still being written from last track
4277 mBytesRemaining = 0;
4278 if (mPausedBytesRemaining) {
4279 // Last track was paused so we also need to flush saved
4280 // mixbuffer state and invalidate track so that it will
4281 // re-submit that unwritten data when it is next resumed
4282 mPausedBytesRemaining = 0;
4283 // Invalidate is a bit drastic - would be more efficient
4284 // to have a flag to tell client that some of the
4285 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004286 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004287 }
4288 // flush data already sent to the DSP if changing audio session as audio
4289 // comes from a different source. Also invalidate previous track to force a
4290 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004291 if (previousTrack->sessionId() != track->sessionId()) {
4292 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004293 }
4294 }
4295 }
4296 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297 // reset retry count
4298 track->mRetryCount = kMaxTrackRetriesOffload;
4299 mActiveTrack = t;
4300 mixerStatus = MIXER_TRACKS_READY;
4301 }
4302 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004303 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004304 if (track->isStopping_1()) {
4305 // Hardware buffer can hold a large amount of audio so we must
4306 // wait for all current track's data to drain before we say
4307 // that the track is stopped.
4308 if (mBytesRemaining == 0) {
4309 // Only start draining when all data in mixbuffer
4310 // has been written
4311 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4312 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004313 // do not drain if no data was ever sent to HAL (mStandby == true)
4314 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004315 // do not modify drain sequence if we are already draining. This happens
4316 // when resuming from pause after drain.
4317 if ((mDrainSequence & 1) == 0) {
4318 sleepTime = 0;
4319 standbyTime = systemTime() + standbyDelay;
4320 mixerStatus = MIXER_DRAIN_TRACK;
4321 mDrainSequence += 2;
4322 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004323 if (mHwPaused) {
4324 // It is possible to move from PAUSED to STOPPING_1 without
4325 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004326 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 mHwPaused = false;
4328 }
4329 }
4330 }
4331 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004332 // Drain has completed or we are in standby, signal presentation complete
4333 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004334 track->mState = TrackBase::STOPPED;
4335 size_t audioHALFrames =
4336 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4337 size_t framesWritten =
4338 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4339 track->presentationComplete(framesWritten, audioHALFrames);
4340 track->reset();
4341 tracksToRemove->add(track);
4342 }
4343 } else {
4344 // No buffers for this track. Give it a few chances to
4345 // fill a buffer, then remove it from active list.
4346 if (--(track->mRetryCount) <= 0) {
4347 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4348 track->name());
4349 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004350 // indicate to client process that the track was disabled because of underrun;
4351 // it will then automatically call start() when data is available
4352 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004353 } else if (last){
4354 mixerStatus = MIXER_TRACKS_ENABLED;
4355 }
4356 }
4357 }
4358 // compute volume for this track
4359 processVolume_l(track, last);
4360 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004361
Eric Laurentea0fade2013-10-04 16:23:48 -07004362 // make sure the pause/flush/resume sequence is executed in the right order.
4363 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4364 // before flush and then resume HW. This can happen in case of pause/flush/resume
4365 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004366 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004367 mOutput->stream->pause(mOutput->stream);
4368 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004369 if (mFlushPending) {
4370 flushHw_l();
4371 mFlushPending = false;
4372 }
Eric Laurentfd477972013-10-25 18:10:40 -07004373 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004374 mOutput->stream->resume(mOutput->stream);
4375 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004376
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 // remove all the tracks that need to be...
4378 removeTracks_l(*tracksToRemove);
4379
4380 return mixerStatus;
4381}
4382
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383// must be called with thread mutex locked
4384bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4385{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004386 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4387 mWriteAckSequence, mDrainSequence);
4388 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004389 return true;
4390 }
4391 return false;
4392}
4393
4394// must be called with thread mutex locked
4395bool AudioFlinger::OffloadThread::shouldStandby_l()
4396{
Glenn Kastene6f35b12013-08-19 09:58:50 -07004397 bool trackPaused = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004398
4399 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4400 // after a timeout and we will enter standby then.
4401 if (mTracks.size() > 0) {
Glenn Kastene6f35b12013-08-19 09:58:50 -07004402 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 }
4404
Glenn Kastene6f35b12013-08-19 09:58:50 -07004405 return !mStandby && !trackPaused;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004406}
4407
4408
4409bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4410{
4411 Mutex::Autolock _l(mLock);
4412 return waitingAsyncCallback_l();
4413}
4414
4415void AudioFlinger::OffloadThread::flushHw_l()
4416{
4417 mOutput->stream->flush(mOutput->stream);
4418 // Flush anything still waiting in the mixbuffer
4419 mCurrentWriteLength = 0;
4420 mBytesRemaining = 0;
4421 mPausedWriteLength = 0;
4422 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004423 mHwPaused = false;
4424
Eric Laurentbfb1b832013-01-07 09:53:42 -08004425 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004426 // discard any pending drain or write ack by incrementing sequence
4427 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4428 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004429 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004430 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4431 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004432 }
4433}
4434
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004435void AudioFlinger::OffloadThread::onAddNewTrack_l()
4436{
4437 sp<Track> previousTrack = mPreviousTrack.promote();
4438 sp<Track> latestTrack = mLatestActiveTrack.promote();
4439
4440 if (previousTrack != 0 && latestTrack != 0 &&
4441 (previousTrack->sessionId() != latestTrack->sessionId())) {
4442 mFlushPending = true;
4443 }
4444 PlaybackThread::onAddNewTrack_l();
4445}
4446
Eric Laurentbfb1b832013-01-07 09:53:42 -08004447// ----------------------------------------------------------------------------
4448
Eric Laurent81784c32012-11-19 14:55:58 -08004449AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4450 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4451 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4452 DUPLICATING),
4453 mWaitTimeMs(UINT_MAX)
4454{
4455 addOutputTrack(mainThread);
4456}
4457
4458AudioFlinger::DuplicatingThread::~DuplicatingThread()
4459{
4460 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4461 mOutputTracks[i]->destroy();
4462 }
4463}
4464
4465void AudioFlinger::DuplicatingThread::threadLoop_mix()
4466{
4467 // mix buffers...
4468 if (outputsReady(outputTracks)) {
4469 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4470 } else {
Andy Hung25c2dac2014-02-27 14:56:00 -08004471 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004472 }
4473 sleepTime = 0;
4474 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004475 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004476 standbyTime = systemTime() + standbyDelay;
4477}
4478
4479void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4480{
4481 if (sleepTime == 0) {
4482 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4483 sleepTime = activeSleepTime;
4484 } else {
4485 sleepTime = idleSleepTime;
4486 }
4487 } else if (mBytesWritten != 0) {
4488 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4489 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004490 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004491 } else {
4492 // flush remaining overflow buffers in output tracks
4493 writeFrames = 0;
4494 }
4495 sleepTime = 0;
4496 }
4497}
4498
Eric Laurentbfb1b832013-01-07 09:53:42 -08004499ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004500{
4501 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung010a1a12014-03-13 13:57:33 -07004502 // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4503 // for delivery downstream as needed. This in-place conversion is safe as
4504 // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4505 // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4506 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4507 memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4508 mSinkBuffer, mFormat, writeFrames * mChannelCount);
4509 }
4510 outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004511 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07004512 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08004513 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004514}
4515
4516void AudioFlinger::DuplicatingThread::threadLoop_standby()
4517{
4518 // DuplicatingThread implements standby by stopping all tracks
4519 for (size_t i = 0; i < outputTracks.size(); i++) {
4520 outputTracks[i]->stop();
4521 }
4522}
4523
4524void AudioFlinger::DuplicatingThread::saveOutputTracks()
4525{
4526 outputTracks = mOutputTracks;
4527}
4528
4529void AudioFlinger::DuplicatingThread::clearOutputTracks()
4530{
4531 outputTracks.clear();
4532}
4533
4534void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4535{
4536 Mutex::Autolock _l(mLock);
4537 // FIXME explain this formula
4538 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Andy Hung010a1a12014-03-13 13:57:33 -07004539 // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4540 // due to current usage case and restrictions on the AudioBufferProvider.
4541 // Actual buffer conversion is done in threadLoop_write().
4542 //
4543 // TODO: This may change in the future, depending on multichannel
4544 // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
Eric Laurent81784c32012-11-19 14:55:58 -08004545 OutputTrack *outputTrack = new OutputTrack(thread,
4546 this,
4547 mSampleRate,
Andy Hung010a1a12014-03-13 13:57:33 -07004548 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurent81784c32012-11-19 14:55:58 -08004549 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004550 frameCount,
4551 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08004552 if (outputTrack->cblk() != NULL) {
4553 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4554 mOutputTracks.add(outputTrack);
4555 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4556 updateWaitTime_l();
4557 }
4558}
4559
4560void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4561{
4562 Mutex::Autolock _l(mLock);
4563 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4564 if (mOutputTracks[i]->thread() == thread) {
4565 mOutputTracks[i]->destroy();
4566 mOutputTracks.removeAt(i);
4567 updateWaitTime_l();
4568 return;
4569 }
4570 }
4571 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4572}
4573
4574// caller must hold mLock
4575void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4576{
4577 mWaitTimeMs = UINT_MAX;
4578 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4579 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4580 if (strong != 0) {
4581 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4582 if (waitTimeMs < mWaitTimeMs) {
4583 mWaitTimeMs = waitTimeMs;
4584 }
4585 }
4586 }
4587}
4588
4589
4590bool AudioFlinger::DuplicatingThread::outputsReady(
4591 const SortedVector< sp<OutputTrack> > &outputTracks)
4592{
4593 for (size_t i = 0; i < outputTracks.size(); i++) {
4594 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4595 if (thread == 0) {
4596 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4597 outputTracks[i].get());
4598 return false;
4599 }
4600 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4601 // see note at standby() declaration
4602 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4603 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4604 thread.get());
4605 return false;
4606 }
4607 }
4608 return true;
4609}
4610
4611uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4612{
4613 return (mWaitTimeMs * 1000) / 2;
4614}
4615
4616void AudioFlinger::DuplicatingThread::cacheParameters_l()
4617{
4618 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4619 updateWaitTime_l();
4620
4621 MixerThread::cacheParameters_l();
4622}
4623
4624// ----------------------------------------------------------------------------
4625// Record
4626// ----------------------------------------------------------------------------
4627
4628AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4629 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08004630 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08004631 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08004632 audio_devices_t inDevice
4633#ifdef TEE_SINK
4634 , const sp<NBAIO_Sink>& teeSink
4635#endif
4636 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08004637 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004638 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004639 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004640 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08004641#ifdef TEE_SINK
4642 , mTeeSink(teeSink)
4643#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07004644 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
4645 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Eric Laurent81784c32012-11-19 14:55:58 -08004646{
4647 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07004648 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08004649
Glenn Kastendeca2ae2014-02-07 10:25:56 -08004650 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08004651}
4652
4653
4654AudioFlinger::RecordThread::~RecordThread()
4655{
Glenn Kasten481fb672013-09-30 14:39:28 -07004656 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004657 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004658}
4659
4660void AudioFlinger::RecordThread::onFirstRef()
4661{
4662 run(mName, PRIORITY_URGENT_AUDIO);
4663}
4664
Eric Laurent81784c32012-11-19 14:55:58 -08004665bool AudioFlinger::RecordThread::threadLoop()
4666{
Eric Laurent81784c32012-11-19 14:55:58 -08004667 nsecs_t lastWarning = 0;
4668
4669 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08004670
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004671reacquire_wakelock:
4672 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08004673 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004674 {
4675 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08004676 size_t size = mActiveTracks.size();
4677 activeTracksGen = mActiveTracksGen;
4678 if (size > 0) {
4679 // FIXME an arbitrary choice
4680 activeTrack = mActiveTracks[0];
4681 acquireWakeLock_l(activeTrack->uid());
4682 if (size > 1) {
4683 SortedVector<int> tmp;
4684 for (size_t i = 0; i < size; i++) {
4685 tmp.add(mActiveTracks[i]->uid());
4686 }
4687 updateWakeLockUids_l(tmp);
4688 }
4689 } else {
4690 acquireWakeLock_l(-1);
4691 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004692 }
4693
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004694 // used to request a deferred sleep, to be executed later while mutex is unlocked
4695 uint32_t sleepUs = 0;
4696
4697 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004698 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07004699 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004700
Glenn Kasten5edadd42013-08-14 16:30:49 -07004701 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004702 if (sleepUs > 0) {
4703 usleep(sleepUs);
4704 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07004705 }
4706
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004707 // activeTracks accumulates a copy of a subset of mActiveTracks
4708 Vector< sp<RecordTrack> > activeTracks;
4709
Eric Laurent81784c32012-11-19 14:55:58 -08004710 { // scope for mLock
4711 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08004712
Glenn Kasten2cfbf882013-08-14 13:12:11 -07004713 processConfigEvents_l();
Glenn Kasten26a40292013-08-14 13:11:40 -07004714 // return value 'reconfig' is currently unused
4715 bool reconfig = checkForNewParameters_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004716
Eric Laurent000a4192014-01-29 15:17:32 -08004717 // check exitPending here because checkForNewParameters_l() and
4718 // checkForNewParameters_l() can temporarily release mLock
4719 if (exitPending()) {
4720 break;
4721 }
4722
Glenn Kasten2b806402013-11-20 16:37:38 -08004723 // if no active track(s), then standby and release wakelock
4724 size_t size = mActiveTracks.size();
4725 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07004726 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07004727 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08004728 releaseWakeLock_l();
4729 ALOGV("RecordThread: loop stopping");
4730 // go to sleep
4731 mWaitWorkCV.wait(mLock);
4732 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004733 goto reacquire_wakelock;
4734 }
4735
Glenn Kasten2b806402013-11-20 16:37:38 -08004736 if (mActiveTracksGen != activeTracksGen) {
4737 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004738 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08004739 for (size_t i = 0; i < size; i++) {
4740 tmp.add(mActiveTracks[i]->uid());
4741 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08004742 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08004743 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004744
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004745 bool doBroadcast = false;
4746 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07004747
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004748 activeTrack = mActiveTracks[i];
4749 if (activeTrack->isTerminated()) {
4750 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08004751 mActiveTracks.remove(activeTrack);
4752 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004753 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07004754 continue;
4755 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004756
4757 TrackBase::track_state activeTrackState = activeTrack->mState;
4758 switch (activeTrackState) {
4759
4760 case TrackBase::PAUSING:
4761 mActiveTracks.remove(activeTrack);
4762 mActiveTracksGen++;
4763 doBroadcast = true;
4764 size--;
4765 continue;
4766
4767 case TrackBase::STARTING_1:
4768 sleepUs = 10000;
4769 i++;
4770 continue;
4771
4772 case TrackBase::STARTING_2:
4773 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004774 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07004775 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004776 break;
4777
4778 case TrackBase::ACTIVE:
4779 break;
4780
4781 case TrackBase::IDLE:
4782 i++;
4783 continue;
4784
4785 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004786 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07004787 }
Glenn Kasten9e982352013-08-14 14:39:50 -07004788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004789 activeTracks.add(activeTrack);
4790 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07004791
Glenn Kasten9e982352013-08-14 14:39:50 -07004792 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004793 if (doBroadcast) {
4794 mStartStopCond.broadcast();
4795 }
4796
4797 // sleep if there are no active tracks to process
4798 if (activeTracks.size() == 0) {
4799 if (sleepUs == 0) {
4800 sleepUs = kRecordThreadSleepUs;
4801 }
4802 continue;
4803 }
4804 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07004805
Eric Laurent81784c32012-11-19 14:55:58 -08004806 lockEffectChains_l(effectChains);
4807 }
4808
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004809 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07004810
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004811 size_t size = effectChains.size();
4812 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004813 // thread mutex is not locked, but effect chain is locked
4814 effectChains[i]->process_l();
4815 }
4816
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004817 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4818 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4819 // slow, then this RecordThread will overrun by not calling HAL read often enough.
4820 // If destination is non-contiguous, first read past the nominal end of buffer, then
4821 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004822
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004823 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4824 ssize_t bytesRead = mInput->stream->read(mInput->stream,
4825 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4826 if (bytesRead <= 0) {
4827 ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4828 // Force input into standby so that it tries to recover at next read attempt
4829 inputStandBy();
4830 sleepUs = kRecordThreadSleepUs;
4831 continue;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07004832 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004833 ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4834 size_t framesRead = bytesRead / mFrameSize;
4835 ALOG_ASSERT(framesRead > 0);
4836 if (mTeeSink != 0) {
4837 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4838 }
4839 // If destination is non-contiguous, we now correct for reading past end of buffer.
4840 size_t part1 = mRsmpInFramesP2 - rear;
4841 if (framesRead > part1) {
4842 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4843 (framesRead - part1) * mFrameSize);
4844 }
4845 rear = mRsmpInRear += framesRead;
4846
4847 size = activeTracks.size();
4848 // loop over each active track
4849 for (size_t i = 0; i < size; i++) {
4850 activeTrack = activeTracks[i];
4851
4852 enum {
4853 OVERRUN_UNKNOWN,
4854 OVERRUN_TRUE,
4855 OVERRUN_FALSE
4856 } overrun = OVERRUN_UNKNOWN;
4857
4858 // loop over getNextBuffer to handle circular sink
4859 for (;;) {
4860
4861 activeTrack->mSink.frameCount = ~0;
4862 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4863 size_t framesOut = activeTrack->mSink.frameCount;
4864 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4865
4866 int32_t front = activeTrack->mRsmpInFront;
4867 ssize_t filled = rear - front;
4868 size_t framesIn;
4869
4870 if (filled < 0) {
4871 // should not happen, but treat like a massive overrun and re-sync
4872 framesIn = 0;
4873 activeTrack->mRsmpInFront = rear;
4874 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004875 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004876 framesIn = (size_t) filled;
4877 } else {
4878 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004879 framesIn = mRsmpInFrames;
4880 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004881 overrun = OVERRUN_TRUE;
4882 }
4883
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004884 if (framesOut == 0 || framesIn == 0) {
4885 break;
4886 }
4887
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004888 if (activeTrack->mResampler == NULL) {
4889 // no resampling
4890 if (framesIn > framesOut) {
4891 framesIn = framesOut;
4892 } else {
4893 framesOut = framesIn;
4894 }
4895 int8_t *dst = activeTrack->mSink.i8;
4896 while (framesIn > 0) {
4897 front &= mRsmpInFramesP2 - 1;
4898 size_t part1 = mRsmpInFramesP2 - front;
4899 if (part1 > framesIn) {
4900 part1 = framesIn;
4901 }
4902 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004903 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004904 memcpy(dst, src, part1 * mFrameSize);
4905 } else if (mChannelCount == 1) {
4906 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4907 part1);
4908 } else {
4909 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4910 part1);
4911 }
4912 dst += part1 * activeTrack->mFrameSize;
4913 front += part1;
4914 framesIn -= part1;
4915 }
4916 activeTrack->mRsmpInFront += framesOut;
4917
4918 } else {
4919 // resampling
4920 // FIXME framesInNeeded should really be part of resampler API, and should
4921 // depend on the SRC ratio
4922 // to keep mRsmpInBuffer full so resampler always has sufficient input
4923 size_t framesInNeeded;
4924 // FIXME only re-calculate when it changes, and optimize for common ratios
4925 double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4926 double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004927 framesInNeeded = ceil(framesOut * inOverOut) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004928 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4929 framesInNeeded, framesOut, inOverOut);
4930 // Although we theoretically have framesIn in circular buffer, some of those are
4931 // unreleased frames, and thus must be discounted for purpose of budgeting.
4932 size_t unreleased = activeTrack->mRsmpInUnrel;
4933 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004934 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004935 ALOGV("not enough to resample: have %u frames in but need %u in to "
4936 "produce %u out given in/out ratio of %.4g",
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004937 framesIn, framesInNeeded, framesOut, inOverOut);
4938 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004939 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4940 if (newFramesOut == 0) {
4941 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004942 }
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004943 framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4944 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4945 framesInNeeded, newFramesOut, outOverIn);
4946 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4947 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4948 "given in/out ratio of %.4g",
4949 framesIn, framesInNeeded, newFramesOut, inOverOut);
4950 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004951 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004952 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004953 "given in/out ratio of %.4g",
4954 framesIn, framesInNeeded, framesOut, inOverOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004955 }
4956
4957 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4958 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004959 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004960 delete[] activeTrack->mRsmpOutBuffer;
4961 // resampler always outputs stereo
4962 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4963 activeTrack->mRsmpOutFrameCount = framesOut;
4964 }
4965
4966 // resampler accumulates, but we only have one source track
4967 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4968 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08004969 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004970 activeTrack->mResamplerBufferProvider
4971 /*this*/ /* AudioBufferProvider* */);
4972 // ditherAndClamp() works as long as all buffers returned by
4973 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08004974 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07004975 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08004976 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4977 framesOut);
4978 // the resampler always outputs stereo samples:
4979 // do post stereo to mono conversion
4980 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4981 (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4982 } else {
4983 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4984 activeTrack->mRsmpOutBuffer, framesOut);
4985 }
4986 // now done with mRsmpOutBuffer
4987
4988 }
4989
4990 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4991 overrun = OVERRUN_FALSE;
4992 }
4993
4994 if (activeTrack->mFramesToDrop == 0) {
4995 if (framesOut > 0) {
4996 activeTrack->mSink.frameCount = framesOut;
4997 activeTrack->releaseBuffer(&activeTrack->mSink);
4998 }
4999 } else {
5000 // FIXME could do a partial drop of framesOut
5001 if (activeTrack->mFramesToDrop > 0) {
5002 activeTrack->mFramesToDrop -= framesOut;
5003 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005004 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005005 }
5006 } else {
5007 activeTrack->mFramesToDrop += framesOut;
5008 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5009 activeTrack->mSyncStartEvent->isCancelled()) {
5010 ALOGW("Synced record %s, session %d, trigger session %d",
5011 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5012 activeTrack->sessionId(),
5013 (activeTrack->mSyncStartEvent != 0) ?
5014 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005015 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005016 }
5017 }
5018 }
5019
5020 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005021 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005022 }
5023 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005024
5025 switch (overrun) {
5026 case OVERRUN_TRUE:
5027 // client isn't retrieving buffers fast enough
5028 if (!activeTrack->setOverflow()) {
5029 nsecs_t now = systemTime();
5030 // FIXME should lastWarning per track?
5031 if ((now - lastWarning) > kWarningThrottleNs) {
5032 ALOGW("RecordThread: buffer overflow");
5033 lastWarning = now;
5034 }
5035 }
5036 break;
5037 case OVERRUN_FALSE:
5038 activeTrack->clearOverflow();
5039 break;
5040 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005041 break;
5042 }
5043
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005044 }
5045
Eric Laurent81784c32012-11-19 14:55:58 -08005046 // enable changes in effect chain
5047 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005048 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005049 }
5050
Glenn Kasten93e471f2013-08-19 08:40:07 -07005051 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005052
5053 {
5054 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005055 for (size_t i = 0; i < mTracks.size(); i++) {
5056 sp<RecordTrack> track = mTracks[i];
5057 track->invalidate();
5058 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005059 mActiveTracks.clear();
5060 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005061 mStartStopCond.broadcast();
5062 }
5063
5064 releaseWakeLock();
5065
5066 ALOGV("RecordThread %p exiting", this);
5067 return false;
5068}
5069
Glenn Kasten93e471f2013-08-19 08:40:07 -07005070void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005071{
5072 if (!mStandby) {
5073 inputStandBy();
5074 mStandby = true;
5075 }
5076}
5077
5078void AudioFlinger::RecordThread::inputStandBy()
5079{
5080 mInput->stream->common.standby(&mInput->stream->common);
5081}
5082
Glenn Kasten05997e22014-03-13 15:08:33 -07005083// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005084sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005085 const sp<AudioFlinger::Client>& client,
5086 uint32_t sampleRate,
5087 audio_format_t format,
5088 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005089 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005090 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005091 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005092 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005093 pid_t tid,
5094 status_t *status)
5095{
Glenn Kasten74935e42013-12-19 08:56:45 -08005096 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005097 sp<RecordTrack> track;
5098 status_t lStatus;
5099
Glenn Kasten90e58b12013-07-31 16:16:02 -07005100 // client expresses a preference for FAST, but we get the final say
5101 if (*flags & IAudioFlinger::TRACK_FAST) {
5102 if (
5103 // use case: callback handler and frame count is default or at least as large as HAL
5104 (
5105 (tid != -1) &&
5106 ((frameCount == 0) ||
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005107 // FIXME not necessarily true, should be native frame count for native SR!
Glenn Kastenb5fed682013-12-03 09:06:43 -08005108 (frameCount >= mFrameCount))
Glenn Kasten90e58b12013-07-31 16:16:02 -07005109 ) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005110 // PCM data
5111 audio_is_linear_pcm(format) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005112 // mono or stereo
Glenn Kasten828f8832014-05-07 11:17:52 -07005113 ( (channelMask == AUDIO_CHANNEL_IN_MONO) ||
5114 (channelMask == AUDIO_CHANNEL_IN_STEREO) ) &&
Glenn Kasten90e58b12013-07-31 16:16:02 -07005115 // hardware sample rate
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005116 // FIXME actually the native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005117 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005118 // record thread has an associated fast capture
5119 hasFastCapture()
5120 // fast capture does not require slots
Glenn Kasten90e58b12013-07-31 16:16:02 -07005121 ) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005122 // if frameCount not specified, then it defaults to fast capture (HAL) frame count
Glenn Kasten90e58b12013-07-31 16:16:02 -07005123 if (frameCount == 0) {
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005124 // FIXME wrong mFrameCount
Glenn Kasten90e58b12013-07-31 16:16:02 -07005125 frameCount = mFrameCount * kFastTrackMultiplier;
5126 }
5127 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5128 frameCount, mFrameCount);
5129 } else {
5130 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5131 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005132 "hasFastCapture=%d tid=%d",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005133 frameCount, mFrameCount, format,
5134 audio_is_linear_pcm(format),
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005135 channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005136 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005137 // 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 -07005138 // For compatibility with AudioRecord calculation, buffer depth is forced
5139 // to be at least 2 x the record thread frame count and cover audio hardware latency.
5140 // This is probably too conservative, but legacy application code may depend on it.
5141 // If you change this calculation, also review the start threshold which is related.
5142 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5143 size_t mNormalFrameCount = 2048; // FIXME
5144 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5145 if (minBufCount < 2) {
5146 minBufCount = 2;
5147 }
5148 size_t minFrameCount = mNormalFrameCount * minBufCount;
5149 if (frameCount < minFrameCount) {
5150 frameCount = minFrameCount;
5151 }
5152 }
5153 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005154 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005155
Glenn Kasten15e57982013-09-24 11:52:37 -07005156 lStatus = initCheck();
5157 if (lStatus != NO_ERROR) {
5158 ALOGE("createRecordTrack_l() audio driver not initialized");
5159 goto Exit;
5160 }
Eric Laurent81784c32012-11-19 14:55:58 -08005161
5162 { // scope for mLock
5163 Mutex::Autolock _l(mLock);
5164
5165 track = new RecordTrack(this, client, sampleRate,
Glenn Kastend776ac62014-05-07 09:16:09 -07005166 format, channelMask, frameCount, sessionId, uid,
5167 (*flags & IAudioFlinger::TRACK_FAST) != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08005168
Glenn Kasten03003332013-08-06 15:40:54 -07005169 lStatus = track->initCheck();
5170 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005171 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005172 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005173 goto Exit;
5174 }
5175 mTracks.add(track);
5176
5177 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5178 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5179 mAudioFlinger->btNrecIsOff();
5180 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5181 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005182
5183 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5184 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5185 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5186 // so ask activity manager to do this on our behalf
5187 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5188 }
Eric Laurent81784c32012-11-19 14:55:58 -08005189 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005190
Eric Laurent81784c32012-11-19 14:55:58 -08005191 lStatus = NO_ERROR;
5192
5193Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005194 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005195 return track;
5196}
5197
5198status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5199 AudioSystem::sync_event_t event,
5200 int triggerSession)
5201{
5202 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5203 sp<ThreadBase> strongMe = this;
5204 status_t status = NO_ERROR;
5205
5206 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005207 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005208 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005209 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005210 triggerSession,
5211 recordTrack->sessionId(),
5212 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005213 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005214 // Sync event can be cancelled by the trigger session if the track is not in a
5215 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005216 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005217 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005218 } else {
5219 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005220 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005221 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005222 }
5223 }
5224
5225 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005226 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005227 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005228 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5229 if (recordTrack->mState == TrackBase::PAUSING) {
5230 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005231 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005232 } else {
5233 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005234 }
5235 return status;
5236 }
5237
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005238 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5239 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5240 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005241 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005242 mActiveTracks.add(recordTrack);
5243 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005244 mLock.unlock();
5245 status_t status = AudioSystem::startInput(mId);
5246 mLock.lock();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005247 // FIXME should verify that recordTrack is still in mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -08005248 if (status != NO_ERROR) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005249 mActiveTracks.remove(recordTrack);
5250 mActiveTracksGen++;
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005251 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005252 return status;
5253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005254 // Catch up with current buffer indices if thread is already running.
5255 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5256 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5257 // see previously buffered data before it called start(), but with greater risk of overrun.
5258
5259 recordTrack->mRsmpInFront = mRsmpInRear;
5260 recordTrack->mRsmpInUnrel = 0;
5261 // FIXME why reset?
5262 if (recordTrack->mResampler != NULL) {
5263 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08005264 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005265 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005266 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005267 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005268 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005269 ALOGV("Record failed to start");
5270 status = BAD_VALUE;
5271 goto startError;
5272 }
Eric Laurent81784c32012-11-19 14:55:58 -08005273 return status;
5274 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005275
Eric Laurent81784c32012-11-19 14:55:58 -08005276startError:
5277 AudioSystem::stopInput(mId);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005278 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005279 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005280 return status;
5281}
5282
Eric Laurent81784c32012-11-19 14:55:58 -08005283void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5284{
5285 sp<SyncEvent> strongEvent = event.promote();
5286
5287 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005288 sp<RefBase> ptr = strongEvent->cookie().promote();
5289 if (ptr != 0) {
5290 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5291 recordTrack->handleSyncStartEvent(strongEvent);
5292 }
Eric Laurent81784c32012-11-19 14:55:58 -08005293 }
5294}
5295
Glenn Kastena8356f62013-07-25 14:37:52 -07005296bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005297 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005298 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005299 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005300 return false;
5301 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005302 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005303 recordTrack->mState = TrackBase::PAUSING;
5304 // do not wait for mStartStopCond if exiting
5305 if (exitPending()) {
5306 return true;
5307 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005308 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005309 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005310 // if we have been restarted, recordTrack is in mActiveTracks here
5311 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005312 ALOGV("Record stopped OK");
5313 return true;
5314 }
5315 return false;
5316}
5317
Glenn Kasten0f11b512014-01-31 16:18:54 -08005318bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005319{
5320 return false;
5321}
5322
Glenn Kasten0f11b512014-01-31 16:18:54 -08005323status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005324{
5325#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
5326 if (!isValidSyncEvent(event)) {
5327 return BAD_VALUE;
5328 }
5329
5330 int eventSession = event->triggerSession();
5331 status_t ret = NAME_NOT_FOUND;
5332
5333 Mutex::Autolock _l(mLock);
5334
5335 for (size_t i = 0; i < mTracks.size(); i++) {
5336 sp<RecordTrack> track = mTracks[i];
5337 if (eventSession == track->sessionId()) {
5338 (void) track->setSyncEvent(event);
5339 ret = NO_ERROR;
5340 }
5341 }
5342 return ret;
5343#else
5344 return BAD_VALUE;
5345#endif
5346}
5347
5348// destroyTrack_l() must be called with ThreadBase::mLock held
5349void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5350{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005351 track->terminate();
5352 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08005353 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08005354 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005355 removeTrack_l(track);
5356 }
5357}
5358
5359void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5360{
5361 mTracks.remove(track);
5362 // need anything related to effects here?
5363}
5364
5365void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5366{
5367 dumpInternals(fd, args);
5368 dumpTracks(fd, args);
5369 dumpEffectChains(fd, args);
5370}
5371
5372void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5373{
Marco Nelissenb2208842014-02-07 14:00:50 -08005374 fdprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08005375
Glenn Kasten2b806402013-11-20 16:37:38 -08005376 if (mActiveTracks.size() > 0) {
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00005377 fdprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005378 } else {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005379 fdprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381
Eric Laurent81784c32012-11-19 14:55:58 -08005382 dumpBase(fd, args);
5383}
5384
Glenn Kasten0f11b512014-01-31 16:18:54 -08005385void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005386{
5387 const size_t SIZE = 256;
5388 char buffer[SIZE];
5389 String8 result;
5390
Marco Nelissenb2208842014-02-07 14:00:50 -08005391 size_t numtracks = mTracks.size();
5392 size_t numactive = mActiveTracks.size();
5393 size_t numactiveseen = 0;
5394 fdprintf(fd, " %d Tracks", numtracks);
5395 if (numtracks) {
5396 fdprintf(fd, " of which %d are active\n", numactive);
5397 RecordTrack::appendDumpHeader(result);
5398 for (size_t i = 0; i < numtracks ; ++i) {
5399 sp<RecordTrack> track = mTracks[i];
5400 if (track != 0) {
5401 bool active = mActiveTracks.indexOf(track) >= 0;
5402 if (active) {
5403 numactiveseen++;
5404 }
5405 track->dump(buffer, SIZE, active);
5406 result.append(buffer);
5407 }
Eric Laurent81784c32012-11-19 14:55:58 -08005408 }
Marco Nelissenb2208842014-02-07 14:00:50 -08005409 } else {
5410 fdprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005411 }
5412
Marco Nelissenb2208842014-02-07 14:00:50 -08005413 if (numactiveseen != numactive) {
5414 snprintf(buffer, SIZE, " The following tracks are in the active list but"
5415 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08005416 result.append(buffer);
5417 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08005418 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08005419 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08005420 if (mTracks.indexOf(track) < 0) {
5421 track->dump(buffer, SIZE, true);
5422 result.append(buffer);
5423 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005424 }
Eric Laurent81784c32012-11-19 14:55:58 -08005425
5426 }
5427 write(fd, result.string(), result.size());
5428}
5429
5430// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005431status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5432 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005433{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005434 RecordTrack *activeTrack = mRecordTrack;
5435 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5436 if (threadBase == 0) {
5437 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005438 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005439 return NOT_ENOUGH_DATA;
5440 }
5441 RecordThread *recordThread = (RecordThread *) threadBase.get();
5442 int32_t rear = recordThread->mRsmpInRear;
5443 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07005444 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005445 // FIXME should not be P2 (don't want to increase latency)
5446 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005447 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07005448 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005449 front &= recordThread->mRsmpInFramesP2 - 1;
5450 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07005451 if (part1 > (size_t) filled) {
5452 part1 = filled;
5453 }
5454 size_t ask = buffer->frameCount;
5455 ALOG_ASSERT(ask > 0);
5456 if (part1 > ask) {
5457 part1 = ask;
5458 }
5459 if (part1 == 0) {
5460 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005461 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07005462 buffer->raw = NULL;
5463 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005464 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07005465 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08005466 }
5467
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005468 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005469 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005470 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08005471 return NO_ERROR;
5472}
5473
5474// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005475void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5476 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08005477{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005478 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07005479 size_t stepCount = buffer->frameCount;
5480 if (stepCount == 0) {
5481 return;
5482 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005483 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5484 activeTrack->mRsmpInUnrel -= stepCount;
5485 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07005486 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005487 buffer->frameCount = 0;
5488}
5489
5490bool AudioFlinger::RecordThread::checkForNewParameters_l()
5491{
5492 bool reconfig = false;
5493
5494 while (!mNewParameters.isEmpty()) {
5495 status_t status = NO_ERROR;
5496 String8 keyValuePair = mNewParameters[0];
5497 AudioParameter param = AudioParameter(keyValuePair);
5498 int value;
5499 audio_format_t reqFormat = mFormat;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005500 uint32_t samplingRate = mSampleRate;
5501 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005502
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005503 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5504 // channel count change can be requested. Do we mandate the first client defines the
5505 // HAL sampling rate and channel count or do we allow changes on the fly?
Eric Laurent81784c32012-11-19 14:55:58 -08005506 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005507 samplingRate = value;
Eric Laurent81784c32012-11-19 14:55:58 -08005508 reconfig = true;
5509 }
5510 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005511 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5512 status = BAD_VALUE;
5513 } else {
5514 reqFormat = (audio_format_t) value;
5515 reconfig = true;
5516 }
Eric Laurent81784c32012-11-19 14:55:58 -08005517 }
5518 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Glenn Kastenec3fb502013-07-17 07:30:58 -07005519 audio_channel_mask_t mask = (audio_channel_mask_t) value;
5520 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5521 status = BAD_VALUE;
5522 } else {
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005523 channelMask = mask;
Glenn Kastenec3fb502013-07-17 07:30:58 -07005524 reconfig = true;
5525 }
Eric Laurent81784c32012-11-19 14:55:58 -08005526 }
5527 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5528 // do not accept frame count changes if tracks are open as the track buffer
5529 // size depends on frame count and correct behavior would not be guaranteed
5530 // if frame count is changed after track creation
Glenn Kasten2b806402013-11-20 16:37:38 -08005531 if (mActiveTracks.size() > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005532 status = INVALID_OPERATION;
5533 } else {
5534 reconfig = true;
5535 }
5536 }
5537 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5538 // forward device change to effects that have requested to be
5539 // aware of attached audio device.
5540 for (size_t i = 0; i < mEffectChains.size(); i++) {
5541 mEffectChains[i]->setDevice_l(value);
5542 }
5543
5544 // store input device and output device but do not forward output device to audio HAL.
5545 // Note that status is ignored by the caller for output device
5546 // (see AudioFlinger::setParameters()
5547 if (audio_is_output_devices(value)) {
5548 mOutDevice = value;
5549 status = BAD_VALUE;
5550 } else {
5551 mInDevice = value;
5552 // disable AEC and NS if the device is a BT SCO headset supporting those
5553 // pre processings
5554 if (mTracks.size() > 0) {
5555 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5556 mAudioFlinger->btNrecIsOff();
5557 for (size_t i = 0; i < mTracks.size(); i++) {
5558 sp<RecordTrack> track = mTracks[i];
5559 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5560 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5561 }
5562 }
5563 }
5564 }
5565 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5566 mAudioSource != (audio_source_t)value) {
5567 // forward device change to effects that have requested to be
5568 // aware of attached audio device.
5569 for (size_t i = 0; i < mEffectChains.size(); i++) {
5570 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5571 }
5572 mAudioSource = (audio_source_t)value;
5573 }
Glenn Kastene198c362013-08-13 09:13:36 -07005574
Eric Laurent81784c32012-11-19 14:55:58 -08005575 if (status == NO_ERROR) {
5576 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5577 keyValuePair.string());
5578 if (status == INVALID_OPERATION) {
5579 inputStandBy();
5580 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5581 keyValuePair.string());
5582 }
5583 if (reconfig) {
5584 if (status == BAD_VALUE &&
5585 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5586 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kastenc4974312012-12-14 07:13:28 -08005587 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005588 <= (2 * samplingRate)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08005589 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5590 <= FCC_2 &&
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005591 (channelMask == AUDIO_CHANNEL_IN_MONO ||
5592 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005593 status = NO_ERROR;
5594 }
5595 if (status == NO_ERROR) {
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005596 readInputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005597 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5598 }
5599 }
5600 }
5601
5602 mNewParameters.removeAt(0);
5603
5604 mParamStatus = status;
5605 mParamCond.signal();
5606 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5607 // already timed out waiting for the status and will never signal the condition.
5608 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5609 }
5610 return reconfig;
5611}
5612
5613String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5614{
Eric Laurent81784c32012-11-19 14:55:58 -08005615 Mutex::Autolock _l(mLock);
5616 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07005617 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08005618 }
5619
Glenn Kastend8ea6992013-07-16 14:17:15 -07005620 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5621 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08005622 free(s);
5623 return out_s8;
5624}
5625
Glenn Kasten0f11b512014-01-31 16:18:54 -08005626void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08005627 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07005628 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005629
5630 switch (event) {
5631 case AudioSystem::INPUT_OPENED:
5632 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07005633 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08005634 desc.samplingRate = mSampleRate;
5635 desc.format = mFormat;
5636 desc.frameCount = mFrameCount;
5637 desc.latency = 0;
5638 param2 = &desc;
5639 break;
5640
5641 case AudioSystem::INPUT_CLOSED:
5642 default:
5643 break;
5644 }
5645 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5646}
5647
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005648void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08005649{
Eric Laurent81784c32012-11-19 14:55:58 -08005650 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5651 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07005652 mChannelCount = popcount(mChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005653 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005654 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08005655 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07005656 }
Eric Laurent81784c32012-11-19 14:55:58 -08005657 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Glenn Kasten548efc92012-11-29 08:48:51 -08005658 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5659 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005660 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08005661 // 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 -07005662 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08005663 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005664 // A larger value should allow more old data to be read after a track calls start(),
5665 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08005666 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07005667 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005668 delete[] mRsmpInBuffer;
Glenn Kasten85948432013-08-19 12:09:05 -07005669 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5670 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08005671
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005672 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5673 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08005674}
5675
Glenn Kasten5f972c02014-01-13 09:59:31 -08005676uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08005677{
5678 Mutex::Autolock _l(mLock);
5679 if (initCheck() != NO_ERROR) {
5680 return 0;
5681 }
5682
5683 return mInput->stream->get_input_frames_lost(mInput->stream);
5684}
5685
5686uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5687{
5688 Mutex::Autolock _l(mLock);
5689 uint32_t result = 0;
5690 if (getEffectChain_l(sessionId) != 0) {
5691 result = EFFECT_SESSION;
5692 }
5693
5694 for (size_t i = 0; i < mTracks.size(); ++i) {
5695 if (sessionId == mTracks[i]->sessionId()) {
5696 result |= TRACK_SESSION;
5697 break;
5698 }
5699 }
5700
5701 return result;
5702}
5703
5704KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5705{
5706 KeyedVector<int, bool> ids;
5707 Mutex::Autolock _l(mLock);
5708 for (size_t j = 0; j < mTracks.size(); ++j) {
5709 sp<RecordThread::RecordTrack> track = mTracks[j];
5710 int sessionId = track->sessionId();
5711 if (ids.indexOfKey(sessionId) < 0) {
5712 ids.add(sessionId, true);
5713 }
5714 }
5715 return ids;
5716}
5717
5718AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5719{
5720 Mutex::Autolock _l(mLock);
5721 AudioStreamIn *input = mInput;
5722 mInput = NULL;
5723 return input;
5724}
5725
5726// this method must always be called either with ThreadBase mLock held or inside the thread loop
5727audio_stream_t* AudioFlinger::RecordThread::stream() const
5728{
5729 if (mInput == NULL) {
5730 return NULL;
5731 }
5732 return &mInput->stream->common;
5733}
5734
5735status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5736{
5737 // only one chain per input thread
5738 if (mEffectChains.size() != 0) {
5739 return INVALID_OPERATION;
5740 }
5741 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5742
5743 chain->setInBuffer(NULL);
5744 chain->setOutBuffer(NULL);
5745
5746 checkSuspendOnAddEffectChain_l(chain);
5747
5748 mEffectChains.add(chain);
5749
5750 return NO_ERROR;
5751}
5752
5753size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5754{
5755 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5756 ALOGW_IF(mEffectChains.size() != 1,
5757 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5758 chain.get(), mEffectChains.size(), this);
5759 if (mEffectChains.size() == 1) {
5760 mEffectChains.removeAt(0);
5761 }
5762 return 0;
5763}
5764
5765}; // namespace android